<commit_before>module.exports = {
	boolean:          require('../../fields/types/boolean/boolean'),
	date:             require('../../fields/types/date/date'),
	datetime:         require('../../fields/types/datetime/datetime'),
	email:            require('../../fields/types/email/email'),
	location:         require('../../fields/types/location/location'),
	markdown:         require('../../fields/types/markdown/markdown'),
	name:             require('../../fields/types/name/name'),
	password:         require('../../fields/types/password/password'),
	select:           require('../../fields/types/select/select'),
	text:             require('../../fields/types/text/text'),
	key:              require('../../fields/types/key/key'),
	textarea:         require('../../fields/types/textarea/textarea'),
	url:              require('../../fields/types/url/url'),
	embedly:          require('../../fields/types/embedly/embedly'),
	color:            require('../../fields/types/color/color'),
	textarray:        require('../../fields/types/textarray/textarray'),
	numberarray:      require('../../fields/types/textarray/textarray'),
	code:             require('../../fields/types/code/code'),
	cloudinaryimage:  require('../../fields/types/cloudinaryimage/cloudinaryimage'),
	cloudinaryimages: require('../../fields/types/cloudinaryimages/cloudinaryimages')
};
<commit_msg>Number field wasn't added to the field index (#792)<commit_after>module.exports = {
	boolean:          require('../../fields/types/boolean/boolean'),
	date:             require('../../fields/types/date/date'),
	datetime:         require('../../fields/types/datetime/datetime'),
	email:            require('../../fields/types/email/email'),
	location:         require('../../fields/types/location/location'),
	markdown:         require('../../fields/types/markdown/markdown'),
	name:             require('../../fields/types/name/name'),
	password:         require('../../fields/types/password/password'),
	select:           require('../../fields/types/select/select'),
	text:             require('../../fields/types/text/text'),
	key:              require('../../fields/types/key/key'),
	textarea:         require('../../fields/types/textarea/textarea'),
	url:              require('../../fields/types/url/url'),
	embedly:          require('../../fields/types/embedly/embedly'),
	color:            require('../../fields/types/color/color'),
	textarray:        require('../../fields/types/textarray/textarray'),
	numberarray:      require('../../fields/types/textarray/textarray'),
	code:             require('../../fields/types/code/code'),
	number:           require('../../fields/types/number/number'),
	cloudinaryimage:  require('../../fields/types/cloudinaryimage/cloudinaryimage'),
	cloudinaryimages: require('../../fields/types/cloudinaryimages/cloudinaryimages')
};
<|endoftext|>


<commit_before>
let bSmiling = false;
let maxTimeWithOutSmile = 2000; // millis
let counterSmileSegs = 0;
let startTimer = 0;
let numSecondsSmiling = 3;
let c1Ini, c1End;

let bReset = true;

//let bDecay = false;
let proportionCam;
let proportionWindow;
let scaleWindow_W;
let scaleWindow_H;

function setup() {
    loadCamera(320*2,240*2);//400, 300);//1280, 720);
    proportionCam = videoInput.width / videoInput.height;
    proportionWindow = windowWidth / windowHeight;
    scaleWindow_W =  windowWidth / videoInput.width;
    scaleWindow_H =  windowHeight / videoInput.height;

    if(true){
      console.log("videoInput.width = " + str(videoInput.width));
      console.log("videoInput.height = " + str(videoInput.height));
      console.log("proportionCam = " + str(proportionCam));

      //console.log("window.screen.width = " + str(window.screen.width));
      //console.log("window.screen.height = " + str(window.screen.height));
      console.log("windowWidth= " + str(windowWidth));
      console.log("windowHeight= " + str(windowHeight));
      console.log("proportionWindow = " + str(proportionWindow));

      console.log("scaleWindow_W = " + str(scaleWindow_W));
      console.log("scaleWindow_H = " + str(scaleWindow_H));
    }

    loadTracker();
    loadCanvas(videoInput.width*scaleWindow_W, videoInput.height*scaleWindow_H); //400,300);
    videoInput.hide();

    console.log("width end= " + str(width));
    console.log("height end= " + str(height));
    c1Ini = color(255,230, 233, 123); //'#FFE9E6');
    c1End = color(255, 77, 100, 123);//'#FFA696');
}
//-----------------------------------------------------

function draw() {
    update();
    clear();

    noStroke();
    if(counterSmileSegs == numSecondsSmiling)fill(0,0);
    else fill(0,150);
    rect(0,0,width,height);

push();
    scale(scaleWindow_W, scaleWindow_H);//window.screen.width, window.screen.height); //400,300);
    fill(255);
    image(videoInput,0,0);
    drawPoints();
    drawSmiling_1(false, true);
pop();

    drawDebugEmotions();

}

//----------------------------------------------------
function update(){
  getPositions();
  getEmotions();

  if(emotions){
    if(predictedEmotions.length){
        let scaleTime = 0.001;
        let timeSegs = millis()*scaleTime;
        //console.log("Angry = " + str(predictedEmotions[0].value)+" HAPPY = " +str(predictedEmotions[3].value));
        bSmiling = updateSmileDetection(predictedEmotions[0].value, predictedEmotions[3].value, 0.3, 0.5);
        if(bSmiling){
            counterSmileSegs = timeSegs - startTimer;
            if(counterSmileSegs > numSecondsSmiling) counterSmileSegs = numSecondsSmiling;
        }else{
            counterSmileSegs = 0;
            startTimer = timeSegs;
          //  if(!bDecay){
          //      bDecay = true;
          //  }
        }
    }
  }
}

//---------------------------------------------------
function updateSmileDetection(_angryVal, _happyVal, _thresholdAngry, _thresholdHappy) {
    let isSimiling = false;
    if(_angryVal < _thresholdAngry && _happyVal > _thresholdHappy){
        isSimiling = true;
    }
    return isSimiling;
}

//////////////////////////////////////////////////////////
//-----------------------------------------------------
function drawDebugEmotions() {
  let scaleIniY = 0.85;
  let scaleIniX = 0.40;
  let scaleValuesEmotion = 30;

  push();
  stroke(255);
  rect(width*scaleIniX, height-80*2-height*scaleIniY, 405, 140);
  pop();

  push();
  fill(255);
  if (emotions) {
      // andry=0, sad=1, surprised=2, happy=3
      for (var i = 0;i < predictedEmotions.length;i++) {
          rect(width*scaleIniX+i * 110+20, height-80-height*scaleIniY, 30, -predictedEmotions[i].value * scaleValuesEmotion);
      }
  }

  text("ANGRY", width*scaleIniX+20, height-40-height*scaleIniY);
  text("SAD", width*scaleIniX+130, height-40-height*scaleIniY);
  text("SURPRISED", width*scaleIniX+220, height-40-height*scaleIniY);
  if(bSmiling)fill(255, 0, 0);
  //else fadoill(0,150);
  text("HAPPY", width*scaleIniX+340, height-40-height*scaleIniY);
  pop();
}

function drawSmiling_1(_bDrawTime, _bDrawTransparentRect){

  if(_bDrawTime){
    push();
      //scale(2, 2, 2);
      //translate(width*0.25, height*0.25);
      textSize(20);
      textAlign(CENTER);
      if(bSmiling)fill(255, 0, 0);
      text(nf(counterSmileSegs, 0, 2), width*0.5, height*0.5);
      //text(str(counterSmileSegs), 0,0);
    pop();
  }

  if(_bDrawTransparentRect){
    push();
      translate(0, height);
      scale(1,-1,1);
      let pct = map(counterSmileSegs, 0, numSecondsSmiling, 0, 1);
      let cLerp = lerpColor(c1Ini, c1End, pct);
      fill(cLerp);
      rect(0,0,width, height*pct);
    pop();
  }

}

function drawPoints() {
    fill(255);
    for (var i=0; i<positions.length -3; i++) {
        ellipse(positions[i][0], positions[i][1], 2, 2);
    }
}

///---------------------------------
function keyPressed(){
  bReset = true;
}
<commit_msg>regular size<commit_after>
let bSmiling = false;
let maxTimeWithOutSmile = 2000; // millis
let counterSmileSegs = 0;
let startTimer = 0;
let numSecondsSmiling = 3;
let c1Ini, c1End;

let bReset = true;

//let bDecay = false;
let bModeFullWindow = false;
let proportionCam;
let proportionWindow;
let scaleWindow_W;
let scaleWindow_H;

function setup() {
    loadCamera(400, 300);//1280, 720);

    if(bModeFullWindow){
      proportionCam = videoInput.width / videoInput.height;
      proportionWindow = windowWidth / windowHeight;
      scaleWindow_W =  windowWidth / videoInput.width;
      scaleWindow_H =  windowHeight / videoInput.height;

      if(true){
        console.log("videoInput.width = " + str(videoInput.width));
        console.log("videoInput.height = " + str(videoInput.height));
        console.log("proportionCam = " + str(proportionCam));

        //console.log("window.screen.width = " + str(window.screen.width));
        //console.log("window.screen.height = " + str(window.screen.height));
        console.log("windowWidth= " + str(windowWidth));
        console.log("windowHeight= " + str(windowHeight));
        console.log("proportionWindow = " + str(proportionWindow));

        console.log("scaleWindow_W = " + str(scaleWindow_W));
        console.log("scaleWindow_H = " + str(scaleWindow_H));
      }

      loadCanvas(videoInput.width*scaleWindow_W, videoInput.height*scaleWindow_H); //400,300);
      videoInput.hide();
    }
    else{
      loadTracker();
      loadCanvas(400,300);
    }

    console.log("width end= " + str(width));
    console.log("height end= " + str(height));
    c1Ini = color(255,230, 233, 123); //'#FFE9E6');
    c1End = color(255, 77, 100, 123);//'#FFA696');
}
//-----------------------------------------------------

function draw() {
    update();
    clear();

    noStroke();
    if(counterSmileSegs == numSecondsSmiling)fill(0,0);
    else fill(0,150);
    rect(0,0,width,height);

if(bModeFullWindow){
  push();
    scale(scaleWindow_W, scaleWindow_H);//window.screen.width, window.screen.height); //400,300);
    fill(255);
    image(videoInput,0,0);
    drawPoints();
    drawSmiling_1(false, true);
  pop();
}
else{
  drawPoints();
  drawSmiling_1(false, true);
}
  drawDebugEmotions();
}

//----------------------------------------------------
function update(){
  getPositions();
  getEmotions();

  if(emotions){
    if(predictedEmotions.length){
        let scaleTime = 0.001;
        let timeSegs = millis()*scaleTime;
        //console.log("Angry = " + str(predictedEmotions[0].value)+" HAPPY = " +str(predictedEmotions[3].value));
        bSmiling = updateSmileDetection(predictedEmotions[0].value, predictedEmotions[3].value, 0.3, 0.5);
        if(bSmiling){
            counterSmileSegs = timeSegs - startTimer;
            if(counterSmileSegs > numSecondsSmiling) counterSmileSegs = numSecondsSmiling;
        }else{
            counterSmileSegs = 0;
            startTimer = timeSegs;
          //  if(!bDecay){
          //      bDecay = true;
          //  }
        }
    }
  }
}

//---------------------------------------------------
function updateSmileDetection(_angryVal, _happyVal, _thresholdAngry, _thresholdHappy) {
    let isSimiling = false;
    if(_angryVal < _thresholdAngry && _happyVal > _thresholdHappy){
        isSimiling = true;
    }
    return isSimiling;
}

//////////////////////////////////////////////////////////
//-----------------------------------------------------
function drawDebugEmotions() {

  if(bModeFullWindow){
    let scaleIniY = 0.85;
    let scaleIniX = 0.40;
    let scaleValuesEmotion = 30;

    push();
    stroke(255);
    rect(width*scaleIniX, height-80*2-height*scaleIniY, 405, 140);
    pop();

    push();
    fill(255);
    if (emotions) {
        // andry=0, sad=1, surprised=2, happy=3
        for (var i = 0;i < predictedEmotions.length;i++) {
            rect(width*scaleIniX+i * 110+20, height-80-height*scaleIniY, 30, -predictedEmotions[i].value * scaleValuesEmotion);
        }
    }

    text("ANGRY", width*scaleIniX+20, height-40-height*scaleIniY);
    text("SAD", width*scaleIniX+130, height-40-height*scaleIniY);
    text("SURPRISED", width*scaleIniX+220, height-40-height*scaleIniY);
    if(bSmiling)fill(255, 0, 0);
    //else fadoill(0,150);
    text("HAPPY", width*scaleIniX+340, height-40-height*scaleIniY);
    pop();
  }
  else{
    let scaleIniY = 0.85;
    let scaleIniX = 0.40;
    let scaleValuesEmotion = 30;

    push();
    fill(255);
    if (emotions) {
      // andry=0, sad=1, surprised=2, happy=3
      for (var i = 0;i < predictedEmotions.length;i++) {
          rect(i * 110+20, height-80, 30, -predictedEmotions[i].value * 30);
      }
    }

    text("ANGRY", 20, height-40);
    text("SAD", 130, height-40);
    text("SURPRISED", 220, height-40);
    if(bSmiling)fill(255, 0, 0);
    //else fadoill(0,150);
    text("HAPPY",340, height-40);
    pop();
  }
}

function drawSmiling_1(_bDrawTime, _bDrawTransparentRect){

  if(_bDrawTime){
    push();
      //scale(2, 2, 2);
      //translate(width*0.25, height*0.25);
      textSize(20);
      textAlign(CENTER);
      if(bSmiling)fill(255, 0, 0);
      text(nf(counterSmileSegs, 0, 2), width*0.5, height*0.5);
      //text(str(counterSmileSegs), 0,0);
    pop();
  }

  if(_bDrawTransparentRect){
    push();
      translate(0, height);
      scale(1,-1,1);
      let pct = map(counterSmileSegs, 0, numSecondsSmiling, 0, 1);
      let cLerp = lerpColor(c1Ini, c1End, pct);
      fill(cLerp);
      rect(0,0,width, height*pct);
    pop();
  }

}

function drawPoints() {
    fill(255);
    for (var i=0; i<positions.length -3; i++) {
        ellipse(positions[i][0], positions[i][1], 2, 2);
    }
}

///---------------------------------
function keyPressed(){
  bReset = true;
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { DeckContext } from '../../hooks/use-deck';

const basePresenterStyle = {
  height: '100vh',
  width: '100vw',
  top: 0,
  bottom: 0,
  left: 0,
  right: 0,
  position: 'absolute',
  display: 'flex',
  flexDirection: 'row'
};

const PresenterDeck = props => {
  const {
    state: { currentNotes, currentSlide }
  } = React.useContext(DeckContext);

  const {
    children,
    isController,
    isReceiver,
    startConnection,
    terminateConnection
  } = props;

  const activeSlide =
    children.length > currentSlide ? children[currentSlide] : null;
  const nextSlide =
    children.length > currentSlide + 1 ? children[currentSlide + 1] : null;

  const slideContainerStyle = {
    position: 'relative',
    overflow: 'hidden',
    borderStyle: 'solid',
    borderWidth: 3,
    borderColor: 'black',
    height: 0,
    paddingTop: '56.25%'
  };
  const slideStyle = {
    position: 'absolute',
    top: 0,
    left: 0,
    width: '100%',
    height: '100%'
  };

  const clonedActiveSlide = React.cloneElement(activeSlide, {
    style: slideStyle
  });

  const clonedNextSlide =
    nextSlide &&
    React.cloneElement(nextSlide, {
      style: slideStyle
    });

  return (

Notes:

          {currentNotes}

        {!isController && !isReceiver && (
          <button onClick={startConnection}>Start Connection</button>
        )}
        {isController && !isReceiver && (
          <button onClick={terminateConnection}>Terminate Connection</button>
        )}

Current Slide:

{clonedActiveSlide}

Next Slide:

{clonedNextSlide}

  );
};

PresenterDeck.propTypes = {
  children: PropTypes.node.isRequired,
  isController: PropTypes.bool.isRequired,
  isReceiver: PropTypes.bool.isRequired,
  startConnection: PropTypes.func.isRequired,
  terminateConnection: PropTypes.func.isRequired
};

export default PresenterDeck;
<commit_msg>fix presenter deck resizing behavior<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { DeckContext } from '../../hooks/use-deck';

const basePresenterStyle = {
  height: '100vh',
  width: '100vw',
  top: 0,
  bottom: 0,
  left: 0,
  right: 0,
  position: 'absolute',
  display: 'flex',
  flexDirection: 'row'
};

const baseColumnContainerStyle = {
  display: 'flex',
  flexDirection: 'column',
  paddingLeft: '4em',
  paddingRight: '4em',
  flex: 1
};

const leftColumnContainerStyle = {
  ...baseColumnContainerStyle,
  paddingTop: '4em',
  backgroundColor: 'rgba(40, 30, 20, 0.2)'
};

const notesContainerStyle = {
  fontSize: '1.3em',
  fontFamily: 'georgia',
  lineHeight: '180%'
};

const rightColumnContainerStyle = {
  ...baseColumnContainerStyle,
  backgroundColor: 'rgba(10, 150, 10, 0.2)',
  justifyContent: 'center',
  // ensure that the combined height of the slide previews
  // never exceeds the height of the screen
  maxWidth: 'calc(((100vh - 10%) / 2) * 16 / 9)'
};

const slideHeaderStyle = {
  margin: 0,
  marginTop: 10,
  marginBottom: 10
};

const slideContainerStyle = {
  position: 'relative',
  overflow: 'hidden',
  borderStyle: 'solid',
  borderWidth: 3,
  borderColor: 'black',
  height: 0,
  // 16 / 9 aspect ratio - https://css-tricks.com/aspect-ratio-boxes/
  paddingTop: '56.25%'
};

const slideStyle = {
  position: 'absolute',
  top: 0,
  left: 0,
  right: 0,
  bottom: 0
};

const buttonContainerStyle = {
  position: 'absolute',
  left: '1em',
  top: '1em'
};

const buttonStyle = {
  height: 20,
  width: 150,
  backgroundColor: 'white'
};

const PresenterDeck = props => {
  const {
    state: { currentSlide, currentNotes }
  } = React.useContext(DeckContext);

  const {
    children,
    isController,
    isReceiver,
    startConnection,
    terminateConnection
  } = props;

  const activeSlide =
    children.length > currentSlide ? children[currentSlide] : null;
  const nextSlide =
    children.length > currentSlide + 1 ? children[currentSlide + 1] : null;

  const clonedActiveSlide = React.cloneElement(activeSlide, {
    style: slideStyle
  });

  const clonedNextSlide =
    nextSlide &&
    React.cloneElement(nextSlide, {
      style: slideStyle
    });

  return (

        {!isController && !isReceiver && (
          <button style={buttonStyle} onClick={startConnection}>
            Start Connection
          </button>
        )}
        {isController && !isReceiver && (
          <button style={buttonStyle} onClick={terminateConnection}>
            Terminate Connection
          </button>
        )}

Notes:

{currentNotes}

Current Slide:

{clonedActiveSlide}

Next Slide:

{clonedNextSlide}

  );
};

PresenterDeck.propTypes = {
  children: PropTypes.node.isRequired,
  isController: PropTypes.bool.isRequired,
  isReceiver: PropTypes.bool.isRequired,
  startConnection: PropTypes.func.isRequired,
  terminateConnection: PropTypes.func.isRequired
};

export default PresenterDeck;
<|endoftext|>


<commit_before>/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// @Copyright ~2016 ☜Samlv9☞ and other contributors
/// @MIT-LICENSE | 1.0.0 | http://apidev.guless.com/
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///                                              }|
///                                              }|
///                                              }|     　 へ　　　 ／|
///      _______     _______         ______      }|      /　│　　 ／ ／
///     /  ___  |   |_   __ \      .' ____ '.    }|     │　Z ＿,＜　／　　 /`ヽ
///    |  (__ \_|     | |__) |     | (____) |    }|     │　　　　　ヽ　　 /　　〉
///     '.___`-.      |  __ /      '_.____. |    }|      Y　　　　　`　 /　　/
///    |`\____) |    _| |  \ \_    | \____| |    }|    ｲ●　､　●　　⊂⊃〈　　/
///    |_______.'   |____| |___|    \______,'    }|    ()　 v　　　　|　＼〈
///    |=========================================\|    　>ｰ ､_　 ィ　 │ ／／
///    |> LESS IS MORE                           ||     / へ　　 /　ﾉ＜|＼＼
///    `=========================================/|    ヽ_ﾉ　　(_／　 │／／
///                                              }|     7　　　　　　  |／
///                                              }|     ＞―r￣￣`ｰ―＿`
///                                              }|
///                                              }|
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import CRC32  from "../crypto/CRC32";
import UTF8 from "../codec/UTF8";
import Base16 from "../codec/Base16";
import tobytes from "../tobytes";
import tochars from "../tochars";

export default function crc32( string ) {
    var buffer = typeof string == "string" ? tobytes(string) : string;
    return tochars((new Base16()).encode((new crc32()).update((new UTF8()).encode(buffer)).digest()));
}<commit_msg>#fixed: raise/crc32 digest 不是一个TypedArray而是一个 32 位的无符号整数。因此需要用 strbin 输出16进制字符串，而不是使用Base16。<commit_after>/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/// @Copyright ~2016 ☜Samlv9☞ and other contributors
/// @MIT-LICENSE | 1.0.0 | http://apidev.guless.com/
/// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
///                                              }|
///                                              }|
///                                              }|     　 へ　　　 ／|
///      _______     _______         ______      }|      /　│　　 ／ ／
///     /  ___  |   |_   __ \      .' ____ '.    }|     │　Z ＿,＜　／　　 /`ヽ
///    |  (__ \_|     | |__) |     | (____) |    }|     │　　　　　ヽ　　 /　　〉
///     '.___`-.      |  __ /      '_.____. |    }|      Y　　　　　`　 /　　/
///    |`\____) |    _| |  \ \_    | \____| |    }|    ｲ●　､　●　　⊂⊃〈　　/
///    |_______.'   |____| |___|    \______,'    }|    ()　 v　　　　|　＼〈
///    |=========================================\|    　>ｰ ､_　 ィ　 │ ／／
///    |> LESS IS MORE                           ||     / へ　　 /　ﾉ＜|＼＼
///    `=========================================/|    ヽ_ﾉ　　(_／　 │／／
///                                              }|     7　　　　　　  |／
///                                              }|     ＞―r￣￣`ｰ―＿`
///                                              }|
///                                              }|
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in all
/// copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
import CRC32 from "../crypto/CRC32";
import UTF8 from "../codec/UTF8";
import Base16 from "../codec/Base16";
import tobytes from "../tobytes";
import strbin from "../strbin";

export default function crc32( string ) {
    var buffer = typeof string == "string" ? tobytes(string) : string;
    return strbin((new CRC32()).update((new UTF8()).encode(buffer)).digest());
}<|endoftext|>


<commit_before>var c = function(m){console.log(m)};

describe("Translator", function() {

  it ("translate elements", function() {
    var z = "(div(div)(span#span1)(span.class1.class2(div#id1.class1)))";

    var t = Translator.translate(z);
    var e = t.element;

    expect(e.down('span')).toHaveId('span1');
    expect(e.down('span').next()).toHaveClass('class1');
    expect(e.down('span').next()).toHaveClass('class2');
    expect(e.down('span').next().down()).toHaveClass('class1');
    expect(e.down('span').next().down()).toHaveId('id1');
    expect(e.descendants().size()).toEqual(4);

  });

  it ("error when after `(` follow not tag", function() {
    var z = "(#)";
    expect(
      function() { Translator.translate(z) }
    ).toThrow();
  });

  it ("2 world", function() {
    var z = "(div div)";
    expect(
      function() { Translator.translate(z) }
    ).toThrow();
  });

  it ("unexpected class", function() {
    var z = "(div.#)";
    expect(
      function() { Translator.translate(z) }
    ).toThrow();
  });

  it ("unexpected id", function() {
    var z = "(div#@)";
    expect(
      function() { Translator.translate(z) }
    ).toThrow();
  });

});

<commit_msg>add spec for binded group<commit_after>var c = function(m){console.log(m)};

describe("Translator", function() {

  it ("translate elements", function() {
    var z = "(div(div)(span#span1)(span.class1.class2(div#id1.class1)))";

    var t = Translator.translate(z);
    var e = t.element;

    expect(e.down('span')).toHaveId('span1');
    expect(e.down('span').next()).toHaveClass('class1');
    expect(e.down('span').next()).toHaveClass('class2');
    expect(e.down('span').next().down()).toHaveClass('class1');
    expect(e.down('span').next().down()).toHaveId('id1');
    expect(e.descendants().size()).toEqual(4);

  });

  it("translate with binded", function() {
    var z = "(div.class1~1(div.class3!1)(div.class2~1)(div.class4~2)(div.class5!2))",
        t = Translator.translate(z),
        b = t.binded,
        h = b.first();

    expect(b.size()).toEqual(2);
    expect(h.get("from")).toEqual(['class1', 'class2']);
    expect(h.get("to")).toEqual(['class3']);

    var e = "(div.class1~1)";
    expect(
      function() { Translator.translate(e); }
    ).toThrow();
  });

  it ("error when after `(` follow not tag", function() {
    var z = "(#)";
    expect(
      function() { Translator.translate(z) }
    ).toThrow();
  });

  it ("2 world", function() {
    var z = "(div div)";
    expect(
      function() { Translator.translate(z) }
    ).toThrow();
  });

  it ("unexpected class", function() {
    var z = "(div.#)";
    expect(
      function() { Translator.translate(z) }
    ).toThrow();
  });

  it ("unexpected id", function() {
    var z = "(div#@)";
    expect(
      function() { Translator.translate(z) }
    ).toThrow();
  });

});

<|endoftext|>


<commit_before>const { RichEmbed } = require('discord.js');

module.exports = {
  commands: [
    'embedsay',
    'say',
    'esay'
  ],
  usage: 'embedsay <texthere>',
  description: 'Takes words you put in and Puts them in a embed!',
  category: 'Other',
  execute: (bot, msg, args) => {
  if (args.length > 0) msg.edit('**Add something after the command silly!**') return;
    const embed = new RichEmbed()
    .setTitle(args.join(' '));
    msg.edit({embed})
  }
};
<commit_msg>I just took a good look at the code and wtf did you commit?<commit_after>const { RichEmbed } = require('discord.js');

module.exports = {
  commands: [
    'embedsay',
    'say',
    'esay'
  ],
  usage: 'embedsay <texthere>',
  description: 'Takes words you put in and Puts them in a embed!',
  category: 'Other',
  execute: (bot, msg, args) => {
  if (args.length > 0) {
    const embed = new RichEmbed()
    .setTitle(args.join(' '));
    msg.edit({embed})
  } else {
    return msg.edit('**Add something after the command silly!**');
  }
};
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  'resources': {
    'fonts': {
      'sans-serif-regular': {
        'src': '/fonts/droid_sans_regular.typeface.json'
      },
      'sans-serif-bold': {
        'src': '/fonts/droid_sans_bold.typeface.json'
      },
      'serif-regular': {
        'src': '/fonts/droid_serif_regular.typeface.json'
      },
      'serif-bold': {
        'src': '/fonts/droid_serif_bold.typeface.json'
      }
    }
  },

  'defaults': {
    'display': 'block',
    'direction': 'column',
    'wrap': 'nowrap',
    'justify-content': 'start',
    'align-items': 'start',
    'align-self': 'initial',
    'grow': 0,
    'padding': 0,
    'margin': 0,
    'width': 'initial',
    'height': 'initial',
    'depth': 'initial'
  },

  'tags': {
    'word': {
      'direction': 'row'
    },
    'body': {
      'font-family': 'sans-serif',
      'font-size': 16,
      'font-height': 1,
      'font-weight': 'regular',
      'color': 0x000000,
      'word-spacing': '0.3em'
    },

    'surface': {
      'display': 'plane'
    },

    'div': {
      'align-self': 'stretch'
    },

    'span': {
    },

    'p': {
      'align-self': 'stretch',
      'margin': '0 1em 0',
      'direction': 'row',
      'wrap': 'wrap'
    },

    'h1': {
      'align-self': 'stretch',
      'direction': 'row',
      'wrap': 'wrap',
      'font-weight': 'bold',
      'font-size': 32,
      'font-height': 8,
      'margin': '0 1em 0'
    },

    'h2': {
      'align-self': 'stretch',
      'direction': 'row',
      'wrap': 'wrap',
      'font-weight': 'bold',
      'font-size': 24,
      'font-height': 6,
      'margin': '0 1em 0'
    },

    'h3': {
      'align-self': 'stretch',
      'direction': 'row',
      'wrap': 'wrap',
      'font-weight': 'bold',
      'font-size': 18.7,
      'font-height': 4.67,
      'margin': '0 1em 0'
    },

    'h4': {
      'align-self': 'stretch',
      'direction': 'row',
      'wrap': 'wrap',
      'font-weight': 'bold',
      'font-size': 16,
      'font-height': 4,
      'margin': '0 1em 0'
    },

    'h5': {
      'align-self': 'stretch',
      'direction': 'row',
      'wrap': 'wrap',
      'font-weight': 'bold',
      'font-size': 13.3,
      'font-height': 3.33,
      'margin': '0 1em 0'

    },

    'h6': {
      'align-self': 'stretch',
      'direction': 'row',
      'wrap': 'wrap',
      'font-weight': 'bold',
      'font-size': 10.7,
      'font-height': 2.67,
      'margin': '0 1em 0'
    }
  }
};
<commit_msg>Implement min- and max- dimensions defaults<commit_after>'use strict';

module.exports = {
  'resources': {
    'fonts': {
      'sans-serif-regular': {
        'src': '/fonts/droid_sans_regular.typeface.json'
      },
      'sans-serif-bold': {
        'src': '/fonts/droid_sans_bold.typeface.json'
      },
      'serif-regular': {
        'src': '/fonts/droid_serif_regular.typeface.json'
      },
      'serif-bold': {
        'src': '/fonts/droid_serif_bold.typeface.json'
      }
    }
  },

  'defaults': {
    'display': 'block',
    'direction': 'column',
    'wrap': 'nowrap',
    'justify-content': 'start',
    'align-items': 'start',
    'align-self': 'initial',
    'grow': 0,
    'padding': 0,
    'margin': 0,
    'width': 'initial',
    'height': 'initial',
    'depth': 'initial',
    'min-width': '0',
    'min-height': '0',
    'min-depth': '0',
    'max-width': Infinity,
    'max-height': Infinity,
    'max-depth': Infinity
  },

  'tags': {
    'word': {
      'direction': 'row'
    },
    'body': {
      'font-family': 'sans-serif',
      'font-size': 16,
      'font-height': 1,
      'font-weight': 'regular',
      'color': 0x000000,
      'word-spacing': '0.3em'
    },

    'surface': {
      'display': 'plane'
    },

    'div': {
      'align-self': 'stretch'
    },

    'span': {
    },

    'p': {
      'align-self': 'stretch',
      'margin': '0 1em 0',
      'direction': 'row',
      'wrap': 'wrap'
    },

    'h1': {
      'align-self': 'stretch',
      'direction': 'row',
      'wrap': 'wrap',
      'font-weight': 'bold',
      'font-size': 32,
      'font-height': 8,
      'margin': '0 1em 0'
    },

    'h2': {
      'align-self': 'stretch',
      'direction': 'row',
      'wrap': 'wrap',
      'font-weight': 'bold',
      'font-size': 24,
      'font-height': 6,
      'margin': '0 1em 0'
    },

    'h3': {
      'align-self': 'stretch',
      'direction': 'row',
      'wrap': 'wrap',
      'font-weight': 'bold',
      'font-size': 18.7,
      'font-height': 4.67,
      'margin': '0 1em 0'
    },

    'h4': {
      'align-self': 'stretch',
      'direction': 'row',
      'wrap': 'wrap',
      'font-weight': 'bold',
      'font-size': 16,
      'font-height': 4,
      'margin': '0 1em 0'
    },

    'h5': {
      'align-self': 'stretch',
      'direction': 'row',
      'wrap': 'wrap',
      'font-weight': 'bold',
      'font-size': 13.3,
      'font-height': 3.33,
      'margin': '0 1em 0'

    },

    'h6': {
      'align-self': 'stretch',
      'direction': 'row',
      'wrap': 'wrap',
      'font-weight': 'bold',
      'font-size': 10.7,
      'font-height': 2.67,
      'margin': '0 1em 0'
    }
  }
};
<|endoftext|>


<commit_before>// Adapted from https://github.com/isaacs/node-lru-cache

function hOP (obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key);
}

function naiveLength () {
  return 1;
}

export function LRUCache (options) {
  if (!(this instanceof LRUCache)) {
    return new LRUCache(options);
  }

  if (typeof options === 'number') {
    options = {max: options};
  }

  if (!options) {
    options = {};
  }

  this._max = options.max;

  if (!this._max || this._max <= 0) {
    this._max = Infinity;
  }

  this._lengthCalculator = options.length || naiveLength;

  if (typeof this._lengthCalculator !== "function") {
    this._lengthCalculator = naiveLength;
  }

  this._allowStale = options.stale || false;
  this._maxAge = options.maxAge || null;
  this._dispose = options.dispose;
  this.reset();
}

Object.defineProperty(LRUCache.prototype, "max", {
  set: function (mL) {
    if (!mL || mL <= 0) {
      mL = Infinity;
    }

    this._max = mL;

    if (this._length > this._max) {
      trim(this);
    }
  },
  get: function () {
    return this._max;
  },
  enumerable : true
});

Object.defineProperty(LRUCache.prototype, "lengthCalculator", {
  set: function (lC) {
    var key;

    if (typeof lC !== "function") {
      this._lengthCalculator = naiveLength;
      this._length = this._itemCount;
      for (key in this._cache) {
        this._cache[key].length = 1;
      }
    } else {
      this._lengthCalculator = lC;
      this._length = 0;
      for (key in this._cache) {
        this._cache[key].length = this._lengthCalculator(this._cache[key].value);
        this._length += this._cache[key].length;
      }
    }

    if (this._length > this._max) {
      trim(this);
    }
  },
  get: function () {
    return this._lengthCalculator;
  },
  enumerable : true
});

Object.defineProperty(LRUCache.prototype, "length", {
  get: function () {
    return this._length;
  },
  enumerable : true
});

Object.defineProperty(LRUCache.prototype, "itemCount", {
  get: function () {
    return this._itemCount;
  },
  enumerable : true
});

LRUCache.prototype.forEach = function (fn, thisp) {
  thisp = thisp || this;
  var i = 0, hit;

  for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) {
    if (this._lruList[k]) {
      hit = this._lruList[k];
      i ++;
      if (this._maxAge && (Date.now() - hit.now > this._maxAge)) {
        del(this, hit);
        if (!this._allowStale) {
          hit = undefined;
        }
      }
      if (hit) {
        fn.call(thisp, hit.value, hit.key, this);
      }
    }
  }
};

LRUCache.prototype.keys = function () {
  var keys = new Array(this._itemCount);
  var i = 0, hit;

  for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) {

    if (this._lruList[k]) {
      hit = this._lruList[k];
      keys[i++] = hit.key;
    }
  }

  return keys;
};

LRUCache.prototype.values = function () {
  var values = new Array(this._itemCount);
  var i = 0, hit;

  for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) {
    if (this._lruList[k]) {
      hit = this._lruList[k];
      values[i++] = hit.value;
    }
  }

  return values;
};

LRUCache.prototype.reset = function () {
  if (this._dispose && this._cache) {
    for (var k in this._cache) {
      this._dispose(k, this._cache[k].value);
    }
  }

  this._cache = Object.create(null);    //items by key
  this._lruList = Object.create(null); // items in order (use recency)
  this._mru = 0;    // most recently used
  this._lru = 0;    // least recently used
  this._length = 0; // number of items
  this._itemCount = 0;
};

LRUCache.prototype.dump = function () {
  return this._cache;
};

LRUCache.prototype.dumpLru = function () {
  return this._lruList;
};

LRUCache.prototype.set = function (key, value) {
  var len, age, hit;

  if (hOP(this._cache, key)) {

    if (this._dispose) {
      this._dispose(key, this._cache[key].value);
    }
    if (this._maxAge) {
      this._cache[key].now = Date.now();
    }

    this._cache[key].value = value;
    this.get(key);

    return true;
  }

  len = this._lengthCalculator(value);
  age = this._maxAge ? Date.now() : 0;
  hit = new Entry(key, value, this._mru++, len, age);

  // oversized objects fall out of cache
  if (hit.length > this._max) {
    if (this._dispose) {
      this._dispose(key, value);
    }

    return false;
  }

  this._length += hit.length;
  this._lruList[hit.lu] = this._cache[key] = hit;
  this._itemCount++;

  if (this._length > this._max) {
    trim(this);
  }
  return true;
};

LRUCache.prototype.has = function (key) {
  var hit = this._cache[key];

  if (!hOP(this._cache, key)) {
    return false;
  }

  if (this._maxAge && (Date.now() - hit.now > this._maxAge)) {
    return false;
  }
  return true;
};

LRUCache.prototype.get = function (key) {
  return get(this, key, true);
};

LRUCache.prototype.peek = function (key) {
  return get(this, key, false);
};

LRUCache.prototype.pop = function () {
  var hit = this._lruList[this._lru];
  del(this, hit);
  return hit || null;
};

LRUCache.prototype.del = function (key) {
  del(this, this._cache[key]);
};

function get(self, key, doUse) {
  var hit = self._cache[key];

  if (hit) {
    if (self._maxAge && (Date.now() - hit.now > self._maxAge)) {
      del(self, hit);
      if (!self._allowStale) {
        hit = undefined;
      }
    } else {
      if (doUse) {
        use(self, hit);
      }
    }
    if (hit) {
      hit = hit.value;
    }
  }

  return hit;
}

function use(self, hit) {
  shiftLU(self, hit);
  hit.lu = self._mru ++;
  self._lruList[hit.lu] = hit;
}

function trim(self) {
  while (self._lru < self._mru && self._length > self._max) {
    del(self, self._lruList[self._lru]);
  }
}

function shiftLU(self, hit) {
  delete self._lruList[hit.lu];
  while (self._lru < self._mru && !self._lruList[self._lru]) {
    self._lru ++;
  }
}

function del(self, hit) {
  if (hit) {
    if (self._dispose) {
      self._dispose(hit.key, hit.value);
    }
    self._length -= hit.length;
    self._itemCount --;
    delete self._cache[hit.key];
    shiftLU(self, hit);
  }
}

function Entry(key, value, lu, length, now) {
  this.key = key;
  this.value = value;
  this.lu = lu;
  this.length = length;
  this.now = now;
}
<commit_msg>formatting<commit_after>// Adapted from https://github.com/isaacs/node-lru-cache

function hOP (obj, key) {
  return Object.prototype.hasOwnProperty.call(obj, key);
}

function naiveLength () {
  return 1;
}

export function LRUCache (options) {
  if (!(this instanceof LRUCache)) {
    return new LRUCache(options);
  }

  if (typeof options === 'number') {
    options = {max: options};
  }

  if (!options) {
    options = {};
  }

  this._max = options.max;

  if (!this._max || this._max <= 0) {
    this._max = Infinity;
  }

  this._lengthCalculator = options.length || naiveLength;

  if (typeof this._lengthCalculator !== "function") {
    this._lengthCalculator = naiveLength;
  }

  this._allowStale = options.stale || false;
  this._maxAge = options.maxAge || null;
  this._dispose = options.dispose;
  this.reset();
}

Object.defineProperty(LRUCache.prototype, "max", {
  set: function (mL) {
    if (!mL || mL <= 0) {
      mL = Infinity;
    }

    this._max = mL;

    if (this._length > this._max) {
      trim(this);
    }
  },
  get: function () {
    return this._max;
  },
  enumerable : true
});

Object.defineProperty(LRUCache.prototype, "lengthCalculator", {
  set: function (lC) {
    var key;

    if (typeof lC !== "function") {
      this._lengthCalculator = naiveLength;
      this._length = this._itemCount;
      for (key in this._cache) {
        this._cache[key].length = 1;
      }
    } else {
      this._lengthCalculator = lC;
      this._length = 0;
      for (key in this._cache) {
        this._cache[key].length = this._lengthCalculator(this._cache[key].value);
        this._length += this._cache[key].length;
      }
    }

    if (this._length > this._max) {
      trim(this);
    }
  },
  get: function () {
    return this._lengthCalculator;
  },
  enumerable : true
});

Object.defineProperty(LRUCache.prototype, "length", {
  get: function () {
    return this._length;
  },
  enumerable : true
});

Object.defineProperty(LRUCache.prototype, "itemCount", {
  get: function () {
    return this._itemCount;
  },
  enumerable : true
});

LRUCache.prototype.forEach = function (fn, thisp) {
  thisp = thisp || this;
  var i = 0, hit;

  for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) {
    if (this._lruList[k]) {
      hit = this._lruList[k];
      i ++;
      if (this._maxAge && (Date.now() - hit.now > this._maxAge)) {
        del(this, hit);
        if (!this._allowStale) {
          hit = undefined;
        }
      }
      if (hit) {
        fn.call(thisp, hit.value, hit.key, this);
      }
    }
  }
};

LRUCache.prototype.keys = function () {
  var keys = new Array(this._itemCount);
  var i = 0, hit;

  for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) {

    if (this._lruList[k]) {
      hit = this._lruList[k];
      keys[i++] = hit.key;
    }
  }

  return keys;
};

LRUCache.prototype.values = function () {
  var values = new Array(this._itemCount);
  var i = 0, hit;

  for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) {
    if (this._lruList[k]) {
      hit = this._lruList[k];
      values[i++] = hit.value;
    }
  }

  return values;
};

LRUCache.prototype.reset = function () {
  if (this._dispose && this._cache) {
    for (var k in this._cache) {
      this._dispose(k, this._cache[k].value);
    }
  }

  this._cache = Object.create(null);   //items by key
  this._lruList = Object.create(null); // items in order (use recency)
  this._mru = 0;    // most recently used
  this._lru = 0;    // least recently used
  this._length = 0; // number of items
  this._itemCount = 0;
};

LRUCache.prototype.dump = function () {
  return this._cache;
};

LRUCache.prototype.dumpLru = function () {
  return this._lruList;
};

LRUCache.prototype.set = function (key, value) {
  var len, age, hit;

  if (hOP(this._cache, key)) {

    if (this._dispose) {
      this._dispose(key, this._cache[key].value);
    }
    if (this._maxAge) {
      this._cache[key].now = Date.now();
    }

    this._cache[key].value = value;
    this.get(key);

    return true;
  }

  len = this._lengthCalculator(value);
  age = this._maxAge ? Date.now() : 0;
  hit = new Entry(key, value, this._mru++, len, age);

  // oversized objects fall out of cache
  if (hit.length > this._max) {
    if (this._dispose) {
      this._dispose(key, value);
    }

    return false;
  }

  this._length += hit.length;
  this._lruList[hit.lu] = this._cache[key] = hit;
  this._itemCount++;

  if (this._length > this._max) {
    trim(this);
  }
  return true;
};

LRUCache.prototype.has = function (key) {
  var hit = this._cache[key];

  if (!hOP(this._cache, key)) {
    return false;
  }

  if (this._maxAge && (Date.now() - hit.now > this._maxAge)) {
    return false;
  }
  return true;
};

LRUCache.prototype.get = function (key) {
  return get(this, key, true);
};

LRUCache.prototype.peek = function (key) {
  return get(this, key, false);
};

LRUCache.prototype.pop = function () {
  var hit = this._lruList[this._lru];
  del(this, hit);
  return hit || null;
};

LRUCache.prototype.del = function (key) {
  del(this, this._cache[key]);
};

function get(self, key, doUse) {
  var hit = self._cache[key];

  if (hit) {
    if (self._maxAge && (Date.now() - hit.now > self._maxAge)) {
      del(self, hit);
      if (!self._allowStale) {
        hit = undefined;
      }
    } else {
      if (doUse) {
        use(self, hit);
      }
    }
    if (hit) {
      hit = hit.value;
    }
  }

  return hit;
}

function use(self, hit) {
  shiftLU(self, hit);
  hit.lu = self._mru ++;
  self._lruList[hit.lu] = hit;
}

function trim(self) {
  while (self._lru < self._mru && self._length > self._max) {
    del(self, self._lruList[self._lru]);
  }
}

function shiftLU(self, hit) {
  delete self._lruList[hit.lu];
  while (self._lru < self._mru && !self._lruList[self._lru]) {
    self._lru ++;
  }
}

function del(self, hit) {
  if (hit) {
    if (self._dispose) {
      self._dispose(hit.key, hit.value);
    }
    self._length -= hit.length;
    self._itemCount --;
    delete self._cache[hit.key];
    shiftLU(self, hit);
  }
}

function Entry(key, value, lu, length, now) {
  this.key = key;
  this.value = value;
  this.lu = lu;
  this.length = length;
  this.now = now;
}
<|endoftext|>


<commit_before>define(['storage'], function (storageContainer) {
	var storage = storageContainer.getNamespace('customPatterns');

	return {
		updatePatterns: function (connector) {
			if (connector.originalMatches) {
				connector.matches = connector.originalMatches;
				delete connector.originalMatches;
			}
			if (storage.has(connector.label)) {
				connector.originalMatches = connector.matches;
				connector.matches = storage.get(connector.label);
			}
		},

		setPatterns: function (connector, patterns) {
			storage.set(connector.label, patterns);

			this.updatePatterns(connector);
		},

		resetPatterns: function (connector) {
			storage.remove(connector.label);

			this.updatePatterns(connector);
		}
	};
});
<commit_msg>Add 'use strict;' to customPatterns<commit_after>'use strict';
define(['storage'], function (storageContainer) {
	var storage = storageContainer.getNamespace('customPatterns');

	return {
		updatePatterns: function (connector) {
			if (connector.originalMatches) {
				connector.matches = connector.originalMatches;
				delete connector.originalMatches;
			}
			if (storage.has(connector.label)) {
				connector.originalMatches = connector.matches;
				connector.matches = storage.get(connector.label);
			}
		},

		setPatterns: function (connector, patterns) {
			storage.set(connector.label, patterns);

			this.updatePatterns(connector);
		},

		resetPatterns: function (connector) {
			storage.remove(connector.label);

			this.updatePatterns(connector);
		}
	};
});
<|endoftext|>


<commit_before>'use strict';

import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as DocumentActions from '../actions/documentActions';
import { generatePid } from '../utilities/general';
import KramdownParser from 'kramed';
import Highlight from 'highlight.js';
import Katex from 'katex';

const THROTTLE = 0;

const STATIC_PID = '_STATIC_PID'

function resizeTextareaOnInput (_event) {
  this.style.height = 'auto'
  this.style.height = `${this.scrollHeight}px`
  console.log('RESIZE')
}

// @TODO move this to constants file
export const Formats = {
  BOLD: 'BOLD',
  ITALIC: 'ITALIC',
  LINEBREAK: 'LINEBREAK',
  STRIKETHRU: 'STRIKETHRU',
  QUOTE: 'QUOTE',
  UL: 'UL',
  OL: 'OL',
  CODE: 'CODE',
  MATH: 'MATH'
};

/**
 * The `uniqueId` is used to pair together uneditable and editable document
 * sections if there is a need to do so.
 */
const propTypes = {
  text: React.PropTypes.string,
  editable: React.PropTypes.bool,
  style: React.PropTypes.object,
  uniqueId: React.PropTypes.string.isRequired
};

const defaultProps = {
  text: ''
};

class DocumentTextSection extends React.Component {

  constructor (props) {
    super(props);

    this.onKeyUp = this.onKeyUp.bind(this);
    this._internalPID = `STATIC_PID_${props.uniqueId}`;
    this.DOMParser = null;
    this.lastDocumentHeight = null;
    this.textThrottle = null;
    this.KramdownParser = KramdownParser.setOptions({
      gfm: true,
      tables: true,
      breaks: false,
      pedantic: false,
      sanitize: true,
      smartLists: true,
      smartypants: true,
      highlight: function (code) {
        return Highlight.highlightAuto(code).value;
      }
    });
  }

  componentDidMount () {
    document && document.querySelector(`.document-text-section[data-document-pid="${this.props.uniqueId}"]`).focus();
    this.DOMParser = new DOMParser();
    if (document.querySelector(`.-uneditable[data-document-pid="${this.props.uniqueId}"]`)) {
      this.lastResultHeight = document.querySelector(`.-uneditable[data-document-pid="${this.props.uniqueId}"]`).offsetHeight;
    } else {
      this.lastResultHeight = null;
    }

    const textareaElement = document.querySelector(`textarea.document-text-section[data-document-pid="${this.props.uniqueId}"]`)
    if (textareaElement) {
      // Set textarea height
      // let newHeight = document.querySelector(`.-uneditable[data-document-pid="${this.props.uniqueId}"]`).offsetHeight;
      // textareaElement.style.height = `${newHeight}px`;
      // Monkey patch textarea autoheight
      textareaElement.addEventListener('input', resizeTextareaOnInput, false)
    }

    // Initialize uneditable text section with transpiled text
    if (this.props) {
      let processedText = this.transpileRawTextData(this.props.text);
      document.querySelector(`[data-text-pid="${this._internalPID}"]`).innerHTML = processedText;
    }
  }

  componentWillUnmount () {
    const textareaElement = document.querySelector(`textarea.document-text-section[data-document-pid="${this.props.uniqueId}"]`)
    if (textareaElement) {
      // Remove event listener
      textareaElement.removeEventListener('input', resizeTextareaOnInput, false)
    }
  }

  componentWillReceiveProps (nextProps) {
    // Update uneditable text
    if (nextProps.text !== this.props.text) {
      let processedText = this.transpileRawTextData(nextProps.text);
      document.querySelector(`[data-text-pid="${this._internalPID}"]`).innerHTML = processedText;
    }

    // Adjust height of textarea
    // if (this.lastResultHeight !== document.querySelector(`.-uneditable[data-document-pid="${this.props.uniqueId}"]`).offsetHeight &&
    //     document.querySelector(`.-uneditable[data-document-pid="${this.props.uniqueId}"]`)) {
    //   let newHeight = document.querySelector(`.-uneditable[data-document-pid="${this.props.uniqueId}"]`).offsetHeight;
    //   document.querySelector(`textarea.document-text-section[data-document-pid="${this.props.uniqueId}"]`).style.height = `${newHeight}px`;
    //   this.lastResultHeight = document.querySelector(`.-uneditable[data-document-pid="${this.props.uniqueId}"]`).offsetHeight;
    // }

    // Check for formatting button being pressed in the banner
    // If the new formatting is coming in null, ignore it (we're resetting)
    if (!!nextProps.formatting && this.props.formatting !== nextProps.formatting) {
      this.replaceSelectedText(nextProps.formatting);
      this.props.documentActions.resetFormatting();
    }
  }

  expandDocument () {
    this.props.documentActions.expandDocument(!this.props.is_expanded);
  }

  purgeChildren (DOMNode) {
    while (DOMNode.firstChild) {
      DOMNode.removeChild(DOMNode.firstChild);
    }
  }

  replaceSelectedText (format) {
    var textNodeDOM = document.querySelector(`textarea.document-text-section[data-document-pid="${this.props.uniqueId}"]`);
    var selectedText = null;

    if (textNodeDOM && typeof textNodeDOM.selectionStart === 'number') {
      let startPos = textNodeDOM.selectionStart;
      let endPos = textNodeDOM.selectionEnd;
      selectedText = textNodeDOM.value.substring(startPos, endPos);

      let blob = {
        selectedText,
        node: textNodeDOM,
        start: startPos,
        end: endPos
      };

      this.formatParser(format, blob);
      this.props.documentActions.updateText(textNodeDOM.value);
    }
  }

  formatParser (format, blob) {
    var {
      start,
      end,
      node,
      selectedText
    } = blob;

    switch (format) {
      case Formats.BOLD:
        node.value = this.replaceString(node.value, `**${selectedText}**`, start, end);
        node.setSelectionRange(start + 2, end + 2);
        break;
      case Formats.ITALIC:
        node.value = this.replaceString(node.value, `_${selectedText}_`, start, end);
        node.setSelectionRange(start + 1, end + 1);
        break;
      case Formats.LINEBREAK:
        node.value = this.replaceString(node.value, `\n\n---\n\n${selectedText}`, start, end);
        node.setSelectionRange(start + 7, end + 7);
        break;
      case Formats.STRIKETHRU:
        node.value = this.replaceString(node.value, `~~${selectedText}~~`, start, end);
        node.setSelectionRange(start + 2, end + 2);
        break;
      case Formats.QUOTE:
        node.value = this.replaceString(node.value, `\n\n> ${selectedText}`, start, end);
        node.setSelectionRange(start + 4, start + 4);
        break;
      case Formats.UL:
        node.value = this.replaceString(node.value, `\n - ${selectedText}`, start, end);
        node.setSelectionRange(start + 4, start + 4);
        break;
      case Formats.OL:
        node.value = this.replaceString(node.value, `\n1. ${selectedText}`, start, end);
        node.setSelectionRange(start + 4, start + 4);
        break;
      case Formats.CODE:
        node.value = this.replaceString(node.value, `\`${selectedText}\``, start, end);
        node.setSelectionRange(start + 1, start + 1);
        break;
      case Formats.MATH:
        node.value = this.replaceString(node.value, `$${selectedText}$`, start, end);
        node.setSelectionRange(start + 2, start + 2);
        break;
      default:
        console.warn(`${format} is currently unsupported.`);
    }
  }

  onKeyUp (event) {
    var newText = event.target.value;
    clearTimeout(this.textThrottle);
    this.textThrottle = setTimeout(() => {
      this.props.documentActions.updateText(newText);
    }, THROTTLE);
  }

  getProcessedDOMNode (rawText) {
    var processedText = rawText;

    // Check if valid text (even with defaultProps, this can still come back null
    // upon instanciation)
    if (!processedText) {
      return processedText;
    }

    // Parse markdown as Kramdown
    processedText = this.KramdownParser(processedText);

    // Parse HTML into DOM node
    var parsedDOMNode = this.DOMParser.parseFromString(processedText, 'text/html');

    return parsedDOMNode;
  }

  replaceString (string, newText, start, end) {
    return string.slice(0, start) + newText + string.slice(end);
  }

  /**
   * It's important to note why we parse the text this way -- removing the expressions,
   * parsing the markdown, filling the expressions back in, and finally parsing the
   * expressions. This is because if we have something within an expression that
   * could be interpreted as markdown, the markdown parser will attempt to parse it:
   *
   * e.g.
   *
   *   Here is some _text_ and $n_i$ and some more _words_
   *
   * The `_` from `n_i` will connect with the first `_` in `_words_`, and the
   * markdown parser will break the expression attemping to parse this as markdown.
   * So we temporarily remove all of the expressions, parse the markdown, then put
   * them back into place to avoid this from happening.
   */
  transpileRawTextData (rawText) {
    if (!rawText) {
      return rawText;
    }

    // Store all of the expressions we extract from the raw text
    var purgedExpressions = [];

    // Extract expressions
    var expressionlessRawText = rawText.replace(/(\$)(?:(?=(\\?))\2.)*?\1/g, function (capturedGroup) {
      purgedExpressions.push(capturedGroup.replace(/([$]*)/g, ''));
      return '$ $';
    });

    // Parse markdown
    var markdownFormattedText = this.KramdownParser(expressionlessRawText);

    // Fill those expressions back in
    markdownFormattedText = markdownFormattedText.replace(/(\$)(?:(?=(\\?))\2.)*?\1/g, function (capturedGroup) {
      return `$${purgedExpressions.shift()}$`;
    });

    // Parse KaTeX
    try {
      let KatexParsedResult = markdownFormattedText.replace(/(\$)(?:(?=(\\?))\2.)*?\1/g, function (capturedGroup) {
        var cleanedString = capturedGroup.replace(/([$]*)/g, '');
        return Katex.renderToString(cleanedString);
      });
      return KatexParsedResult;
    } catch (err) {
      console.warn(err);
    }
    return markdownFormattedText;
  }

  render() {
    if (this.props.editable) {
      return (
        <textarea
          style={this.props.style}
          className="document-text-section"
          data-document-pid={this.props.uniqueId}
          onKeyUp={this.onKeyUp}
          defaultValue={this.props.text}
        />
      );
    }

    const expandDocumentClass = this.props.is_expanded ? '-expanded-document' : ''
    const expandIconClass = this.props.is_expanded ? '-icon-activated' : ''

    // We append on new DOM node when props change
    return (
      <div
        style={this.props.style}
        data-document-pid={this.props.uniqueId}
        className={`document-text-section -uneditable ${expandDocumentClass}`}
      >
        <span
          className={`icon-expand -icon-size -icon-spacing -expand-icon ${expandIconClass}`}
          onClick={() => this.expandDocument()}
        />
        <div data-text-pid={this._internalPID} />
      </div>
    );
  }
};

DocumentTextSection.propTypes = propTypes;
DocumentTextSection.defaultProps = defaultProps;

const actions = (dispatch) => ({
  documentActions: bindActionCreators(DocumentActions, dispatch)
});

const selector = (state) => ({
  is_expanded: state.document.is_expanded
});

export default connect(selector, actions)(DocumentTextSection);
<commit_msg>Remove console output<commit_after>'use strict';

import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as DocumentActions from '../actions/documentActions';
import { generatePid } from '../utilities/general';
import KramdownParser from 'kramed';
import Highlight from 'highlight.js';
import Katex from 'katex';

const THROTTLE = 0;

const STATIC_PID = '_STATIC_PID'

function resizeTextareaOnInput (_event) {
  this.style.height = 'auto'
  this.style.height = `${this.scrollHeight}px`
}

// @TODO move this to constants file
export const Formats = {
  BOLD: 'BOLD',
  ITALIC: 'ITALIC',
  LINEBREAK: 'LINEBREAK',
  STRIKETHRU: 'STRIKETHRU',
  QUOTE: 'QUOTE',
  UL: 'UL',
  OL: 'OL',
  CODE: 'CODE',
  MATH: 'MATH'
};

/**
 * The `uniqueId` is used to pair together uneditable and editable document
 * sections if there is a need to do so.
 */
const propTypes = {
  text: React.PropTypes.string,
  editable: React.PropTypes.bool,
  style: React.PropTypes.object,
  uniqueId: React.PropTypes.string.isRequired
};

const defaultProps = {
  text: ''
};

class DocumentTextSection extends React.Component {

  constructor (props) {
    super(props);

    this.onKeyUp = this.onKeyUp.bind(this);
    this._internalPID = `STATIC_PID_${props.uniqueId}`;
    this.DOMParser = null;
    this.lastDocumentHeight = null;
    this.textThrottle = null;
    this.KramdownParser = KramdownParser.setOptions({
      gfm: true,
      tables: true,
      breaks: false,
      pedantic: false,
      sanitize: true,
      smartLists: true,
      smartypants: true,
      highlight: function (code) {
        return Highlight.highlightAuto(code).value;
      }
    });
  }

  componentDidMount () {
    document && document.querySelector(`.document-text-section[data-document-pid="${this.props.uniqueId}"]`).focus();
    this.DOMParser = new DOMParser();
    if (document.querySelector(`.-uneditable[data-document-pid="${this.props.uniqueId}"]`)) {
      this.lastResultHeight = document.querySelector(`.-uneditable[data-document-pid="${this.props.uniqueId}"]`).offsetHeight;
    } else {
      this.lastResultHeight = null;
    }

    const textareaElement = document.querySelector(`textarea.document-text-section[data-document-pid="${this.props.uniqueId}"]`)
    if (textareaElement) {
      // Set textarea height
      // let newHeight = document.querySelector(`.-uneditable[data-document-pid="${this.props.uniqueId}"]`).offsetHeight;
      // textareaElement.style.height = `${newHeight}px`;
      // Monkey patch textarea autoheight
      textareaElement.addEventListener('input', resizeTextareaOnInput, false)
    }

    // Initialize uneditable text section with transpiled text
    if (this.props) {
      let processedText = this.transpileRawTextData(this.props.text);
      document.querySelector(`[data-text-pid="${this._internalPID}"]`).innerHTML = processedText;
    }
  }

  componentWillUnmount () {
    const textareaElement = document.querySelector(`textarea.document-text-section[data-document-pid="${this.props.uniqueId}"]`)
    if (textareaElement) {
      // Remove event listener
      textareaElement.removeEventListener('input', resizeTextareaOnInput, false)
    }
  }

  componentWillReceiveProps (nextProps) {
    // Update uneditable text
    if (nextProps.text !== this.props.text) {
      let processedText = this.transpileRawTextData(nextProps.text);
      document.querySelector(`[data-text-pid="${this._internalPID}"]`).innerHTML = processedText;
    }

    // Adjust height of textarea
    // if (this.lastResultHeight !== document.querySelector(`.-uneditable[data-document-pid="${this.props.uniqueId}"]`).offsetHeight &&
    //     document.querySelector(`.-uneditable[data-document-pid="${this.props.uniqueId}"]`)) {
    //   let newHeight = document.querySelector(`.-uneditable[data-document-pid="${this.props.uniqueId}"]`).offsetHeight;
    //   document.querySelector(`textarea.document-text-section[data-document-pid="${this.props.uniqueId}"]`).style.height = `${newHeight}px`;
    //   this.lastResultHeight = document.querySelector(`.-uneditable[data-document-pid="${this.props.uniqueId}"]`).offsetHeight;
    // }

    // Check for formatting button being pressed in the banner
    // If the new formatting is coming in null, ignore it (we're resetting)
    if (!!nextProps.formatting && this.props.formatting !== nextProps.formatting) {
      this.replaceSelectedText(nextProps.formatting);
      this.props.documentActions.resetFormatting();
    }
  }

  expandDocument () {
    this.props.documentActions.expandDocument(!this.props.is_expanded);
  }

  purgeChildren (DOMNode) {
    while (DOMNode.firstChild) {
      DOMNode.removeChild(DOMNode.firstChild);
    }
  }

  replaceSelectedText (format) {
    var textNodeDOM = document.querySelector(`textarea.document-text-section[data-document-pid="${this.props.uniqueId}"]`);
    var selectedText = null;

    if (textNodeDOM && typeof textNodeDOM.selectionStart === 'number') {
      let startPos = textNodeDOM.selectionStart;
      let endPos = textNodeDOM.selectionEnd;
      selectedText = textNodeDOM.value.substring(startPos, endPos);

      let blob = {
        selectedText,
        node: textNodeDOM,
        start: startPos,
        end: endPos
      };

      this.formatParser(format, blob);
      this.props.documentActions.updateText(textNodeDOM.value);
    }
  }

  formatParser (format, blob) {
    var {
      start,
      end,
      node,
      selectedText
    } = blob;

    switch (format) {
      case Formats.BOLD:
        node.value = this.replaceString(node.value, `**${selectedText}**`, start, end);
        node.setSelectionRange(start + 2, end + 2);
        break;
      case Formats.ITALIC:
        node.value = this.replaceString(node.value, `_${selectedText}_`, start, end);
        node.setSelectionRange(start + 1, end + 1);
        break;
      case Formats.LINEBREAK:
        node.value = this.replaceString(node.value, `\n\n---\n\n${selectedText}`, start, end);
        node.setSelectionRange(start + 7, end + 7);
        break;
      case Formats.STRIKETHRU:
        node.value = this.replaceString(node.value, `~~${selectedText}~~`, start, end);
        node.setSelectionRange(start + 2, end + 2);
        break;
      case Formats.QUOTE:
        node.value = this.replaceString(node.value, `\n\n> ${selectedText}`, start, end);
        node.setSelectionRange(start + 4, start + 4);
        break;
      case Formats.UL:
        node.value = this.replaceString(node.value, `\n - ${selectedText}`, start, end);
        node.setSelectionRange(start + 4, start + 4);
        break;
      case Formats.OL:
        node.value = this.replaceString(node.value, `\n1. ${selectedText}`, start, end);
        node.setSelectionRange(start + 4, start + 4);
        break;
      case Formats.CODE:
        node.value = this.replaceString(node.value, `\`${selectedText}\``, start, end);
        node.setSelectionRange(start + 1, start + 1);
        break;
      case Formats.MATH:
        node.value = this.replaceString(node.value, `$${selectedText}$`, start, end);
        node.setSelectionRange(start + 2, start + 2);
        break;
      default:
        console.warn(`${format} is currently unsupported.`);
    }
  }

  onKeyUp (event) {
    var newText = event.target.value;
    clearTimeout(this.textThrottle);
    this.textThrottle = setTimeout(() => {
      this.props.documentActions.updateText(newText);
    }, THROTTLE);
  }

  getProcessedDOMNode (rawText) {
    var processedText = rawText;

    // Check if valid text (even with defaultProps, this can still come back null
    // upon instanciation)
    if (!processedText) {
      return processedText;
    }

    // Parse markdown as Kramdown
    processedText = this.KramdownParser(processedText);

    // Parse HTML into DOM node
    var parsedDOMNode = this.DOMParser.parseFromString(processedText, 'text/html');

    return parsedDOMNode;
  }

  replaceString (string, newText, start, end) {
    return string.slice(0, start) + newText + string.slice(end);
  }

  /**
   * It's important to note why we parse the text this way -- removing the expressions,
   * parsing the markdown, filling the expressions back in, and finally parsing the
   * expressions. This is because if we have something within an expression that
   * could be interpreted as markdown, the markdown parser will attempt to parse it:
   *
   * e.g.
   *
   *   Here is some _text_ and $n_i$ and some more _words_
   *
   * The `_` from `n_i` will connect with the first `_` in `_words_`, and the
   * markdown parser will break the expression attemping to parse this as markdown.
   * So we temporarily remove all of the expressions, parse the markdown, then put
   * them back into place to avoid this from happening.
   */
  transpileRawTextData (rawText) {
    if (!rawText) {
      return rawText;
    }

    // Store all of the expressions we extract from the raw text
    var purgedExpressions = [];

    // Extract expressions
    var expressionlessRawText = rawText.replace(/(\$)(?:(?=(\\?))\2.)*?\1/g, function (capturedGroup) {
      purgedExpressions.push(capturedGroup.replace(/([$]*)/g, ''));
      return '$ $';
    });

    // Parse markdown
    var markdownFormattedText = this.KramdownParser(expressionlessRawText);

    // Fill those expressions back in
    markdownFormattedText = markdownFormattedText.replace(/(\$)(?:(?=(\\?))\2.)*?\1/g, function (capturedGroup) {
      return `$${purgedExpressions.shift()}$`;
    });

    // Parse KaTeX
    try {
      let KatexParsedResult = markdownFormattedText.replace(/(\$)(?:(?=(\\?))\2.)*?\1/g, function (capturedGroup) {
        var cleanedString = capturedGroup.replace(/([$]*)/g, '');
        return Katex.renderToString(cleanedString);
      });
      return KatexParsedResult;
    } catch (err) {
      console.warn(err);
    }
    return markdownFormattedText;
  }

  render() {
    if (this.props.editable) {
      return (
        <textarea
          style={this.props.style}
          className="document-text-section"
          data-document-pid={this.props.uniqueId}
          onKeyUp={this.onKeyUp}
          defaultValue={this.props.text}
        />
      );
    }

    const expandDocumentClass = this.props.is_expanded ? '-expanded-document' : ''
    const expandIconClass = this.props.is_expanded ? '-icon-activated' : ''

    // We append on new DOM node when props change
    return (
      <div
        style={this.props.style}
        data-document-pid={this.props.uniqueId}
        className={`document-text-section -uneditable ${expandDocumentClass}`}
      >
        <span
          className={`icon-expand -icon-size -icon-spacing -expand-icon ${expandIconClass}`}
          onClick={() => this.expandDocument()}
        />
        <div data-text-pid={this._internalPID} />
      </div>
    );
  }
};

DocumentTextSection.propTypes = propTypes;
DocumentTextSection.defaultProps = defaultProps;

const actions = (dispatch) => ({
  documentActions: bindActionCreators(DocumentActions, dispatch)
});

const selector = (state) => ({
  is_expanded: state.document.is_expanded
});

export default connect(selector, actions)(DocumentTextSection);
<|endoftext|>


<commit_before>var painless = require('../../assertion/painless')
var test = painless.createGroup('Test object/stampit::deep-props')
var t = painless.assert
var stampit = require('../../../src/object/stamp')

// Props safety

test('Stamp deepProps deep cloned for object created', function () {
  var deep = { foo: 'foo', bar: 'bar' };
  var stamp1 = stampit().deepProps({ deep: deep, foo: 'foo' });
  // var stamp1 = stampit({ deepProps: { deep: deep, foo: 'foo' } });
  var stamp2 = stampit({ deepProps: { deep: deep, foo: 'foo' } });

  var o1 = stamp1();
  var o2 = stamp1();

  o1.foo = 'another value';
  t.ne(o1.foo, o2.foo);
  o1.deep.foo = 'another value';
  t.ne(o1.deep.foo, o2.deep.foo);

  o1 = stamp2();
  o2 = stamp2();
  o1.foo = 'another value';
  t.ne(o1.foo, o2.foo);
  o1.deep.foo = 'another value';
  t.ne(o1.deep.foo, o2.deep.foo);
});

test('stamp.deepProps(deepProps) deep merge into stamp', () => {
  const stamp = stampit()
    .deepProps({ deep: { foo: 'foo', bar: 'bar' }, foo: 'foo', bar: 'bar' })
    .deepProps({ deep: { foo: 'override', baz: 'baz' }, foo: 'override', baz: 'baz' });
  const o = stamp();

  t.is(o.foo, 'override');
  t.is(o.bar, 'bar');
  t.is(o.baz, 'baz');
  t.is(o.deep.foo, 'override');
  t.is(o.deep.bar, 'bar');
  t.is(o.deep.baz, 'baz');
});

test('stamp.compose() deep merge deepProps', () => {
  const stamp = stampit({ deepProps: { deep: { foo: 'foo', bar: 'bar' }, foo: 'foo', bar: 'bar' } })
    .compose(stampit({ deepProps: { deep: { foo: 'override', baz: 'baz' }, foo: 'override', baz: 'baz' } }));
  const o = stamp();

  t.is(o.foo, 'override');
  t.is(o.bar, 'bar');
  t.is(o.baz, 'baz');
  t.is(o.deep.foo, 'override');
  t.is(o.deep.bar, 'bar');
  t.is(o.deep.baz, 'baz');
});
<commit_msg>update test stamp/deep-props — stampit v3, lint<commit_after>var painless = require('../../assertion/painless')
var test = painless.createGroup('Test object/stampit::deep-props')
var t = painless.assert
var stampit = require('../../../src/object/stamp')

// Props safety

test('Stamp deepProps deep cloned for object created', function () {
  var deep = {foo: 'foo', bar: 'bar'}
  var stamp1 = stampit().deepProps({deep: deep, foo: 'foo'})
  var stamp2 = stampit().deepProps({deep: deep, foo: 'foo'})

  var o1 = stamp1()
  var o2 = stamp1()

  o1.foo = 'another value'
  t.ne(o1.foo, o2.foo)
  o1.deep.foo = 'another value'
  t.ne(o1.deep.foo, o2.deep.foo)

  o1 = stamp2()
  o2 = stamp2()
  o1.foo = 'another value'
  t.ne(o1.foo, o2.foo)
  o1.deep.foo = 'another value'
  t.ne(o1.deep.foo, o2.deep.foo)
})

test('stamp.deepProps(deepProps) deep merge into stamp', () => {
  const stamp = stampit()
    .deepProps({deep: {foo: 'foo', bar: 'bar'}, foo: 'foo', bar: 'bar'})
    .deepProps({deep: {foo: 'override', baz: 'baz'}, foo: 'override', baz: 'baz'})
  const o = stamp()

  t.is(o.foo, 'override')
  t.is(o.bar, 'bar')
  t.is(o.baz, 'baz')
  t.is(o.deep.foo, 'override')
  t.is(o.deep.bar, 'bar')
  t.is(o.deep.baz, 'baz')
})

test('stamp.compose() deep merge deepProps', () => {
  const stamp = stampit()
    .deepProps({deep: {foo: 'foo', bar: 'bar'}, foo: 'foo', bar: 'bar'})
    .compose(stampit().deepProps({deep: {foo: 'override', baz: 'baz'}, foo: 'override', baz: 'baz'}))

  const o = stamp()

  t.is(o.foo, 'override')
  t.is(o.bar, 'bar')
  t.is(o.baz, 'baz')
  t.is(o.deep.foo, 'override')
  t.is(o.deep.bar, 'bar')
  t.is(o.deep.baz, 'baz')
})
<|endoftext|>


<commit_before>const config = require('../userconfig/config.json'); // Import configuration

exports.main = function(selfbot, msg, msgArray) { // Export command function
	var command = "shutdown";
	msg.edit("Selfbot shutting down!").then(msg => msg.delete(1000));
	// Edit the command call and set auto-delete to 1s
	setTimeout(function(){
		selfbot.destroy().then(console.log("Motiful signed out!"); process.exit(0));
		// Sign out motiful and then end the node process
	}, 2000);
	// Set timeout for shutting down the selfbot to 2sec after the command is triggered.
};

exports.desc = "Shut down the selfbot remotely"; // Export command description
exports.syntax = ""; // Export command syntax <commit_msg>Fix shutdown command<commit_after>const config = require('../userconfig/config.json'); // Import configuration

exports.main = function(selfbot, msg, msgArray) { // Export command function
	var command = "shutdown";
	msg.edit("Selfbot shutting down!").then(msg => msg.delete(1000));
	// Edit the command call and set auto-delete to 1s
	setTimeout(function(){
		selfbot.destroy().then(()=>{console.log("Motiful signed out!"); process.exit(0)});
		// Sign out motiful and then end the node process
	}, 2000);
	// Set timeout for shutting down the selfbot to 2sec after the command is triggered.
};

exports.desc = "Shut down the selfbot remotely"; // Export command description
exports.syntax = ""; // Export command syntax <|endoftext|>


<commit_before>module.exports = {
    title: 'Gerbil Scheme',
    description: '',
    themeConfig: {
        nav: [
          { text: 'Home', link: '/' },
          { text: 'Guide', link: '/guide/' },
          { text: 'Tutorials', link: '/tutorials/' },
          { text: 'StdLib', link: '/stdlib/' },
        ],
        sidebarDepth: 2,
        sidebar: {
          '/guide/': [
            {
              collapsable: false,
              title: 'Guide',
              children: ['', 'intro', 'shell', 'package-manager', 'ffi', 'build', 'profiler', 'srfi', 'core-prelude', 'r7rs', 'bootstrap', 'nix']
            }
          ],
          '/stdlib/': [
            {
              collapsable: false,
              title: 'Gerbil API Reference',
              children: ['', 'actor', 'coroutine', 'crypto', 'db', 'debug', 'errors', 'events', 'format', 'generic', 'getopt', 'iterators',
              'lazy', 'logger', 'make', 'misc', 'net', 'os', 'parser', 'regexp', 'sort', 'srfi', 'stxparam', 'sugar', 'test', 'text',
              'web', 'xml']
            }
          ]
        },
        // Assumes GitHub. Can also be a full GitLab url.
        repo: 'vyzo/gerbil',
        // Customising the header label
        // Defaults to "GitHub"/"GitLab"/"Bitbucket" depending on `themeConfig.repo`
        repoLabel: 'Contribute!',

        // Optional options for generating "Edit this page" link

        // if your docs are in a different repo from your main project:
        docsRepo: 'vyzo/gerbil',
        // if your docs are not at the root of the repo:
        docsDir: 'doc',
        // if your docs are in a specific branch (defaults to 'master'):
        docsBranch: 'master',
        // defaults to false, set to true to enable
        editLinks: true,
        // custom text for edit link. Defaults to "Edit this page"
        editLinkText: 'Help us improve this page!',
      },
      current_version: 'v0.12'
  }<commit_msg>add getting-started to the guide sidebar<commit_after>module.exports = {
    title: 'Gerbil Scheme',
    description: '',
    themeConfig: {
        nav: [
          { text: 'Home', link: '/' },
          { text: 'Guide', link: '/guide/' },
          { text: 'Tutorials', link: '/tutorials/' },
          { text: 'StdLib', link: '/stdlib/' },
        ],
        sidebarDepth: 2,
        sidebar: {
          '/guide/': [
            {
              collapsable: false,
              title: 'Guide',
                children: ['', 'intro', 'getting-started', 'shell', 'package-manager', 'ffi', 'build', 'profiler', 'bootstrap', 'nix', 'r7rs', 'srfi', 'core-prelude']
            }
          ],
          '/stdlib/': [
            {
              collapsable: false,
              title: 'Gerbil Standard Library Reference',
              children: ['', 'actor', 'coroutine', 'crypto', 'db', 'debug', 'errors', 'events', 'format', 'generic', 'getopt', 'iterators',
              'lazy', 'logger', 'make', 'misc', 'net', 'os', 'parser', 'regexp', 'sort', 'srfi', 'stxparam', 'sugar', 'test', 'text',
              'web', 'xml']
            }
          ]
        },
        // Assumes GitHub. Can also be a full GitLab url.
        repo: 'vyzo/gerbil',
        // Customising the header label
        // Defaults to "GitHub"/"GitLab"/"Bitbucket" depending on `themeConfig.repo`
        repoLabel: 'Contribute!',

        // Optional options for generating "Edit this page" link

        // if your docs are in a different repo from your main project:
        docsRepo: 'vyzo/gerbil',
        // if your docs are not at the root of the repo:
        docsDir: 'doc',
        // if your docs are in a specific branch (defaults to 'master'):
        docsBranch: 'master',
        // defaults to false, set to true to enable
        editLinks: true,
        // custom text for edit link. Defaults to "Edit this page"
        editLinkText: 'Help us improve this page!',
      },
      current_version: 'v0.12'
  }
<|endoftext|>