<commit_before>import test from 'ava';
import { join, resolve } from 'path';
import getFiles from '../lib/get-files';
import hash from '../lib/hash';
import { asc as alpha } from 'alpha-sort';

const prefix = join(__dirname, '_fixtures') + '/';
const base = (path) => path.replace(prefix, '');
const fixture = (name) => resolve(`./_fixtures/${name}`);

test('`files` + README', async t => {
  let files = await getFiles(fixture('files-in-package'));
  t.same(files.length, 3);
  files = files.sort(alpha);
  t.same(base(files[0]), 'files-in-package/build/a/b/c/d.js');
  t.same(base(files[1]), 'files-in-package/build/a/e.js');
  t.same(base(files[2]), 'files-in-package/package.json');
});

test('`files` + README + `.*.swp` + `.npmignore`', async t => {
  let files = await getFiles(fixture('files-in-package-ignore'));
  t.same(files.length, 3);
  files = files.sort(alpha);
  t.same(base(files[0]), 'files-in-package-ignore/build/a/b/c/d.js');
  t.same(base(files[1]), 'files-in-package-ignore/build/a/e.js');
  t.same(base(files[2]), 'files-in-package-ignore/package.json');
});

test('simple', async t => {
  let files = await getFiles(fixture('simple'));
  t.same(files.length, 5);
  files = files.sort(alpha);
  t.same(base(files[0]), 'simple/bin/test');
  t.same(base(files[1]), 'simple/index.js');
  t.same(base(files[2]), 'simple/lib/woot');
  t.same(base(files[3]), 'simple/lib/woot.jsx');
  t.same(base(files[4]), 'simple/package.json');
});

test('simple with main', async t => {
  let files = await getFiles(fixture('simple-main'));
  t.same(files.length, 3);
  files = files.sort(alpha);
  t.same(base(files[0]), 'simple-main/build/a.js');
  t.same(base(files[1]), 'simple-main/index.js');
  t.same(base(files[2]), 'simple-main/package.json');
});

test('hashes', async t => {
  const files = await getFiles(fixture('hashes'));
  const hashes = await hash(files);
  t.same(hashes.size, 3);
  t.same(hashes.get(prefix + 'hashes/dei.png'), '277c55a2042910b9fe706ad00859e008c1b7d172');
  t.same(hashes.get(prefix + 'hashes/index.js'), '56c00d0466fc6bdd41b13dac5fc920cc30a63b45');
  t.same(hashes.get(prefix + 'hashes/package.json'), '706214f42ae940a01d2aa60c5e32408f4d2127dd');
});
<commit_msg>index: fix hashes test<commit_after>import test from 'ava';
import { join, resolve } from 'path';
import getFiles from '../lib/get-files';
import hash from '../lib/hash';
import { asc as alpha } from 'alpha-sort';

const prefix = join(__dirname, '_fixtures') + '/';
const base = (path) => path.replace(prefix, '');
const fixture = (name) => resolve(`./_fixtures/${name}`);

test('`files` + README', async t => {
  let files = await getFiles(fixture('files-in-package'));
  t.same(files.length, 3);
  files = files.sort(alpha);
  t.same(base(files[0]), 'files-in-package/build/a/b/c/d.js');
  t.same(base(files[1]), 'files-in-package/build/a/e.js');
  t.same(base(files[2]), 'files-in-package/package.json');
});

test('`files` + README + `.*.swp` + `.npmignore`', async t => {
  let files = await getFiles(fixture('files-in-package-ignore'));
  t.same(files.length, 3);
  files = files.sort(alpha);
  t.same(base(files[0]), 'files-in-package-ignore/build/a/b/c/d.js');
  t.same(base(files[1]), 'files-in-package-ignore/build/a/e.js');
  t.same(base(files[2]), 'files-in-package-ignore/package.json');
});

test('simple', async t => {
  let files = await getFiles(fixture('simple'));
  t.same(files.length, 5);
  files = files.sort(alpha);
  t.same(base(files[0]), 'simple/bin/test');
  t.same(base(files[1]), 'simple/index.js');
  t.same(base(files[2]), 'simple/lib/woot');
  t.same(base(files[3]), 'simple/lib/woot.jsx');
  t.same(base(files[4]), 'simple/package.json');
});

test('simple with main', async t => {
  let files = await getFiles(fixture('simple-main'));
  t.same(files.length, 3);
  files = files.sort(alpha);
  t.same(base(files[0]), 'simple-main/build/a.js');
  t.same(base(files[1]), 'simple-main/index.js');
  t.same(base(files[2]), 'simple-main/package.json');
});

test('hashes', async t => {
  const files = await getFiles(fixture('hashes'));
  const hashes = await hash(files);
  t.same(hashes.size, 3);
  t.same(hashes.get('277c55a2042910b9fe706ad00859e008c1b7d172'), prefix + 'hashes/dei.png');
  t.same(hashes.get('56c00d0466fc6bdd41b13dac5fc920cc30a63b45'), prefix + 'hashes/index.js');
  t.same(hashes.get('706214f42ae940a01d2aa60c5e32408f4d2127dd'), prefix + 'hashes/package.json');
});
<|endoftext|>


<commit_before>/**
*
*  Copyright 2005 Sabre Airline Solutions
*
*  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.
**/

var Rico = new Object();
Rico.Corner = {

   round: function(e, options) {
      var e = $(e);
      this._setOptions(options);

      var color = this.options.color;
      if ( this.options.color == "fromElement" )
         color = this._background(e);

      var bgColor = this.options.bgColor;
      if ( this.options.bgColor == "fromParent" )
         bgColor = this._background(e.offsetParent);

      this._roundCornersImpl(e, color, bgColor);
   },

    /**   This is a helper function to change the background
    *     color of
 that has had Rico rounded corners added.
    *
    *     It seems we cannot just set the background color for the
    *     outer
 so each  element used to create the
    *     corners must have its background color set individually.
    *
    * @param {DOM} theDiv - A child of the outer
 that was
    *                        supplied to the `round` method.
    *
    * @param {str} newColor - The new background color to use.
    */
    changeColor: function(theDiv, newColor) {

        theDiv.style.backgroundColor = newColor;

        var spanElements = theDiv.parentNode.getElementsByTagName("span");

        for (var currIdx = 0; currIdx < spanElements.length; currIdx++) {
            spanElements[currIdx].style.backgroundColor = newColor;
        }
    },

    /**   This is a helper function to change the background
    *     opacity of
 that has had Rico rounded corners added.
    *
    *     See changeColor (above) for algorithm explanation
    *
    * @param {DOM} theDiv - A child of the outer
 that was
    *                        supplied to the `round` method.
    *
    * @param {int} newOpacity - The new opacity to use (1-10).
    */
    changeOpacity: function(theDiv, newOpacity) {

        var mozillaOpacity = newOpacity / 10
        var ieOpacity = 'alpha(opacity=' + newOpacity * 10 + ')';

        theDiv.style.opacity = mozillaOpacity;
        theDiv.style.filter = ieOpacity;

        var spanElements = theDiv.parentNode.getElementsByTagName("span");

        for (var currIdx = 0; currIdx < spanElements.length; currIdx++) {
            spanElements[currIdx].style.opacity = mozillaOpacity;
            spanElements[currIdx].style.filter = ieOpacity;
        }

    },

    /** this function takes care of redoing the rico cornering
    *
    *    you can't just call updateRicoCorners() again and pass it a
    *    new options string. you have to first remove the divs that
    *    rico puts on top and below the content div.
    *
    * @param {DOM} theDiv - A child of the outer
 that was
    *                        supplied to the `round` method.
    *
    * @param {Array} options - list of options
    */
    reRound: function(theDiv, options) {

        var topRico = theDiv.parentNode.childNodes[0];
        //theDiv would be theDiv.parentNode.childNodes[1]
        var bottomRico = theDiv.parentNode.childNodes[2];

        theDiv.parentNode.removeChild(topRico);
        theDiv.parentNode.removeChild(bottomRico);

        this.round(theDiv.parentNode, options);
    },

   _roundCornersImpl: function(e, color, bgColor) {
      if(this.options.border)
         this._renderBorder(e,bgColor);
      if(this._isTopRounded())
         this._roundTopCorners(e,color,bgColor);
      if(this._isBottomRounded())
         this._roundBottomCorners(e,color,bgColor);
   },

   _renderBorder: function(el,bgColor) {
      var borderValue = "1px solid " + this._borderColor(bgColor);
      var borderL = "border-left: "  + borderValue;
      var borderR = "border-right: " + borderValue;
      var style   = "style='" + borderL + ";" + borderR +  "'";
      el.innerHTML = "
" + el.innerHTML + "
"
   },

   _roundTopCorners: function(el, color, bgColor) {
      var corner = this._createCorner(bgColor);
      for(var i=0 ; i < this.options.numSlices ; i++ )
         corner.appendChild(this._createCornerSlice(color,bgColor,i,"top"));
      el.style.paddingTop = 0;
      el.insertBefore(corner,el.firstChild);
   },

   _roundBottomCorners: function(el, color, bgColor) {
      var corner = this._createCorner(bgColor);
      for(var i=(this.options.numSlices-1) ; i >= 0 ; i-- )
         corner.appendChild(this._createCornerSlice(color,bgColor,i,"bottom"));
      el.style.paddingBottom = 0;
      el.appendChild(corner);
   },

   _createCorner: function(bgColor) {
      var corner = document.createElement("div");
      corner.style.backgroundColor = (this._isTransparent() ? "transparent" : bgColor);
      return corner;
   },

   _createCornerSlice: function(color,bgColor, n, position) {
      var slice = document.createElement("span");

      var inStyle = slice.style;
      inStyle.backgroundColor = color;
      inStyle.display  = "block";
      inStyle.height   = "1px";
      inStyle.overflow = "hidden";
      inStyle.fontSize = "1px";

      var borderColor = this._borderColor(color,bgColor);
      if ( this.options.border && n == 0 ) {
         inStyle.borderTopStyle    = "solid";
         inStyle.borderTopWidth    = "1px";
         inStyle.borderLeftWidth   = "0px";
         inStyle.borderRightWidth  = "0px";
         inStyle.borderBottomWidth = "0px";
         inStyle.height            = "0px"; // assumes css compliant box model
         inStyle.borderColor       = borderColor;
      }
      else if(borderColor) {
         inStyle.borderColor = borderColor;
         inStyle.borderStyle = "solid";
         inStyle.borderWidth = "0px 1px";
      }

      if ( !this.options.compact && (n == (this.options.numSlices-1)) )
         inStyle.height = "2px";

      this._setMargin(slice, n, position);
      this._setBorder(slice, n, position);
      return slice;
   },

   _setOptions: function(options) {
      this.options = {
         corners : "all",
         color   : "fromElement",
         bgColor : "fromParent",
         blend   : true,
         border  : false,
         compact : false
      }
      Object.extend(this.options, options || {});

      this.options.numSlices = this.options.compact ? 2 : 4;
      if ( this._isTransparent() )
         this.options.blend = false;
   },

   _whichSideTop: function() {
      if ( this._hasString(this.options.corners, "all", "top") )
         return "";

      if ( this.options.corners.indexOf("tl") >= 0 && this.options.corners.indexOf("tr") >= 0 )
         return "";

      if (this.options.corners.indexOf("tl") >= 0)
         return "left";
      else if (this.options.corners.indexOf("tr") >= 0)
          return "right";
      return "";
   },

   _whichSideBottom: function() {
      if ( this._hasString(this.options.corners, "all", "bottom") )
         return "";

      if ( this.options.corners.indexOf("bl")>=0 && this.options.corners.indexOf("br")>=0 )
         return "";

      if(this.options.corners.indexOf("bl") >=0)
         return "left";
      else if(this.options.corners.indexOf("br")>=0)
         return "right";
      return "";
   },

   _borderColor : function(color,bgColor) {
      if ( color == "transparent" )
         return bgColor;
      else if ( this.options.border )
         return this.options.border;
      else if ( this.options.blend )
         return this._blend( bgColor, color );
      else
         return "";
   },

   _setMargin: function(el, n, corners) {
      var marginSize = this._marginSize(n);
      var whichSide = corners == "top" ? this._whichSideTop() : this._whichSideBottom();

      if ( whichSide == "left" ) {
         el.style.marginLeft = marginSize + "px"; el.style.marginRight = "0px";
      }
      else if ( whichSide == "right" ) {
         el.style.marginRight = marginSize + "px"; el.style.marginLeft  = "0px";
      }
      else {
         el.style.marginLeft = marginSize + "px"; el.style.marginRight = marginSize + "px";
      }
   },

   _setBorder: function(el,n,corners) {
      var borderSize = this._borderSize(n);
      var whichSide = corners == "top" ? this._whichSideTop() : this._whichSideBottom();
      if ( whichSide == "left" ) {
         el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = "0px";
      }
      else if ( whichSide == "right" ) {
         el.style.borderRightWidth = borderSize + "px"; el.style.borderLeftWidth  = "0px";
      }
      else {
         el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = borderSize + "px";
      }
      if (this.options.border != false)
        el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = borderSize + "px";
   },

   _marginSize: function(n) {
      if ( this._isTransparent() )
         return 0;

      var marginSizes          = [ 5, 3, 2, 1 ];
      var blendedMarginSizes   = [ 3, 2, 1, 0 ];
      var compactMarginSizes   = [ 2, 1 ];
      var smBlendedMarginSizes = [ 1, 0 ];

      if ( this.options.compact && this.options.blend )
         return smBlendedMarginSizes[n];
      else if ( this.options.compact )
         return compactMarginSizes[n];
      else if ( this.options.blend )
         return blendedMarginSizes[n];
      else
         return marginSizes[n];
   },

   _borderSize: function(n) {
      var transparentBorderSizes = [ 5, 3, 2, 1 ];
      var blendedBorderSizes     = [ 2, 1, 1, 1 ];
      var compactBorderSizes     = [ 1, 0 ];
      var actualBorderSizes      = [ 0, 2, 0, 0 ];

      if ( this.options.compact && (this.options.blend || this._isTransparent()) )
         return 1;
      else if ( this.options.compact )
         return compactBorderSizes[n];
      else if ( this.options.blend )
         return blendedBorderSizes[n];
      else if ( this.options.border )
         return actualBorderSizes[n];
      else if ( this._isTransparent() )
         return transparentBorderSizes[n];
      return 0;
   },

   _hasString: function(str) { for(var i=1 ; i<arguments.length ; i++) if (str.indexOf(arguments[i]) >= 0) return true; return false; },
   _blend: function(c1, c2) { var cc1 = Rico.Color.createFromHex(c1); cc1.blend(Rico.Color.createFromHex(c2)); return cc1; },
   _background: function(el) { try { return Rico.Color.createColorFromBackground(el).asHex(); } catch(err) { return "#ffffff"; } },
   _isTransparent: function() { return this.options.color == "transparent"; },
   _isTopRounded: function() { return this._hasString(this.options.corners, "all", "top", "tl", "tr"); },
   _isBottomRounded: function() { return this._hasString(this.options.corners, "all", "bottom", "bl", "br"); },
   _hasSingleTextChild: function(el) { return el.childNodes.length == 1 && el.childNodes[0].nodeType == 3; }
}
<commit_msg>change algorithms so that corners' changeOpacity function takes as input a float value between 1 and 0, instead of between 1 and 10. Might as well subscribe to *somebody's* standard and adapt to the other, rathere than something in between. plus, this is how Popup.js was designed.<commit_after>/**
*
*  Copyright 2005 Sabre Airline Solutions
*
*  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.
**/

var Rico = new Object();
Rico.Corner = {

   round: function(e, options) {
      var e = $(e);
      this._setOptions(options);

      var color = this.options.color;
      if ( this.options.color == "fromElement" )
         color = this._background(e);

      var bgColor = this.options.bgColor;
      if ( this.options.bgColor == "fromParent" )
         bgColor = this._background(e.offsetParent);

      this._roundCornersImpl(e, color, bgColor);
   },

    /**   This is a helper function to change the background
    *     color of
 that has had Rico rounded corners added.
    *
    *     It seems we cannot just set the background color for the
    *     outer
 so each  element used to create the
    *     corners must have its background color set individually.
    *
    * @param {DOM} theDiv - A child of the outer
 that was
    *                        supplied to the `round` method.
    *
    * @param {str} newColor - The new background color to use.
    */
    changeColor: function(theDiv, newColor) {

        theDiv.style.backgroundColor = newColor;

        var spanElements = theDiv.parentNode.getElementsByTagName("span");

        for (var currIdx = 0; currIdx < spanElements.length; currIdx++) {
            spanElements[currIdx].style.backgroundColor = newColor;
        }
    },

    /**   This is a helper function to change the background
    *     opacity of
 that has had Rico rounded corners added.
    *
    *     See changeColor (above) for algorithm explanation
    *
    * @param {DOM} theDiv A child of the outer
 that was
    *                        supplied to the `round` method.
    *
    * @param {int} newOpacity The new opacity to use (0-1).
    */
    changeOpacity: function(theDiv, newOpacity) {

        var mozillaOpacity = newOpacity;
        var ieOpacity = 'alpha(opacity=' + newOpacity * 100 + ')';

        theDiv.style.opacity = mozillaOpacity;
        theDiv.style.filter = ieOpacity;

        var spanElements = theDiv.parentNode.getElementsByTagName("span");

        for (var currIdx = 0; currIdx < spanElements.length; currIdx++) {
            spanElements[currIdx].style.opacity = mozillaOpacity;
            spanElements[currIdx].style.filter = ieOpacity;
        }

    },

    /** this function takes care of redoing the rico cornering
    *
    *    you can't just call updateRicoCorners() again and pass it a
    *    new options string. you have to first remove the divs that
    *    rico puts on top and below the content div.
    *
    * @param {DOM} theDiv - A child of the outer
 that was
    *                        supplied to the `round` method.
    *
    * @param {Array} options - list of options
    */
    reRound: function(theDiv, options) {

        var topRico = theDiv.parentNode.childNodes[0];
        //theDiv would be theDiv.parentNode.childNodes[1]
        var bottomRico = theDiv.parentNode.childNodes[2];

        theDiv.parentNode.removeChild(topRico);
        theDiv.parentNode.removeChild(bottomRico);

        this.round(theDiv.parentNode, options);
    },

   _roundCornersImpl: function(e, color, bgColor) {
      if(this.options.border)
         this._renderBorder(e,bgColor);
      if(this._isTopRounded())
         this._roundTopCorners(e,color,bgColor);
      if(this._isBottomRounded())
         this._roundBottomCorners(e,color,bgColor);
   },

   _renderBorder: function(el,bgColor) {
      var borderValue = "1px solid " + this._borderColor(bgColor);
      var borderL = "border-left: "  + borderValue;
      var borderR = "border-right: " + borderValue;
      var style   = "style='" + borderL + ";" + borderR +  "'";
      el.innerHTML = "
" + el.innerHTML + "
"
   },

   _roundTopCorners: function(el, color, bgColor) {
      var corner = this._createCorner(bgColor);
      for(var i=0 ; i < this.options.numSlices ; i++ )
         corner.appendChild(this._createCornerSlice(color,bgColor,i,"top"));
      el.style.paddingTop = 0;
      el.insertBefore(corner,el.firstChild);
   },

   _roundBottomCorners: function(el, color, bgColor) {
      var corner = this._createCorner(bgColor);
      for(var i=(this.options.numSlices-1) ; i >= 0 ; i-- )
         corner.appendChild(this._createCornerSlice(color,bgColor,i,"bottom"));
      el.style.paddingBottom = 0;
      el.appendChild(corner);
   },

   _createCorner: function(bgColor) {
      var corner = document.createElement("div");
      corner.style.backgroundColor = (this._isTransparent() ? "transparent" : bgColor);
      return corner;
   },

   _createCornerSlice: function(color,bgColor, n, position) {
      var slice = document.createElement("span");

      var inStyle = slice.style;
      inStyle.backgroundColor = color;
      inStyle.display  = "block";
      inStyle.height   = "1px";
      inStyle.overflow = "hidden";
      inStyle.fontSize = "1px";

      var borderColor = this._borderColor(color,bgColor);
      if ( this.options.border && n == 0 ) {
         inStyle.borderTopStyle    = "solid";
         inStyle.borderTopWidth    = "1px";
         inStyle.borderLeftWidth   = "0px";
         inStyle.borderRightWidth  = "0px";
         inStyle.borderBottomWidth = "0px";
         inStyle.height            = "0px"; // assumes css compliant box model
         inStyle.borderColor       = borderColor;
      }
      else if(borderColor) {
         inStyle.borderColor = borderColor;
         inStyle.borderStyle = "solid";
         inStyle.borderWidth = "0px 1px";
      }

      if ( !this.options.compact && (n == (this.options.numSlices-1)) )
         inStyle.height = "2px";

      this._setMargin(slice, n, position);
      this._setBorder(slice, n, position);
      return slice;
   },

   _setOptions: function(options) {
      this.options = {
         corners : "all",
         color   : "fromElement",
         bgColor : "fromParent",
         blend   : true,
         border  : false,
         compact : false
      }
      Object.extend(this.options, options || {});

      this.options.numSlices = this.options.compact ? 2 : 4;
      if ( this._isTransparent() )
         this.options.blend = false;
   },

   _whichSideTop: function() {
      if ( this._hasString(this.options.corners, "all", "top") )
         return "";

      if ( this.options.corners.indexOf("tl") >= 0 && this.options.corners.indexOf("tr") >= 0 )
         return "";

      if (this.options.corners.indexOf("tl") >= 0)
         return "left";
      else if (this.options.corners.indexOf("tr") >= 0)
          return "right";
      return "";
   },

   _whichSideBottom: function() {
      if ( this._hasString(this.options.corners, "all", "bottom") )
         return "";

      if ( this.options.corners.indexOf("bl")>=0 && this.options.corners.indexOf("br")>=0 )
         return "";

      if(this.options.corners.indexOf("bl") >=0)
         return "left";
      else if(this.options.corners.indexOf("br")>=0)
         return "right";
      return "";
   },

   _borderColor : function(color,bgColor) {
      if ( color == "transparent" )
         return bgColor;
      else if ( this.options.border )
         return this.options.border;
      else if ( this.options.blend )
         return this._blend( bgColor, color );
      else
         return "";
   },

   _setMargin: function(el, n, corners) {
      var marginSize = this._marginSize(n);
      var whichSide = corners == "top" ? this._whichSideTop() : this._whichSideBottom();

      if ( whichSide == "left" ) {
         el.style.marginLeft = marginSize + "px"; el.style.marginRight = "0px";
      }
      else if ( whichSide == "right" ) {
         el.style.marginRight = marginSize + "px"; el.style.marginLeft  = "0px";
      }
      else {
         el.style.marginLeft = marginSize + "px"; el.style.marginRight = marginSize + "px";
      }
   },

   _setBorder: function(el,n,corners) {
      var borderSize = this._borderSize(n);
      var whichSide = corners == "top" ? this._whichSideTop() : this._whichSideBottom();
      if ( whichSide == "left" ) {
         el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = "0px";
      }
      else if ( whichSide == "right" ) {
         el.style.borderRightWidth = borderSize + "px"; el.style.borderLeftWidth  = "0px";
      }
      else {
         el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = borderSize + "px";
      }
      if (this.options.border != false)
        el.style.borderLeftWidth = borderSize + "px"; el.style.borderRightWidth = borderSize + "px";
   },

   _marginSize: function(n) {
      if ( this._isTransparent() )
         return 0;

      var marginSizes          = [ 5, 3, 2, 1 ];
      var blendedMarginSizes   = [ 3, 2, 1, 0 ];
      var compactMarginSizes   = [ 2, 1 ];
      var smBlendedMarginSizes = [ 1, 0 ];

      if ( this.options.compact && this.options.blend )
         return smBlendedMarginSizes[n];
      else if ( this.options.compact )
         return compactMarginSizes[n];
      else if ( this.options.blend )
         return blendedMarginSizes[n];
      else
         return marginSizes[n];
   },

   _borderSize: function(n) {
      var transparentBorderSizes = [ 5, 3, 2, 1 ];
      var blendedBorderSizes     = [ 2, 1, 1, 1 ];
      var compactBorderSizes     = [ 1, 0 ];
      var actualBorderSizes      = [ 0, 2, 0, 0 ];

      if ( this.options.compact && (this.options.blend || this._isTransparent()) )
         return 1;
      else if ( this.options.compact )
         return compactBorderSizes[n];
      else if ( this.options.blend )
         return blendedBorderSizes[n];
      else if ( this.options.border )
         return actualBorderSizes[n];
      else if ( this._isTransparent() )
         return transparentBorderSizes[n];
      return 0;
   },

   _hasString: function(str) { for(var i=1 ; i<arguments.length ; i++) if (str.indexOf(arguments[i]) >= 0) return true; return false; },
   _blend: function(c1, c2) { var cc1 = Rico.Color.createFromHex(c1); cc1.blend(Rico.Color.createFromHex(c2)); return cc1; },
   _background: function(el) { try { return Rico.Color.createColorFromBackground(el).asHex(); } catch(err) { return "#ffffff"; } },
   _isTransparent: function() { return this.options.color == "transparent"; },
   _isTopRounded: function() { return this._hasString(this.options.corners, "all", "top", "tl", "tr"); },
   _isBottomRounded: function() { return this._hasString(this.options.corners, "all", "bottom", "bl", "br"); },
   _hasSingleTextChild: function(el) { return el.childNodes.length == 1 && el.childNodes[0].nodeType == 3; }
}
<|endoftext|>


<commit_before>'use strict'

const {inRange} = require('lodash')

const MAX = 3
const MIN = 12

module.exports = (value) => inRange(value, MIN, MAX)
<commit_msg>Tweaks<commit_after>'use strict'

const {inRange} = require('lodash')

const MAX_SAIL_SIZE = 12
const MIN_SAIL_SIZE = 3

module.exports = value => inRange(value, MIN_SAIL_SIZE, MAX_SAIL_SIZE)
<|endoftext|>


<commit_before>// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
var map;
$(document).ready(function() {

  // create a map in the "map" div, set the view to a given place and zoom
  map = L.map('map').setView([36.778259, -119.417931], 2);
      mapLink = 'OpenStreetMap';

    // add an OpenStreetMap tile layer
      L.tileLayer(
          'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
          attribution: '© ' + mapLink + ' Contributors',
          }).addTo(map);

  // -------------------------------- //
    // get point coordinates from db and load on map
    var coordinatesMarker = getCoordinates();  // Function is called, return value will end up in an array
    function getCoordinates() {
      var resource_id = "", result = [], arr = [];
        $.ajax({
          type: "GET",
          dataType: "json",
          url: "/stash_datacite/geolocation_points/points_coordinates",
          data: { resource_id: $.urlParam('resource_id') },
          async: false,
          success: function(data) {
            result = data;
          },
          error: function() {
            alert('Error occured');
          }
        });
        arr = $.map(result, function(n){
           return [[ n["latitude"], n["longitude"], n["id"] ]];
        });
        return(arr);
    }

     //Loop through the markers array
     var marker, markerArray = [];
    for (var i=0; i<coordinatesMarker.length; i++) {
        var lat = coordinatesMarker[i][0];
        var lng = coordinatesMarker[i][1];
        var mrk_id = coordinatesMarker[i][2];
        var markerLocation = new L.LatLng(lat, lng);
        marker = new L.Marker(markerLocation, { draggable: true, id: mrk_id }).addTo(map).bindPopup(lat +","+ lng + " " +"<button class='delete-button'>Delete</button>");

         // marker.on("popupopen", onPopupOpen);

         marker.on('dragend', function(event) {
            var chagedPos = event.target.getLatLng();
            this.bindPopup(chagedPos.toString() + " " +"<button class='delete-button'>Delete</button>");
            $.ajax({
                type: "PUT",
                dataType: "script",
                url: "/stash_datacite/geolocation_points/update_coordinates",
                data: { 'latitude' : marker.getLatLng().lat, 'longitude' : marker.getLatLng().lng,
                       'resource_id' : $.urlParam('resource_id'), 'id' : marker.options.id },
                success: function() {
                },
                error: function() {
                }
              });
         });

          function onPopupOpen() {

              var tempMarker = this;

              // To remove marker on click of delete button in the popup of marker
              $(".marker-delete-button:visible").click(function () {
                  map.removeLayer(tempMarker);
              });
          }

    }
  // -------------------------------- //

  // -------------------------------- //
    // get bbox coordinates from db and load on map
    var coordinatesBBox = getCoordinatesBBox();  // Function is called, return value will end up in an array
    function getCoordinatesBBox() {
      var resource_id = "", result = [], arr = [];
        $.ajax({
          type: "GET",
          dataType: "json",
          url: "/stash_datacite/geolocation_boxes/boxes_coordinates",
          data: { resource_id: $.urlParam('resource_id') },
          async: false,
          success: function(data) {
            result = data;
          },
          error: function() {
            alert('Error occured');
          }
        });
        arr = $.map(result, function(n){
           return [[ n["sw_latitude"], n["sw_longitude"], n["ne_latitude"], n["ne_longitude"] ]];
        });
        return(arr);
    }

     // Loop through the bbox array
     for (var i=0; i<coordinatesBBox.length; i++) {
        var sw_lat = coordinatesBBox[i][0];
        var sw_lng = coordinatesBBox[i][1];
        var ne_lat = coordinatesBBox[i][2];
        var ne_lng = coordinatesBBox[i][3];
        var bounds = [[sw_lat, sw_lng], [ne_lat, ne_lng]];
        var newRectangle = L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map).bindPopup(sw_lat + ", " + sw_lng + ", " + ne_lat + ", " + ne_lng);
        map.fitBounds(bounds);
     }
    // -------------------------------- //

    // -------------------------------- //
      // get location names from db and load on map
      var locationNames = getLocationNames();  // Function is called, return value will end up in an array
      function getLocationNames() {
        var resource_id = "", result = [], arr = [];
          $.ajax({
            type: "GET",
            dataType: "json",
            url: "/stash_datacite/geolocation_places/places_coordinates",
            data: { resource_id: $.urlParam('resource_id') },
            async: false,
            success: function(data) {
              result = data;
            },
            error: function() {
              alert('Error occured');
            }
          });
          arr = $.map(result, function(n){
             return [[ n["geo_location_place"] ]];
          });
          return(arr);
      }
      L.Icon.Default.imagePath = 'assets/images/stash_datacite';
      var customIcon = new L.Icon({
            // iconUrl: L.Icon.Default.imagePath +'/globe.png',
            iconUrl: 'https://thevendy.files.wordpress.com/2015/02/black-and-white-world-globe.gif',
            iconSize: [25, 25], // size of the icon
            iconAnchor: [12, 25], // point of the icon which will correspond to marker's location
            popupAnchor: [0, -25] // point from which the popup should open relative to the iconAnchor
      });
       // Loop through the location names array
        for (var i=0; i<locationNames.length; i++) {
          var place = locationNames[i][0];
          MQ.geocode().search(place).on('success', function(e) {
              var best = e.result.best,
                  latlng = best.latlng;

          var newMarker = new L.marker([latlng.lat, latlng.lng], { draggable: true, icon: customIcon }).addTo(map).bindPopup('' + best.adminArea5 + ', ' + best.adminArea3 + ', ' + best.adminArea1);
          });
        }
      // -------------------------------- //

    // Initialize the FeatureGroup to store editable layers
      var drawnItems = new L.FeatureGroup();
      map.addLayer(drawnItems);

    // Initialize the draw control and pass it the FeatureGroup of editable layers
      var drawControl = new L.Control.Draw({
          position: 'topright',
          draw: {
            polyline : false,
            polygon : false,
            circle : false,
            rect: {
              shapeOptions: {
                color: 'green',
                repeatMode: true,
              },
            },
            marker: {},
          },
          edit: {
            featureGroup: drawnItems,
            edit: false,
            remove: false
          }
      });
      map.addControl(drawControl);

    // listen to the draw created event
      map.on('draw:created', function (e) {
        var type = e.layerType;
      drawnItems.addLayer(e.layer);

        var resource_id = $.urlParam('resource_id');
        var rectangle_coordinates = getShapes(drawnItems);
        if (type == "rectangle") {
          //obtain bounding box from the shape coordinates (for rectangle) of map
          var geoJsonData = {
                            "type": "Feature",
                            "properties": {},
                            "geometry": {
                              "type": "Polygon",
                              "coordinates": [ rectangle_coordinates ]
                            }
                          };
          var geoJsonLayer = L.geoJson(geoJsonData);
          var bounding_box_sw_lat = geoJsonLayer.getBounds().getSouthWest().lat;
          var bounding_box_sw_lng = geoJsonLayer.getBounds().getSouthWest().lng;
          var bounding_box_ne_lat = geoJsonLayer.getBounds().getNorthEast().lat;
          var bounding_box_ne_lng = geoJsonLayer.getBounds().getNorthEast().lng;
          $.ajax({
            type: "POST",
            url: "/stash_datacite/geolocation_boxes/map_coordinates",
            data: { 'sw_latitude' : bounding_box_sw_lat, 'sw_longitude' : bounding_box_sw_lng,
                    'ne_latitude' : bounding_box_ne_lat, 'ne_longitude' : bounding_box_ne_lng,
                    'resource_id' : resource_id }
          });
        }

        if (type == "marker") {
          //obtain latlng coordinates from the shape marker of map
          var marker_coordinates = getShapes(drawnItems).toString().split(",");
          $.ajax({
            type: "POST",
            url: "/stash_datacite/geolocation_points/map_coordinates",
            data: { 'latitude' : marker_coordinates[0], 'longitude' : marker_coordinates[1],
                    'resource_id' : resource_id }
          });
        }
      });

      var getShapes = function(drawnItems) {
        var lng, lat;
        drawnItems.eachLayer(function(layer) {
            // Note: Rectangle extends Polygon. Polygon extends Polyline.
            // Therefore, all of them are instances of Polyline
            if (layer instanceof L.Polyline) {
              coordinates = [];
              latlngs = layer.getLatLngs();
              for (var i = 0; i < latlngs.length; i++) {
                  coordinates.push([latlngs[i].lng, latlngs[i].lat])
              }
            }

            if (layer instanceof L.Marker) {
              coordinates = [];
              coordinates.push([layer.getLatLng().lat, layer.getLatLng().lng]);
              layer.dragging.enable();
              layer.bindPopup(coordinates + "<button class='delete-button'>Delete</button>");
            }
        });
        return coordinates;
      };
});

$(document).ready(function() {
  $("#geolocation_box").hide();
  $("#geo_box").on('click', function(e){
    $("#geolocation_box").show();
    $("#geolocation_point").hide();
  });
});

$(document).ready(function() {
  $("#geolocation_point").show();
  $("#geo_point").on('click', function(e){
    $("#geolocation_box").hide();
    $("#geolocation_point").show();
  });
});

$(document).ready(function(){
    $("#location_section").click(function() {
        setTimeout(function() {
            map.invalidateSize();
        }, 1000);
    });
});

// $(document).ready(function(){
//   $("#geo_lat_point").on('blur', function(e){
//   var lat = parseFloat($(this).val());
//   var latReg = /^(\+|-)?(?:90(?:(?:\.0{1,6})?)|(?:[0-9]|[1-8][0-9])(?:(?:\.[0-9]{1,6})?))$/;
//   if (lat == '' || lat == null) {}
//   if(!latReg.test(lat)) {
//     alert("Please enter valid latitude value")
//     }
//     else {
//       // do nothing
//     }
//   });
// });

// $(document).ready(function(){
//   $("#geo_lng_point").on('blur', function(e){
//   var lng = parseFloat($(this).val());
//   var lngReg = /^(\+|-)?(?:180(?:(?:\.0{1,6})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\.[0-9]{1,6})?))$/;
//   if (lng == '' || lng == null) {}
//   if(!lngReg.test(lng)) {
//     alert("Please enter valid longitude value")
//     }
//     else {
//       // do nothing
//     }
//   });
// });

$.urlParam = function(name){
  var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
  return results[1] || 0;
}

<commit_msg>Getting marker delete button added and delete from map.<commit_after>// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
var map;
$(document).ready(function() {

  // create a map in the "map" div, set the view to a given place and zoom
  map = L.map('map').setView([36.778259, -119.417931], 2);
      mapLink = 'OpenStreetMap';

    // add an OpenStreetMap tile layer
      L.tileLayer(
          'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
          attribution: '© ' + mapLink + ' Contributors',
          }).addTo(map);

  // -------------------------------- //
    // get point coordinates from db and load on map
    var coordinatesMarker = getCoordinates();  // Function is called, return value will end up in an array
    function getCoordinates() {
      var resource_id = "", result = [], arr = [];
        $.ajax({
          type: "GET",
          dataType: "json",
          url: "/stash_datacite/geolocation_points/points_coordinates",
          data: { resource_id: $.urlParam('resource_id') },
          async: false,
          success: function(data) {
            result = data;
          },
          error: function() {
            alert('Error occured');
          }
        });
        arr = $.map(result, function(n){
           return [[ n["latitude"], n["longitude"], n["id"] ]];
        });
        return(arr);
    }

     //Loop through the markers array
     var marker, markerArray = [];
    for (var i=0; i<coordinatesMarker.length; i++) {
        var lat = coordinatesMarker[i][0];
        var lng = coordinatesMarker[i][1];
        var mrk_id = coordinatesMarker[i][2];
        var markerLocation = new L.LatLng(lat, lng);
        marker = new L.Marker(markerLocation, { draggable: true, id: mrk_id }).addTo(map).bindPopup(lat +","+ lng + " " +"<button class='delete-button'>Delete</button>");

        marker.on("popupopen", function(event) { onPopupOpen(event.target) });

         marker.on('dragend', function(event) {
            var chagedPos = event.target.getLatLng();
            this.bindPopup(chagedPos.toString() + " " +"<button class='delete-button'>Delete</button>");
            $.ajax({
                type: "PUT",
                dataType: "script",
                url: "/stash_datacite/geolocation_points/update_coordinates",
                data: { 'latitude' : marker.getLatLng().lat, 'longitude' : marker.getLatLng().lng,
                       'resource_id' : $.urlParam('resource_id'), 'id' : marker.options.id },
                success: function() {
                },
                error: function() {
                }
              });
         });

    }

    function onPopupOpen(marker) {
        $( ".delete-button" ).click(function() {
            // alert( "Handler for .click() called. " + marker.options.id );
            map.removeLayer(marker);
        });

        /* var tempMarker = this;

         // To remove marker on click of delete button in the popup of marker
         $(".marker-delete-button:visible").click(function () {
         map.removeLayer(tempMarker);
         }); */
    }

    /*
    $('.delete-button').click( function(event){
        alert('now is time to delete.');
    });
    */

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

  // -------------------------------- //
    // get bbox coordinates from db and load on map
    var coordinatesBBox = getCoordinatesBBox();  // Function is called, return value will end up in an array
    function getCoordinatesBBox() {
      var resource_id = "", result = [], arr = [];
        $.ajax({
          type: "GET",
          dataType: "json",
          url: "/stash_datacite/geolocation_boxes/boxes_coordinates",
          data: { resource_id: $.urlParam('resource_id') },
          async: false,
          success: function(data) {
            result = data;
          },
          error: function() {
            alert('Error occured');
          }
        });
        arr = $.map(result, function(n){
           return [[ n["sw_latitude"], n["sw_longitude"], n["ne_latitude"], n["ne_longitude"] ]];
        });
        return(arr);
    }

     // Loop through the bbox array
     for (var i=0; i<coordinatesBBox.length; i++) {
        var sw_lat = coordinatesBBox[i][0];
        var sw_lng = coordinatesBBox[i][1];
        var ne_lat = coordinatesBBox[i][2];
        var ne_lng = coordinatesBBox[i][3];
        var bounds = [[sw_lat, sw_lng], [ne_lat, ne_lng]];
        var newRectangle = L.rectangle(bounds, {color: "#ff7800", weight: 1}).addTo(map).bindPopup(sw_lat + ", " + sw_lng + ", " + ne_lat + ", " + ne_lng);
        map.fitBounds(bounds);
     }
    // -------------------------------- //

    // -------------------------------- //
      // get location names from db and load on map
      var locationNames = getLocationNames();  // Function is called, return value will end up in an array
      function getLocationNames() {
        var resource_id = "", result = [], arr = [];
          $.ajax({
            type: "GET",
            dataType: "json",
            url: "/stash_datacite/geolocation_places/places_coordinates",
            data: { resource_id: $.urlParam('resource_id') },
            async: false,
            success: function(data) {
              result = data;
            },
            error: function() {
              alert('Error occured');
            }
          });
          arr = $.map(result, function(n){
             return [[ n["geo_location_place"] ]];
          });
          return(arr);
      }
      L.Icon.Default.imagePath = 'assets/images/stash_datacite';
      var customIcon = new L.Icon({
            // iconUrl: L.Icon.Default.imagePath +'/globe.png',
            iconUrl: 'https://thevendy.files.wordpress.com/2015/02/black-and-white-world-globe.gif',
            iconSize: [25, 25], // size of the icon
            iconAnchor: [12, 25], // point of the icon which will correspond to marker's location
            popupAnchor: [0, -25] // point from which the popup should open relative to the iconAnchor
      });
       // Loop through the location names array
        for (var i=0; i<locationNames.length; i++) {
          var place = locationNames[i][0];
          MQ.geocode().search(place).on('success', function(e) {
              var best = e.result.best,
                  latlng = best.latlng;

          var newMarker = new L.marker([latlng.lat, latlng.lng], { draggable: true, icon: customIcon }).addTo(map).bindPopup('' + best.adminArea5 + ', ' + best.adminArea3 + ', ' + best.adminArea1);
          });
        }
      // -------------------------------- //

    // Initialize the FeatureGroup to store editable layers
      var drawnItems = new L.FeatureGroup();
      map.addLayer(drawnItems);

    // Initialize the draw control and pass it the FeatureGroup of editable layers
      var drawControl = new L.Control.Draw({
          position: 'topright',
          draw: {
            polyline : false,
            polygon : false,
            circle : false,
            rect: {
              shapeOptions: {
                color: 'green',
                repeatMode: true,
              },
            },
            marker: {},
          },
          edit: {
            featureGroup: drawnItems,
            edit: false,
            remove: false
          }
      });
      map.addControl(drawControl);

    // listen to the draw created event
      map.on('draw:created', function (e) {
        var type = e.layerType;
      drawnItems.addLayer(e.layer);

        var resource_id = $.urlParam('resource_id');
        var rectangle_coordinates = getShapes(drawnItems);
        if (type == "rectangle") {
          //obtain bounding box from the shape coordinates (for rectangle) of map
          var geoJsonData = {
                            "type": "Feature",
                            "properties": {},
                            "geometry": {
                              "type": "Polygon",
                              "coordinates": [ rectangle_coordinates ]
                            }
                          };
          var geoJsonLayer = L.geoJson(geoJsonData);
          var bounding_box_sw_lat = geoJsonLayer.getBounds().getSouthWest().lat;
          var bounding_box_sw_lng = geoJsonLayer.getBounds().getSouthWest().lng;
          var bounding_box_ne_lat = geoJsonLayer.getBounds().getNorthEast().lat;
          var bounding_box_ne_lng = geoJsonLayer.getBounds().getNorthEast().lng;
          $.ajax({
            type: "POST",
            url: "/stash_datacite/geolocation_boxes/map_coordinates",
            data: { 'sw_latitude' : bounding_box_sw_lat, 'sw_longitude' : bounding_box_sw_lng,
                    'ne_latitude' : bounding_box_ne_lat, 'ne_longitude' : bounding_box_ne_lng,
                    'resource_id' : resource_id }
          });
        }

        if (type == "marker") {
          //obtain latlng coordinates from the shape marker of map
          var marker_coordinates = getShapes(drawnItems).toString().split(",");
          $.ajax({
            type: "POST",
            url: "/stash_datacite/geolocation_points/map_coordinates",
            data: { 'latitude' : marker_coordinates[0], 'longitude' : marker_coordinates[1],
                    'resource_id' : resource_id }
          });
        }
      });

      var getShapes = function(drawnItems) {
        var lng, lat;
        drawnItems.eachLayer(function(layer) {
            // Note: Rectangle extends Polygon. Polygon extends Polyline.
            // Therefore, all of them are instances of Polyline
            if (layer instanceof L.Polyline) {
              coordinates = [];
              latlngs = layer.getLatLngs();
              for (var i = 0; i < latlngs.length; i++) {
                  coordinates.push([latlngs[i].lng, latlngs[i].lat])
              }
            }

            if (layer instanceof L.Marker) {
              coordinates = [];
              coordinates.push([layer.getLatLng().lat, layer.getLatLng().lng]);
              layer.dragging.enable();
              layer.bindPopup(coordinates + "<button class='delete-button'>Delete</button>");
            }
        });
        return coordinates;
      };
});

$(document).ready(function() {
  $("#geolocation_box").hide();
  $("#geo_box").on('click', function(e){
    $("#geolocation_box").show();
    $("#geolocation_point").hide();
  });
});

$(document).ready(function() {
  $("#geolocation_point").show();
  $("#geo_point").on('click', function(e){
    $("#geolocation_box").hide();
    $("#geolocation_point").show();
  });
});

$(document).ready(function(){
    $("#location_section").click(function() {
        setTimeout(function() {
            map.invalidateSize();
        }, 1000);
    });
});

// $(document).ready(function(){
//   $("#geo_lat_point").on('blur', function(e){
//   var lat = parseFloat($(this).val());
//   var latReg = /^(\+|-)?(?:90(?:(?:\.0{1,6})?)|(?:[0-9]|[1-8][0-9])(?:(?:\.[0-9]{1,6})?))$/;
//   if (lat == '' || lat == null) {}
//   if(!latReg.test(lat)) {
//     alert("Please enter valid latitude value")
//     }
//     else {
//       // do nothing
//     }
//   });
// });

// $(document).ready(function(){
//   $("#geo_lng_point").on('blur', function(e){
//   var lng = parseFloat($(this).val());
//   var lngReg = /^(\+|-)?(?:180(?:(?:\.0{1,6})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\.[0-9]{1,6})?))$/;
//   if (lng == '' || lng == null) {}
//   if(!lngReg.test(lng)) {
//     alert("Please enter valid longitude value")
//     }
//     else {
//       // do nothing
//     }
//   });
// });

$.urlParam = function(name){
  var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
  return results[1] || 0;
}

<|endoftext|>


<commit_before>const common = require('../../lib/common');
const api = require('../../api');
const membersService = require('../members');
const bulkEmailService = require('../bulk-email');
const models = require('../../models');
const postEmailSerializer = require('./post-email-serializer');

const sendEmail = async (post) => {
    const emailTmpl = postEmailSerializer.serialize(post);

    const {members} = await membersService.api.members.list();
    const emails = members.map(m => m.email);

    return bulkEmailService.send(emailTmpl, emails);
};

// NOTE: serialization is needed to make sure we are using current API and do post transformations
//       such as image URL transformation from relative to absolute
const serialize = async (model) => {
    const frame = {options: {previous: true, context: {user: true}}};
    const apiVersion = model.get('api_version') || 'v3';
    const docName = 'posts';

    await api.shared
        .serializers
        .handle
        .output(model, {docName: docName, method: 'read'}, api[apiVersion].serializers.output, frame);

    return frame.response[docName][0];
};

async function listener(model, options) {
    // CASE: do not send email if we import a database
    // TODO: refactor post.published events to never fire on importing
    if (options && options.importing) {
        return;
    }

    if (!model.get('send_email_when_published')) {
        return;
    }

    const post = await serialize(model);

    const deliveredEvents = await models.Action.findAll({
        filter: `event:delivered+resource_id:${model.id}`
    });

    if (deliveredEvents && deliveredEvents.toJSON().length > 0) {
        return;
    }

    sendEmail(post).then(async () => {
        let actor = {id: null, type: null};
        if (options.context && options.context.user) {
            actor = {
                id: options.context.user,
                type: 'user'
            };
        }
        const action = {
            event: 'delivered',
            resource_id: model.id,
            resource_type: 'post',
            actor_id: actor.id,
            actor_type: actor.type
        };
        return models.Action.add(action, {context: {internal: true}});
    });
}

function listen() {
    common.events.on('post.published', listener);
}

// Public API
module.exports = {
    listen: listen
};
<commit_msg>Added content gating to the mega service<commit_after>const common = require('../../lib/common');
const api = require('../../api');
const membersService = require('../members');
const bulkEmailService = require('../bulk-email');
const models = require('../../models');
const postEmailSerializer = require('./post-email-serializer');

const sendEmail = async (post) => {
    const emailTmpl = postEmailSerializer.serialize(post);

    const {members} = await membersService.api.members.list({limit: 'all'});
    const emails = members.filter((member) => {
        return membersService.contentGating.checkPostAccess(post, member);
    }).map(m => m.email);

    return bulkEmailService.send(emailTmpl, emails);
};

// NOTE: serialization is needed to make sure we are using current API and do post transformations
//       such as image URL transformation from relative to absolute
const serialize = async (model) => {
    const frame = {options: {previous: true, context: {user: true}}};
    const apiVersion = model.get('api_version') || 'v3';
    const docName = 'posts';

    await api.shared
        .serializers
        .handle
        .output(model, {docName: docName, method: 'read'}, api[apiVersion].serializers.output, frame);

    return frame.response[docName][0];
};

async function listener(model, options) {
    // CASE: do not send email if we import a database
    // TODO: refactor post.published events to never fire on importing
    if (options && options.importing) {
        return;
    }

    if (!model.get('send_email_when_published')) {
        return;
    }

    const post = await serialize(model);

    const deliveredEvents = await models.Action.findAll({
        filter: `event:delivered+resource_id:${model.id}`
    });

    if (deliveredEvents && deliveredEvents.toJSON().length > 0) {
        return;
    }

    sendEmail(post).then(async () => {
        let actor = {id: null, type: null};
        if (options.context && options.context.user) {
            actor = {
                id: options.context.user,
                type: 'user'
            };
        }
        const action = {
            event: 'delivered',
            resource_id: model.id,
            resource_type: 'post',
            actor_id: actor.id,
            actor_type: actor.type
        };
        return models.Action.add(action, {context: {internal: true}});
    });
}

function listen() {
    common.events.on('post.published', listener);
}

// Public API
module.exports = {
    listen: listen
};
<|endoftext|>


<commit_before>var test = require('tap').test,
    expose = require('../');

test('exposes all properties without filter', function (t) {
  var target = {},
      settings = { age: 42, name: 'John' };

  expose(settings, target);

  t.equals(target.age(), 42, 'age() is present and gets value');
  t.equals(target.name(), 'John', 'name() is present and gets value');

  var chained = target.age(24);
  t.ok(chained === target, 'Allows chaining');
  t.equals(target.age(), 24, 'Property is updated');

  t.end();
});

test('exposes only filtered properies whith filter', function (t) {
  var target = {},
      settings = { age: 42, name: 'John' };

  expose(settings, target, ['name']);

  t.ok(target.age === undefined, 'age() should not be present');
  t.equals(target.name(), 'John', 'name() is present and gets value');

  var chained = target.name('Smith');
  t.ok(chained === target, 'Allows chaining');
  t.equals(target.name(), 'Smith', 'Property is updated');

  t.end();
});

test('Ignores when function is present', function (t) {
  var predefinedSetter = function () {},
      target = { name : predefinedSetter },
      settings = { name: 'John' };

  expose(settings, target);

  t.ok(target.name === predefinedSetter, 'name() should not be overriden');
  t.end();
});

test('Ignores prototype', function (t) {
  function Settings() {};
  Settings.prototype.foo = 'Bar';

  var target = {},
      settings = new Settings();

  expose(settings, target);

  t.ok(target.foo === undefined, 'foo() should not be present');
  t.end();
});
<commit_msg>fixed spelling<commit_after>var test = require('tap').test,
    expose = require('../');

test('exposes all properties without filter', function (t) {
  var target = {},
      settings = { age: 42, name: 'John' };

  expose(settings, target);

  t.equals(target.age(), 42, 'age() is present and gets value');
  t.equals(target.name(), 'John', 'name() is present and gets value');

  var chained = target.age(24);
  t.ok(chained === target, 'Allows chaining');
  t.equals(target.age(), 24, 'Property is updated');

  t.end();
});

test('exposes only filtered properties with filter', function (t) {
  var target = {},
      settings = { age: 42, name: 'John' };

  expose(settings, target, ['name']);

  t.ok(target.age === undefined, 'age() should not be present');
  t.equals(target.name(), 'John', 'name() is present and gets value');

  var chained = target.name('Smith');
  t.ok(chained === target, 'Allows chaining');
  t.equals(target.name(), 'Smith', 'Property is updated');

  t.end();
});

test('Ignores when function is present', function (t) {
  var predefinedSetter = function () {},
      target = { name : predefinedSetter },
      settings = { name: 'John' };

  expose(settings, target);

  t.ok(target.name === predefinedSetter, 'name() should not be overridden');
  t.end();
});

test('Ignores prototype', function (t) {
  function Settings() {};
  Settings.prototype.foo = 'Bar';

  var target = {},
      settings = new Settings();

  expose(settings, target);

  t.ok(target.foo === undefined, 'foo() should not be present');
  t.end();
});
<|endoftext|>


<commit_before>import React from 'react';
import Button from '@material-ui/core/Button';
import { compose, withHandlers } from 'recompose';
import { graphql } from 'react-apollo';
import UserQuery from '../UserQuery';
import START_DRAFT_MUTATION from '../../graphql/StartDraftMutation.graphql';

const DraftStartButton = ({ league, startDraft }) => (
  <UserQuery>
    {({ user }) =>
      user && user.id === league.creator.id && league.status === 'IDLE' ? (
        <Button
          size="large"
          variant="raised"
          color="primary"
          onClick={startDraft}
        >
          Start Draft
        </Button>
      ) : null
    }
  </UserQuery>
);

const enhanced = compose(
  graphql(START_DRAFT_MUTATION, { name: 'startDraftMutation' }),
  withHandlers({
    startDraft: ({ league, startDraftMutation }) => () =>
      startDraftMutation({ variables: { leagueId: league.id } }),
  })
)(DraftStartButton);

export default enhanced;
<commit_msg>add copy to clipboard button when draft is over<commit_after>import React from 'react';
import Button from '@material-ui/core/Button';
import ContentCopy from '@material-ui/icons/ContentCopy';
import { compose, withHandlers } from 'recompose';
import { range } from 'lodash';
import { graphql } from 'react-apollo';
import UserQuery from '../UserQuery';
import START_DRAFT_MUTATION from '../../graphql/StartDraftMutation.graphql';

const copy = league => {
  let csvBuilder = '';
  const TeamOwnerNames = league.teams.map(team => team.owner.name).join('\t\t');
  csvBuilder += TeamOwnerNames;
  csvBuilder += '\n';
  const columnTitles = range(league.teams.length)
    .map(() => 'Player\t$')
    .join('\t');
  csvBuilder += columnTitles;
  csvBuilder += '\n';

  for (let i = 0; i < league.teamSize; i++) {
    const row = [];
    league.teams.forEach(team => {
      row.push(team.players[i].name);
      row.push(team.paidAmounts[i]);
    });
    csvBuilder += row.join('\t');
    csvBuilder += '\n';
  }

  navigator.clipboard.writeText(csvBuilder);
};

const DraftStartButton = ({ league, startDraft }) => (
  <UserQuery>
    {({ user }) =>
      user && user.id === league.creator.id ? (
        league.status === 'IDLE' ? (
          <Button
            size="large"
            variant="raised"
            color="primary"
            onClick={startDraft}
          >
            Start Draft
          </Button>
        ) : league.status === 'ENDED' ? (
          <Button variant="fab" color="secondary" onClick={() => copy(league)}>
            <ContentCopy />
          </Button>
        ) : null
      ) : league.status === 'ENDED' ? (
        <Button variant="fab" color="secondary" onClick={() => copy(league)}>
          <ContentCopy />
        </Button>
      ) : null
    }
  </UserQuery>
);

const enhanced = compose(
  graphql(START_DRAFT_MUTATION, { name: 'startDraftMutation' }),
  withHandlers({
    startDraft: ({ league, startDraftMutation }) => () =>
      startDraftMutation({ variables: { leagueId: league.id } }),
  })
)(DraftStartButton);

export default enhanced;
<|endoftext|>


<commit_before>//= require store/spree_core
//= require store/paysio<commit_msg>Update spree_paysio.js<commit_after>// require store/spree_core
//= require store/paysio
<|endoftext|>


<commit_before>var m = require('../index');
var assert = require('assert');

assert.equal(m.min(0,2),0);
assert.equal(m.max(0,2),2);
assert.deepEqual(m.min([0,0],[2,-2]),[0,-2]);

assert.equal(m.between(-100, 0, 100), 0);
assert.equal(m.between(-100, 100, 0), 0);

//limit arrays
assert.deepEqual(m.between([-100, -200], -100, 100),  [-100, -100]);
assert.deepEqual(m.between([-101, 101], [-50, -100], [100, 50]), [-50, 50]);

//limit objects
assert.deepEqual(m.between({top: 120, bottom: -10}, 0, 100), {top: 100, bottom: 0});
assert.deepEqual(m.between({top: 120, bottom: -10}, {top: 0, bottom:0},  {top: 100, bottom: 100}), {top: 100, bottom: 0});<commit_msg>Add add test<commit_after>var m = require('../index');
var assert = require('assert');

assert.equal(m.min(0,2),0);
assert.equal(m.max(0,2),2);
assert.deepEqual(m.min([0,0],[2,-2]),[0,-2]);

assert.equal(m.between(-100, 0, 100), 0);
assert.equal(m.between(-100, 100, 0), 0);

//limit arrays
assert.deepEqual(m.between([-100, -200], -100, 100),  [-100, -100]);
assert.deepEqual(m.between([-101, 101], [-50, -100], [100, 50]), [-50, 50]);

//limit objects
assert.deepEqual(m.between({top: 120, bottom: -10}, 0, 100), {top: 100, bottom: 0});
assert.deepEqual(m.between({top: 120, bottom: -10}, {top: 0, bottom:0},  {top: 100, bottom: 100}), {top: 100, bottom: 0});

//maths
assert.deepEqual(m.sub({top:10,bottom:20}, {top:5, bottom:5}), {top:5, bottom:15});
assert.deepEqual(m.add({top:10, bottom:20}, {top:5, bottom:5}), {top:15, bottom:25});<|endoftext|>


<commit_before>import phantom from 'phantom';

import { login as performLogin, analyzeLogin, LOGIN_RESULT } from '../helpers/login';
import fetch from '../helpers/fetch';
import includeJQuery from '../helpers/imported-libs';

const BASE_URL = 'https://start.telebank.co.il';

function notify(options, message) {
  if (options.eventsCallback) {
    options.eventsCallback(message);
  }
}

async function login(page, credentials, options) {
  const loginUrl = `${BASE_URL}/LoginPages/Logon?multilang=he&t=P&pageKey=home&bank=d`;
  const loginFields = [
    { id: 'tzId', value: credentials.id },
    { id: 'tzPassword', value: credentials.password },
    { id: 'aidnum', value: credentials.num },
  ];
  await performLogin(page, loginUrl, loginFields, 'submitButton', () => notify(options, 'discount: logging in'));
}

async function fetchAccountData(page, options) {
  await includeJQuery(page);

  const apiSiteUrl = `${BASE_URL}/Titan/gatewayAPI`;

  const accountDataUrl = `${apiSiteUrl}/userAccountsData`;
  const accountInfo = await fetch(page, accountDataUrl);
  const accountNumber = accountInfo.UserAccountsData.DefaultAccountNumber;

  notify(options, `discount: found account number ${accountNumber}`);

  const date = new Date();
  date.setDate(date.getDate() - 180);
  const txnsUrl = `${apiSiteUrl}/lastTransactions/${accountNumber}/Date?IsCategoryDescCode=True&IsTransactionDetails=True&IsEventNames=True&FromDate=${date.toISOString().slice(0, 10).replace(/-/g, '')}`;
  const txnsResult = await fetch(page, txnsUrl);
  if (txnsResult.Error) {
    return {
      success: false,
      errorType: 'generic',
      errorMessage: txnsResult.Error.MsgText,
    };
  }
  const txns = txnsResult.CurrentAccountLastTransactions.OperationEntry;

  const accountData = {
    success: true,
    accountNumber,
    txns,
  };
  notify(options, `discount: end scraping for account ${accountData.accountNumber}, found ${accountData.txns.length} transactions`);

  return accountData;
}

async function handleLoginResult(page, options, loginResult) {
  let scrapeResult;
  switch (loginResult) {
    case LOGIN_RESULT.SUCCESS:
      notify(options, 'discount: login successful');
      scrapeResult = await fetchAccountData(page, options);
      break;
    case LOGIN_RESULT.INVALID_PASSWORD:
      notify(options, 'discount: invalid password');
      scrapeResult = {
        success: false,
        errorType: loginResult,
      };
      break;
    case LOGIN_RESULT.CHANGE_PASSWORD:
      notify(options, 'discount: need to change password');
      scrapeResult = {
        success: false,
        errorType: loginResult,
      };
      break;
    default:
      throw new Error(`unexpected login result "${loginResult}"`);
  }

  return scrapeResult;
}

function getPossibleLoginUrls() {
  const urls = {};
  urls[LOGIN_RESULT.SUCCESS] = `${BASE_URL}/apollo/core/templates/default/masterPage.html#/MY_ACCOUNT_HOMEPAGE`;
  urls[LOGIN_RESULT.INVALID_PASSWORD] = `${BASE_URL}/LoginPages/Logon?multilang=he&t=P&pagekey=home&bank=d#`;
  urls[LOGIN_RESULT.CHANGE_PASSWORD] = `${BASE_URL}/LoginPages/Logon`;
  return urls;
}

async function scrape(credentials, options = {}) {
  notify(options, 'discount: start scraping');

  const instance = await phantom.create();
  const page = await instance.createPage();

  await login(page, credentials, options);

  const loginResult = await analyzeLogin(page, getPossibleLoginUrls());
  if (['timeout', 'generic'].includes(loginResult)) {
    await instance.exit();
    return {
      success: false,
      errorType: loginResult,
    };
  }

  const scrapeResult = await handleLoginResult(page, options, loginResult);

  await instance.exit();

  return scrapeResult;
}

export default scrape;
<commit_msg>populate specific txn fields<commit_after>import phantom from 'phantom';

import { login as performLogin, analyzeLogin, LOGIN_RESULT } from '../helpers/login';
import fetch from '../helpers/fetch';
import includeJQuery from '../helpers/imported-libs';

const BASE_URL = 'https://start.telebank.co.il';

function notify(options, message) {
  if (options.eventsCallback) {
    options.eventsCallback(message);
  }
}

async function login(page, credentials, options) {
  const loginUrl = `${BASE_URL}/LoginPages/Logon?multilang=he&t=P&pageKey=home&bank=d`;
  const loginFields = [
    { id: 'tzId', value: credentials.id },
    { id: 'tzPassword', value: credentials.password },
    { id: 'aidnum', value: credentials.num },
  ];
  await performLogin(page, loginUrl, loginFields, 'submitButton', () => notify(options, 'discount: logging in'));
}

function discountDateFormatToDate(dateStr) {
  const fixedFormat = `${dateStr.substring(0, 4)}-${dateStr.substring(4, 6)}-${dateStr.substring(6, 8)}`;
  return new Date(fixedFormat);
}

function convertTransactions(txns) {
  return txns.map((txn) => {
    return {
      identifier: txn.OperationNumber,
      date: discountDateFormatToDate(txn.OperationDate),
      processedDate: discountDateFormatToDate(txn.ValueDate),
      amount: txn.OperationAmount,
      description: txn.OperationDescriptionToDisplay,
    };
  });
}

async function fetchAccountData(page, options) {
  await includeJQuery(page);

  const apiSiteUrl = `${BASE_URL}/Titan/gatewayAPI`;

  const accountDataUrl = `${apiSiteUrl}/userAccountsData`;
  const accountInfo = await fetch(page, accountDataUrl);
  const accountNumber = accountInfo.UserAccountsData.DefaultAccountNumber;

  notify(options, `discount: found account number ${accountNumber}`);

  const date = new Date();
  date.setDate(date.getDate() - 180);
  const txnsUrl = `${apiSiteUrl}/lastTransactions/${accountNumber}/Date?IsCategoryDescCode=True&IsTransactionDetails=True&IsEventNames=True&FromDate=${date.toISOString().slice(0, 10).replace(/-/g, '')}`;
  const txnsResult = await fetch(page, txnsUrl);
  if (txnsResult.Error) {
    return {
      success: false,
      errorType: 'generic',
      errorMessage: txnsResult.Error.MsgText,
    };
  }
  const txns = convertTransactions(txnsResult.CurrentAccountLastTransactions.OperationEntry);

  const accountData = {
    success: true,
    accountNumber,
    txns,
  };
  notify(options, `discount: end scraping for account ${accountData.accountNumber}, found ${accountData.txns.length} transactions`);

  return accountData;
}

async function handleLoginResult(page, options, loginResult) {
  let scrapeResult;
  switch (loginResult) {
    case LOGIN_RESULT.SUCCESS:
      notify(options, 'discount: login successful');
      scrapeResult = await fetchAccountData(page, options);
      break;
    case LOGIN_RESULT.INVALID_PASSWORD:
      notify(options, 'discount: invalid password');
      scrapeResult = {
        success: false,
        errorType: loginResult,
      };
      break;
    case LOGIN_RESULT.CHANGE_PASSWORD:
      notify(options, 'discount: need to change password');
      scrapeResult = {
        success: false,
        errorType: loginResult,
      };
      break;
    default:
      throw new Error(`unexpected login result "${loginResult}"`);
  }

  return scrapeResult;
}

function getPossibleLoginUrls() {
  const urls = {};
  urls[LOGIN_RESULT.SUCCESS] = `${BASE_URL}/apollo/core/templates/default/masterPage.html#/MY_ACCOUNT_HOMEPAGE`;
  urls[LOGIN_RESULT.INVALID_PASSWORD] = `${BASE_URL}/LoginPages/Logon?multilang=he&t=P&pagekey=home&bank=d#`;
  urls[LOGIN_RESULT.CHANGE_PASSWORD] = `${BASE_URL}/LoginPages/Logon`;
  return urls;
}

async function scrape(credentials, options = {}) {
  notify(options, 'discount: start scraping');

  const instance = await phantom.create();
  const page = await instance.createPage();

  await login(page, credentials, options);

  const loginResult = await analyzeLogin(page, getPossibleLoginUrls());
  if (['timeout', 'generic'].includes(loginResult)) {
    await instance.exit();
    return {
      success: false,
      errorType: loginResult,
    };
  }

  const scrapeResult = await handleLoginResult(page, options, loginResult);

  await instance.exit();

  return scrapeResult;
}

export default scrape;
<|endoftext|>


<commit_before>var Transform = require('pipestream').Transform;
var util = require('../util');
var config = require('../config');
var HTTPS_FIELD = config.HTTPS_FIELD;
var HTTPS_FLAG = config.HTTPS_FLAG;
var HTTPS_FLAG_LEN = HTTPS_FLAG.length;
var HTTPS_RE = /https:(\/\/|\\\/\\\/)/ig;
var RESET_COOKIE_RE = /secure;?|domain=([^;]*);?/ig;

function getTransform() {
	var transform = new Transform();
	var rest = '';
	transform._transform = function(chunk, encoding, callback) {
		if (chunk) {
			rest = chunk = (rest + chunk).replace(HTTPS_RE, 'http:$1' + HTTPS_FLAG);
			var len = chunk.length - 7;
			if (len > 0) {
				rest = chunk.substring(len);
				chunk = chunk.substring(0, len);
			} else {
				chunk = null;
			}
		} else {
			chunk = rest || null;
		}
		callback(null, chunk);
	};
	return transform;
}

module.exports = function(req, res, next) {
	if (req.headers[HTTPS_FIELD] || req.socket.isHttps) {//防止socket长连接导致新请求的头部无法加util.HTTPS_FIELD
		req.socket.isHttps = true;
		req.isHttps = true;
		delete req.headers[HTTPS_FIELD];
	} else {
		var host = req.headers.host;
		var isHttps = host && host.indexOf(HTTPS_FLAG) == 0 && host.indexOf('.', HTTPS_FLAG_LEN) != -1;
		if (isHttps) {
			host = req.headers.host = host.substring(HTTPS_FLAG_LEN);
			req.isHttps = req.isWhistleHttps = true;
			var referer = req.headers.referer;
			if (referer) {
				req.headers.referer = referer.replace('http://' + HTTPS_FLAG, 'https://');
			}

			res.on('src', function(_res) {
				var headers = _res.headers;
				if (/^https:\/\//i.test(headers.location)) {
					headers.location = 'http:' + HTTPS_FLAG + util.removeProtocol(headers.location, true);
				}

				var cookies = headers['set-cookie'];
				if (Array.isArray(cookies)) {
					host = host.split(':')[0].split('.');
					host = '.' + host.slice(host.length - 2).join('.');
					headers['set-cookie'] = cookies.map(function(cookie) {
						return cookie.replace(RESET_COOKIE_RE, '') + '; DOMAIN=' + host + ';';
					});
				}

				if (util.supportHtmlTransform(_res)) {
					res.addTextTransform(getTransform(), true);
				}
			});
		}
	}

	next();
};<commit_msg>end if chunk == null<commit_after>var Transform = require('pipestream').Transform;
var util = require('../util');
var config = require('../config');
var HTTPS_FIELD = config.HTTPS_FIELD;
var HTTPS_FLAG = config.HTTPS_FLAG;
var HTTPS_FLAG_LEN = HTTPS_FLAG.length;
var HTTPS_RE = /https:(\/\/|\\\/\\\/)/ig;
var RESET_COOKIE_RE = /secure;?|domain=([^;]*);?/ig;

function getTransform() {
	var transform = new Transform();
	var rest = '';
	transform._transform = function(chunk, encoding, callback) {
		if (chunk != null) {
			rest = chunk = (rest + chunk).replace(HTTPS_RE, 'http:$1' + HTTPS_FLAG);
			var len = chunk.length - 7;
			if (len > 0) {
				rest = chunk.substring(len);
				chunk = chunk.substring(0, len);
			} else {
				chunk = null;
			}
		} else {
			chunk = rest || null;
		}
		callback(null, chunk);
	};
	return transform;
}

module.exports = function(req, res, next) {
	if (req.headers[HTTPS_FIELD] || req.socket.isHttps) {//防止socket长连接导致新请求的头部无法加util.HTTPS_FIELD
		req.socket.isHttps = true;
		req.isHttps = true;
		delete req.headers[HTTPS_FIELD];
	} else {
		var host = req.headers.host;
		var isHttps = host && host.indexOf(HTTPS_FLAG) == 0 && host.indexOf('.', HTTPS_FLAG_LEN) != -1;
		if (isHttps) {
			host = req.headers.host = host.substring(HTTPS_FLAG_LEN);
			req.isHttps = req.isWhistleHttps = true;
			var referer = req.headers.referer;
			if (referer) {
				req.headers.referer = referer.replace('http://' + HTTPS_FLAG, 'https://');
			}

			res.on('src', function(_res) {
				var headers = _res.headers;
				if (/^https:\/\//i.test(headers.location)) {
					headers.location = 'http:' + HTTPS_FLAG + util.removeProtocol(headers.location, true);
				}

				var cookies = headers['set-cookie'];
				if (Array.isArray(cookies)) {
					host = host.split(':')[0].split('.');
					host = '.' + host.slice(host.length - 2).join('.');
					headers['set-cookie'] = cookies.map(function(cookie) {
						return cookie.replace(RESET_COOKIE_RE, '') + '; DOMAIN=' + host + ';';
					});
				}

				if (util.supportHtmlTransform(_res)) {
					res.addTextTransform(getTransform(), true);
				}
			});
		}
	}

	next();
};<|endoftext|>


<commit_before>'use strict';

var MIN_DEPTH_REQUIRED = 30;

var validator = require('./validator');
var mainLineOptimizer = require('./main-line-optimizer');
var analysisPriority = require('../../analysis/analysis-priority');
var timeoutInMilliseconds = 1000;

var optimizeSync = function (base, analyzer, baseIterator) {
    validator.validate(base);
    if(baseIterator) {
        let movesList = baseIterator.getMovesToInsufficientEvaluationDepth(base, MIN_DEPTH_REQUIRED);
        if(movesList) {
          console.log("Moves identified for deeper analysis: ", movesList.length);
          movesList.forEach(function(moves) {
            analyzer.analyzeLater(moves, base, analysisPriority.OptimizationOfNotAnalyzedEnough)
          });
          movesList = baseIterator.getMovesWithSameFenButDifferentEvaluation(base);
          movesList.forEach(function(moves) {
            analyzer.analyzeLater(moves, base, analysisPriority.OptimizationOfNotAnalyzedEnough)
          });
        }
        mainLineOptimizer.goDeeper(base, baseIterator, analyzer);
    }
};

module.exports.optimizeSync = optimizeSync;

module.exports.optimize = function (base, analyzer, baseIterator) {
    setTimeout(optimizeSync, timeoutInMilliseconds, base, analyzer, baseIterator);
};
<commit_msg>base-optimizer min depth is changed to 32<commit_after>'use strict';

var MIN_DEPTH_REQUIRED = 32;

var validator = require('./validator');
var mainLineOptimizer = require('./main-line-optimizer');
var analysisPriority = require('../../analysis/analysis-priority');
var timeoutInMilliseconds = 1000;

var optimizeSync = function (base, analyzer, baseIterator) {
    validator.validate(base);
    if(baseIterator) {
        let movesList = baseIterator.getMovesToInsufficientEvaluationDepth(base, MIN_DEPTH_REQUIRED);
        if(movesList) {
          console.log("Moves identified for deeper analysis: ", movesList.length);
          movesList.forEach(function(moves) {
            analyzer.analyzeLater(moves, base, analysisPriority.OptimizationOfNotAnalyzedEnough)
          });
          movesList = baseIterator.getMovesWithSameFenButDifferentEvaluation(base);
          movesList.forEach(function(moves) {
            analyzer.analyzeLater(moves, base, analysisPriority.OptimizationOfNotAnalyzedEnough)
          });
        }
        mainLineOptimizer.goDeeper(base, baseIterator, analyzer);
    }
};

module.exports.optimizeSync = optimizeSync;

module.exports.optimize = function (base, analyzer, baseIterator) {
    setTimeout(optimizeSync, timeoutInMilliseconds, base, analyzer, baseIterator);
};
<|endoftext|>


<commit_before>import "6to5/polyfill";

import test from "tape-catch";

import m from "mithril";
import n from "../source/n";

// Prepare a DOM container for tests
var testContainer = document.createElement("div");
document.body.appendChild(testContainer);

function flush (target) {
  var childNode;
  while ((childNode = target.lastChild)) {
    target.removeChild(childNode);
    }
  }

test("Does the same as Mithril", (is) => {
  var noop = () => {};

  is.deepEqual
    ( m("div", {an: "attribute", onclick: noop})
    , n("div", {an: "attribute", onclick: noop})
    , "with a single vnode"
    );

  is.deepEqual
    ( m("div", {an: "attribute", onclick: noop}, m("a"), [m(".b"), m("#c")])
    , n("div", {an: "attribute", onclick: noop}, m("a"), [m(".b"), m("#c")])
    , "even when the vnode has vchildren"
    );

  m.render(testContainer, n
    ( ".something"
    , {config: () => {
      is.pass("keeping an existing config attribute when the vnode has no children,");
      }}
    ));

  m.render(testContainer, n
    ( ".somethingElse"
    , {config: () => {
      is.pass("as well as when it does have vchildren and child nodes");
      }}
    , document.createElement("div")
    , m(".another-child")
    ));

  flush(testContainer);
  is.end();
  });

test("Renders a child node", (is) => {
  var grandpa;
  var [pa, daughter, son] = Array(3).fill(null).map(
    () => document.createElement("div")
    );
  var baby = document.createTextNode("balbablaba ballablabla ba blbbla");
  pa.setAttribute("some-attr", "some value");
  pa.appendChild(son);
  pa.appendChild(daughter);
  pa.appendChild(baby);

  m.render
    ( testContainer
    , n("article"
      , {config: (element) => {
        grandpa = element;
        }}
      , pa
      )
    );
  is.equal
    ( pa && pa.parentNode
    , grandpa
    , "in the parent vnode"
    );
  is.equal
    ( pa.getAttribute("some-attr")
    , "some value"
    , "keeping attributes and their values"
    );
  is.ok
    (  pa.firstChild == son
    && son.nextSibling == daughter
    ,  "and the node's subtree"
    );
  is.ok
    (  daughter.nextSibling == baby
    && pa.lastChild == baby
    ,  "including text nodes"
    );

  flush(testContainer);
  is.end();
});

test("Renders a bunch of child nodes", (is) => {
  var aunt, grandpa;
  var [ma, pa, uncle] = Array(3).fill(null).map(
    () => document.createElement("div")
    );

  m.render(testContainer
    , n(".grandpa"
      , {config: (element) => {grandpa = element;}}
      , ma
      , m(".aunt", { config: (element) => {aunt = element;}
                   , key: "aunt"
                   })
      , uncle
      , pa
      )
    );
  is.equal
    ( grandpa && grandpa.parentNode
    , testContainer
    , "just where told to render"
    );
  is.ok
    ( [ma, pa, uncle].every((element) =>
      element && element.parentNode == grandpa
      )
    , "in the parent node"
    );
  is.equal
    ( aunt && aunt.parentNode
    , grandpa
    , "alongside virtual nodes"
    );
  is.ok
    ( [ma, aunt, uncle, pa].every((element, index, elements) =>
      (  index === 0
      || element.previousSibling == elements[index - 1]
      ))
    , "in the correct order"
    );

  var [oldUncle, oldAunt, oldPa] = [uncle, aunt, pa];
  m.render(testContainer
    , n(".other-grandpa"
      , {key: "other-grandpa"}
      , uncle
      , m(".aunt", { config: (element) => {aunt = element;}
                   , key: "aunt"
                   })
      )
    );
  is.notEqual
    ( uncle.parentNode
    , grandpa
    , "moving nodes when needed instead of cloning them"
    );
  is.equal
    ( uncle
    , oldUncle
    , "without breaking references across redraws"
    );
  is.equal
    ( aunt
    , oldAunt
    , "and keeping references to keyed vnodes"
    );

  m.render(testContainer
    , n(".other-grandpa"
      , {key: "other-grandpa"}
      , m(".aunt", { config: (element) => {aunt = element;}
                   , key: "aunt"
                   })
      , uncle
      , n("", pa)
      )
    );
  is.equal
    ( uncle
    , oldUncle
    , "even when changing the order"
    );
  is.equal
    ( pa
    , oldPa
    , "even when called more than once in a single view"
    );

  flush(testContainer);
  is.end();
  });
<commit_msg>Add test for syntax<commit_after>import "6to5/polyfill";

import test from "tape-catch";

import m from "mithril";
import n from "../source/n";

// Prepare a DOM container for tests
var testContainer = document.createElement("div");
document.body.appendChild(testContainer);

function flush (target) {
  var childNode;
  while ((childNode = target.lastChild)) {
    target.removeChild(childNode);
    }
  }

test("Does the same as Mithril", (is) => {
  var noop = () => {};

  is.deepEqual
    ( m("div", {an: "attribute", onclick: noop})
    , n("div", {an: "attribute", onclick: noop})
    , "with a single vnode"
    );

  is.deepEqual
    ( m("div", {an: "attribute", onclick: noop}, m("a"), [m(".b"), m("#c")])
    , n("div", {an: "attribute", onclick: noop}, m("a"), [m(".b"), m("#c")])
    , "even when the vnode has vchildren"
    );

  m.render(testContainer, n
    ( ".something"
    , {config: () => {
      is.pass("keeping an existing config attribute when the vnode has no children,");
      }}
    ));

  m.render(testContainer, n
    ( ".somethingElse"
    , {config: () => {
      is.pass("as well as when it does have vchildren and child nodes");
      }}
    , document.createElement("div")
    , m(".another-child")
    ));

  flush(testContainer);
  is.end();
  });

test("Renders a child node", (is) => {
  var grandpa;
  var [pa, daughter, son] = Array(3).fill(null).map(
    () => document.createElement("div")
    );
  var baby = document.createTextNode("balbablaba ballablabla ba blbbla");
  pa.setAttribute("some-attr", "some value");
  pa.appendChild(son);
  pa.appendChild(daughter);
  pa.appendChild(baby);

  m.render
    ( testContainer
    , n("article"
      , {config: (element) => {
        grandpa = element;
        }}
      , pa
      )
    );
  is.equal
    ( pa && pa.parentNode
    , grandpa
    , "in the parent vnode"
    );
  is.equal
    ( pa.getAttribute("some-attr")
    , "some value"
    , "keeping attributes and their values"
    );
  is.ok
    (  pa.firstChild == son
    && son.nextSibling == daughter
    ,  "and the node's subtree"
    );
  is.ok
    (  daughter.nextSibling == baby
    && pa.lastChild == baby
    ,  "including text nodes"
    );

  flush(testContainer);
  is.end();
});

test("Renders a bunch of child nodes", (is) => {
  var aunt, grandpa;
  var [ma, pa, uncle] = Array(3).fill(null).map(
    () => document.createElement("div")
    );

  m.render(testContainer
    , n(".grandpa"
      , {config: (element) => {grandpa = element;}}
      , ma
      , m(".aunt", { config: (element) => {aunt = element;}
                   , key: "aunt"
                   })
      , uncle
      , pa
      )
    );
  is.equal
    ( grandpa && grandpa.parentNode
    , testContainer
    , "just where told to render"
    );
  is.ok
    ( [ma, pa, uncle].every((element) =>
      element && element.parentNode == grandpa
      )
    , "in the parent node"
    );
  is.equal
    ( aunt && aunt.parentNode
    , grandpa
    , "alongside virtual nodes"
    );
  is.ok
    ( [ma, aunt, uncle, pa].every((element, index, elements) =>
      (  index === 0
      || element.previousSibling == elements[index - 1]
      ))
    , "in the correct order"
    );

  var [oldUncle, oldAunt, oldPa] = [uncle, aunt, pa];
  m.render(testContainer
    , n(".other-grandpa"
      , {key: "other-grandpa"}
      , uncle
      , m(".aunt", { config: (element) => {aunt = element;}
                   , key: "aunt"
                   })
      )
    );
  is.notEqual
    ( uncle.parentNode
    , grandpa
    , "moving nodes when needed instead of cloning them"
    );
  is.equal
    ( uncle
    , oldUncle
    , "without breaking references across redraws"
    );
  is.equal
    ( aunt
    , oldAunt
    , "and keeping references to keyed vnodes"
    );

  m.render(testContainer
    , n(".other-grandpa"
      , {key: "other-grandpa"}
      , m(".aunt", { config: (element) => {aunt = element;}
                   , key: "aunt"
                   })
      , uncle
      , n("", pa)
      )
    );
  is.equal
    ( uncle
    , oldUncle
    , "even when changing the order"
    );
  is.equal
    ( pa
    , oldPa
    , "even when called more than once in a single view"
    );

  flush(testContainer);
  is.end();
  });

test("Accepts different types of syntax", (is) => {
  var otherSon;
  var [daughter, otherDaughter, son, baby] = Array(4).fill(null).map(
    () => document.createElement("div")
    );
  var vOtherSon = m(".other-son", {config: (element) => {otherSon = element;}});
  var children =
    [ [baby, [daughter, otherDaughter]]
    , [vOtherSon, son]
    ];

  function testPa (message) {
    return (pa) => {
      is.equal
        ( pa && pa.childNodes.length
        , 5
        , message + " (has all nodes)"
        );
      is.ok
        (  pa.firstChild == baby
        && baby.nextSibling == daughter
        && daughter.nextSibling == otherDaughter
        && otherDaughter.nextSibling == otherSon
        && otherSon.nextSibling == son
        && pa.lastChild == son
        , message + " (has them in the right order)"
        );
      };
    }

  m.render(testContainer, n(".pa"
    , {config: testPa("array syntax")}
    , children
    ));

  m.render(testContainer, n(".pa"
    , {config: testPa("non-array syntax")}
    , baby, daughter, otherDaughter, vOtherSon, son
    ));

  m.render(testContainer, n(".pa"
    , {config: testPa("mixed syntax")}
    , ...children
    ));

  m.render(testContainer, n(".pa"
    , {config: testPa("ignoring invalid children values")}
    , children.concat([undefined, 1, null])
    ));

  flush(testContainer);
  is.end();
  });
<|endoftext|>