<commit_before>String.inject({
	endsWith: function(end) {
		return end != null && this.length >= end.length
				&& this.substring(this.length - end.length) == end;
	},

	startsWith: function(start) {
		return start != null && this.length >= start.length
				&& this.substring(0, start.length) == start;
	},

	indexOfPattern: function(pattern, start) {
		start = start || 0;
		var res = this.substring(start).search(pattern);
		return res == -1 ? -1 : res + start;
	},

	lastIndexOfPattern: function(pattern, start) {
		start = start === undefined ? this.length : start;
		var res = this.substring(0, start).reverse().indexOfPattern(pattern);
		return res == -1 ? -1 : this.length - res + 1;
	},

	reverse: function() {
		return new java.lang.StringBuffer(this).reverse().toString();
//		Pure JS: return this.split('').reverse().join('');
	},

	unaccent: function() {
		// Use encodeEntities instead of encode, so no
 are produced
		str = encodeEntities(this);
		// Convert to html entities, replace them by the normal unnaccented chars and convert back
		str = str.replace(/&(.)(?:uml);/gi, '$1e'); // replace ö with oe, ä with ae, etc.
		str = str.replace(/&(.)(?:acute|grave|cedil|circ|ring|tilde);/gi, '$1'); // replace é with e, à with a, etc.
		return Packages.org.htmlparser.util.Translate.decode(str);
	},

	urlize: function() {
		return this.unaccent().replace(/([^a-z0-9\.]+)/gi, '-').trim('-').toLowerCase();
	},

	truncate: function(length, suffix, preserveWords) {
		if (this.length < length)
			return this;
		suffix = suffix || '';
		length -= suffix.length;
		var part = this.substring(0, length);
		if (preserveWords && !/\s/.test(this[length])) {
			var i = part.lastIndexOfPattern(/\s/);
			if (i > 0)
				part = part.substring(0, i - 1);
		}
		return part.trim() + suffix;
	},

	stripTags: function() {
		return stripTags(this);
	},

	/**
	 * The name wordwrap is not quite right, since all it does is forcing too long
	 * words appart with a space. The wrapping is then done by the HTML engine...
	 */
	wordwrap: function(width) {
		if (this.length > width) {
			// See if we can break at special chars. If not, force a break:
			var st = new java.util.StringTokenizer(this, ' \t\n\r\f!#$%&()*+,-./:;<=>?@[\]^_`{|}~', true);
			res.push();
			var length = 0;
			while (st.hasMoreTokens()) {
				var token = st.nextToken();
				if (length + token.length > width) {
					if (!length) { // we haven't had a word yet, so force break the current token
						res.write(token.substring(0, width));
						// the second part will be written bellow
						token = token.substring(width);
					}
					res.write(' ');
					length = 0;
				}
				res.write(token);
				length += token.length;
			}
			return res.pop();
		}
		return this;
	},

	replaceAll: function(search, replace) {
		return String.replaceAll(this, search, replace);
	},

	shuffle: function() {
		var buf = new java.lang.StringBuffer(this);
		for (var i = 0; i < this.length; i++) {
			var dest = Math.floor(Math.random() * this.length);
			var tmp = buf.charAt(i);
			buf.setCharAt(i, buf.charAt(dest));
			buf.setCharAt(dest, tmp);
		}
		return buf.toString();
	},

	/*
	 * Title Caps
	 *
	 * Ported to JavaScript By John Resig - http://ejohn.org/ - 21 May 2008
	 * Original by John Gruber - http://daringfireball.net/ - 10 May 2008
	 * License: http://www.opensource.org/licenses/mit-license.php
	 */
	toTitleCase: function() {
		var small = '(s|a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|v[.]?|via|vs[.]?)';
		var punct = '([!"#$%&\'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]*)';

		function lower(word) {
			return word.toLowerCase();
		}

		function upper(word) {
			return word.substr(0,1).toUpperCase() + word.substr(1);
		}

		// “ = \u201c, ’ = \u2019
		var parts = [], split = /[:.;?!] |(?: |^)["\u201c]/g, index = 0;

		while (true) {
			var m = split.exec(this);
			parts.push(this.substring(index, m ? m.index : this.length)
				.replace(/\b([A-Za-z][a-z.'\u2019]*)\b/g, function(all) {
					return /[A-Za-z]\.[A-Za-z]/.test(all) ? all : upper(all);
				})
				.replace(new RegExp('\\b' + small + '\\b', 'ig'), lower)
				.replace(new RegExp('^' + punct + small + '\\b', 'ig'), function(all, punct, word) {
					return punct + upper(word);
				})
				.replace(new RegExp('\\b' + small + punct + '$', 'ig'), upper));
			index = split.lastIndex;
			if (m) parts.push(m[0]);
			else break;
		}

		return parts.join('').replace(/ V(s?)\. /ig, ' v$1. ')
			.replace(/(['\u2019])S\b/ig, '$1s')
			.replace(/\b(AT&T|Q&A)\b/ig, function(all) {
				return all.toUpperCase();
			});
	},

	statics: {
		replaceAll: Packages.org.mortbay.util.StringUtil.replace
	}
});
<commit_msg>Do not allow '.' in urlized strings, since they do not work in CSS names, and producig CSS compatible strings is beneficial in many ways.<commit_after>String.inject({
	endsWith: function(end) {
		return end != null && this.length >= end.length
				&& this.substring(this.length - end.length) == end;
	},

	startsWith: function(start) {
		return start != null && this.length >= start.length
				&& this.substring(0, start.length) == start;
	},

	indexOfPattern: function(pattern, start) {
		start = start || 0;
		var res = this.substring(start).search(pattern);
		return res == -1 ? -1 : res + start;
	},

	lastIndexOfPattern: function(pattern, start) {
		start = start === undefined ? this.length : start;
		var res = this.substring(0, start).reverse().indexOfPattern(pattern);
		return res == -1 ? -1 : this.length - res + 1;
	},

	reverse: function() {
		return new java.lang.StringBuffer(this).reverse().toString();
//		Pure JS: return this.split('').reverse().join('');
	},

	unaccent: function() {
		// Use encodeEntities instead of encode, so no
 are produced
		str = encodeEntities(this);
		// Convert to html entities, replace them by the normal unnaccented chars and convert back
		str = str.replace(/&(.)(?:uml);/gi, '$1e'); // replace ö with oe, ä with ae, etc.
		str = str.replace(/&(.)(?:acute|grave|cedil|circ|ring|tilde);/gi, '$1'); // replace é with e, à with a, etc.
		return Packages.org.htmlparser.util.Translate.decode(str);
	},

	urlize: function() {
		return this.unaccent().replace(/([^a-z0-9]+)/gi, '-').trim('-').toLowerCase();
	},

	truncate: function(length, suffix, preserveWords) {
		if (this.length < length)
			return this;
		suffix = suffix || '';
		length -= suffix.length;
		var part = this.substring(0, length);
		if (preserveWords && !/\s/.test(this[length])) {
			var i = part.lastIndexOfPattern(/\s/);
			if (i > 0)
				part = part.substring(0, i - 1);
		}
		return part.trim() + suffix;
	},

	stripTags: function() {
		return stripTags(this);
	},

	/**
	 * The name wordwrap is not quite right, since all it does is forcing too long
	 * words appart with a space. The wrapping is then done by the HTML engine...
	 */
	wordwrap: function(width) {
		if (this.length > width) {
			// See if we can break at special chars. If not, force a break:
			var st = new java.util.StringTokenizer(this, ' \t\n\r\f!#$%&()*+,-./:;<=>?@[\]^_`{|}~', true);
			res.push();
			var length = 0;
			while (st.hasMoreTokens()) {
				var token = st.nextToken();
				if (length + token.length > width) {
					if (!length) { // we haven't had a word yet, so force break the current token
						res.write(token.substring(0, width));
						// the second part will be written bellow
						token = token.substring(width);
					}
					res.write(' ');
					length = 0;
				}
				res.write(token);
				length += token.length;
			}
			return res.pop();
		}
		return this;
	},

	replaceAll: function(search, replace) {
		return String.replaceAll(this, search, replace);
	},

	shuffle: function() {
		var buf = new java.lang.StringBuffer(this);
		for (var i = 0; i < this.length; i++) {
			var dest = Math.floor(Math.random() * this.length);
			var tmp = buf.charAt(i);
			buf.setCharAt(i, buf.charAt(dest));
			buf.setCharAt(dest, tmp);
		}
		return buf.toString();
	},

	/*
	 * Title Caps
	 *
	 * Ported to JavaScript By John Resig - http://ejohn.org/ - 21 May 2008
	 * Original by John Gruber - http://daringfireball.net/ - 10 May 2008
	 * License: http://www.opensource.org/licenses/mit-license.php
	 */
	toTitleCase: function() {
		var small = '(s|a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|v[.]?|via|vs[.]?)';
		var punct = '([!"#$%&\'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]*)';

		function lower(word) {
			return word.toLowerCase();
		}

		function upper(word) {
			return word.substr(0,1).toUpperCase() + word.substr(1);
		}

		// “ = \u201c, ’ = \u2019
		var parts = [], split = /[:.;?!] |(?: |^)["\u201c]/g, index = 0;

		while (true) {
			var m = split.exec(this);
			parts.push(this.substring(index, m ? m.index : this.length)
				.replace(/\b([A-Za-z][a-z.'\u2019]*)\b/g, function(all) {
					return /[A-Za-z]\.[A-Za-z]/.test(all) ? all : upper(all);
				})
				.replace(new RegExp('\\b' + small + '\\b', 'ig'), lower)
				.replace(new RegExp('^' + punct + small + '\\b', 'ig'), function(all, punct, word) {
					return punct + upper(word);
				})
				.replace(new RegExp('\\b' + small + punct + '$', 'ig'), upper));
			index = split.lastIndex;
			if (m) parts.push(m[0]);
			else break;
		}

		return parts.join('').replace(/ V(s?)\. /ig, ' v$1. ')
			.replace(/(['\u2019])S\b/ig, '$1s')
			.replace(/\b(AT&T|Q&A)\b/ig, function(all) {
				return all.toUpperCase();
			});
	},

	statics: {
		replaceAll: Packages.org.mortbay.util.StringUtil.replace
	}
});
<|endoftext|>


<commit_before>"use strict";

var Freya = Freya || {};

// Get real width and height even for hidden element
Freya.getRealDimensions = function ($el, outer) {
  if ($el.length == 0) {
    return false;
  }
  var $clone = $el.clone()
    .show()
    .css("visibility","hidden")
    .appendTo("body");
  var result = {
    width:      (outer) ? $clone.outerWidth() : $clone.innerWidth(),
    height:     (outer) ? $clone.outerHeight() : $clone.innerHeight(),
    offsetTop:  $clone.offset().top,
    offsetLeft: $clone.offset().left
  };
  $clone.remove();
  return result;
};

// Clean MSWord tags
Freya.cleanWordHtml = function(input) {
    // 1. remove line breaks / Mso classes
    var stringStripper = /(\n|\r| class=(")?Mso[a-zA-Z]+(")?)/g;
    var output = input.replace(stringStripper, ' ');

    // 2. strip Word generated HTML comments
    var commentSripper = new RegExp('', 'g');
    var output = output.replace(commentSripper, '');

    // 3. remove
    var output = output.replace(/ /gi, '');
    return output;
}

Freya.removeAttributes = function (value) {
    var content = $('
').html(value);
    $(content).find('*').each(function(){
        $(this).removeAttributes();
    });
    return $(content)[0].outerHTML;
}

jQuery.fn.removeAttributes = function() {
    return this.each(function() {
        var attributes = $.map(this.attributes, function(item) {
            return item.name;
        });
        var tag = $(this);
        $.each(attributes, function(i, item) {
            if (item !== 'href'){
                tag.removeAttr(item);
            }
        });
    });
}

// Left only valid tags in the string
Freya.sanitize_html = function(value, valid_tags) {
    value = Freya.cleanWordHtml(value);
    value =  Freya.removeAttributes(value);
    valid_tags.join('')
            .toLowerCase()
            .match(/<[a-z][a-z0-9]*>/g);
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
    return value.replace(tags, function($0, $1) {
        return valid_tags.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
    });
}
//// Tests for sanitize_html
//var str;
//valid_tags = ['', '
', '
', '
', '
', '
', '
', '', '', '
', '']
//str = '
This text should be valid. ' +
//              'Let\'s have em, ,' +
//              'and br here ->>
 <<-
';
//console.log(Freya.sanitize_html(str, valid_tags));
//if (sanitize_html(str, valid_tags) == str) console.log('pass')
//else console.log('error');
//
//str = 'Lists test:

aa

bb

aa

bb

';
//console.log(sanitize_html(str, valid_tags));
//if (sanitize_html(str, valid_tags) == str) console.log('pass')
//else console.log('error');
//
//str = 'Test links: Here is the link';
//console.log(sanitize_html(str, valid_tags));
//if (sanitize_html(str, valid_tags) == str) console.log('pass')
//else console.log('error');
//
//str = 'Images are not valid: ';
//console.log(sanitize_html(str, valid_tags));
//if (sanitize_html(str, valid_tags) != str) console.log('pass')
//else console.log('error');
//
//str = 'As well as js scripts: ';
//console.log(sanitize_html(str, valid_tags));
//if (sanitize_html(str, valid_tags) != str) console.log('pass')
//else console.log('error');
<commit_msg>Update helpers.js<commit_after>"use strict";

var Freya = Freya || {};

// Get real width and height even for hidden element
Freya.getRealDimensions = function ($el, outer) {
  if ($el.length == 0) {
    return false;
  }
  var $clone = $el.clone()
    .show()
    .css("visibility","hidden")
    .appendTo("body");
  var result = {
    width:      (outer) ? $clone.outerWidth() : $clone.innerWidth(),
    height:     (outer) ? $clone.outerHeight() : $clone.innerHeight(),
    offsetTop:  $clone.offset().top,
    offsetLeft: $clone.offset().left
  };
  $clone.remove();
  return result;
};

// Clean MSWord tags
Freya.cleanWordHtml = function(input) {
    // 1. remove line breaks / Mso classes
    var stringStripper = /(\n|\r| class=(")?Mso[a-zA-Z]+(")?)/g;
    var output = input.replace(stringStripper, ' ');

    // 2. strip Word generated HTML comments
    var commentSripper = new RegExp('', 'g');
    var output = output.replace(commentSripper, '');

    // 3. remove
    var output = output.replace(/ /gi, '');
    return output;
};

Freya.removeAttributes = function (value) {
    var content = $('
').html(value);
    $(content).find('*').each(function(){
        $(this).removeAttributes();
    });
    return $(content)[0].outerHTML;
};

jQuery.fn.removeAttributes = function() {
    return this.each(function() {
        var attributes = $.map(this.attributes, function(item) {
            return item.name;
        });
        var tag = $(this);
        $.each(attributes, function(i, item) {
            if (item !== 'href'){
                tag.removeAttr(item);
            }
        });
    });
};

// Left only valid tags in the string
Freya.sanitize_html = function(value, allowedTags) {
    value = Freya.cleanWordHtml(value);
    value = Freya.removeAttributes(value);
    if (allowedTags.indexOf("br")) {
      allowedTags.push("br /");
      allowedTags.push("br/");
    }
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi;
    return value.replace(tags, function($0, $1) {
        return allowedTags.indexOf($1.toLowerCase()) > -1 ? $0 : '';
    });
};

// Tests for sanitize_html
//var str, newstr;
//var allowedTags = ['em', 'p', 'ul', 'ol', 'li', 'br', 'a', 'span', 'div', 'strong'];
//
//str = 'Valid tags: em,
p
,

 ' +
//      'span
div
 strong ';
//newstr = Freya.sanitize_html(str, allowedTags);
//console.log('str:', str);
//console.log('new:', newstr);
//if (newstr == str) console.log('pass');
//else console.log('error');
//
//str = '

';
//newstr = Freya.sanitize_html(str, allowedTags);
//console.log('str:', str);
//console.log('new:', newstr);
//if (newstr == '

') console.log('pass');
//else console.log('error');
//
//str = 'Test links: Here is the link';
//newstr = Freya.sanitize_html(str, allowedTags);
//console.log('str:', str);
//console.log('new:', newstr);
//if (newstr == str) console.log('pass');
//else console.log('error');
//
//str = 'Test links with attr: Here is the link';
//newstr = Freya.sanitize_html(str, allowedTags);
//console.log('str:', str);
//console.log('new:', newstr);
//if (newstr != str) console.log('pass');
//else console.log('error');
//
//str = 'Images are not valid: ';
//newstr = Freya.sanitize_html(str, allowedTags);
//console.log('str:', str);
//console.log('new:', newstr);
//if (newstr != str) console.log('pass');
//else console.log('error');
//
//str = 'As well as js scripts and frames:  iframe';
//newstr = Freya.sanitize_html(str, allowedTags);
//console.log('str:', str);
//console.log('newstr:', newstr);
//newstr = Freya.sanitize_html(str, allowedTags);
//if (newstr != str) console.log('pass');
//else console.log('error');
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import TabStaff from './TabStaff';
import _ from 'lodash';
import song from './song';

export default class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      song: song,
      current: {
        measure: 0,
        noteIndex: 0
      },
      audioContext: new AudioContext(),
      isPlaying: false,
      speed: 500
    };
  }

  playSequence = (song) => {
    this.setState({
      isPlaying: true
    }, () => {
      let interval = setInterval(() => {
        let { current, speed } = this.state;
        let { measure, noteIndex } = current;

        let currentNote = song[measure].notes[noteIndex];

        for(let i = 0; i < currentNote.string.length; i++) {
          let pitch = currentNote.fret[i] + (5 * currentNote.string[i]);
          if(currentNote.string[i] >= 4) {
            pitch = pitch - 1;
          }

          this.play(0, pitch, speed / 1000);
        }

        if(measure === song.length - 1 && noteIndex === song[measure].notes.length - 1) {
          clearInterval(interval);

          setTimeout(() => {
            this.setState({
              isPlaying: false,
              current: {
                measure: 0,
                noteIndex: 0
              }
            });
          }, speed);
        } else if(measure !== song.length - 1 && noteIndex === song[measure].notes.length - 1) {
          this.setState({
            current: {
              measure: measure + 1,
              noteIndex: 0
            }
          });
        } else {
          this.setState({
            current: {
              measure,
              noteIndex: noteIndex + 1
            }
          });
        }
      }, this.state.speed);
    });
  }

  play = (delay, pitch, duration) => {
    let startTime = this.state.audioContext.currentTime + delay;
    let endTime = startTime + duration;

    let oscillator = this.state.audioContext.createOscillator();
    let gainNode = this.state.audioContext.createGain();
    oscillator.connect(gainNode);
    gainNode.connect(this.state.audioContext.destination);

    oscillator.type = 'square';
    oscillator.detune.value = (pitch - 29) * 100;

    gainNode.gain.value = 0.025;

    oscillator.start(startTime);
    oscillator.stop(endTime);
  }

  bpmChanged = (event) => {
    this.setState({
      speed: 60000 / event.target.value
    });
  }

  render() {
    return (

          BPM:
          <input onChange={this.bpmChanged} />
          <button onClick={this.playSequence.bind(this, song)}>Play</button>

        <TabStaff song={song} currentNote={this.state.current} isPlaying={this.state.isPlaying} />

    );
  }
}
<commit_msg>refactored replay timing to use requestAnimationFrame<commit_after>import React, { Component } from 'react';
import TabStaff from './TabStaff';
import _ from 'lodash';
import song from './song';

let requestId;
let noteTime;
let currentPlayingIndex = {
  measure: 0,
  noteIndex: 0
};

export default class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      song: song,
      current: {
        measure: 0,
        noteIndex: 0
      },
      audioContext: new AudioContext(),
      isPlaying: false,
      speed: 485
    };
  }

  changeNotes = () => {
    let startTimestamp = Date.now();
    let endTimestamp = startTimestamp + this.state.speed;

    let noteInterval = () => {
      let { current, speed } = this.state;
      let { measure, noteIndex } = current;

      let currentTimestamp = Date.now();
      let replayDiff = currentTimestamp - startTimestamp;

      if(replayDiff >= this.state.speed) {
        startTimestamp = currentTimestamp;

        if(measure === song.length - 1 && noteIndex === song[measure].notes.length - 1) {

          this.setState({
            isPlaying: false,
            current: {
              measure: 0,
              noteIndex: 0
            }
          });
        } else if(measure !== song.length - 1 && noteIndex === song[measure].notes.length - 1) {
          this.setState({
            current: {
              measure: measure + 1,
              noteIndex: 0
            },
            timer: requestAnimationFrame(noteInterval)
          });
        } else {
          this.setState({
            current: {
              measure: measure,
              noteIndex: noteIndex + 1
            },
            timer: requestAnimationFrame(noteInterval)
          });
        }
      } else {
        this.setState({
          timer: requestAnimationFrame(noteInterval)
        });
      }
    };

    this.setState({
      timer: requestAnimationFrame(noteInterval)
    });
  }

  play = (startTime, delay, pitch, duration) => {
    let endTime = startTime + duration;

    let oscillator = this.state.audioContext.createOscillator();
    let gainNode = this.state.audioContext.createGain();
    oscillator.connect(gainNode);
    gainNode.connect(this.state.audioContext.destination);

    oscillator.type = 'square';
    oscillator.detune.value = (pitch - 29) * 100;

    gainNode.gain.value = 0.025;

    oscillator.start(startTime);
    oscillator.stop(endTime);
  }

  playNoteAtTime = (currentNote, playTime) => {
    for(let i = 0; i < currentNote.string.length; i++) {
      let pitch = currentNote.fret[i] + (5 * currentNote.string[i]);
      if(currentNote.string[i] >= 4) {
        pitch = pitch - 1;
      }

      this.play(playTime, 0, pitch, .5);
    }
  }

  handlePlay = (event) => {
    noteTime = 0.0;

    this.setState({
      isPlaying: true,
      startTime: this.state.audioContext.currentTime + .005,
    }, () => {
      this.changeNotes(0, 0);
      this.schedule();
    });
  }

  schedule = () => {
    let currentTime = this.state.audioContext.currentTime - this.state.startTime;

    while(noteTime < currentTime + 0.200) {
      let contextPlayTime = noteTime + this.state.startTime;
      let { measure, noteIndex } = currentPlayingIndex;

      if(measure === 'NO') {
        return;
      }

      let noteToPlay = song[measure].notes[noteIndex];

      this.playNoteAtTime(noteToPlay, contextPlayTime);
      currentPlayingIndex = this.advanceNote(measure, noteIndex);
    }
    requestId = requestAnimationFrame(this.schedule);
  }

  advanceNote = (measure, noteIndex) => {
    let tempo = 60.0;
    let secondsPerBeat = 60.0 / tempo;
    noteTime = noteTime + (0.5 * secondsPerBeat);

    if(measure === song.length - 1 && noteIndex === song[measure].notes.length - 1) {
      return {
        measure: 'NO',
        noteIndex: 0
      };
    } else if(measure !== song.length - 1 && noteIndex === song[measure].notes.length - 1) {
      return {
        measure: measure + 1,
        noteIndex: 0
      };
    } else {
      return {
        measure: measure,
        noteIndex: noteIndex + 1
      };
    }
  }

  handleStop = () => {
    cancelAnimationFrame(requestId);
  }

  bpmChanged = (event) => {
    this.setState({
      speed: 60000 / event.target.value
    });
  }

  render() {
    return (

          BPM:
          <input onChange={this.bpmChanged} />
          <button onClick={this.handlePlay.bind(this, song)}>Play</button>

        <TabStaff song={song} currentNote={this.state.current} isPlaying={this.state.isPlaying} />

    );
  }
}
<|endoftext|>


<commit_before>import { resolve } from 'rsvp';
import { get, set, computed } from '@ember/object';
import { alias } from '@ember/object/computed';
import { inject as service } from '@ember/service';
import Component from '@ember/component';
import NewOrEdit from 'shared/mixins/new-or-edit';
import layout from './template';

export default Component.extend(NewOrEdit, {
  intl:  service(),
  scope: service(),

  layout,
  ingress:                null,
  editing:                null,
  existing:               null,
  namespacedCertificates: null,
  certificates:           null,

  isGKE: alias('scope.currentCluster.isGKE'),

  primaryResource: alias('ingress'),

  actions: {
    done() {
      this.sendAction('done');
    },
    cancel() {
      this.sendAction('cancel');
    },

    setLabels(labels) {
      let out = {};

      labels.forEach((row) => {
        out[row.key] = row.value;
      });

      set(this, 'ingress.labels', out);
    },
  },

  headerLabel: computed('intl.locale', 'existing', function() {
    let k;

    if (get(this, 'existing')) {
      k = 'newIngress.header.edit';
    } else {
      k = 'newIngress.header.add';
    }

    return get(this, 'intl').t(k);
  }),

  willSave() {
    let pr = get(this, 'primaryResource');

    // Namespace is required, but doesn't exist yet... so lie to the validator
    let nsId = get(pr, 'namespaceId');

    set(pr, 'namespaceId', '__TEMP__');
    let ok = this.validate();

    set(pr, 'namespaceId', nsId);

    return ok;
  },

  doSave() {
    let pr = get(this, 'primaryResource');

    let namespacePromise = resolve();

    if (!get(this, 'existing')) {
      // Set the namespace ID
      if (get(this, 'namespace.id')) {
        set(pr, 'namespaceId', get(this, 'namespace.id'));
      } else if (get(this, 'namespace')) {
        namespacePromise = get(this, 'namespace').save()
          .then((newNamespace) => {
            set(pr, 'namespaceId', get(newNamespace, 'id'));

            return newNamespace.waitForState('active');
          });
      }
    }

    let self = this;
    let sup = self._super;

    return namespacePromise.then(() => sup.apply(self, arguments));
  },

  validate() {
    let intl = get(this, 'intl');

    let pr = get(this, 'primaryResource');
    let errors = pr.validationErrors() || [];

    errors.pushObjects(get(this, 'namespaceErrors') || []);
    errors.pushObjects(get(this, 'certErrors') || []);

    if (!get(this, 'ingress.rules.length') && !get(this, 'ingress.defaultBackend')) {
      errors.push(intl.t('newIngress.error.noRules'));
    }
    if (get(this, 'ingress.rules.length')) {
      const invalid = get(this, 'ingress.rules').some((rule) => {
        const paths = [];

        Object.keys(rule.paths).forEach((key) => {
          paths.push(rule.paths[key]);
        });

        return paths.some((path) => !path.targetPort)
      });

      if (invalid) {
        errors.push(intl.t('validation.required', { key: intl.t('generic.port') }));
      }
    }

    if (errors.length) {
      set(this, 'errors', errors.uniq());

      return false;
    }

    return true;
  },

  doneSaving() {
    this._super(...arguments);
    this.send('done');
  },
});
<commit_msg>Fix the issue that ns is wrong in edit ingress page<commit_after>import { resolve } from 'rsvp';
import { get, set, computed } from '@ember/object';
import { alias } from '@ember/object/computed';
import { inject as service } from '@ember/service';
import Component from '@ember/component';
import NewOrEdit from 'shared/mixins/new-or-edit';
import layout from './template';

export default Component.extend(NewOrEdit, {
  intl:  service(),
  scope: service(),

  layout,
  ingress:                null,
  editing:                null,
  existing:               null,
  namespacedCertificates: null,
  certificates:           null,

  isGKE: alias('scope.currentCluster.isGKE'),

  primaryResource: alias('ingress'),

  init() {
    this._super(...arguments);

    if ( get(this, 'existing')) {
      set(this, 'namespace', get(this, 'existing.namespace'));
    }
  },
  actions: {
    done() {
      this.sendAction('done');
    },
    cancel() {
      this.sendAction('cancel');
    },

    setLabels(labels) {
      let out = {};

      labels.forEach((row) => {
        out[row.key] = row.value;
      });

      set(this, 'ingress.labels', out);
    },
  },

  headerLabel: computed('intl.locale', 'existing', function() {
    let k;

    if (get(this, 'existing')) {
      k = 'newIngress.header.edit';
    } else {
      k = 'newIngress.header.add';
    }

    return get(this, 'intl').t(k);
  }),

  willSave() {
    let pr = get(this, 'primaryResource');

    // Namespace is required, but doesn't exist yet... so lie to the validator
    let nsId = get(pr, 'namespaceId');

    set(pr, 'namespaceId', '__TEMP__');
    let ok = this.validate();

    set(pr, 'namespaceId', nsId);

    return ok;
  },

  doSave() {
    let pr = get(this, 'primaryResource');

    let namespacePromise = resolve();

    if (!get(this, 'existing')) {
      // Set the namespace ID
      if (get(this, 'namespace.id')) {
        set(pr, 'namespaceId', get(this, 'namespace.id'));
      } else if (get(this, 'namespace')) {
        namespacePromise = get(this, 'namespace').save()
          .then((newNamespace) => {
            set(pr, 'namespaceId', get(newNamespace, 'id'));

            return newNamespace.waitForState('active');
          });
      }
    }

    let self = this;
    let sup = self._super;

    return namespacePromise.then(() => sup.apply(self, arguments));
  },

  validate() {
    let intl = get(this, 'intl');

    let pr = get(this, 'primaryResource');
    let errors = pr.validationErrors() || [];

    errors.pushObjects(get(this, 'namespaceErrors') || []);
    errors.pushObjects(get(this, 'certErrors') || []);

    if (!get(this, 'ingress.rules.length') && !get(this, 'ingress.defaultBackend')) {
      errors.push(intl.t('newIngress.error.noRules'));
    }
    if (get(this, 'ingress.rules.length')) {
      const invalid = get(this, 'ingress.rules').some((rule) => {
        const paths = [];

        Object.keys(rule.paths).forEach((key) => {
          paths.push(rule.paths[key]);
        });

        return paths.some((path) => !path.targetPort)
      });

      if (invalid) {
        errors.push(intl.t('validation.required', { key: intl.t('generic.port') }));
      }
    }

    if (errors.length) {
      set(this, 'errors', errors.uniq());

      return false;
    }

    return true;
  },

  doneSaving() {
    this._super(...arguments);
    this.send('done');
  },
});
<|endoftext|>


<commit_before>import React, { Fragment } from 'react'
import propPath from 'crocks/Maybe/propPath'
import { RichText } from 'prismic-reactjs'
import styled, { keyframes } from 'styled-components'
import { key } from 'styled-theme'

import { Lazy } from 'Components'
import {
  Row,
  ResultSection,
  SectionHeader,
  SectionImage,
  ImageCopyright,
  SectionBlock,
} from 'Styled'
import { linkResolver, s4, isOdd, htmlSerializer } from 'Helpers'

const SectionImageBlock = SectionBlock.extend`
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  margin: 0 auto;
  width: ${key('sizes.width')};
  &.header {
    padding-bottom: ${key(['space', 7])}px;
  }
  &.odd div,
  &.even div {
    width: 45%;
  }
  &.text div {
    max-width: 720px;
  }
  & .sectionimage {
    width:  450px;
    height: 275px;
    &.margin-top {
      margin-top: ${key(['space', 9])}px;
    }
  }
  &.even .sectionimage {
    order: -1;
  }
  @media (min-width: 1210px) {
    &.odd .sectionimage {
      margin-right: -50px;
    }
    &.even .sectionimage {
      margin-left: -50px;
    }
  }
  & p {
    padding-bottom: ${key(['space', 2])}px;
  }
  & li {
    padding-bottom: ${key(['space', 2])}px;
    padding-left: ${key(['space', 4])}px;
    text-indent: -${key(['space', 4])}px;
    &::before {
      content: '— ';
    }
  }
`

export const ResultImage = ({ section }) => {
  const { primary, items } = section
  const header = propPath(['primary', 'header'])
  const head = propPath([0])
  const text = propPath(['text'])
  const getHeader = header(section).chain(head).chain(text).option('')

  return (
    <ResultSection id={primary.anchor || null} >
    {getHeader.length > 0 &&
      <Lazy height={50}>
        <Row>
          <SectionHeader color='text' shade='pink' >
          { RichText.asText(primary.header) }
          </SectionHeader>
        </Row>
      </Lazy>
    }
    {items.map((item, i) =>
      <Lazy key={s4()} height={300}>
      {item.sectionimage.url
      ? <SectionImageBlock className={isOdd(i) ? 'odd' : 'even'} key={s4()}>
        <Fragment key={s4()}>
            { RichText.render(item.text, linkResolver, htmlSerializer) }
            <SectionImage
              key={s4()}
              className={
                item.text.filter(x => x.type.includes('heading')).length
                  ? 'sectionimage margin-top' : 'sectionimage'
              }
              url={item.sectionimage.url}
            >
            { item.sectionimage.copyright !== null &&
              <ImageCopyright>
                `Copyright: ${item.sectionimage.copyright}`
              </ImageCopyright>
            }
            </SectionImage>
          </Fragment>
      </SectionImageBlock>
      : <SectionImageBlock
          className={item.text.map(x => x.type).indexOf('paragraph') >= 0 ? 'text' : 'header' }
          key={s4()}
        >
        { RichText.render(item.text, linkResolver, htmlSerializer) }
        </SectionImageBlock>
      }
      </Lazy>
    )}
    </ResultSection>
  )
}<commit_msg>fix fox<commit_after>import React, { Fragment } from 'react'
import propPath from 'crocks/Maybe/propPath'
import { RichText } from 'prismic-reactjs'
import styled, { keyframes } from 'styled-components'
import { key } from 'styled-theme'

import { Lazy } from 'Components'
import {
  Row,
  ResultSection,
  SectionHeader,
  SectionImage,
  ImageCopyright,
  SectionBlock,
} from 'Styled'
import { linkResolver, s4, isOdd, htmlSerializer } from 'Helpers'

const SectionImageBlock = SectionBlock.extend`
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-between;
  margin: 0 auto;
  width: ${key('sizes.width')};
  &.header {
    padding-bottom: ${key(['space', 7])}px;
  }
  &.odd div,
  &.even div {
    width: 45%;
  }
  &.text div {
    max-width: 720px;
  }
  & .sectionimage {
    width:  450px;
    height: 275px;
    &.margin-top {
      margin-top: ${key(['space', 9])}px;
    }
  }
  &.even .sectionimage {
    order: -1;
  }
  @media (min-width: 1210px) {
    &.odd .sectionimage {
      margin-right: -50px;
    }
    &.even .sectionimage {
      margin-left: -50px;
    }
  }
  & p {
    padding-bottom: ${key(['space', 2])}px;
  }
  & li {
    padding-bottom: ${key(['space', 2])}px;
    padding-left: ${key(['space', 4])}px;
    text-indent: -${key(['space', 4])}px;
    &::before {
      content: '— ';
    }
  }
`

export const ResultImage = ({ section }) => {
  const { primary, items } = section
  const header = propPath(['primary', 'header'])
  const head = propPath([0])
  const text = propPath(['text'])
  const getHeader = header(section).chain(head).chain(text).option('')

  return (
    <ResultSection id={primary.anchor || null} >
    {getHeader.length > 0 &&
      <Lazy height={50}>
        <Row>
          <SectionHeader color='text' shade='pink' >
          { RichText.asText(primary.header) }
          </SectionHeader>
        </Row>
      </Lazy>
    }
    {items.map((item, i) =>
      <Lazy key={s4()} height={300}>
      {item.sectionimage.url
      ? <SectionImageBlock className={isOdd(i) ? 'odd' : 'even'} key={s4()}>
        <Fragment key={s4()}>
            { RichText.render(item.text, linkResolver, htmlSerializer) }
            <SectionImage
              key={s4()}
              className={
                item.text.filter(x => x.type.includes('heading')).length
                  ? 'sectionimage margin-top' : 'sectionimage'
              }
              url={item.sectionimage.url}
            >
            { item.sectionimage.copyright !== null &&
              <ImageCopyright>
                Copyright: { item.sectionimage.copyright }
              </ImageCopyright>
            }
            </SectionImage>
          </Fragment>
      </SectionImageBlock>
      : <SectionImageBlock
          className={item.text.map(x => x.type).indexOf('paragraph') >= 0 ? 'text' : 'header' }
          key={s4()}
        >
        { RichText.render(item.text, linkResolver, htmlSerializer) }
        </SectionImageBlock>
      }
      </Lazy>
    )}
    </ResultSection>
  )
}<|endoftext|>


<commit_before>var User  = require('../models/user');
var debug = require('debug')('omnisplit:jwt');
var jwt   = require('jwt-simple');
var redis = require('redis');

module.exports = function(req, res, next) {
    var token = (req.body && req.body.access_token) || (req.query && req.query.access_token) || (req.cookies && req.cookies.token) || req.headers['x-access-token'];

    var client = redis.createClient();

    if (token) {
        try {
            var decoded = jwt.decode(token, req.app.get('jwtTokenSecret'));

            if (decoded.exp <= Date.now()) {
                res.clearCookie('token');
                res.redirect('/login');
            }
            client.get(token, function(err, result) {
                if (err) {
                    res.clearCookie('token');
                    debug(err.stack);
                    res.redirect('/login');
                }
                else if (result) { //Cookie is cached
                    var obj = JSON.parse(result);
                    if (obj.iss == decoded.iss && obj.exp == decoded.exp) {
                        client.setex(token, 60 * 10, result);
                        return next();
                    }
                    else { //Invalid cookie
                        res.clearCookie('token');
                        res.redirect('/login');
                    }
                }
                else { //Not cached, look for user in database
                    User.findOne({ _id: decoded.iss }, function(err, user) {
                        if (user) {
                            client.setex(token, 60 * 10, JSON.stringify({ iss: decoded.iss, exp: decoded.exp }) );
                            return next();
                        }
                        else { //Not found in database
                            res.clearCookie('token');
                            res.redirect('/login');
                        }
                    });
                }
            });
        } catch (err) { //Token parsing probably failed
            res.clearCookie('token');
            debug(err.stack);
            res.redirect('/login');
        }
    } else {
        return res.redirect('/login');
    }
 };
<commit_msg>Clear token when log out<commit_after>var User  = require('../models/user');
var debug = require('debug')('omnisplit:jwt');
var jwt   = require('jwt-simple');
var redis = require('redis');

module.exports = function(req, res, next) {
    var token = (req.body && req.body.access_token) || (req.query && req.query.access_token) || (req.cookies && req.cookies.token) || req.headers['x-access-token'];

    var client = redis.createClient();

    if (token) {
        try {
            var decoded = jwt.decode(token, req.app.get('jwtTokenSecret'));

            if (decoded.exp <= Date.now()) {
                res.clearCookie('token');
                client.del(token);
                res.redirect('/login');
            }
            client.get(token, function(err, result) {
                if (err) {
                    res.clearCookie('token');
                    client.del(token);
                    debug(err.stack);
                    res.redirect('/login');
                }
                else if (result) { //Cookie is cached
                    var obj = JSON.parse(result);
                    if (obj.iss == decoded.iss && obj.exp == decoded.exp) {
                        client.setex(token, 60 * 10, result);
                        return next();
                    }
                    else { //Invalid cookie
                        res.clearCookie('token');
                        client.del(token);
                        res.redirect('/login');
                    }
                }
                else { //Not cached, look for user in database
                    User.findOne({ _id: decoded.iss }, function(err, user) {
                        if (user) {
                            client.setex(token, 60 * 10, JSON.stringify({ iss: decoded.iss, exp: decoded.exp }) );
                            return next();
                        }
                        else { //Not found in database
                            res.clearCookie('token');
                            client.del(token);
                            res.redirect('/login');
                        }
                    });
                }
            });
        } catch (err) { //Token parsing probably failed
            res.clearCookie('token');
            debug(err.stack);
            res.redirect('/login');
        }
    } else {
        return res.redirect('/login');
    }
 };
<|endoftext|>


<commit_before>import React, { Component } from 'react';

export default class App extends Component {
  render() {
    return (

Hello, world.

    );
  }
}
<commit_msg>Modify <App /> to use PokemonList<commit_after>import React, { Component } from 'react';
import PokemonList from './PokemonList';

const pokemons = [
  {
    id: 1,
    name: 'Bulbasaur'
  }
];

const App = () => <PokemonList
  pokemons={pokemons}
  onPokemonClick={() => undefined}
/>

export default App;
<|endoftext|>


<commit_before>define([
    'vellum/form',
    'jquery',
    'underscore',
    'vellum/mugs',
    'vellum/parser',
    'vellum/tree',
    'vellum/util',
    'vellum/widgets',
    'vellum/core'
], function (
    form_,
    $,
    _,
    mugs,
    parser,
    Tree,
    util,
    widgets
) {
    var nextId = 0,
        setvalueData = {
            Balance: [
                {
                    attr: "entryId",
                    path: "entry/@id"
                }, {
                    attr: "entityId",
                    path: "@entity-id"
                }, {
                    attr: "date",
                    path: "@date"
                }
            ],
            Transfer: [
                {
                    attr: "entryId",
                    path: "entry/@id"
                }, {
                    attr: "src",
                    path: "@src"
                }, {
                    attr: "dest",
                    path: "@dest"
                }, {
                    attr: "date",
                    path: "@date"
                }
            ],
        },
        sectionData = {
            Balance: [
                {
                    slug: "main",
                    displayName: "Basic",
                    help: {
                        title: "Basic",
                        text: "
The Question ID is an internal identifier for a question. " +
                            "It does not appear on the phone. It is the name of the question in data exports.
" +
                            "
Click through for more info.
",
                        link: "https://help.commcarehq.org/display/commcarepublic/Transactions",
                    },
                    properties: [
                        "nodeID",
                        "entityId",
                        "sectionId",
                        "entryId",
                        "quantity"
                    ],
                }
            ],
            Transfer: [
                {
                    slug: "main",
                    displayName: "Basic",
                    help: {
                        title: "Basic",
                        text: "
The Question ID is an internal identifier for a question. " +
                            "It does not appear on the phone. It is the name of the question in data exports.
" +
                            "
Click through for more info.
",
                        link: "https://help.commcarehq.org/display/commcarepublic/Transactions",
                    },
                    properties: [
                        "nodeID",
                        "src",
                        "dest",
                        "sectionId",
                        "entryId",
                        "quantity"
                    ],
                }
            ]
        },
        baseTransactionOptions = {
            isDataOnly: true,
            isTypeChangeable: false,
            supportsDataNodeRole: true,
            parseDataNode: function (mug, $node) {
                mug.p.nodeID = mug.p.rawDataAttributes.type || "tx-" + nextId++;
                delete mug.p.rawDataAttributes.type;
                mug.p.sectionId = mug.p.rawDataAttributes["section-id"];
                delete mug.p.rawDataAttributes["section-id"];
                return $([]);
            },
            getPathName: function (mug, name) {
                return mug.options.getTagName() + "[@type='" + name + "']";
            },
            dataChildFilter: function (children, mug) {
                return [new Tree.Node(children, {
                    getNodeID: function () { return "entry"; },
                    p: {rawDataAttributes: null},
                    options: {
                        getExtraDataAttributes: function (mug) {
                            return {id: "", quantity: ""};
                        }
                    }
                })];
            },
            getBindList: function (mug) {
                return [{
                    nodeset: mug.absolutePath + "/entry/@quantity",
                    calculate: mug.p.quantity
                }];
            }
        },
        balanceMugOptions = {
            typeName: 'Balance',
            getTagName: function () { return "balance"; },
            getExtraDataAttributes: function (mug) {
                // HACK must happen before <setvalue> and "other" <instance> elements are written
                prepareForWrite(mug);
                var attrs = mug.p.rawDataAttributes || {};
                return {
                    xmlns: "http://commcarehq.org/ledger/v1",
                    type: mug.p.nodeID,
                    "entity-id": attrs.src || "",
                    "section-id": mug.p.sectionId,
                    date: attrs.date || "",
                    "vellum:role": "Balance"
                };
            },
            icon: 'fcc fcc-fd-hash',
            init: function (mug, form) {
                mug.p.entityId = {value: ""};
                mug.p.sectionId = "";
                mug.p.entryId = {value: ""};
                mug.p.quantity = "";
                mug.p.date = {value: "today()"};
                addLedgerDBInstance(mug, form);
            },
            spec: {
                xmlnsAttr: { presence: "optional" },
                entityId: {
                    lstring: 'Case',
                    visibility: 'visible',
                    presence: 'optional',
                    widget: setValueWidget,
                    xpathType: "generic",
                    help: 'XPath expression for the case ID associated with this balance.',
                },
                sectionId: {
                    lstring: 'Balance ID',
                    visibility: 'visible',
                    presence: 'optional',
                    widget: widgets.text,
                    help: 'The name of the balance you are tracking. ' +
                         'This is an internal identifier which does not appear on the phone.',
                },
                entryId: {
                    lstring: 'Product',
                    visibility: 'visible',
                    presence: 'optional',
                    widget: setValueWidget,
                    xpathType: "generic",
                    help: 'A reference to a product ID, e.g., "/data/products/current_product"',
                },
                quantity: {
                    lstring: 'Quantity',
                    visibility: 'visible',
                    presence: 'optional',
                    widget: widgets.xPath,
                    xpathType: "generic",
                    help: 'A reference to an integer question in this form.',
                },
                requiredAttr: { presence: "notallowed" },
                constraintAttr: { presence : "notallowed" },
                calculateAttr: { presence: "notallowed" }
            }
        },
        transferMugValidation = function (mug) {
            if (mug.p.dest.value || mug.p.src.value) {
                return 'pass';
            }
            return 'Transfer must have at least one of source case and destination case.';
        },
        transferMugOptions = {
            typeName: 'Transfer',
            getTagName: function () { return "transfer"; },
            getExtraDataAttributes: function (mug) {
                // HACK must happen before <setvalue> and "other" <instance> elements are written
                prepareForWrite(mug);
                var raw = mug.p.rawDataAttributes || {},
                    attrs = {
                        xmlns: "http://commcarehq.org/ledger/v1",
                        type: mug.p.nodeID,
                        date: raw.date || "",
                        "section-id": mug.p.sectionId,
                        "vellum:role": "Transfer"
                    };
                if ($.trim(mug.p.src.value)) {
                    attrs.src = raw.src || "";
                } else {
                    delete raw.src;
                }
                if ($.trim(mug.p.dest.value)) {
                    attrs.dest = raw.dest || "";
                } else {
                    delete raw.dest;
                }
                return attrs;
            },
            icon: 'icon-exchange',
            init: function (mug, form) {
                mug.p.src = {value: ""};
                mug.p.dest = {value: ""};
                mug.p.sectionId = "";
                mug.p.entryId = {value: ""};
                mug.p.quantity = "";
                mug.p.date = {value: "today()"};
                addLedgerDBInstance(mug, form);
            },
            spec: {
                xmlnsAttr: { presence: "optional" },
                src: {
                    lstring: 'Source Case',
                    visibility: 'visible',
                    presence: 'optional',
                    widget: setValueWidget,
                    xpathType: "generic",
                    help: 'XPath expression for the case ID issuing the transaction. Leave blank if unknown or not applicable.',
                    validationFunc: transferMugValidation,
                },
                dest: {
                    lstring: 'Destination Case',
                    visibility: 'visible',
                    presence: 'optional',
                    widget: setValueWidget,
                    xpathType: "generic",
                    help: 'XPath expression for the case ID receiving the transaction. Leave blank if unknown or not applicable.',
                    validationFunc: transferMugValidation,
                },
                sectionId: {
                    lstring: 'Balance ID',
                    visibility: 'visible',
                    presence: 'optional',
                    widget: widgets.text,
                    help: 'The name of the balance you are tracking. ' +
                         'This is an internal identifier which does not appear on the phone.',
                },
                entryId: {
                    lstring: 'Product',
                    visibility: 'visible',
                    presence: 'optional',
                    widget: setValueWidget,
                    xpathType: "generic",
                    help: 'A reference to a product ID, e.g., "/data/products/current_product"',
                },
                quantity: {
                    lstring: 'Quantity',
                    visibility: 'visible',
                    presence: 'optional',
                    widget: widgets.xPath,
                    xpathType: "generic",
                    help: 'A reference to an integer question in this form.',
                },
                requiredAttr: { presence: "notallowed" },
                constraintAttr: { presence : "notallowed" },
                calculateAttr: { presence: "notallowed" }
            }
        };

    $.vellum.plugin("commtrack", {}, {
        getAdvancedQuestions: function () {
            return this.__callOld().concat(["Balance", "Transfer"]);
        },
        getMugTypes: function () {
            var types = this.__callOld();
            types.normal.Balance = util.extend(
                mugs.defaultOptions, baseTransactionOptions, balanceMugOptions);
            types.normal.Transfer = util.extend(
                mugs.defaultOptions, baseTransactionOptions, transferMugOptions);
            return types;
        },
        parseBindElement: function (form, el, path) {
            var mug = form.getMugByPath(path);
            if (!mug) {
                var basePath = path.replace(/\/entry\/@quantity$/, "");
                if (path !== basePath) {
                    mug = form.getMugByPath(basePath);
                    if (isTransaction(mug)) {
                        mug.p.quantity = el.attr("calculate");
                        return;
                    }
                }
            }
            this.__callOld();
        },
        handleMugParseFinish: function (mug) {
            this.__callOld();
            if (!isTransaction(mug)) {
                return;
            }
            var path = mug.absolutePath;
            var values = _.object(_.map(mug.form.getSetValues(), function (value) {
                    return [value.ref, value];
                }));
            _.each(setvalueData[mug.__className], function (data) {
                mug.p[data.attr] = values[path + "/" + data.path] || {
                    value: ""
                };
            });
        },
        getSections: function (mug) {
            if (sectionData.hasOwnProperty(mug.__className)) {
                return _.map(sectionData[mug.__className], function (section) {
                    return _.clone(section);
                });
            }
            return this.__callOld();
        },
        loadXML: function () {
            this.__callOld();
            this.data.core.form.on("question-remove", function (event) {
                dropSetValues(event.mug);
            });
        }
    });

    function isTransaction(mug) {
        return mug && (mug.__className === "Balance" || mug.__className === "Transfer");
    }

    function isInRepeat(mug) {
        if (mug.__className === "Repeat") { // HACK hard-coded class name
            return true;
        }
        return mug.parentMug && isInRepeat(mug.parentMug);
    }

    function addLedgerDBInstance(mug, form) {
        var data = {id: "ledger", src: "jr://instance/ledgerdb"};
        form.addInstanceIfNotExists(data, mug, "");
    }

    function prepareForWrite(mug) {
        var path = mug.absolutePath,
            event = isInRepeat(mug) ? "jr-insert" : "xforms-ready",
            drops = {};

        // update <setvalue> refs
        _.each(setvalueData[mug.__className], function (data) {
            var value = mug.p[data.attr];
            if (!value.ref) {
                mug.p[data.attr] = value = mug.form.addSetValue(
                    event,
                    path + "/" + data.path,
                    value.value
                );
            } else {
                value.ref = path + "/" + data.path;
                value.event = event;
            }
            if (!$.trim(value.value)) {
                drops[event + " " + value.ref] = true;
                drops.enabled = true;
            }
        });

        if (drops.enabled) {
            mug.form.dropSetValues(function (value) {
                return drops.hasOwnProperty(value.event + " " + value.ref);
            });
        }
    }

    function dropSetValues(mug) {
        // remove <setvalue> elements
        var setvaluesToRemove = {};
        _.each(setvalueData[mug.__className], function (data) {
            var value = mug.p[data.attr];
            if (value._id) {
                setvaluesToRemove[value._id] = true;
            }
        });
        if (!_.isEmpty(setvaluesToRemove)) {
            mug.form.dropSetValues(function (value) {
                return setvaluesToRemove.hasOwnProperty(value._id);
            });
        }
    }

    function setValueWidget(mug, options) {
        var widget = widgets.xPath(mug, options),
            _getValue = widget.getValue,
            _setValue = widget.setValue,
            _value = null;

        widget.setValue = function (value) {
            _value = value;
            _setValue(value.value);
        };

        widget.getValue = function () {
            var val = _value || {};
            val.value = _getValue();
            return val;
        };

        return widget;
    }
});
<commit_msg>Define commtrack ledger constants<commit_after>define([
    'vellum/form',
    'jquery',
    'underscore',
    'vellum/mugs',
    'vellum/parser',
    'vellum/tree',
    'vellum/util',
    'vellum/widgets',
    'vellum/core'
], function (
    form_,
    $,
    _,
    mugs,
    parser,
    Tree,
    util,
    widgets
) {
    var LEDGER_XMLNS = "http://commcarehq.org/ledger/v1",
        LEDGER_INSTANCE_ID = "ledger",
        LEDGER_INSTANCE_URI = "jr://instance/ledgerdb",
        nextId = 0,
        setvalueData = {
            Balance: [
                {
                    attr: "entryId",
                    path: "entry/@id"
                }, {
                    attr: "entityId",
                    path: "@entity-id"
                }, {
                    attr: "date",
                    path: "@date"
                }
            ],
            Transfer: [
                {
                    attr: "entryId",
                    path: "entry/@id"
                }, {
                    attr: "src",
                    path: "@src"
                }, {
                    attr: "dest",
                    path: "@dest"
                }, {
                    attr: "date",
                    path: "@date"
                }
            ],
        },
        sectionData = {
            Balance: [
                {
                    slug: "main",
                    displayName: "Basic",
                    help: {
                        title: "Basic",
                        text: "
The Question ID is an internal identifier for a question. " +
                            "It does not appear on the phone. It is the name of the question in data exports.
" +
                            "
Click through for more info.
",
                        link: "https://help.commcarehq.org/display/commcarepublic/Transactions",
                    },
                    properties: [
                        "nodeID",
                        "entityId",
                        "sectionId",
                        "entryId",
                        "quantity"
                    ],
                }
            ],
            Transfer: [
                {
                    slug: "main",
                    displayName: "Basic",
                    help: {
                        title: "Basic",
                        text: "
The Question ID is an internal identifier for a question. " +
                            "It does not appear on the phone. It is the name of the question in data exports.
" +
                            "
Click through for more info.
",
                        link: "https://help.commcarehq.org/display/commcarepublic/Transactions",
                    },
                    properties: [
                        "nodeID",
                        "src",
                        "dest",
                        "sectionId",
                        "entryId",
                        "quantity"
                    ],
                }
            ]
        },
        baseTransactionOptions = {
            isDataOnly: true,
            isTypeChangeable: false,
            supportsDataNodeRole: true,
            parseDataNode: function (mug, $node) {
                mug.p.nodeID = mug.p.rawDataAttributes.type || "tx-" + nextId++;
                delete mug.p.rawDataAttributes.type;
                mug.p.sectionId = mug.p.rawDataAttributes["section-id"];
                delete mug.p.rawDataAttributes["section-id"];
                return $([]);
            },
            getPathName: function (mug, name) {
                return mug.options.getTagName() + "[@type='" + name + "']";
            },
            dataChildFilter: function (children, mug) {
                return [new Tree.Node(children, {
                    getNodeID: function () { return "entry"; },
                    p: {rawDataAttributes: null},
                    options: {
                        getExtraDataAttributes: function (mug) {
                            return {id: "", quantity: ""};
                        }
                    }
                })];
            },
            getBindList: function (mug) {
                return [{
                    nodeset: mug.absolutePath + "/entry/@quantity",
                    calculate: mug.p.quantity
                }];
            }
        },
        balanceMugOptions = {
            typeName: 'Balance',
            getTagName: function () { return "balance"; },
            getExtraDataAttributes: function (mug) {
                // HACK must happen before <setvalue> and "other" <instance> elements are written
                prepareForWrite(mug);
                var attrs = mug.p.rawDataAttributes || {};
                return {
                    xmlns: LEDGER_XMLNS,
                    type: mug.p.nodeID,
                    "entity-id": attrs.src || "",
                    "section-id": mug.p.sectionId,
                    date: attrs.date || "",
                    "vellum:role": "Balance"
                };
            },
            icon: 'fcc fcc-fd-hash',
            init: function (mug, form) {
                mug.p.entityId = {value: ""};
                mug.p.sectionId = "";
                mug.p.entryId = {value: ""};
                mug.p.quantity = "";
                mug.p.date = {value: "today()"};
                addLedgerDBInstance(mug, form);
            },
            spec: {
                xmlnsAttr: { presence: "optional" },
                entityId: {
                    lstring: 'Case',
                    visibility: 'visible',
                    presence: 'optional',
                    widget: setValueWidget,
                    xpathType: "generic",
                    help: 'XPath expression for the case ID associated with this balance.',
                },
                sectionId: {
                    lstring: 'Balance ID',
                    visibility: 'visible',
                    presence: 'optional',
                    widget: widgets.text,
                    help: 'The name of the balance you are tracking. ' +
                         'This is an internal identifier which does not appear on the phone.',
                },
                entryId: {
                    lstring: 'Product',
                    visibility: 'visible',
                    presence: 'optional',
                    widget: setValueWidget,
                    xpathType: "generic",
                    help: 'A reference to a product ID, e.g., "/data/products/current_product"',
                },
                quantity: {
                    lstring: 'Quantity',
                    visibility: 'visible',
                    presence: 'optional',
                    widget: widgets.xPath,
                    xpathType: "generic",
                    help: 'A reference to an integer question in this form.',
                },
                requiredAttr: { presence: "notallowed" },
                constraintAttr: { presence : "notallowed" },
                calculateAttr: { presence: "notallowed" }
            }
        },
        transferMugValidation = function (mug) {
            if (mug.p.dest.value || mug.p.src.value) {
                return 'pass';
            }
            return 'Transfer must have at least one of source case and destination case.';
        },
        transferMugOptions = {
            typeName: 'Transfer',
            getTagName: function () { return "transfer"; },
            getExtraDataAttributes: function (mug) {
                // HACK must happen before <setvalue> and "other" <instance> elements are written
                prepareForWrite(mug);
                var raw = mug.p.rawDataAttributes || {},
                    attrs = {
                        xmlns: LEDGER_XMLNS,
                        type: mug.p.nodeID,
                        date: raw.date || "",
                        "section-id": mug.p.sectionId,
                        "vellum:role": "Transfer"
                    };
                if ($.trim(mug.p.src.value)) {
                    attrs.src = raw.src || "";
                } else {
                    delete raw.src;
                }
                if ($.trim(mug.p.dest.value)) {
                    attrs.dest = raw.dest || "";
                } else {
                    delete raw.dest;
                }
                return attrs;
            },
            icon: 'icon-exchange',
            init: function (mug, form) {
                mug.p.src = {value: ""};
                mug.p.dest = {value: ""};
                mug.p.sectionId = "";
                mug.p.entryId = {value: ""};
                mug.p.quantity = "";
                mug.p.date = {value: "today()"};
                addLedgerDBInstance(mug, form);
            },
            spec: {
                xmlnsAttr: { presence: "optional" },
                src: {
                    lstring: 'Source Case',
                    visibility: 'visible',
                    presence: 'optional',
                    widget: setValueWidget,
                    xpathType: "generic",
                    help: 'XPath expression for the case ID issuing the transaction. Leave blank if unknown or not applicable.',
                    validationFunc: transferMugValidation,
                },
                dest: {
                    lstring: 'Destination Case',
                    visibility: 'visible',
                    presence: 'optional',
                    widget: setValueWidget,
                    xpathType: "generic",
                    help: 'XPath expression for the case ID receiving the transaction. Leave blank if unknown or not applicable.',
                    validationFunc: transferMugValidation,
                },
                sectionId: {
                    lstring: 'Balance ID',
                    visibility: 'visible',
                    presence: 'optional',
                    widget: widgets.text,
                    help: 'The name of the balance you are tracking. ' +
                         'This is an internal identifier which does not appear on the phone.',
                },
                entryId: {
                    lstring: 'Product',
                    visibility: 'visible',
                    presence: 'optional',
                    widget: setValueWidget,
                    xpathType: "generic",
                    help: 'A reference to a product ID, e.g., "/data/products/current_product"',
                },
                quantity: {
                    lstring: 'Quantity',
                    visibility: 'visible',
                    presence: 'optional',
                    widget: widgets.xPath,
                    xpathType: "generic",
                    help: 'A reference to an integer question in this form.',
                },
                requiredAttr: { presence: "notallowed" },
                constraintAttr: { presence : "notallowed" },
                calculateAttr: { presence: "notallowed" }
            }
        };

    $.vellum.plugin("commtrack", {}, {
        getAdvancedQuestions: function () {
            return this.__callOld().concat(["Balance", "Transfer"]);
        },
        getMugTypes: function () {
            var types = this.__callOld();
            types.normal.Balance = util.extend(
                mugs.defaultOptions, baseTransactionOptions, balanceMugOptions);
            types.normal.Transfer = util.extend(
                mugs.defaultOptions, baseTransactionOptions, transferMugOptions);
            return types;
        },
        parseBindElement: function (form, el, path) {
            var mug = form.getMugByPath(path);
            if (!mug) {
                var basePath = path.replace(/\/entry\/@quantity$/, "");
                if (path !== basePath) {
                    mug = form.getMugByPath(basePath);
                    if (isTransaction(mug)) {
                        mug.p.quantity = el.attr("calculate");
                        return;
                    }
                }
            }
            this.__callOld();
        },
        handleMugParseFinish: function (mug) {
            this.__callOld();
            if (!isTransaction(mug)) {
                return;
            }
            var path = mug.absolutePath;
            var values = _.object(_.map(mug.form.getSetValues(), function (value) {
                    return [value.ref, value];
                }));
            _.each(setvalueData[mug.__className], function (data) {
                mug.p[data.attr] = values[path + "/" + data.path] || {
                    value: ""
                };
            });
        },
        getSections: function (mug) {
            if (sectionData.hasOwnProperty(mug.__className)) {
                return _.map(sectionData[mug.__className], function (section) {
                    return _.clone(section);
                });
            }
            return this.__callOld();
        },
        loadXML: function () {
            this.__callOld();
            this.data.core.form.on("question-remove", function (event) {
                dropSetValues(event.mug);
            });
        }
    });

    function isTransaction(mug) {
        return mug && (mug.__className === "Balance" || mug.__className === "Transfer");
    }

    function isInRepeat(mug) {
        if (mug.__className === "Repeat") { // HACK hard-coded class name
            return true;
        }
        return mug.parentMug && isInRepeat(mug.parentMug);
    }

    function addLedgerDBInstance(mug, form) {
        var data = {id: LEDGER_INSTANCE_ID, src: LEDGER_INSTANCE_URI};
        form.addInstanceIfNotExists(data, mug, "");
    }

    function prepareForWrite(mug) {
        var path = mug.absolutePath,
            event = isInRepeat(mug) ? "jr-insert" : "xforms-ready",
            drops = {};

        // update <setvalue> refs
        _.each(setvalueData[mug.__className], function (data) {
            var value = mug.p[data.attr];
            if (!value.ref) {
                mug.p[data.attr] = value = mug.form.addSetValue(
                    event,
                    path + "/" + data.path,
                    value.value
                );
            } else {
                value.ref = path + "/" + data.path;
                value.event = event;
            }
            if (!$.trim(value.value)) {
                drops[event + " " + value.ref] = true;
                drops.enabled = true;
            }
        });

        if (drops.enabled) {
            mug.form.dropSetValues(function (value) {
                return drops.hasOwnProperty(value.event + " " + value.ref);
            });
        }
    }

    function dropSetValues(mug) {
        // remove <setvalue> elements
        var setvaluesToRemove = {};
        _.each(setvalueData[mug.__className], function (data) {
            var value = mug.p[data.attr];
            if (value._id) {
                setvaluesToRemove[value._id] = true;
            }
        });
        if (!_.isEmpty(setvaluesToRemove)) {
            mug.form.dropSetValues(function (value) {
                return setvaluesToRemove.hasOwnProperty(value._id);
            });
        }
    }

    function setValueWidget(mug, options) {
        var widget = widgets.xPath(mug, options),
            _getValue = widget.getValue,
            _setValue = widget.setValue,
            _value = null;

        widget.setValue = function (value) {
            _value = value;
            _setValue(value.value);
        };

        widget.getValue = function () {
            var val = _value || {};
            val.value = _getValue();
            return val;
        };

        return widget;
    }
});
<|endoftext|>


<commit_before>var tag = document.createElement('script');
		tag.src = 'https://www.youtube.com/player_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
		firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var tv,
		playerDefaults = {autoplay: 0, autohide: 1, modestbranding: 0, rel: 0, showinfo: 0, controls: 0, disablekb: 1, enablejsapi: 0, iv_load_policy: 3};
var vid = [
			{'videoId': 'F4gJsKZvqE4', 'startSeconds': 0, 'endSeconds': 148, 'suggestedQuality': 'hd720'},
			{'videoId': 'RfJgT89hEME', 'startSeconds': 0, 'endSeconds': 160, 'suggestedQuality': 'hd720'},
			{'videoId': 'ViuDsy7yb8M', 'startSeconds': 0, 'endSeconds': 139, 'suggestedQuality': 'hd720'},
			{'videoId': 'gLJdzky63BA', 'startSeconds': 6, 'endSeconds': 152, 'suggestedQuality': 'hd720'},
			{'videoId': 'deSRpSn8Pyk', 'startSeconds': 0, 'endSeconds': 121, 'suggestedQuality': 'hd720'},
			{'videoId': 'QEAW49qjBtc', 'startSeconds': 2, 'endSeconds': 30, 'suggestedQuality': 'hd720'}
		],
		randomvid = Math.floor(Math.random() * (vid.length - 1 + 1));

function onYouTubePlayerAPIReady(){
  tv = new YT.Player('tv', {events: {'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange}, playerVars: playerDefaults});
}

function onPlayerReady(){
  tv.loadVideoById(vid[randomvid]);
  tv.mute();
}

function onPlayerStateChange(e) {
  if (e.data === 1){
    $('#tv').addClass('active');
  } else if (e.data === 0){
    tv.seekTo(vid[randomvid].startSeconds)
  }
}

function vidRescale(){

  var w = $(window).width()+200,
    h = $(window).height()+200;

  if (w/h > 16/9){
    tv.setSize(w, w/16*9);
    $('.tv .screen').css({'left': '0px'});
  } else {
    tv.setSize(h/9*16, h);
    $('.tv .screen').css({'left': -($('.tv .screen').outerWidth()-w)/2});
  }
}

$(window).on('load resize', function(){
  vidRescale();
});

$('.hi span').on('click', function(){
  $('#tv').toggleClass('mute');
  if($('#tv').hasClass('mute')){
    tv.mute();
  } else {
    tv.unMute();
  }
});
<commit_msg>Update landing.js<commit_after>var tag = document.createElement('script');
		tag.src = 'https://www.youtube.com/player_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
		firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var tv,
		playerDefaults = {autoplay: 0, autohide: 1, modestbranding: 0, rel: 0, showinfo: 0, controls: 0, disablekb: 1, enablejsapi: 0, iv_load_policy: 3};
var vid = [
			{'videoId': 'F4gJsKZvqE4', 'startSeconds': 0, 'endSeconds': 148, 'suggestedQuality': 'hd720'},
			{'videoId': 'RfJgT89hEME', 'startSeconds': 0, 'endSeconds': 160, 'suggestedQuality': 'hd720'},
			{'videoId': 'ViuDsy7yb8M', 'startSeconds': 0, 'endSeconds': 139, 'suggestedQuality': 'hd720'},
			{'videoId': 'gLJdzky63BA', 'startSeconds': 6, 'endSeconds': 152, 'suggestedQuality': 'hd720'},
			{'videoId': 'deSRpSn8Pyk', 'startSeconds': 0, 'endSeconds': 121, 'suggestedQuality': 'hd720'},
			{'videoId': 'QEAW49qjBtc', 'startSeconds': 2, 'endSeconds': 30, 'suggestedQuality': 'hd720'}
		],
		randomvid = Math.floor(Math.random() * (vid.length - 1 + 1));

function onYouTubePlayerAPIReady(){
  tv = new YT.Player('tv', {events: {'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange}, playerVars: playerDefaults});
}

function onPlayerReady(){
  tv.loadVideoById(vid[randomvid]);
  tv.mute();
}

function onPlayerStateChange(e) {
  if (e.data === 1){
    $('#tv').addClass('active');
  } else if (e.data === 0){
    tv.seekTo(vid[randomvid].startSeconds)
  }
}

function vidRescale(){

  var w = $(window).width()/2,
    h = $(window).height()+200;

  if (w/h > 16/9){
    tv.setSize(w, w/16*9);
    $('.tv .screen').css({'left': '0px'});
  } else {
    tv.setSize(h/9*16, h);
    $('.tv .screen').css({'left': -($('.tv .screen').outerWidth()-w)/2});
  }
}

$(window).on('load resize', function(){
  vidRescale();
});

$('.hi span').on('click', function(){
  $('#tv').toggleClass('mute');
  if($('#tv').hasClass('mute')){
    tv.mute();
  } else {
    tv.unMute();
  }
});
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import Hello from './Hello/Hello';
import NavigationBar from './Navigation/NavigationBar';

class App extends Component {
  render() {
    return (

        <Hello appName="My React Movie App" />
        <NavigationBar />
        {this.props.children}

    );
  }
}

App.PropTypes = {
  children: PropTypes.object.isRequired
};

export default App;
<commit_msg>clean up code<commit_after>import React, { Component } from 'react';
import Hello from './Hello/Hello';
import NavigationBar from './Navigation/NavigationBar';

class App extends Component {
  render() {
    return (

        <Hello appName="My React Movie App" />
        <NavigationBar />
        {this.props.children}

    );
  }
}

export default App;
<|endoftext|>


<commit_before>import React from 'react/addons';
import { expect} from 'chai';
import { InfoBar } from 'components';
import { Provider } from 'react-redux';
import createStore from 'redux/create';
import ApiClient from 'ApiClient';
const { TestUtils } = React.addons;
const client = new ApiClient();

describe('InfoBar', () => {
  const mockStore = {
    info: {
      load: () => {},
      loaded: true,
      loading: false,
      data: {
        message: 'This came from the api server',
        time: Date.now()
      }
    }
  };

  const store = createStore(client, mockStore);
  const renderer = TestUtils.renderIntoDocument(
    <Provider store={store} key="provider">
      {() => <InfoBar/>}
    </Provider>
  );
  const dom = React.findDOMNode(renderer);

  it('should render correctly', () => {
    expect(renderer).to.be.ok;
  });

  it('should render with correct value', () => {
    const text = dom.getElementsByTagName('strong')[0].textContent;
    expect(text).to.equal(mockStore.info.data.message);
  });

  it('should render with a reload button', () => {
    const text = dom.getElementsByTagName('button')[0].textContent;
    expect(text).to.be.a('string');
  });

  it('should render the correct className', () => {
    const styles = require('components/InfoBar/InfoBar.scss');
    expect(styles.infoBar).to.be.a('string');
    expect(dom.className).to.include(styles.infoBar);
  });

});
<commit_msg>Update ApiClient in InfoBar test<commit_after>import React from 'react/addons';
import { expect} from 'chai';
import { InfoBar } from 'components';
import { Provider } from 'react-redux';
import createStore from 'redux/create';
import ApiClient from 'helpers/ApiClient';
const { TestUtils } = React.addons;
const client = new ApiClient();

describe('InfoBar', () => {
  const mockStore = {
    info: {
      load: () => {},
      loaded: true,
      loading: false,
      data: {
        message: 'This came from the api server',
        time: Date.now()
      }
    }
  };

  const store = createStore(client, mockStore);
  const renderer = TestUtils.renderIntoDocument(
    <Provider store={store} key="provider">
      {() => <InfoBar/>}
    </Provider>
  );
  const dom = React.findDOMNode(renderer);

  it('should render correctly', () => {
    expect(renderer).to.be.ok;
  });

  it('should render with correct value', () => {
    const text = dom.getElementsByTagName('strong')[0].textContent;
    expect(text).to.equal(mockStore.info.data.message);
  });

  it('should render with a reload button', () => {
    const text = dom.getElementsByTagName('button')[0].textContent;
    expect(text).to.be.a('string');
  });

  it('should render the correct className', () => {
    const styles = require('components/InfoBar/InfoBar.scss');
    expect(styles.infoBar).to.be.a('string');
    expect(dom.className).to.include(styles.infoBar);
  });

});
<|endoftext|>


<commit_before>import { compensateForBorder } from '../util/borderTools'
import { css } from 'glamor'
import { createElement, PropTypes } from 'react'
import { boxModelRuleVerticalRhythm as vr } from '../util/verticalRhythm'

const styles = {
  root: css({
    overflow: 'hidden'
  })
}

const Bit = (
  {
    as = 'div',

    bottom,
    left,
    right,
    top,

    minHeight,
    height,
    maxHeight,

    minWidth,
    width,
    maxWidth,

    className,
    children,

    margin,
    marginVertical = margin,
    marginHorizontal = margin,
    marginTop = marginVertical,
    marginBottom = marginVertical,
    marginLeft = marginHorizontal,
    marginRight = marginHorizontal,

    borderColor,
    borderTopColor = borderColor,
    borderRightColor = borderColor,
    borderBottomColor = borderColor,
    borderLeftColor = borderColor,
    borderWidth = 0,
    borderTopWidth = borderWidth,
    borderBottomWidth = borderWidth,
    borderLeftWidth = borderWidth,
    borderRightWidth = borderWidth,
    borderStyle = 'solid',
    borderTopStyle = borderStyle,
    borderRightStyle = borderStyle,
    borderBottomStyle = borderStyle,
    borderLeftStyle = borderStyle,
    borderRadius,
    borderBottomRadius = borderRadius,
    borderTopRadius = borderRadius,
    borderBottomLeftRadius = borderBottomRadius,
    borderBottomRightRadius = borderBottomRadius,
    borderTopLeftRadius = borderTopRadius,
    borderTopRightRadius = borderTopRadius,

    padding,
    paddingVertical = padding,
    paddingHorizontal = padding,
    paddingTop = paddingVertical,
    paddingBottom = paddingVertical,
    paddingLeft = paddingHorizontal,
    paddingRight = paddingHorizontal,

    backgroundColor,
    color,

    nativeProps,
    ...props
  },
  context
) => {
  const rhythmProps = {
    bottom,
    height,
    left,
    marginBottom,
    marginLeft,
    marginRight,
    marginTop,
    maxHeight,
    maxWidth,
    minHeight,
    minWidth,
    paddingBottom,
    paddingLeft,
    paddingRight,
    paddingTop,
    right,
    top,
    width
  }
  const boxModelRules = Object.keys(rhythmProps).reduce(
    (rules, propName) => ({
      ...rules,
      [propName]: vr(rhythmProps[propName], context)
    }),
    {}
  )
  const borderWidthRules = compensateForBorder(boxModelRules, context, {
    borderBottomStyle,
    borderBottomWidth,
    borderLeftStyle,
    borderLeftWidth,
    borderRightStyle,
    borderRightWidth,
    borderTopStyle,
    borderTopWidth
  })
  /*
   * Merge all the styles and convert to string so that the `as` property can
   * interop with other 3rd party components
   */
  const boxModelClassName = css(
    {
      ...boxModelRules,
      ...borderWidthRules
    },
    styles.root,
    {
      backgroundColor,
      borderBottomColor,
      borderBottomLeftRadius,
      borderBottomRightRadius,
      borderLeftColor,
      borderRightColor,
      borderTopColor,
      borderTopLeftRadius,
      borderTopRightRadius,
      color
    }
  )
  // TODO: Add stemcell version of cx for easy addition of various classes (or look if glamor has its own)
  return createElement(
    as,
    {
      className: `${boxModelClassName} ${className || ''}`,
      ...props,
      ...nativeProps
    },
    children
  )
}

Bit.contextTypes = {
  baseFontSize: PropTypes.number,
  lineHeightRatio: PropTypes.number,
  scaleRatio: PropTypes.oneOfType([PropTypes.number, PropTypes.string])
}

Bit.defaultProps = {
  as: 'div',
  nativeProps: {}
}

Bit.propTypes = {
  as: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
  backgroundColor: PropTypes.string,
  borderBottomColor: PropTypes.string,
  borderBottomLeftRadius: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.string
  ]),
  borderBottomRadius: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  borderBottomRightRadius: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.string
  ]),
  borderBottomStyle: PropTypes.string,
  borderBottomWidth: PropTypes.number,
  borderColor: PropTypes.string,
  borderHorizontalWidth: PropTypes.number,
  borderLeftColor: PropTypes.string,
  borderLeftStyle: PropTypes.string,
  borderLeftWidth: PropTypes.number,
  borderRadius: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  borderRightColor: PropTypes.string,
  borderRightStyle: PropTypes.string,
  borderRightWidth: PropTypes.number,
  borderStyle: PropTypes.string,
  borderTopColor: PropTypes.string,
  borderTopLeftRadius: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.string
  ]),
  borderTopRadius: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  borderTopRightRadius: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.string
  ]),
  borderTopStyle: PropTypes.string,
  borderTopWidth: PropTypes.number,
  borderVertical: PropTypes.number,
  borderWidth: PropTypes.number,
  bottom: PropTypes.number,
  children: PropTypes.node,
  className: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
  color: PropTypes.string,
  height: PropTypes.number,
  left: PropTypes.number,
  margin: PropTypes.number,
  marginBottom: PropTypes.number,
  marginHorizontal: PropTypes.number,
  marginLeft: PropTypes.number,
  marginRight: PropTypes.number,
  marginTop: PropTypes.number,
  marginVertical: PropTypes.number,
  maxHeight: PropTypes.number,
  maxWidth: PropTypes.number,
  minHeight: PropTypes.number,
  minWidth: PropTypes.number,
  nativeProps: PropTypes.object,
  padding: PropTypes.number,
  paddingBottom: PropTypes.number,
  paddingHorizontal: PropTypes.number,
  paddingLeft: PropTypes.number,
  paddingRight: PropTypes.number,
  paddingTop: PropTypes.number,
  paddingVertical: PropTypes.number,
  right: PropTypes.number,
  top: PropTypes.number,
  width: PropTypes.number
}

export default Bit
<commit_msg>Fix bug preventing negative positioning of elements<commit_after>import { compensateForBorder } from '../util/borderTools'
import { css } from 'glamor'
import { createElement, PropTypes } from 'react'
import { boxModelRuleVerticalRhythm as vr } from '../util/verticalRhythm'

const Bit = (
  {
    as = 'div',

    bottom,
    left,
    right,
    top,

    minHeight,
    height,
    maxHeight,

    minWidth,
    width,
    maxWidth,

    className,
    children,

    margin,
    marginVertical = margin,
    marginHorizontal = margin,
    marginTop = marginVertical,
    marginBottom = marginVertical,
    marginLeft = marginHorizontal,
    marginRight = marginHorizontal,

    borderColor,
    borderTopColor = borderColor,
    borderRightColor = borderColor,
    borderBottomColor = borderColor,
    borderLeftColor = borderColor,
    borderWidth = 0,
    borderTopWidth = borderWidth,
    borderBottomWidth = borderWidth,
    borderLeftWidth = borderWidth,
    borderRightWidth = borderWidth,
    borderStyle = 'solid',
    borderTopStyle = borderStyle,
    borderRightStyle = borderStyle,
    borderBottomStyle = borderStyle,
    borderLeftStyle = borderStyle,
    borderRadius,
    borderBottomRadius = borderRadius,
    borderTopRadius = borderRadius,
    borderBottomLeftRadius = borderBottomRadius,
    borderBottomRightRadius = borderBottomRadius,
    borderTopLeftRadius = borderTopRadius,
    borderTopRightRadius = borderTopRadius,

    padding,
    paddingVertical = padding,
    paddingHorizontal = padding,
    paddingTop = paddingVertical,
    paddingBottom = paddingVertical,
    paddingLeft = paddingHorizontal,
    paddingRight = paddingHorizontal,

    backgroundColor,
    color,

    nativeProps,
    ...props
  },
  context
) => {
  const rhythmProps = {
    bottom,
    height,
    left,
    marginBottom,
    marginLeft,
    marginRight,
    marginTop,
    maxHeight,
    maxWidth,
    minHeight,
    minWidth,
    paddingBottom,
    paddingLeft,
    paddingRight,
    paddingTop,
    right,
    top,
    width
  }
  const boxModelRules = Object.keys(rhythmProps).reduce(
    (rules, propName) => ({
      ...rules,
      [propName]: vr(rhythmProps[propName], context)
    }),
    {}
  )
  const borderWidthRules = compensateForBorder(boxModelRules, context, {
    borderBottomStyle,
    borderBottomWidth,
    borderLeftStyle,
    borderLeftWidth,
    borderRightStyle,
    borderRightWidth,
    borderTopStyle,
    borderTopWidth
  })
  /*
   * Merge all the styles and convert to string so that the `as` property can
   * interop with other 3rd party components
   */
  const boxModelClassName = css({
    ...boxModelRules,
    ...borderWidthRules,
    backgroundColor,
    borderBottomColor,
    borderBottomLeftRadius,
    borderBottomRightRadius,
    borderLeftColor,
    borderRightColor,
    borderTopColor,
    borderTopLeftRadius,
    borderTopRightRadius,
    color
  })
  // TODO: Add stemcell version of cx for easy addition of various classes (or look if glamor has its own)
  return createElement(
    as,
    {
      className: `${boxModelClassName} ${className || ''}`,
      ...props,
      ...nativeProps
    },
    children
  )
}

Bit.contextTypes = {
  baseFontSize: PropTypes.number,
  lineHeightRatio: PropTypes.number,
  scaleRatio: PropTypes.oneOfType([PropTypes.number, PropTypes.string])
}

Bit.defaultProps = {
  as: 'div',
  nativeProps: {}
}

Bit.propTypes = {
  as: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
  backgroundColor: PropTypes.string,
  borderBottomColor: PropTypes.string,
  borderBottomLeftRadius: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.string
  ]),
  borderBottomRadius: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  borderBottomRightRadius: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.string
  ]),
  borderBottomStyle: PropTypes.string,
  borderBottomWidth: PropTypes.number,
  borderColor: PropTypes.string,
  borderHorizontalWidth: PropTypes.number,
  borderLeftColor: PropTypes.string,
  borderLeftStyle: PropTypes.string,
  borderLeftWidth: PropTypes.number,
  borderRadius: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  borderRightColor: PropTypes.string,
  borderRightStyle: PropTypes.string,
  borderRightWidth: PropTypes.number,
  borderStyle: PropTypes.string,
  borderTopColor: PropTypes.string,
  borderTopLeftRadius: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.string
  ]),
  borderTopRadius: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
  borderTopRightRadius: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.string
  ]),
  borderTopStyle: PropTypes.string,
  borderTopWidth: PropTypes.number,
  borderVertical: PropTypes.number,
  borderWidth: PropTypes.number,
  bottom: PropTypes.number,
  children: PropTypes.node,
  className: PropTypes.oneOfType([PropTypes.object, PropTypes.string]),
  color: PropTypes.string,
  height: PropTypes.number,
  left: PropTypes.number,
  margin: PropTypes.number,
  marginBottom: PropTypes.number,
  marginHorizontal: PropTypes.number,
  marginLeft: PropTypes.number,
  marginRight: PropTypes.number,
  marginTop: PropTypes.number,
  marginVertical: PropTypes.number,
  maxHeight: PropTypes.number,
  maxWidth: PropTypes.number,
  minHeight: PropTypes.number,
  minWidth: PropTypes.number,
  nativeProps: PropTypes.object,
  padding: PropTypes.number,
  paddingBottom: PropTypes.number,
  paddingHorizontal: PropTypes.number,
  paddingLeft: PropTypes.number,
  paddingRight: PropTypes.number,
  paddingTop: PropTypes.number,
  paddingVertical: PropTypes.number,
  right: PropTypes.number,
  top: PropTypes.number,
  width: PropTypes.number
}

export default Bit
<|endoftext|>


<commit_before>import React from 'react';
import styled from 'styled-components';
import {name} from '../../config.json';
import hub from '../img/hub';

import {colors, sizes, zIndex} from '../constants';

const Wrapper = styled.div`
  width: ${sizes.hub.width};
  height: ${sizes.hub.height};
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
`;

const Item = styled.div`
  width: ${sizes.hub.width};
  height: ${sizes.hub.height};
  z-index: ${props => zIndex.hub[props.id]};
  background-image: url(${props => hub[props.id]});
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  position: absolute;
  top: 0;
  left: 0;
`;

const Images = styled.div`
  position: relative;
  top: 0;
  left: 0;
  position: absolute;
`;

const Text = styled.span`
  color: ${colors.white};
  margin-top: -9vh;
  font-size: 3vh;
`;

export default () => {
  return (
    <Wrapper>
      <Text>{name}</Text>
      <Images>
        <Item id="north_front" />
        <Item id="north_back" />
        <Item id="jar" />
        <Item id="south_front" />
        <Item id="south_back" />
        <Item id="platform" />
      </Images>
    </Wrapper>
  );
}
<commit_msg>shouldComponentUpdate false but still happens<commit_after>import React, {Component} from 'react';
import styled from 'styled-components';
import {name} from '../../config.json';
import hub from '../img/hub';

import {colors, sizes, zIndex} from '../constants';

const Wrapper = styled.div`
  width: ${sizes.hub.width};
  height: ${sizes.hub.height};
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
`;

const Item = styled.div`
  width: ${sizes.hub.width};
  height: ${sizes.hub.height};
  z-index: ${props => zIndex.hub[props.id]};
  background-image: url(${props => hub[props.id]});
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  position: absolute;
  top: 0;
  left: 0;
`;

const Images = styled.div`
  position: relative;
  top: 0;
  left: 0;
  position: absolute;
`;

const Text = styled.span`
  color: ${colors.white};
  margin-top: -9vh;
  font-size: 3vh;
`;

class Hub extends Component {
  shouldComponentUpdate(nextProps, nextState) {
    return false;
  }

  render() {
    return (
      <Wrapper>
        <Text>{name}</Text>
        <Images>
          <Item id="north_front" />
          <Item id="north_back" />
          <Item id="jar" />
          <Item id="south_front" />
          <Item id="south_back" />
          <Item id="platform" />
        </Images>
      </Wrapper>
    );
  }
};

export default Hub;
<|endoftext|>