<commit_before>'use strict';

var React = require('react');

var DOM = React.DOM;
var DateTimePickerTime = React.createClass({
	getInitialState: function(){
		return this.calculateState( this.props );
	},
	calculateState: function( props ){
		var date = props.selectedDate || props.viewDate,
			format = props.timeFormat,
			counters = []
		;

		if( format.indexOf('H') != -1 || format.indexOf('h') != -1 ){
			counters.push('hours');
			if( format.indexOf('m') != -1 ){
				counters.push('minutes');
				if( format.indexOf('s') != -1 ){
					counters.push('seconds');
				}
			}
		}

		var daypart = false;
		if( this.props.timeFormat.indexOf(' A') != -1  && this.state != null ){
			daypart = ( this.state.hours > 12 ) ? 'PM' : 'AM';
		}

		return {
			hours: date.format('H'),
			minutes: date.format('mm'),
			seconds: date.format('ss'),
			milliseconds: date.format('SSS'),
			daypart: daypart,
			counters: counters
		};
	},
	renderCounter: function( type ){
		if (type !== 'daypart') {
			var value = this.state[ type ];
			if (type === 'hours' && this.props.timeFormat.indexOf(' A') != -1 && value > 12) {
				value = value - 12;
			}
			return DOM.div({ key: type, className: 'rdtCounter'}, [
				DOM.span({ key:'up', className: 'rdtBtn', onMouseDown: this.onStartClicking( 'increase', type ) }, '▲' ),
				DOM.div({ key:'c', className: 'rdtCount' }, value ),
				DOM.span({ key:'do', className: 'rdtBtn', onMouseDown: this.onStartClicking( 'decrease', type ) }, '▼' )
			]);
		}
		return '';
	},
	render: function() {
		var me = this,
			counters = []
		;

		this.state.counters.forEach( function(c){
			if( counters.length )
				counters.push( DOM.div( {key: 'sep' + counters.length, className: 'rdtCounterSeparator' }, ':' ));
			counters.push( me.renderCounter( c ) );
		});

		if (this.state.daypart !== false) {
			counters.push(DOM.div({ key: this.state.daypart, className: 'rdtDayPart'}, this.state.daypart ));
		}

		if( this.state.counters.length == 3 && this.props.timeFormat.indexOf('S') != -1 ){
			counters.push( DOM.div( {className: 'rdtCounterSeparator', key: 'sep5' }, ':' ));
			counters.push(
				DOM.div( {className: 'rdtCounter rdtMilli', key:'m'},
					DOM.input({ value: this.state.milliseconds, type: 'text', onChange: this.updateMilli })
					)
				);
		}

		return DOM.div( {className: 'rdtTime'},
			DOM.table( {}, [
				this.renderHeader(),
				DOM.tbody({key: 'b'}, DOM.tr({}, DOM.td({},
					DOM.div({ className: 'rdtCounters' }, counters )
				)))
			])
		);
	},
	componentWillReceiveProps: function( nextProps, nextState ){
		this.setState( this.calculateState( nextProps ) );
	},
	updateMilli: function( e ){
		var milli = parseInt( e.target.value );
		if( milli == e.target.value && milli >= 0 && milli < 1000 ){
			this.props.setTime( 'milliseconds', milli );
			this.setState({ milliseconds: milli });
		}
	},
	renderHeader: function(){
		if( !this.props.dateFormat )
			return null;

		var date = this.props.selectedDate || this.props.viewDate;
		return DOM.thead({ key: 'h'}, DOM.tr({},
			DOM.th( {className: 'rdtSwitch', colSpan: 4, onClick: this.props.showView('days')}, date.format( this.props.dateFormat ) )
		));
	},
	onStartClicking: function( action, type ){
		var me = this,
			update = {},
			value = this.state[ type ]
		;

		return function(){
			var update = {};
			update[ type ] = me[ action ]( type );
			me.setState( update );

			me.timer = setTimeout( function(){
				me.increaseTimer = setInterval( function(){
					update[ type ] = me[ action ]( type );
					me.setState( update );
				},70);
			}, 500);

			me.mouseUpListener = function(){
				clearTimeout( me.timer );
				clearInterval( me.increaseTimer );
				me.props.setTime( type, me.state[ type ] );
				document.body.removeEventListener('mouseup', me.mouseUpListener);
			};

			document.body.addEventListener('mouseup', me.mouseUpListener);
		};
	},

	maxValues: {
		hours: 23,
		minutes: 59,
		seconds: 59,
		milliseconds: 999
	},
	padValues: {
		hours: 1,
		minutes: 2,
		seconds: 2,
		milliseconds: 3
	},
	increase: function( type ){
		var value = parseInt(this.state[ type ]) + 1;
		if( value > this.maxValues[ type ] )
			value = 0;
		return this.pad( type, value );
	},
	decrease: function( type ){
		var value = parseInt(this.state[ type ]) - 1;
		if( value < 0 )
			value = this.maxValues[ type ];
		return this.pad( type, value );
	},
	pad: function( type, value ){
		var str = value + '';
		while( str.length < this.padValues[ type ] )
			str = '0' + str;
		return str;
	}
});

module.exports = DateTimePickerTime;
<commit_msg>fix 12 hour time clock to display correct 12AM /12PM in the picker component<commit_after>'use strict';

var React = require('react');

var DOM = React.DOM;
var DateTimePickerTime = React.createClass({
	getInitialState: function(){
		return this.calculateState( this.props );
	},
	calculateState: function( props ){
		var date = props.selectedDate || props.viewDate,
			format = props.timeFormat,
			counters = []
		;

		if( format.indexOf('H') != -1 || format.indexOf('h') != -1 ){
			counters.push('hours');
			if( format.indexOf('m') != -1 ){
				counters.push('minutes');
				if( format.indexOf('s') != -1 ){
					counters.push('seconds');
				}
			}
		}

		var daypart = false;
		if( this.props.timeFormat.indexOf(' A') != -1  && this.state != null ){
			daypart = ( this.state.hours >= 12 ) ? 'PM' : 'AM';
		}

		return {
			hours: date.format('H'),
			minutes: date.format('mm'),
			seconds: date.format('ss'),
			milliseconds: date.format('SSS'),
			daypart: daypart,
			counters: counters
		};
	},
	renderCounter: function( type ){
		if (type !== 'daypart') {
			var value = this.state[ type ];
			if (type === 'hours' && this.props.timeFormat.indexOf(' A') != -1 && value > 12) {
				if(value > 12){
					value = value - 12;
				}
				if(value == 0) {
					value = 12;
				}
			}
			return DOM.div({ key: type, className: 'rdtCounter'}, [
				DOM.span({ key:'up', className: 'rdtBtn', onMouseDown: this.onStartClicking( 'increase', type ) }, '▲' ),
				DOM.div({ key:'c', className: 'rdtCount' }, value ),
				DOM.span({ key:'do', className: 'rdtBtn', onMouseDown: this.onStartClicking( 'decrease', type ) }, '▼' )
			]);
		}
		return '';
	},
	render: function() {
		var me = this,
			counters = []
		;

		this.state.counters.forEach( function(c){
			if( counters.length )
				counters.push( DOM.div( {key: 'sep' + counters.length, className: 'rdtCounterSeparator' }, ':' ));
			counters.push( me.renderCounter( c ) );
		});

		if (this.state.daypart !== false) {
			counters.push(DOM.div({ key: this.state.daypart, className: 'rdtDayPart'}, this.state.daypart ));
		}

		if( this.state.counters.length == 3 && this.props.timeFormat.indexOf('S') != -1 ){
			counters.push( DOM.div( {className: 'rdtCounterSeparator', key: 'sep5' }, ':' ));
			counters.push(
				DOM.div( {className: 'rdtCounter rdtMilli', key:'m'},
					DOM.input({ value: this.state.milliseconds, type: 'text', onChange: this.updateMilli })
					)
				);
		}

		return DOM.div( {className: 'rdtTime'},
			DOM.table( {}, [
				this.renderHeader(),
				DOM.tbody({key: 'b'}, DOM.tr({}, DOM.td({},
					DOM.div({ className: 'rdtCounters' }, counters )
				)))
			])
		);
	},
	componentWillReceiveProps: function( nextProps, nextState ){
		this.setState( this.calculateState( nextProps ) );
	},
	updateMilli: function( e ){
		var milli = parseInt( e.target.value );
		if( milli == e.target.value && milli >= 0 && milli < 1000 ){
			this.props.setTime( 'milliseconds', milli );
			this.setState({ milliseconds: milli });
		}
	},
	renderHeader: function(){
		if( !this.props.dateFormat )
			return null;

		var date = this.props.selectedDate || this.props.viewDate;
		return DOM.thead({ key: 'h'}, DOM.tr({},
			DOM.th( {className: 'rdtSwitch', colSpan: 4, onClick: this.props.showView('days')}, date.format( this.props.dateFormat ) )
		));
	},
	onStartClicking: function( action, type ){
		var me = this,
			update = {},
			value = this.state[ type ]
		;

		return function(){
			var update = {};
			update[ type ] = me[ action ]( type );
			me.setState( update );

			me.timer = setTimeout( function(){
				me.increaseTimer = setInterval( function(){
					update[ type ] = me[ action ]( type );
					me.setState( update );
				},70);
			}, 500);

			me.mouseUpListener = function(){
				clearTimeout( me.timer );
				clearInterval( me.increaseTimer );
				me.props.setTime( type, me.state[ type ] );
				document.body.removeEventListener('mouseup', me.mouseUpListener);
			};

			document.body.addEventListener('mouseup', me.mouseUpListener);
		};
	},

	maxValues: {
		hours: 23,
		minutes: 59,
		seconds: 59,
		milliseconds: 999
	},
	padValues: {
		hours: 1,
		minutes: 2,
		seconds: 2,
		milliseconds: 3
	},
	increase: function( type ){
		var value = parseInt(this.state[ type ]) + 1;
		if( value > this.maxValues[ type ] )
			value = 0;
		return this.pad( type, value );
	},
	decrease: function( type ){
		var value = parseInt(this.state[ type ]) - 1;
		if( value < 0 )
			value = this.maxValues[ type ];
		return this.pad( type, value );
	},
	pad: function( type, value ){
		var str = value + '';
		while( str.length < this.padValues[ type ] )
			str = '0' + str;
		return str;
	}
});

module.exports = DateTimePickerTime;
<|endoftext|>


<commit_before>var UISwitch = function(element, options) {
    options = options || {};

    if (typeof element.type === 'undefined' || element.type !== 'checkbox') {
        throw new Error("'element' must be a checkbox");
    }

    for (var option in UISwitch.defaultOptions) {
        if (!(option in options)) {
            options[option] = UISwitch.defaultOptions[option];
        }
    }

    this._enabled = options.enabled;
    this._activatedColor = options.activatedColor;
    this._deactivatedColor = options.deactivatedColor;
    this._transitionTime = options.transitionTime;
    this._disabledOpacity = options.disabledOpacity;
};

UISwitch.defaultOptions = {
    enabled: true,
    activatedColor: '#4bd963',
    deactivatedColor: '#ffffff',
    transitionTime: 2500,
    disabledOpacity: 0.5
};

Object.defineProperty(UISwitch.prototype, 'enabled', {
    get: function() {
        return this._enabled;
    },
    set: function(enabled) {
        this._enabled = enabled;
    }
});

Object.defineProperty(UISwitch.prototype, 'activatedColor', {
    get: function() {
        return this._activatedColor;
    },
    set: function(activatedColor) {
        this._activatedColor = activatedColor;
    }
});

Object.defineProperty(UISwitch.prototype, 'deactivatedColor', {
    get: function() {
        return this._deactivatedColor;
    },
    set: function(deactivatedColor) {
        this._deactivatedColor = deactivatedColor;
    }
});

Object.defineProperty(UISwitch.prototype, 'transitionTime', {
    get: function() {
        return this._transitionTime;
    },
    set: function(transitionTime) {
        this._transitionTime = transitionTime;
    }
});

Object.defineProperty(UISwitch.prototype, 'className', {
    get: function() {
        return this._className;
    },
    set: function(className) {
        this._className = className;
    }
});

Object.defineProperty(UISwitch.prototype, 'disabledOpacity', {
    get: function() {
        return this._disabledOpacity;
    },
    set: function(disabledOpacity) {
        this._disabledOpacity = disabledOpacity;
    }
});
<commit_msg>Added activated property.<commit_after>var UISwitch = function(element, options) {
    options = options || {};

    if (typeof element.type === 'undefined' || element.type !== 'checkbox') {
        throw new Error("'element' must be a checkbox");
    }

    for (var option in UISwitch.defaultOptions) {
        if (!(option in options)) {
            options[option] = UISwitch.defaultOptions[option];
        }
    }

    this._enabled = options.enabled;
    this._activatedColor = options.activatedColor;
    this._deactivatedColor = options.deactivatedColor;
    this._transitionTime = options.transitionTime;
    this._disabledOpacity = options.disabledOpacity;
    this._activated = element.checked;
};

UISwitch.defaultOptions = {
    enabled: true,
    activatedColor: '#4bd963',
    deactivatedColor: '#ffffff',
    transitionTime: 2500,
    disabledOpacity: 0.5
};

Object.defineProperty(UISwitch.prototype, 'enabled', {
    get: function() {
        return this._enabled;
    },
    set: function(enabled) {
        this._enabled = enabled;
    }
});

Object.defineProperty(UISwitch.prototype, 'activatedColor', {
    get: function() {
        return this._activatedColor;
    },
    set: function(activatedColor) {
        this._activatedColor = activatedColor;
    }
});

Object.defineProperty(UISwitch.prototype, 'deactivatedColor', {
    get: function() {
        return this._deactivatedColor;
    },
    set: function(deactivatedColor) {
        this._deactivatedColor = deactivatedColor;
    }
});

Object.defineProperty(UISwitch.prototype, 'transitionTime', {
    get: function() {
        return this._transitionTime;
    },
    set: function(transitionTime) {
        this._transitionTime = transitionTime;
    }
});

Object.defineProperty(UISwitch.prototype, 'className', {
    get: function() {
        return this._className;
    },
    set: function(className) {
        this._className = className;
    }
});

Object.defineProperty(UISwitch.prototype, 'disabledOpacity', {
    get: function() {
        return this._disabledOpacity;
    },
    set: function(disabledOpacity) {
        this._disabledOpacity = disabledOpacity;
    }
});

Object.defineProperty(UISwitch.prototype, 'activated', {
    get: function() {
        return this._activated;
    },
    set: function() {
        this._activated = activated;
    }
});<|endoftext|>


<commit_before>var WARNINGS = {
  warnings: [
    { keyword: 'just',
      source:  'http://www.taramohr.com/8-ways-women-undermine-themselves-with-their-words/',
      message: '"Just" demeans what you have to say. "Just" shrinks your power. ' +
               'It\'s time to say goodbye to the justs. --Tara Sophia Mohr', },
    { keyword: 'actually',
      source:  'http://www.taramohr.com/8-ways-women-undermine-themselves-with-their-words/',
      message: '"Actually" communicates a sense of surprise that you have ' +
               'something to say. Of course you want to add something. Of ' +
               'course you have questions. There\'s nothing surprising about ' +
               'it.  --Tara Sophia Mohr', },
    { keyword: 'sorry',
      source:  'http://www.fastcompany.com/3032112/strong-female-lead/sorry-not-sorry-why-women-need-to-stop-apologizing-for-everything',
      message: 'Using "sorry" frequently undermines your gravitas and makes you ' +
               'appear unfit for leadership. --Sylvia Ann Hewlett', },
    { keyword: 'apologize|apologies|forgive',
      source:  'http://www.fastcompany.com/3032112/strong-female-lead/sorry-not-sorry-why-women-need-to-stop-apologizing-for-everything',
      message: 'Apologizing unnecessarily puts you in a subservient position and ' +
               'makes people lose respect for you --Bonnie Marcus', },
    { keyword: 'I think|We think',
      source:  'http://www.fastcompany.com/3049609/the-future-of-work/4-types-of-useless-phrases-you-need-to-eliminate-from-your-emails',
      message: '"I think" undermines your idea and displays an overall lack of ' +
               'self-confidence. --Lydia Dishman', },
    { keyword: 'I\'m no expert|We\'re no expert',
      source:  'http://www.fastcompany.com/3049609/the-future-of-work/4-types-of-useless-phrases-you-need-to-eliminate-from-your-emails',
      message: '"I\'m no expert" undermines your idea and displays an overall ' +
              'lack of self-confidence. --Lydia Dishman', },
    { keyword: 'Yes, but',
      source:  'http://www.strategicserendipityforlife.com/documents/Articles/Communication_8TipsForFearlessCommunicationInTheWorkplace.pdf',
      message: 'The "Yes, but" syndrome is entirely counterproductive, particularly in a work setting. ' +
               'You will become an integral part of any team if you are willing ' +
               'to build ideas rather than discard them. --Victoria Simon, Ph.D. and Holly Pedersen, Ph.D.', },
    { keyword: 'literally',
      source:  'https://expresswriters.com/50-weak-words-and-phrases-to-cut-out-of-your-blogging/',
      message: 'If something is literal, your readers should know it without you needing to use this word to clarify it. ' +
               'More often than not, the word "literally" makes writing sound flabby and juvenile, ' +
               'which is probably not what you\'re going for. --Julia McCoy', },
    { keyword: 'very',
      source:  'http://blog.crew.co/5-weak-words-to-avoid/',
      message: 'The word \'very\' does not communicate enough information. Find a stronger, more meaningful adverb, or omit it completely. --Andrea Ayres', },
    { keyword: 'kind of|sort of',
      source:  'http://www.strategicserendipityforlife.com/documents/Articles/Communication_8TipsForFearlessCommunicationInTheWorkplace.pdf',
      message: 'This qualifier weakens the message as well as the authority of the writer. --Victoria Simon, Ph.D. and Holly Pedersen, Ph.D.',
    },
    { keyword: 'does that make sense',
      source:  'http://goop.com/how-women-undermine-themselves-with-words/',
      message: '"does that make sense" comes across either as condescending ' +
               '(like your audience can\'t understand) or it implies you feel ' +
               'you\'ve been incoherent. A better way to close is something like ' +
               '"I look forward to hearing your thoughts." You can leave it up ' +
               'to the other party to let you know if they are confused about ' +
               'something, rather than implying that you "didn\'t make sense." ' +
               '--Tara Sophia Mohr', },
    { keyword: 'try|trying',
      source:  'http://www.lifehack.org/articles/communication/7-things-not-to-say-and-7-things-to-start-saying.html',
      message: '"Do or do not. There is no try." --Yoda' },
    { keyword: 'I should',
      source:  'http://www.lifehack.org/articles/communication/7-things-not-to-say-and-7-things-to-start-saying.html',
      message: 'The word "should" is inherently negative. "Should" implies a lose: lose ' +
               'situation and it\'s just not conducive to positive outcomes in life. ' +
               'It\'s a form of criticism, and it\'s best left out of your everyday language. ' +
               'Instead of beating yourself up for what you should have done, ' +
               'focus on what you have the power to change. ' +
               '-- Zoe B', },
    { keyword: 'I feel',
      source:  'http://www.freelancewriting.com/articles/ten-words-to-avoid-when-writing.php',
      message: 'If you write an opinion, the reader understands that you also ' +
               'believe it is right. ' +
               '--David Bowman', },
    { keyword: 'I believe',
      source:  'https://hbr.org/2011/12/replace-meaningless-words-with',
      message: 'Phrases containing "we believe," "we think," and "we feel" pervade ' +
               'presentation narratives to such a degree that they spill over into ' +
               'sentences where caution is unnecessary. ' +
               '--Jerry Weissman', },
    { keyword: 'I\'m just saying',
      source:  'http://101books.net/2012/03/02/7-annoying-words-that-should-die-a-horrible-death/',
      message: 'I think what you\'re saying is that you said something. If ' +
               'you\'re using it to mitigate something that may be offensive or ' +
               'embarrassing, then don\'t say it. Say something else. Otherwise, ' +
               'say what you\'re saying without the "just saying." We already ' +
               'know you\'re saying it... after all, you just said it! ' +
               '--Robert Bruce', },
    { keyword: 'In my opinion',
      source:  'https://preciseedit.wordpress.com/2009/06/19/in-my-opinion-i-think-that-i-believe-this-is-bad-writing/',
      message: 'Phrases such as "in my opinion," "I think that," and "I believe" create three problems for writers: ' +
               '1. They delay the writer\'s message; ' +
               '2. They demonstrate insecurity; and ' +
               '3. They tell the reader what he already knows. Remove that phrase, or any similar phrase, ' +
               'and get to the point. --David Bowman', },
    { keyword: 'This might be a stupid question',
      source:  'http://www.vogue.com/13362056/things-working-women-should-never-email/',
      message: 'Like they said in school, there are no stupid ' +
               'questions. Well, sometimes there are--but ask, don\'t caveat. --Alexandra Macon', },
    { keyword: 'I may be wrong|I might be wrong',
      source:  'http://www.vogue.com/13362056/things-working-women-should-never-email/',
      message: 'Don\'t lessen the impact of what you say before ' +
               'you say it. --Alexandra Macon', },
  ],
};
<commit_msg>Add additional warnings per suggestions<commit_after>var WARNINGS = {
  warnings: [
    { keyword: 'just',
      source:  'http://www.taramohr.com/8-ways-women-undermine-themselves-with-their-words/',
      message: '"Just" demeans what you have to say. "Just" shrinks your power. ' +
               'It\'s time to say goodbye to the justs. --Tara Sophia Mohr', },
    { keyword: 'actually',
      source:  'http://www.taramohr.com/8-ways-women-undermine-themselves-with-their-words/',
      message: '"Actually" communicates a sense of surprise that you have ' +
               'something to say. Of course you want to add something. Of ' +
               'course you have questions. There\'s nothing surprising about ' +
               'it.  --Tara Sophia Mohr', },
    { keyword: 'sorry',
      source:  'http://www.fastcompany.com/3032112/strong-female-lead/sorry-not-sorry-why-women-need-to-stop-apologizing-for-everything',
      message: 'Using "sorry" frequently undermines your gravitas and makes you ' +
               'appear unfit for leadership. --Sylvia Ann Hewlett', },
    { keyword: 'apologize|apologies|forgive',
      source:  'http://www.fastcompany.com/3032112/strong-female-lead/sorry-not-sorry-why-women-need-to-stop-apologizing-for-everything',
      message: 'Apologizing unnecessarily puts you in a subservient position and ' +
               'makes people lose respect for you --Bonnie Marcus', },
    { keyword: 'I think|We think',
      source:  'http://www.fastcompany.com/3049609/the-future-of-work/4-types-of-useless-phrases-you-need-to-eliminate-from-your-emails',
      message: '"I think" undermines your idea and displays an overall lack of ' +
               'self-confidence. --Lydia Dishman', },
    { keyword: 'I\'m no expert|We\'re no expert',
      source:  'http://www.fastcompany.com/3049609/the-future-of-work/4-types-of-useless-phrases-you-need-to-eliminate-from-your-emails',
      message: '"I\'m no expert" undermines your idea and displays an overall ' +
              'lack of self-confidence. --Lydia Dishman', },
    { keyword: 'Yes, but',
      source:  'http://www.strategicserendipityforlife.com/documents/Articles/Communication_8TipsForFearlessCommunicationInTheWorkplace.pdf',
      message: 'The "Yes, but" syndrome is entirely counterproductive, particularly in a work setting. ' +
               'You will become an integral part of any team if you are willing ' +
               'to build ideas rather than discard them. --Victoria Simon, Ph.D. and Holly Pedersen, Ph.D.', },
    { keyword: 'literally',
      source:  'https://expresswriters.com/50-weak-words-and-phrases-to-cut-out-of-your-blogging/',
      message: 'If something is literal, your readers should know it without you needing to use this word to clarify it. ' +
               'More often than not, the word "literally" makes writing sound flabby and juvenile, ' +
               'which is probably not what you\'re going for. --Julia McCoy', },
    { keyword: 'very',
      source:  'http://blog.crew.co/5-weak-words-to-avoid/',
      message: 'The word \'very\' does not communicate enough information. Find a stronger, more meaningful adverb, or omit it completely. --Andrea Ayres', },
    { keyword: 'kind of|sort of',
      source:  'http://www.strategicserendipityforlife.com/documents/Articles/Communication_8TipsForFearlessCommunicationInTheWorkplace.pdf',
      message: 'This qualifier weakens the message as well as the authority of the writer. --Victoria Simon, Ph.D. and Holly Pedersen, Ph.D.',
    },
    { keyword: 'does that make sense',
      source:  'http://goop.com/how-women-undermine-themselves-with-words/',
      message: '"does that make sense" comes across either as condescending ' +
               '(like your audience can\'t understand) or it implies you feel ' +
               'you\'ve been incoherent. A better way to close is something like ' +
               '"I look forward to hearing your thoughts." You can leave it up ' +
               'to the other party to let you know if they are confused about ' +
               'something, rather than implying that you "didn\'t make sense." ' +
               '--Tara Sophia Mohr', },
    { keyword: 'try|trying',
      source:  'http://www.lifehack.org/articles/communication/7-things-not-to-say-and-7-things-to-start-saying.html',
      message: '"Do or do not. There is no try." --Yoda' },
    { keyword: 'I should',
      source:  'http://www.lifehack.org/articles/communication/7-things-not-to-say-and-7-things-to-start-saying.html',
      message: 'The word "should" is inherently negative. "Should" implies a lose: lose ' +
               'situation and it\'s just not conducive to positive outcomes in life. ' +
               'It\'s a form of criticism, and it\'s best left out of your everyday language. ' +
               'Instead of beating yourself up for what you should have done, ' +
               'focus on what you have the power to change. ' +
               '-- Zoe B', },
    { keyword: 'I feel',
      source:  'http://www.freelancewriting.com/articles/ten-words-to-avoid-when-writing.php',
      message: 'If you write an opinion, the reader understands that you also ' +
               'believe it is right. ' +
               '--David Bowman', },
    { keyword: 'I believe',
      source:  'https://hbr.org/2011/12/replace-meaningless-words-with',
      message: 'Phrases containing "we believe," "we think," and "we feel" pervade ' +
               'presentation narratives to such a degree that they spill over into ' +
               'sentences where caution is unnecessary. ' +
               '--Jerry Weissman', },
    { keyword: 'I\'m just saying',
      source:  'http://101books.net/2012/03/02/7-annoying-words-that-should-die-a-horrible-death/',
      message: 'I think what you\'re saying is that you said something. If ' +
               'you\'re using it to mitigate something that may be offensive or ' +
               'embarrassing, then don\'t say it. Say something else. Otherwise, ' +
               'say what you\'re saying without the "just saying." We already ' +
               'know you\'re saying it... after all, you just said it! ' +
               '--Robert Bruce', },
    { keyword: 'In my opinion',
      source:  'https://preciseedit.wordpress.com/2009/06/19/in-my-opinion-i-think-that-i-believe-this-is-bad-writing/',
      message: 'Phrases such as "in my opinion," "I think that," and "I believe" create three problems for writers: ' +
               '1. They delay the writer\'s message; ' +
               '2. They demonstrate insecurity; and ' +
               '3. They tell the reader what he already knows. Remove that phrase, or any similar phrase, ' +
               'and get to the point. --David Bowman', },
    { keyword: 'This might be a stupid question',
      source:  'http://www.vogue.com/13362056/things-working-women-should-never-email/',
      message: 'Like they said in school, there are no stupid ' +
               'questions. Well, sometimes there are--but ask, don\'t caveat. --Alexandra Macon', },
    { keyword: 'I may be wrong|I might be wrong',
      source:  'http://www.vogue.com/13362056/things-working-women-should-never-email/',
      message: 'Don\'t lessen the impact of what you say before ' +
               'you say it. --Alexandra Macon', },
    { keyword: 'I\'m just being honest here|If I\'m being honest|Honestly|to be honest|if I\'m honest|to be perfectly honest|in all honesty',
      source:  'https://lifehacker.com/the-verbal-tee-ups-that-often-reveal-dishonesty-1505870461',
      message: 'Tee-ups like this may make the reader shut down and respond negatively to your comment.', },
    { keyword: 'I guess',
      source:  'https://www.inc.com/mary-rezek/cut-kinda-sorta-i-guess-how-to-end-your-filler-word-bad-habits.html',
      message: 'If you\'re sure of something, \"guessing\" detracts from your message and opens doubt in the reader\'s mind.', },
  ],
};
<|endoftext|>


<commit_before>define([
    './utils/StringUtil',
    './Binding',
    './polyfills/CustomEvent',
    './polyfills/Object.assign',
    '../bower_components/webcomponentsjs/webcomponents-lite.js',
    '../bower_components/matchMedia/matchMedia',
    '../bower_components/matchMedia/matchMedia.addListener'
], function (
    StringUtil,
    Binding
) {
    'use strict';

    function XElement () {}

    XElement.mixin = {

        customAttributes: {},

        createdCallback: function () {
            this.bindings = [];
            this.mqDefs = [];
        },

        attachedCallback: function () {
            var attrName;
            var attrDef;
            for (attrName in this.customAttributes) {
                if (this.customAttributes.hasOwnProperty(attrName)) {
                    attrDef = this.customAttributes[attrName];
                    if (attrDef.responsive === true) {
                        XElement.updateResponsiveAttribute(this, attrName, attrDef);
                    }
                }
            }
        },

        detachedCallback: function () {
            var attrName;
            var attrDef;
            for (attrName in this.customAttributes) {
                if (this.customAttributes.hasOwnProperty(attrName)) {
                    attrDef = this.customAttributes[attrName];
                    if (attrDef.responsive === true) {
                        XElement.removeAttributeMqDefinitions(this, attrName);
                    }
                }
            }
        },

        attributeChangedCallback: function (attrName, oldVal, newVal) {
            var attrDef = this.customAttributes[attrName];
            if (attrDef === undefined) {
                return;
            }
            var oldProp;
            var oldEvaluatedProp;
            var newEvaluatedProp;
            var currentProp = 'current' + StringUtil.capitalize(StringUtil.toCamelCase(attrName));
            if (attrDef.responsive === true && document.contains(this)) {
                oldProp = (oldVal === null) ? '' + attrDef.default : oldVal;
                oldEvaluatedProp = XElement.evaluateResponsiveAttribute(oldProp, attrDef.type);
                XElement.updateResponsiveAttribute(this, attrName, attrDef);
                newEvaluatedProp = this[currentProp];
                if (oldEvaluatedProp !== newEvaluatedProp && attrDef.mediaChangedCallback instanceof Function) {
                    attrDef.mediaChangedCallback.call(this, oldEvaluatedProp, newEvaluatedProp);
                }
            }
            if (attrDef.changedCallback !== undefined) {
                attrDef.changedCallback.call(this, oldVal, newVal);
            }
        },

        getComponent: function (T, tag) {
            var selector = T.prototype.selector;
            if (tag !== undefined) {
                selector += '[data-tag="' + tag + '"]';
            }
            return this.querySelector(selector);
        },

        getComponents: function (T, tag) {
            var selector = T.prototype.selector;
            if (tag !== undefined) {
                selector += '[data-tag="' + tag + '"]';
            }
            return this.querySelectorAll(selector);
        },

        findWithTag: function (tag) {
            return this.querySelector('[data-tag="' + tag + '"]');
        },

        findAllWithTag: function (tag) {
            return this.querySelectorAll('[data-tag="' + tag + '"]');
        },

        createBinding: function (target, type, handler) {
            var binding = new Binding(target, type, handler);
            this.bindings.push(binding);
            return binding;
        },

        enable: function () {
            var i;
            var l = this.bindings.length;
            for (i = 0; i < l; i++) {
                this.bindings[i].enable();
            }
        },

        disable: function () {
            var i;
            var l = this.bindings.length;
            for (i = 0; i < l; i++) {
                this.bindings[i].disable();
            }
        },

        trigger: function (type, detail) {
            var e = new CustomEvent(type, { detail: detail });
            return this.dispatchEvent(e);
        }

    };

    XElement.registerCustomAttribute = function (prototype, attrName, attrDef) {
        var prop = StringUtil.toCamelCase(attrName);
        Object.defineProperty(prototype, prop, {
            get: function () {
                var attrValue = this.getAttribute(attrName);
                switch (attrDef.type) {

                    case Number:
                        // If the attribute is responsive, fallthrough to the String case
                        if (attrDef.responsive !== true) {
                            if (attrValue === null || attrValue.trim() === '' || isNaN(+attrValue)) {
                                attrValue = attrDef.default;
                            }
                            return +attrValue; // `+` quickly casts to a number
                        }

                    case String:
                        if (attrValue === null) {
                            attrValue = attrDef.default + '';
                        }
                        return attrValue;

                    case Boolean:
                        return attrValue !== null;
                }
            },
            set: function (value) {
                switch (attrDef.type) {
                    case Number:
                        // If the attribute is responsive, fallthrough to the String case
                        if (attrDef.responsive !== true) {
                            if (isNaN(+value) ) {
                                break;
                            }
                            this.setAttribute(attrName, value);
                            break;
                        }

                    case String:
                        this.setAttribute(attrName, value);
                        break;

                    case Boolean:
                        if (!!value) { // `!!` quickly casts to a boolean
                            this.setAttribute(attrName, '');
                        } else {
                            this.removeAttribute(attrName);
                        }
                        break;
                }
            }
        });
        if (attrDef.responsive === true) {
            Object.defineProperty(prototype, 'current' + StringUtil.capitalize(prop), {
                get: function () {
                    return XElement.evaluateResponsiveAttribute(this[prop], attrDef.type);
                }
            });
        }
    };

    XElement.parseResponsiveAttribute = function (value, type) {
        var definitions = value.split(',').map(function (x) { return x.trim(); });
        var unmatched = definitions.pop();
        if (type === Number) {
            unmatched = +unmatched;
        }
        return {
            unmatched: unmatched,
            breakpoints: definitions.map(function (definition) {
                var parts = definition.split(/\s(?=[^\s]*$)/); // Find last occurence of whitespace and split at it
                var mediaQuery = parts[0];
                var value = parts[1];
                if (type === Number) {
                    value = +value;
                }
                return {
                    mediaQuery: mediaQuery,
                    value: value
                };
            })
        };
    };

    XElement.evaluateResponsiveAttribute = function (value, type) {
        var parsed = XElement.parseResponsiveAttribute(value, type);
        return parsed.breakpoints.reduce(function (previous, breakpoint) {
            if (window.matchMedia(breakpoint.mediaQuery).matches) {
                return breakpoint.value;
            }
            return previous;
        }, parsed.unmatched);
    };

    XElement.removeAttributeMqDefinitions = function (instance, attrName) {
        var mqDef;
        var i = instance.mqDefs.length;

        // Loop backwards because we're potetially going to remove items from the array
        while ((mqDef = instance.mqDefs[--i]) !== undefined) {
            if (mqDef.attribute !== attrName) {
                continue;
            }
            mqDef.mql.removeListener(mqDef.mqlListner);
            instance.mqDefs.splice(i, 1);
        }
    };

    XElement.updateResponsiveAttribute = function (instance, attrName, attrDef) {
        XElement.removeAttributeMqDefinitions(instance, attrName);
        var prop = StringUtil.toCamelCase(attrName);
        var parsed = XElement.parseResponsiveAttribute(instance[prop], attrDef.type);
        var oldVal = parsed.unmatched;
        parsed.breakpoints.forEach(function (breakpoint) {
            var mql = window.matchMedia(breakpoint.mediaQuery);
            if (mql.matches) {
                oldVal = breakpoint.value;
            }
            var mqlListner = function () {
                var currentProp = 'current' + StringUtil.capitalize(prop);
                var newVal = instance[currentProp];
                if (newVal !== oldVal) {
                    if (attrDef.mediaChangedCallback instanceof Function) {
                        attrDef.mediaChangedCallback.call(instance, oldVal, newVal);
                    }
                    oldVal = newVal;
                }
            };
            mql.addListener(mqlListner);
            instance.mqDefs.push({
                mql: mql,
                mqlListner: mqlListner,
                attribute: attrName
            });
        });
    };

    XElement.define = function (customTagName, definition) {
        var attrName;

        // Define prototype
        var base = HTMLElement.prototype;
        var prototype = Object.create(base);
        Object.assign(prototype, XElement.mixin);
        Object.defineProperty(prototype, 'selector', { value: customTagName });
        definition(prototype, XElement.mixin, base);

        // Register custom attributes
        for (attrName in prototype.customAttributes) {
            if (prototype.customAttributes.hasOwnProperty(attrName)) {
                XElement.registerCustomAttribute(prototype, attrName, prototype.customAttributes[attrName]);
            }
        }

        // Register element
        return document.registerElement(customTagName, { prototype: prototype });
    };

    XElement.extend = function () {
        if (typeof arguments[0] === 'string') {
            return _extendNative.apply(this, arguments);
        }
        return _extendCustom.apply(this, arguments);
    };

    var _extendNative = function (tagName, customTagName, definition) {
        var attrName;

        // Define prototype
        var base = document.createElement(tagName).constructor.prototype;
        var prototype = Object.create(base);
        Object.assign(prototype, XElement.mixin);
        Object.defineProperty(prototype, 'selector', { value: tagName + '[is="' + customTagName + '"]' });
        definition(prototype, XElement.mixin, base);

        // Register custom attributes
        for (attrName in prototype.customAttributes) {
            if (prototype.customAttributes.hasOwnProperty(attrName)) {
                XElement.registerCustomAttribute(prototype, attrName, prototype.customAttributes[attrName]);
            }
        }

        // Register element
        return document.registerElement(customTagName, { prototype: prototype, extends: tagName });
    };

    var _extendCustom = function (T, customTagName, definition) {
        var options = {};
        var selector;
        var selectorParts = T.prototype.selector.split('[');
        var extendsNative = selectorParts.length > 1;
        if (extendsNative) {
            options.extends = selectorParts[0];
            selector = selectorParts[0] + '[is="' + customTagName + '"]';
        } else {
            selector = customTagName;
        }
        var base = T.prototype;
        var prototype = Object.create(base);
        Object.defineProperty(prototype, 'selector', { value: selector });
        definition(prototype, XElement.mixin, base);

        // Register custom attributes
        var attrName;
        for (attrName in prototype.customAttributes) {
            if (prototype.customAttributes.hasOwnProperty(attrName)) {
                XElement.registerCustomAttribute(prototype, attrName, prototype.customAttributes[attrName]);
            }
        }

        options.prototype = prototype;
        return document.registerElement(customTagName, options);
    };

    return XElement;
});
<commit_msg>Simplifies the different factory method variations.<commit_after>define([
    './utils/StringUtil',
    './Binding',
    './polyfills/CustomEvent',
    './polyfills/Object.assign',
    '../bower_components/webcomponentsjs/webcomponents-lite.js',
    '../bower_components/matchMedia/matchMedia',
    '../bower_components/matchMedia/matchMedia.addListener'
], function (
    StringUtil,
    Binding
) {
    'use strict';

    function XElement () {}

    XElement.mixin = {

        customAttributes: {},

        createdCallback: function () {
            this.bindings = [];
            this.mqDefs = [];
        },

        attachedCallback: function () {
            var attrName;
            var attrDef;
            for (attrName in this.customAttributes) {
                if (this.customAttributes.hasOwnProperty(attrName)) {
                    attrDef = this.customAttributes[attrName];
                    if (attrDef.responsive === true) {
                        XElement.updateResponsiveAttribute(this, attrName, attrDef);
                    }
                }
            }
        },

        detachedCallback: function () {
            var attrName;
            var attrDef;
            for (attrName in this.customAttributes) {
                if (this.customAttributes.hasOwnProperty(attrName)) {
                    attrDef = this.customAttributes[attrName];
                    if (attrDef.responsive === true) {
                        XElement.removeAttributeMqDefinitions(this, attrName);
                    }
                }
            }
        },

        attributeChangedCallback: function (attrName, oldVal, newVal) {
            var attrDef = this.customAttributes[attrName];
            if (attrDef === undefined) {
                return;
            }
            var oldProp;
            var oldEvaluatedProp;
            var newEvaluatedProp;
            var currentProp = 'current' + StringUtil.capitalize(StringUtil.toCamelCase(attrName));
            if (attrDef.responsive === true && document.contains(this)) {
                oldProp = (oldVal === null) ? '' + attrDef.default : oldVal;
                oldEvaluatedProp = XElement.evaluateResponsiveAttribute(oldProp, attrDef.type);
                XElement.updateResponsiveAttribute(this, attrName, attrDef);
                newEvaluatedProp = this[currentProp];
                if (oldEvaluatedProp !== newEvaluatedProp && attrDef.mediaChangedCallback instanceof Function) {
                    attrDef.mediaChangedCallback.call(this, oldEvaluatedProp, newEvaluatedProp);
                }
            }
            if (attrDef.changedCallback !== undefined) {
                attrDef.changedCallback.call(this, oldVal, newVal);
            }
        },

        getComponent: function (T, tag) {
            var selector = T.prototype.selector;
            if (tag !== undefined) {
                selector += '[data-tag="' + tag + '"]';
            }
            return this.querySelector(selector);
        },

        getComponents: function (T, tag) {
            var selector = T.prototype.selector;
            if (tag !== undefined) {
                selector += '[data-tag="' + tag + '"]';
            }
            return this.querySelectorAll(selector);
        },

        findWithTag: function (tag) {
            return this.querySelector('[data-tag="' + tag + '"]');
        },

        findAllWithTag: function (tag) {
            return this.querySelectorAll('[data-tag="' + tag + '"]');
        },

        createBinding: function (target, type, handler) {
            var binding = new Binding(target, type, handler);
            this.bindings.push(binding);
            return binding;
        },

        enable: function () {
            var i;
            var l = this.bindings.length;
            for (i = 0; i < l; i++) {
                this.bindings[i].enable();
            }
        },

        disable: function () {
            var i;
            var l = this.bindings.length;
            for (i = 0; i < l; i++) {
                this.bindings[i].disable();
            }
        },

        trigger: function (type, detail) {
            var e = new CustomEvent(type, { detail: detail });
            return this.dispatchEvent(e);
        }

    };

    XElement.registerCustomAttribute = function (prototype, attrName, attrDef) {
        var prop = StringUtil.toCamelCase(attrName);
        Object.defineProperty(prototype, prop, {
            get: function () {
                var attrValue = this.getAttribute(attrName);
                switch (attrDef.type) {

                    case Number:
                        // If the attribute is responsive, fallthrough to the String case
                        if (attrDef.responsive !== true) {
                            if (attrValue === null || attrValue.trim() === '' || isNaN(+attrValue)) {
                                attrValue = attrDef.default;
                            }
                            return +attrValue; // `+` quickly casts to a number
                        }

                    case String:
                        if (attrValue === null) {
                            attrValue = attrDef.default + '';
                        }
                        return attrValue;

                    case Boolean:
                        return attrValue !== null;
                }
            },
            set: function (value) {
                switch (attrDef.type) {
                    case Number:
                        // If the attribute is responsive, fallthrough to the String case
                        if (attrDef.responsive !== true) {
                            if (isNaN(+value) ) {
                                break;
                            }
                            this.setAttribute(attrName, value);
                            break;
                        }

                    case String:
                        this.setAttribute(attrName, value);
                        break;

                    case Boolean:
                        if (!!value) { // `!!` quickly casts to a boolean
                            this.setAttribute(attrName, '');
                        } else {
                            this.removeAttribute(attrName);
                        }
                        break;
                }
            }
        });
        if (attrDef.responsive === true) {
            Object.defineProperty(prototype, 'current' + StringUtil.capitalize(prop), {
                get: function () {
                    return XElement.evaluateResponsiveAttribute(this[prop], attrDef.type);
                }
            });
        }
    };

    XElement.parseResponsiveAttribute = function (value, type) {
        var definitions = value.split(',').map(function (x) { return x.trim(); });
        var unmatched = definitions.pop();
        if (type === Number) {
            unmatched = +unmatched;
        }
        return {
            unmatched: unmatched,
            breakpoints: definitions.map(function (definition) {
                var parts = definition.split(/\s(?=[^\s]*$)/); // Find last occurence of whitespace and split at it
                var mediaQuery = parts[0];
                var value = parts[1];
                if (type === Number) {
                    value = +value;
                }
                return {
                    mediaQuery: mediaQuery,
                    value: value
                };
            })
        };
    };

    XElement.evaluateResponsiveAttribute = function (value, type) {
        var parsed = XElement.parseResponsiveAttribute(value, type);
        return parsed.breakpoints.reduce(function (previous, breakpoint) {
            if (window.matchMedia(breakpoint.mediaQuery).matches) {
                return breakpoint.value;
            }
            return previous;
        }, parsed.unmatched);
    };

    XElement.removeAttributeMqDefinitions = function (instance, attrName) {
        var mqDef;
        var i = instance.mqDefs.length;

        // Loop backwards because we're potetially going to remove items from the array
        while ((mqDef = instance.mqDefs[--i]) !== undefined) {
            if (mqDef.attribute !== attrName) {
                continue;
            }
            mqDef.mql.removeListener(mqDef.mqlListner);
            instance.mqDefs.splice(i, 1);
        }
    };

    XElement.updateResponsiveAttribute = function (instance, attrName, attrDef) {
        XElement.removeAttributeMqDefinitions(instance, attrName);
        var prop = StringUtil.toCamelCase(attrName);
        var parsed = XElement.parseResponsiveAttribute(instance[prop], attrDef.type);
        var oldVal = parsed.unmatched;
        parsed.breakpoints.forEach(function (breakpoint) {
            var mql = window.matchMedia(breakpoint.mediaQuery);
            if (mql.matches) {
                oldVal = breakpoint.value;
            }
            var mqlListner = function () {
                var currentProp = 'current' + StringUtil.capitalize(prop);
                var newVal = instance[currentProp];
                if (newVal !== oldVal) {
                    if (attrDef.mediaChangedCallback instanceof Function) {
                        attrDef.mediaChangedCallback.call(instance, oldVal, newVal);
                    }
                    oldVal = newVal;
                }
            };
            mql.addListener(mqlListner);
            instance.mqDefs.push({
                mql: mql,
                mqlListner: mqlListner,
                attribute: attrName
            });
        });
    };

    XElement.define = function (customTagName, definition) {
        var base = HTMLElement.prototype;
        var prototype = Object.create(base);
        Object.assign(prototype, XElement.mixin);
        Object.defineProperty(prototype, 'selector', { value: customTagName });
        definition(prototype, XElement.mixin, base);
        return _register(customTagName, { prototype: prototype });
    };

    XElement.extend = function () {
        if (typeof arguments[0] === 'string') {
            return _extendNative.apply(this, arguments);
        }
        return _extendCustom.apply(this, arguments);
    };

    var _extendNative = function (tagName, customTagName, definition) {
        var base = document.createElement(tagName).constructor.prototype;
        var prototype = Object.create(base);
        Object.assign(prototype, XElement.mixin);
        Object.defineProperty(prototype, 'selector', { value: tagName + '[is="' + customTagName + '"]' });
        definition(prototype, XElement.mixin, base);

        return _register(customTagName, { prototype: prototype, extends: tagName });
    };

    var _extendCustom = function (T, customTagName, definition) {
        var options = {};
        var selector;
        var selectorParts = T.prototype.selector.split('[');
        var extendsNative = selectorParts.length > 1;
        if (extendsNative) {
            options.extends = selectorParts[0];
            selector = options.extends + '[is="' + customTagName + '"]';
        } else {
            selector = customTagName;
        }
        var base = T.prototype;
        var prototype = Object.create(base);
        Object.defineProperty(prototype, 'selector', { value: selector });
        definition(prototype, XElement.mixin, base);

        options.prototype = prototype;
        return _register(customTagName, options);
    };

    var _register = function (customTagName, options) {

        // Register custom attributes
        var prototype = options.prototype;
        var attrName;
        for (attrName in prototype.customAttributes) {
            if (prototype.customAttributes.hasOwnProperty(attrName)) {
                XElement.registerCustomAttribute(prototype, attrName, prototype.customAttributes[attrName]);
            }
        }

        // Register the custom element
        return document.registerElement(customTagName, options);
    };

    return XElement;
});
<|endoftext|>


<commit_before>UALinkModule = undefined;
UALinkPlugin = undefined;
UALog = undefined;
<commit_msg>linting<commit_after>/* global
    UALinkModule: true,
    UALinkPlugin: true,
    UALog: true
*/

UALinkModule = undefined;
UALinkPlugin = undefined;
UALog = undefined;
<|endoftext|>


<commit_before>"use strict";

import urlTransform from "./urlTransform";
import isFunction from "lodash/lang/isFunction";
import each from "lodash/collection/each";
import fetchResolver from "./fetchResolver";

function none() {}

/**
 * Constructor for create action
 * @param  {String} url          endpoint's url
 * @param  {String} name         action name
 * @param  {Object} options      action configuration
 * @param  {Object} ACTIONS      map of actions
 * @param  {[type]} fetchAdapter adapter for fetching data
 * @return {Function+Object}     action function object
 */
export default function actionFn(url, name, options, ACTIONS={}, meta={}) {
  const {actionFetch, actionSuccess, actionFail, actionReset} = ACTIONS;

  /**
   * Fetch data from server
   * @param  {Object}   pathvars    path vars for url
   * @param  {Object}   params      fetch params
   * @param  {Function} callback)   callback execute after end request
   * @param  {Object}   info        addition system information for internal usage
   */
  const fn = (pathvars, params={}, callback=none, info={})=> {
    const urlT = urlTransform(url, pathvars);
    return (dispatch, getState)=> {
      const state = getState();
      const store = state[name];
      if (store && store.loading) {
        callback("request still loading");
        return;
      }
      dispatch({ type: actionFetch, syncing: !!info.syncing });
      const baseOptions = isFunction(options) ? options(urlT, params, getState) : options;
      const opts = { ...baseOptions, ...params };

      const fetchResolverOpts = {
        dispatch, getState,
        actions: meta.actions,
        prefetch: meta.prefetch
      };

      fetchResolver(0, fetchResolverOpts,
        (err)=> err ? callback(err) : meta.holder.fetch(urlT, opts)
          .then((data)=> {
            dispatch({ type: actionSuccess, syncing: false, data });
            each(meta.broadcast, (btype)=> dispatch({type: btype, data}));
            callback(null, data);
          })
          .catch((error)=> {
            dispatch({ type: actionFail, syncing: false, error });
            callback(error);
          }));
    };
  };
  /**
   * Reset store to initial state
   */
  fn.reset = ()=> ({type: actionReset});
  /**
   * Sync store with server. In server mode works as usual method.
   * If data have already synced, data would not fetch after call this method.
   * @param  {Object} pathvars    path vars for url
   * @param  {Object} params      fetch params
   * @param  {Function} callback) callback execute after end request
   */
  fn.sync = (pathvars, params, callback=none)=> (dispatch, getState)=> {
    const state = getState();
    const store = state[name];
    if (!meta.holder.server && store && store.sync) {
      callback();
      return;
    }
    return fn(pathvars, params, callback, {syncing: true})(dispatch, getState);
  };
  return fn;
}
<commit_msg>Remove: info param from actionFn => fn<commit_after>"use strict";

import urlTransform from "./urlTransform";
import isFunction from "lodash/lang/isFunction";
import each from "lodash/collection/each";
import fetchResolver from "./fetchResolver";

function none() {}

/**
 * Constructor for create action
 * @param  {String} url          endpoint's url
 * @param  {String} name         action name
 * @param  {Object} options      action configuration
 * @param  {Object} ACTIONS      map of actions
 * @param  {[type]} fetchAdapter adapter for fetching data
 * @return {Function+Object}     action function object
 */
export default function actionFn(url, name, options, ACTIONS={}, meta={}) {
  const {actionFetch, actionSuccess, actionFail, actionReset} = ACTIONS;

  /**
   * Fetch data from server
   * @param  {Object}   pathvars    path vars for url
   * @param  {Object}   params      fetch params
   * @param  {Function} callback)   callback execute after end request
   */
  const fn = (pathvars, params={}, callback=none)=> {
    const urlT = urlTransform(url, pathvars);
    const syncing = params ? !!params.syncing : false;
    params && delete params.syncing;
    return (dispatch, getState)=> {
      const state = getState();
      const store = state[name];
      if (store && store.loading) {
        callback("request still loading");
        return;
      }

      dispatch({ type: actionFetch, syncing});
      const baseOptions = isFunction(options) ? options(urlT, params, getState) : options;
      const opts = { ...baseOptions, ...params };

      const fetchResolverOpts = {
        dispatch, getState,
        actions: meta.actions,
        prefetch: meta.prefetch
      };

      fetchResolver(0, fetchResolverOpts,
        (err)=> err ? callback(err) : meta.holder.fetch(urlT, opts)
          .then((data)=> {
            dispatch({ type: actionSuccess, syncing: false, data });
            each(meta.broadcast, (btype)=> dispatch({type: btype, data}));
            callback(null, data);
          })
          .catch((error)=> {
            dispatch({ type: actionFail, syncing: false, error });
            callback(error);
          }));
    };
  };
  /**
   * Reset store to initial state
   */
  fn.reset = ()=> ({type: actionReset});
  /**
   * Sync store with server. In server mode works as usual method.
   * If data have already synced, data would not fetch after call this method.
   * @param  {Object} pathvars    path vars for url
   * @param  {Object} params      fetch params
   * @param  {Function} callback) callback execute after end request
   */
  fn.sync = (pathvars, params, callback=none)=> (dispatch, getState)=> {
    const state = getState();
    const store = state[name];
    if (!meta.holder.server && store && store.sync) {
      callback();
      return;
    }
    const modifyParams = {...params, syncing: true};
    return fn(pathvars, modifyParams, callback)(dispatch, getState);
  };
  return fn;
}
<|endoftext|>


<commit_before>import 'babel-core/register';
import 'babel-polyfill';
import 'whatwg-fetch';
import './assets/stylesheets/app.scss';
import plugins from 'app/utils/JsPlugins';
import Iso from 'iso';
import universalRender from 'shared/UniversalRender';
import ConsoleExports from './utils/ConsoleExports';
import {serverApiRecordEvent} from 'app/utils/ServerApiClient';
import * as steem from 'steem';

window.onerror = error => {
    if (window.$STM_csrf) serverApiRecordEvent('client_error', error);
};

const CMD_LOG_T = 'log-t'
const CMD_LOG_TOGGLE = 'log-toggle'
const CMD_LOG_O = 'log-on'

try {
    if(process.env.NODE_ENV === 'development') {
        // Adds some object refs to the global window object
        ConsoleExports.init(window)
    }
} catch (e) {
    console.error(e)
}

function runApp(initial_state) {
    console.log('Initial state', initial_state);
    const konami = {
        code: 'xyzzy',
        enabled: false
    };
    const buff = konami.code.split('');
    const cmd = (command) => {
        console.log('got command:' + command);
        switch (command) {
            case CMD_LOG_O :
                konami.enabled = false;
            case CMD_LOG_TOGGLE :
            case CMD_LOG_T :
                konami.enabled = !konami.enabled;
                if(konami.enabled) {
                    steem.api.setOptions({logger: console});
                } else {
                    steem.api.setOptions({logger: false});
                }
                return 'api logging ' + konami.enabled;
            default :
                return 'That command is not supported.';
        }
        return 'done';
    }

    const enableKonami = () => {
        if(!window.s) {
            console.log('The cupie doll is yours.');
            window.s = (command) => { return cmd.call(this, command) };
        }
    }

    window.document.body.onkeypress = (e) => {
        buff.shift()
        buff.push(e.key)
        if(buff.join('') === konami.code) {
            enableKonami();
            cmd(CMD_LOG_T)
        }
    };

    if(window.location.hash.indexOf('#'+konami.code) === 0) {
        enableKonami()
        cmd(CMD_LOG_O)
    }

    const config = initial_state.offchain.config
    steem.api.setOptions({ url: config.steemd_connection_client });
    steem.config.set('address_prefix', config.address_prefix);
    steem.config.set('chain_id', config.chain_id);
    window.$STM_Config = config;
    plugins(config);
    if (initial_state.offchain.serverBusy) {
        window.$STM_ServerBusy = true;
    }
    if (initial_state.offchain.csrf) {
        window.$STM_csrf = initial_state.offchain.csrf;
        delete initial_state.offchain.csrf;
    }

    const location = `${window.location.pathname}${window.location.search}${window.location.hash}`;
    universalRender({history, location, initial_state})
    .catch(error => {
        console.error(error);
        serverApiRecordEvent('client_error', error);
    });
}

if (!window.Intl) {
    require.ensure(['intl/dist/Intl'], (require) => {
        window.IntlPolyfill = window.Intl = require('intl/dist/Intl')
        require('intl/locale-data/jsonp/en-US.js')
        require('intl/locale-data/jsonp/es.js')
        Iso.bootstrap(runApp);
    }, "IntlBundle");
}
else {
    Iso.bootstrap(runApp);
}
<commit_msg>code climate fiddlyness<commit_after>import 'babel-core/register';
import 'babel-polyfill';
import 'whatwg-fetch';
import './assets/stylesheets/app.scss';
import plugins from 'app/utils/JsPlugins';
import Iso from 'iso';
import universalRender from 'shared/UniversalRender';
import ConsoleExports from './utils/ConsoleExports';
import {serverApiRecordEvent} from 'app/utils/ServerApiClient';
import * as steem from 'steem';

window.onerror = error => {
    if (window.$STM_csrf) serverApiRecordEvent('client_error', error);
};

const CMD_LOG_T = 'log-t'
const CMD_LOG_TOGGLE = 'log-toggle'
const CMD_LOG_O = 'log-on'

try {
    if(process.env.NODE_ENV === 'development') {
        // Adds some object refs to the global window object
        ConsoleExports.init(window)
    }
} catch (e) {
    console.error(e)
}

function runApp(initial_state) {
    console.log('Initial state', initial_state);
    const konami = {
        code: 'xyzzy',
        enabled: false
    };
    const buff = konami.code.split('');
    const cmd = (command) => {
        console.log('got command:' + command);
        switch (command) {
            case CMD_LOG_O :
                konami.enabled = false;
            case CMD_LOG_TOGGLE :
            case CMD_LOG_T :
                konami.enabled = !konami.enabled;
                if(konami.enabled) {
                    steem.api.setOptions({logger: console});
                } else {
                    steem.api.setOptions({logger: false});
                }
                return 'api logging ' + konami.enabled;
            default :
                return 'That command is not supported.';
        }
        //return 'done';
    }

    const enableKonami = () => {
        if(!window.s) {
            console.log('The cupie doll is yours.');
            window.s = (command) => { return cmd.call(this, command) };
        }
    }

    window.document.body.onkeypress = (e) => {
        buff.shift()
        buff.push(e.key)
        if(buff.join('') === konami.code) {
            enableKonami();
            cmd(CMD_LOG_T)
        }
    };

    if(window.location.hash.indexOf('#'+konami.code) === 0) {
        enableKonami()
        cmd(CMD_LOG_O)
    }

    const config = initial_state.offchain.config
    steem.api.setOptions({ url: config.steemd_connection_client });
    steem.config.set('address_prefix', config.address_prefix);
    steem.config.set('chain_id', config.chain_id);
    window.$STM_Config = config;
    plugins(config);
    if (initial_state.offchain.serverBusy) {
        window.$STM_ServerBusy = true;
    }
    if (initial_state.offchain.csrf) {
        window.$STM_csrf = initial_state.offchain.csrf;
        delete initial_state.offchain.csrf;
    }

    const location = `${window.location.pathname}${window.location.search}${window.location.hash}`;
    universalRender({history, location, initial_state})
    .catch(error => {
        console.error(error);
        serverApiRecordEvent('client_error', error);
    });
}

if (!window.Intl) {
    require.ensure(['intl/dist/Intl'], (require) => {
        window.IntlPolyfill = window.Intl = require('intl/dist/Intl')
        require('intl/locale-data/jsonp/en-US.js')
        require('intl/locale-data/jsonp/es.js')
        Iso.bootstrap(runApp);
    }, "IntlBundle");
}
else {
    Iso.bootstrap(runApp);
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

base.exportTo('base', function() {
  var pendingPreAFs = [];
  var pendingRAFs = [];
  var currentRAFDispatchList = undefined;

  var rafScheduled = false;
  function scheduleRAF() {
    if (rafScheduled)
      return;
    rafScheduled = true;
    window.webkitRequestAnimationFrame(processRequests);
  }

  function processRequests() {
    rafScheduled = false;
    var currentPreAFs = pendingPreAFs;
    var currentRAFs = pendingRAFs;
    pendingPreAFs = [];
    pendingRAFs = [];
    for (var i = 0; i < pendingPreAFs; i++)
      this.pendingPreAFs.callback.call(pendingPreAFs.context);

    currentRAFDispatchList = currentRAFs;
    while (currentRAFDispatchList.length > 0) {
      var task = currentRAFDispatchList.shift();
      try {
        task.callback.call(task.context);
      } catch (e) {
        console.error(e);
      }
    }
    currentRAFDispatchList = undefined;
  }

  function requestPreAnimationFrame(callback, opt_this) {
    scheduleRAF();
    pendingRAFs.push({
      callback: callback,
      context: opt_this || window});
  }

  function requestAnimationFrameInThisFrameIfPossible(callback, opt_this) {
    if (!currentRAFDispatchList) {
      requestAnimationFrame(callback, opt_this);
      return;
    }
    currentRAFDispatchList.push({
      callback: callback,
      context: opt_this || window});
    return;
  }

  function requestAnimationFrame(callback, opt_this) {
    scheduleRAF();
    pendingRAFs.push({
      callback: callback,
      context: opt_this || window});
  }
  return {
    requestPreAnimationFrame: requestPreAnimationFrame,
    requestAnimationFrame: requestAnimationFrame,
    requestAnimationFrameInThisFrameIfPossible:
        requestAnimationFrameInThisFrameIfPossible
  };
});
<commit_msg>Better error printing when raf explodes<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

base.exportTo('base', function() {
  var pendingPreAFs = [];
  var pendingRAFs = [];
  var currentRAFDispatchList = undefined;

  var rafScheduled = false;
  function scheduleRAF() {
    if (rafScheduled)
      return;
    rafScheduled = true;
    window.webkitRequestAnimationFrame(processRequests);
  }

  function processRequests() {
    rafScheduled = false;
    var currentPreAFs = pendingPreAFs;
    var currentRAFs = pendingRAFs;
    pendingPreAFs = [];
    pendingRAFs = [];
    for (var i = 0; i < pendingPreAFs; i++)
      this.pendingPreAFs.callback.call(pendingPreAFs.context);

    currentRAFDispatchList = currentRAFs;
    while (currentRAFDispatchList.length > 0) {
      var task = currentRAFDispatchList.shift();
      try {
        task.callback.call(task.context);
      } catch (e) {
        if (e.message)
          console.error(e.message, e.stack);
        else
          console.error(e);
      }
    }
    currentRAFDispatchList = undefined;
  }

  function requestPreAnimationFrame(callback, opt_this) {
    scheduleRAF();
    pendingRAFs.push({
      callback: callback,
      context: opt_this || window});
  }

  function requestAnimationFrameInThisFrameIfPossible(callback, opt_this) {
    if (!currentRAFDispatchList) {
      requestAnimationFrame(callback, opt_this);
      return;
    }
    currentRAFDispatchList.push({
      callback: callback,
      context: opt_this || window});
    return;
  }

  function requestAnimationFrame(callback, opt_this) {
    scheduleRAF();
    pendingRAFs.push({
      callback: callback,
      context: opt_this || window});
  }
  return {
    requestPreAnimationFrame: requestPreAnimationFrame,
    requestAnimationFrame: requestAnimationFrame,
    requestAnimationFrameInThisFrameIfPossible:
        requestAnimationFrameInThisFrameIfPossible
  };
});
<|endoftext|>


<commit_before>/**
 * @since 2019-03-13 12:50
 * @author vivaxy
 * @see https://www.youtube.com/watch?v=IpfZ8Nj3uiE
 */

const requestDeviceButton = document.querySelector('.js-request-device');

requestDeviceButton.addEventListener('click', async() => {
  try {
    const options = {
      /**
       * @see http://www.linux-usb.org/usb.ids
       */
      filters: [{ vendorId: 0x2a45 }],
    };

    const device = await navigator.usb.requestDevice(options);
    console.log('device', device);

    await device.open();

    await device.selectConfiguration(1);
    await device.claimInterface(0);

    await device.transferOut(1, 0x1a);
    const response = await device.transferIn(2, 5);
    console.log('response', response);
  } catch (exception) {
    console.log('exception', exception);
  }
});
<commit_msg>chore:<commit_after>/**
 * @since 2019-03-13 12:50
 * @author vivaxy
 * @see https://www.youtube.com/watch?v=IpfZ8Nj3uiE
 */

const requestDeviceButton = document.querySelector('.js-request-device');

requestDeviceButton.addEventListener('click', async() => {
  try {
    const options = {
      /**
       * @see http://www.linux-usb.org/usb.ids
       */
      filters: [{ vendorId: 0x2a45 }],
    };

    const device = await navigator.usb.requestDevice(options);
    console.log('device', device);

    await device.open();

    await device.selectConfiguration(1);
    await device.claimInterface(0);

    await device.transferOut(1, 0x1a);
    const response = await device.transferIn(2, 5);
    console.log('response', response);
  } catch (exception) {
    console.log('exception.code', exception.code, 'exception.name', exception.name, 'exception.message', exception.message);
  }
});
<|endoftext|>


<commit_before>import {createNode, emptyNode, selectNodes, removeNode} from "./util/nodes.js";
import {getNamespace} from "./util/namespaces.js";

//Selection class
export function Selection (nodes, root) {
    this.nodes = nodes;
    this.root = root;
};

//Selection prototype
Selection.prototype = {
    //Iterate over the nodes of the selection
    "each": function (callback) {
        for (let i = 0; i < this.nodes.length; i++) {
            callback.call(this.nodes[i], this, i);
        }
        return this;
    },
    //Set or get an attribute for each node
    "attr": function (name, value) {
        //Check for undefined value to set --> get the current attribute value
        if (typeof value === "undefined") {
            if (this.nodes.length === 0) {
                return null;
            }
            //Return the attribute value only of the first node
            return this.nodes[0].getAttribute(name);
        }
        //Set the value for each node in the selection
        return this.each(function (self, index) {
            //Check for null value --> remove this attribute
            if (value === null) {
                this.removeAttribute(name);
            }
            //Check if the value is a function
            else if (typeof value === "function") {
                this.setAttribute(name, value.call(this, null, index));
            }
            //String value --> set this attribute
            else {
                this.setAttribute(name, value);
            }
        });
    },
    //Set the style of all nodes
    "style": function (name, value) {
        //Check for undefined value to set --> get the current attribute value
        if (typeof value === "undefined") {
            if (this.nodes.length === 0) {
                return null;
            }
            //Return the style value of the first node
            return this.nodes[0].style.getPropertyValue(name);
        }
        //Set the value for each node in the selection
        return this.each(function (self, index) {
            //Check no value to set
            if (value === null) {
                this.style.removeProperty(name);
            }
            //Check if value is a function
            else if (typeof value === "function") {
                this.style.setProperty(name, value.call(this, self.getData(index)));
            }
            //String value --> set this style value
            else {
                this.style.setProperty(name, value);
            }
        });
    },
    //Get the size of the first element
    "size": function () {
        if (this.nodes.length > 0) {
            let bb = this.nodes[0].getBoundingClientRect();
            return {
                "width": bb.width,
                "height": bb.height
            };
        }
        //No nodes on the selection
        return null;
    },
    //Register element listeners
    "on": function (name, listener) {
        return this.each(function () {
            this.addEventListener(name, listener, false);
        });
    },
    //Remove an event listener
    "off": function (name, listener) {
        return this.each(function () {
            this.removeEventListener(name, listener, false);
        });
    },
    //Remove all children element of the selection
    "empty": function () {
        return this.each(function () {
            return emptyNode(this);
        });
    },
    //Set the text of the elements
    "text": function (content) {
        return this.each(function () {
            this.textContent = content;
        });
    },
    //Set the html of the selected elements
    "html": function (content) {
        return this.each(function () {
            this.innerHTML = content;
        });
    },
    //Remove the selection
    "remove": function () {
        return this.each(function () {
            return removeNode(this);
        });
    },
    //Append a new DOM element
    "append": function (name) {
        let parent = (this.nodes.length > 0) ? this.nodes[0] : this.root;
        let node = createNode(name, parent);
        parent.appendChild(node);
        //Return a new selection instance
        return new Selection([node], parent);
    },
    //Select all children nodes that matches the specified pattern
    "selectAll": function (selector) {
        //Get the root element
        let rootElement = (this.nodes.length === 0) ? this.root : this.nodes[0];
        let selection = selectNodes(selector, rootElement);
        //Return a new selection instance with the selected nodes list and the root element
        return new Selection(selection.nodes, selection.root);
    }
};

//Select the first element
export function select (selector) {
    let selection = selectNodes(selector, null);
    //Get only the first node
    let firstNode = (selection.nodes.length === 0) ? [] : [selection.nodes[0]];
    return new Selection(firstNode, selection.root);
}

//Select all elements
export function selectAll (selector) {
    let selection = selectNodes(selector, null);
    //Return a new instance for the selected nodes
    return new Selection(selection.nodes, selection.root, null);
}

<commit_msg>Minor fixes setting an attribute or a style to the selection<commit_after>import {createNode, emptyNode, selectNodes, removeNode} from "./util/nodes.js";
import {getNamespace} from "./util/namespaces.js";

//Selection class
export function Selection (nodes, root) {
    this.nodes = nodes;
    this.root = root;
};

//Selection prototype
Selection.prototype = {
    //Iterate over the nodes of the selection
    "each": function (callback) {
        for (let i = 0; i < this.nodes.length; i++) {
            callback.call(this.nodes[i], this, i);
        }
        return this;
    },
    //Set an attribute for each node
    "attr": function (name, value) {
        //Check for undefined value to set --> nothing to do
        if (typeof value === "undefined") {
            return this;
        }
        //Set the value for each node in the selection
        return this.each(function (self, index) {
            //Check for null value --> remove this attribute
            if (value === null) {
                this.removeAttribute(name);
            }
            //Check if the value is a function
            else if (typeof value === "function") {
                this.setAttribute(name, value.call(this, null, index));
            }
            //String value --> set this attribute
            else {
                this.setAttribute(name, value);
            }
        });
    },
    //Set the style of all nodes
    "style": function (name, value) {
        //Check for undefined value to set --> nothing to do
        if (typeof value === "undefined") {
            return this;
        }
        //Set the value for each node in the selection
        return this.each(function (self, index) {
            //Check no value to set
            if (value === null) {
                this.style.removeProperty(name);
            }
            //Check if value is a function
            else if (typeof value === "function") {
                this.style.setProperty(name, value.call(this, self.getData(index)));
            }
            //String value --> set this style value
            else {
                this.style.setProperty(name, value);
            }
        });
    },
    //Get the size of the first element
    "size": function () {
        if (this.nodes.length > 0) {
            let bb = this.nodes[0].getBoundingClientRect();
            return {
                "width": bb.width,
                "height": bb.height
            };
        }
        //No nodes on the selection
        return null;
    },
    //Register element listeners
    "on": function (name, listener) {
        return this.each(function () {
            this.addEventListener(name, listener, false);
        });
    },
    //Remove an event listener
    "off": function (name, listener) {
        return this.each(function () {
            this.removeEventListener(name, listener, false);
        });
    },
    //Remove all children element of the selection
    "empty": function () {
        return this.each(function () {
            return emptyNode(this);
        });
    },
    //Set the text of the elements
    "text": function (content) {
        return this.each(function () {
            this.textContent = content;
        });
    },
    //Set the html of the selected elements
    "html": function (content) {
        return this.each(function () {
            this.innerHTML = content;
        });
    },
    //Remove the selection
    "remove": function () {
        return this.each(function () {
            return removeNode(this);
        });
    },
    //Append a new DOM element
    "append": function (name) {
        let parent = (this.nodes.length > 0) ? this.nodes[0] : this.root;
        let node = createNode(name, parent);
        parent.appendChild(node);
        //Return a new selection instance
        return new Selection([node], parent);
    },
    //Select all children nodes that matches the specified pattern
    "selectAll": function (selector) {
        //Get the root element
        let rootElement = (this.nodes.length === 0) ? this.root : this.nodes[0];
        let selection = selectNodes(selector, rootElement);
        //Return a new selection instance with the selected nodes list and the root element
        return new Selection(selection.nodes, selection.root);
    }
};

//Select the first element
export function select (selector) {
    let selection = selectNodes(selector, null);
    //Get only the first node
    let firstNode = (selection.nodes.length === 0) ? [] : [selection.nodes[0]];
    return new Selection(firstNode, selection.root);
}

//Select all elements
export function selectAll (selector) {
    let selection = selectNodes(selector, null);
    //Return a new instance for the selected nodes
    return new Selection(selection.nodes, selection.root, null);
}

<|endoftext|>


<commit_before>import { remote, ipcRenderer } from 'electron'
import 'core-js/es/reflect'
import ky from 'ky/umd'
import logger from 'electron-timber'

const BASE_URL = 'http://' + remote.getGlobal('osmServerHost') + '/'

export function Api ({ baseUrl }) {
  // We append this to requests for presets and map styles, in order to override
  // the local static server cache whenever the app is restarted. NB. sprite,
  // font, and map tile requests might still be cached, only changes in the map
  // style will be cache-busted.
  const startupTime = Date.now()

  const req = ky.extend({
    prefixUrl: baseUrl,
    // No timeout because indexing after first sync takes a long time, which mean
    // requests to the server take a long time
    timeout: false,
    headers: {
      'cache-control': 'no-cache',
      pragma: 'no-cache'
    }
  })

  function logRequest (prefix, promise) {
    const start = Date.now()
    promise
      .then(data => {
        logger.log(prefix, Date.now() - start + 'ms', data)
      })
      .catch(error => {
        logger.error(prefix, error)
      })
    return promise
  }

  // Request convenience methods that wait for the server to be ready
  function get (url) {
    return logRequest('<GET: ' + url, req.get(url).json())
  }
  function del (url) {
    return logRequest('<DEL: ' + url, req.delete(url).json())
  }
  function put (url, data) {
    logger.log('>PUT:', url, data)
    return logRequest('<PUT: ' + url, req.put(url, { json: data }).json())
  }
  function post (url, data) {
    logger.log('>POST:', url, data)
    return logRequest('<POST: ' + url, req.post(url, { json: data }).json())
  }

  // All public methods
  const api = {
    /**
     * GET async methods
     */

    getPresets: function getPresets () {
      return get(`presets/default/presets.json?${startupTime}`).then(data =>
        mapToArray(data.presets)
      )
    },

    getFields: function getFields () {
      return get(`presets/default/presets.json?${startupTime}`).then(data =>
        mapToArray(data.fields)
      )
    },

    getObservations: function getObservations () {
      return get('observations')
    },

    getMapStyle: function getMapStyle (id) {
      return get(`styles/${id}/style.json`)
    },

    /**
     * DELETE methods
     */

    deleteObservation: function deleteObservation (id) {
      return del(`observations/${id}`)
    },

    /**
     * PUT and POST methods
     */

    updateObservation: function updateObservation (id, value) {
      const valueForServer = {
        ...value,
        type: 'observation',
        schemaVersion: 3,
        id
      }
      return put(`observations/${id}`, valueForServer)
    },

    createObservation: function createObservation (value) {
      const valueForServer = {
        ...value,
        type: 'observation',
        schemaVersion: 3
      }
      return post('observations', valueForServer)
    },

    /**
     * SYNC methods
     */

    // Listens to the server for updates to the list of peers available for sync
    // returns a remove() function to unscubribe
    addPeerListener: function addPeerListener (handler) {
      // We sidestep the http API here, and instead of polling the endpoint, we
      // listen for an event from mapeo-core whenever the peers change, then
      // request an updated peer list.
      function onPeerUpdate (event, ...args) {
        logger.log('peer-update', args[0])
        handler.apply(null, args)
      }
      ipcRenderer.on('peer-update', onPeerUpdate)
      api.syncGetPeers().then(handler)
      return {
        remove: () => ipcRenderer.removeListener('peer-update', onPeerUpdate)
      }
    },

    // Start listening for sync peers and advertise with `deviceName`
    syncJoin: function syncJoin () {
      logger.log('Join sync')
      req.get('sync/join')
    },

    // Stop listening for sync peers and stop advertising
    syncLeave: function syncLeave () {
      logger.log('Leave sync')
      req.get('sync/leave')
    },

    // Get a list of discovered sync peers
    syncGetPeers: function syncGetPeers () {
      return get('sync/peers').then(data => data && data.message)
    },

    // Start sync with a peer
    syncStart: function syncStart (target) {
      ipcRenderer.send('sync-start', target)
    },

    /**
     * HELPER synchronous methods
     */

    // Return the url for an icon
    getIconUrl: function getIconUrl (iconId, size = 'medium') {
      // Some devices are @4x or above, but we only generate icons up to @3x
      // Also we don't have @1.5x, so we round it up
      const roundedRatio = Math.min(Math.ceil(window.devicePixelRatio), 3)
      return `${baseUrl}presets/default/icons/${iconId}-medium@${roundedRatio}x.png`
    },

    // Return the url for a media attachment
    getMediaUrl: function getMediaUrl (attachmentId, size) {
      return `${baseUrl}media/${size}/${attachmentId}`
    },

    // Return the url to a map style
    getMapStyleUrl: function getMapStyleUrl (id) {
      return `${baseUrl}styles/${id}/style.json?${startupTime}`
    }
  }

  return api
}

export default Api({ baseUrl: BASE_URL })

function mapToArray (map) {
  return Object.keys(map).map(id => ({
    ...map[id],
    id: id
  }))
}
<commit_msg>chore: remove detailed logs of get requests<commit_after>import { remote, ipcRenderer } from 'electron'
import 'core-js/es/reflect'
import ky from 'ky/umd'
import logger from 'electron-timber'

const BASE_URL = 'http://' + remote.getGlobal('osmServerHost') + '/'

export function Api ({ baseUrl }) {
  // We append this to requests for presets and map styles, in order to override
  // the local static server cache whenever the app is restarted. NB. sprite,
  // font, and map tile requests might still be cached, only changes in the map
  // style will be cache-busted.
  const startupTime = Date.now()

  const req = ky.extend({
    prefixUrl: baseUrl,
    // No timeout because indexing after first sync takes a long time, which mean
    // requests to the server take a long time
    timeout: false,
    headers: {
      'cache-control': 'no-cache',
      pragma: 'no-cache'
    }
  })

  function logRequest (prefix, promise) {
    const start = Date.now()
    promise
      .then(data => {
        logger.log(prefix, Date.now() - start + 'ms')
      })
      .catch(error => {
        logger.error(prefix, error)
      })
    return promise
  }

  // Request convenience methods that wait for the server to be ready
  function get (url) {
    return logRequest('<GET: ' + url, req.get(url).json())
  }
  function del (url) {
    return logRequest('<DEL: ' + url, req.delete(url).json())
  }
  function put (url, data) {
    logger.log('>PUT:', url, data)
    return logRequest('<PUT: ' + url, req.put(url, { json: data }).json())
  }
  function post (url, data) {
    logger.log('>POST:', url, data)
    return logRequest('<POST: ' + url, req.post(url, { json: data }).json())
  }

  // All public methods
  const api = {
    /**
     * GET async methods
     */

    getPresets: function getPresets () {
      return get(`presets/default/presets.json?${startupTime}`).then(data =>
        mapToArray(data.presets)
      )
    },

    getFields: function getFields () {
      return get(`presets/default/presets.json?${startupTime}`).then(data =>
        mapToArray(data.fields)
      )
    },

    getObservations: function getObservations () {
      return get('observations')
    },

    getMapStyle: function getMapStyle (id) {
      return get(`styles/${id}/style.json`)
    },

    /**
     * DELETE methods
     */

    deleteObservation: function deleteObservation (id) {
      return del(`observations/${id}`)
    },

    /**
     * PUT and POST methods
     */

    updateObservation: function updateObservation (id, value) {
      const valueForServer = {
        ...value,
        type: 'observation',
        schemaVersion: 3,
        id
      }
      return put(`observations/${id}`, valueForServer)
    },

    createObservation: function createObservation (value) {
      const valueForServer = {
        ...value,
        type: 'observation',
        schemaVersion: 3
      }
      return post('observations', valueForServer)
    },

    /**
     * SYNC methods
     */

    // Listens to the server for updates to the list of peers available for sync
    // returns a remove() function to unscubribe
    addPeerListener: function addPeerListener (handler) {
      // We sidestep the http API here, and instead of polling the endpoint, we
      // listen for an event from mapeo-core whenever the peers change, then
      // request an updated peer list.
      function onPeerUpdate (event, ...args) {
        logger.log('peer-update', args[0])
        handler.apply(null, args)
      }
      ipcRenderer.on('peer-update', onPeerUpdate)
      api.syncGetPeers().then(handler)
      return {
        remove: () => ipcRenderer.removeListener('peer-update', onPeerUpdate)
      }
    },

    // Start listening for sync peers and advertise with `deviceName`
    syncJoin: function syncJoin () {
      logger.log('Join sync')
      req.get('sync/join')
    },

    // Stop listening for sync peers and stop advertising
    syncLeave: function syncLeave () {
      logger.log('Leave sync')
      req.get('sync/leave')
    },

    // Get a list of discovered sync peers
    syncGetPeers: function syncGetPeers () {
      return get('sync/peers').then(data => data && data.message)
    },

    // Start sync with a peer
    syncStart: function syncStart (target) {
      ipcRenderer.send('sync-start', target)
    },

    /**
     * HELPER synchronous methods
     */

    // Return the url for an icon
    getIconUrl: function getIconUrl (iconId, size = 'medium') {
      // Some devices are @4x or above, but we only generate icons up to @3x
      // Also we don't have @1.5x, so we round it up
      const roundedRatio = Math.min(Math.ceil(window.devicePixelRatio), 3)
      return `${baseUrl}presets/default/icons/${iconId}-medium@${roundedRatio}x.png`
    },

    // Return the url for a media attachment
    getMediaUrl: function getMediaUrl (attachmentId, size) {
      return `${baseUrl}media/${size}/${attachmentId}`
    },

    // Return the url to a map style
    getMapStyleUrl: function getMapStyleUrl (id) {
      return `${baseUrl}styles/${id}/style.json?${startupTime}`
    }
  }

  return api
}

export default Api({ baseUrl: BASE_URL })

function mapToArray (map) {
  return Object.keys(map).map(id => ({
    ...map[id],
    id: id
  }))
}
<|endoftext|>


<commit_before>const fs = require('fs');
const readFlight = require('./read-flight');

describe('readFlight()', () => {
  it(`reads "SW_77flqgg1" flight log correctly`, () => {
    let flight = readFlight(`${__dirname}/../fixtures/2017-07-15-lev/SW_77flqgg1.igc`);
    expect(flight).toMatchSnapshot();
  })
});
<commit_msg>Fix test fixture path<commit_after>const fs = require('fs');
const readFlight = require('./read-flight');

describe('readFlight()', () => {
  it(`reads "SW_77flqgg1" flight log correctly`, () => {
    let flight = readFlight(`${__dirname}/../fixtures/2017-07-15-lev/SW_77flqgg1.IGC`);
    expect(flight).toMatchSnapshot();
  })
});
<|endoftext|>


<commit_before>/**
 * CoffeeTe
 * https://github.com/icetan/coffeete
 *
 * Copyright 2012, Christopher Fredén
 * Released under the MIT License
 */

!function (name, definition) {
  if (typeof module != 'undefined') module.exports = definition()
  else if (typeof define == 'function' && typeof define.amd == 'object') define(definition)
  else this[name] = definition()
}('coffeete', function () {
  var text = (function () {
      if (typeof window !== 'undefined') {
        var div = document.createElement('div');
        return function (str) {
          div.innerHTML = str;
          return div.innerText || div.textContent;
        };
      } else {
        return function (str) {return str;};
      }
    })()
    , dotRe = /([^\w\\]|^)\.([^\w]|$)/;

  function comp(str) {
    var len = str.indexOf('\n')
      , txt = '"""'+str.slice(len)+'""" '
      , cs = text(str.slice(0,len))
      , dot = dotRe.test(cs);
    if (dot) {
      return '"""+('+cs.replace(dotRe, '$1'+txt+'$2')+')+"""';
    } else {
      return '"""+(if (_lst=('+txt+cs+')) then (if _lst.join then _lst.join(\'\') else _lst) else \'\')+"""';
    }
  }

  function parse(str) {
    var res = {}
      , c = 0;
    while (true) {
      var start = str.indexOf('!{')
        , end = str.indexOf('}!')
        , open = start !== -1 && start < end
        , len = open ? start : end;
      if (start === -1 && (end === -1 || c === 0)) {
        res[c] = (res[c] ? res[c]+str : str);
        break;
      }
      res[c] = res[c] ? res[c]+str.slice(0,len) : str.slice(0,len);
      if (open) {
        c++;
      } else {
        res[c-1] += comp(res[c]);
        delete res[c];
        c--;
      }
      str = str.slice(len+2);
    }
    return '"""'+res[0].replace(/\n/g, '\\n')+'"""';
  }

  function coffeete(str) {
    var cs = parse(str)
      , js = coffeete.coffeeScriptCompile('return '+cs);
    return eval('var f=function(v){with(v){return '+js+'}};f');
  }

  coffeete.coffeeScriptCompile = typeof CoffeeScript !== 'undefined'
    ? CoffeeScript.compile
    : (function (udef) {
        try {
          return require('coffee-script').compile;
        } catch (e) {
          return udef;
        }
      })();
  return coffeete;
});
<commit_msg>Added toJavaScript method to get un-evaled JS, removed CoffeeScript function wrapper and added .coffeete to require.extensions<commit_after>/**
 * CoffeeTe
 * https://github.com/icetan/coffeete
 *
 * Copyright 2012, Christopher Fredén
 * Released under the MIT License
 */

!function (name, definition) {
  if (typeof module !== 'undefined') {
    var fs, coffeete = module.exports = definition();
    if (typeof require !== 'undefined') {
      // Add Node.js extensions
      if (typeof require.extensions !== 'undefined') {
        fs = require('fs');
        require.extensions['.coffeete'] = function (module, filename) {
          var content = fs.readFileSync(filename, 'utf8');
          module._compile('module.exports='+coffeete.toJavaScript(content), filename);
        };
      } else if (typeof require.registerExtension !== 'undefined') {
        // Remove when registerExtension is depricated
        require.registerExtension('.coffeete', function (content) {
          return 'module.exports='+coffeete.toJavaScript(content);
        });
      }
    }
  } else if (typeof define === 'function' && typeof define.amd === 'object') {
    define(definition);
  } else {
    this[name] = definition();
  }
}('coffeete', function () {
  var text = (function () {
      if (typeof window !== 'undefined') {
        var div = document.createElement('div');
        return function (str) {
          div.innerHTML = str;
          return div.innerText || div.textContent;
        };
      } else {
        return function (str) {return str;};
      }
    })()
    , dotRe = /([^\w\\]|^)\.([^\w]|$)/;

  function comp(str) {
    var len = str.indexOf('\n')
      , txt = '"""'+str.slice(len)+'""" '
      , cs = text(str.slice(0,len))
      , dot = dotRe.test(cs);
    if (dot) {
      return '"""+('+cs.replace(dotRe, '$1'+txt+'$2')+')+"""';
    } else {
      return '"""+(if (_lst=('+txt+cs+')) then (if _lst.join then _lst.join(\'\') else _lst) else \'\')+"""';
    }
  }

  function parse(str) {
    var res = {}
      , c = 0;
    while (true) {
      var start = str.indexOf('!{')
        , end = str.indexOf('}!')
        , open = start !== -1 && start < end
        , len = open ? start : end;
      if (start === -1 && (end === -1 || c === 0)) {
        res[c] = (res[c] ? res[c]+str : str);
        break;
      }
      res[c] = res[c] ? res[c]+str.slice(0,len) : str.slice(0,len);
      if (open) {
        c++;
      } else {
        res[c-1] += comp(res[c]);
        delete res[c];
        c--;
      }
      str = str.slice(len+2);
    }
    return '"""'+res[0].replace(/\n/g, '\\n')+'"""';
  }

  function toJavaScriptFunction(str) {
    var cs = parse(str)
      , js = coffeete.coffeeScriptCompile('return '+cs, {bare:true});
    return 'function(v){with(v){'+js+'}}';
  }

  function coffeete(str) {
    var js = toJavaScriptFunction(str);
    return eval('var f='+js+';f');
  }

  coffeete.toJavaScript = toJavaScriptFunction;

  coffeete.coffeeScriptCompile = typeof CoffeeScript !== 'undefined'
    ? CoffeeScript.compile
    : (function (udef) {
        try {
          return require('coffee-script').compile;
        } catch (e) {
          return udef;
        }
      })();
  return coffeete;
});
<|endoftext|>