<commit_before>// /*
//  TouchyFeely
// 	Swipe controller library - handles swipes, touches, and pinches on any object, icnluding the body
// 	Created by John Bragg for Seabright Studios
// */

var TouchyFeely = function(element,options) {
	var touchy = this;
	var TouchHooks = {
		touchstart : function(event) {
			if(event.touches.length == 1) {
				touchy.update(event,false);
				touchy.currentEvent.target = touchy.getTarget(event);
			};
		},
		touchmove : function(event) {
			if(touchy.currentEvent) {
				touchy.update(event);
				if(touchy.currentEvent.type) { TouchEvent(touchy.currentEvent.type+"move"); };
				return(false);
			};
			return(true);
		},
		touchend : function(event) {
			if(touchy.currentEvent) {
				touchy.update(event);
				if(touchy.currentEvent.type) { TouchEvent(touchy.currentEvent.type+"end"); };
			};
			touchy.cancel();
		},
		touchcancel : function(event) { touchy.cancel(); }
	};
	var TouchEvent = function(type) {
		var evObj = document.createEvent('UIEvents');
		evObj.initUIEvent(type, true, true, window, 1);
		for(var i in touchy.currentEvent) { evObj[i] = touchy.currentEvent[i]; };
		touchy.element.dispatchEvent(evObj);
		// console.log("Event: "+type,evObj);
	};
	var baseEvent = {
		history : []
	};
	touchy.element = element;
	touchy.config = {
		minLength : 20,
		capturescroll : true,
		captureswipe : true
	};
	for(var o in (options||{})) {
		touchy.config[o] = options[o];
	};
	touchy.clone = function(obj) {
	  var newObj = (obj instanceof Array) ? [] : {};
	  for(i in obj) {
	    if(obj[i] && typeof obj[i] == "object") {
	      newObj[i] = touchy.clone(obj[i]);
	    } else newObj[i] = obj[i];
	  };
		return newObj;
	};
	touchy.hook = function(elem) { for(var i in TouchHooks) { elem.addEventListener(i, TouchHooks[i], true); }; };
	touchy.swipeLength = function() {
		return(Math.round(Math.sqrt(Math.pow(touchy.currentEvent.deltaX,2)+Math.pow(touchy.currentEvent.deltaY,2))));
	};
	touchy.calculateAngle = function() {
		var ang = Math.round((Math.atan2(touchy.currentEvent.vertDiff,touchy.currentEvent.horzDiff))*180/Math.PI); //angle in degrees
		if(ang < 0) ang = 360 - Math.abs(ang);
		return(ang);
	};
	touchy.swipeDirection = function() {
		if ( ((this.currentEvent.swipeAngle <= 45) && (this.currentEvent.swipeAngle >= 0)) || ((this.currentEvent.swipeAngle <= 360) && (this.currentEvent.swipeAngle >= 315)) ) {
			return('left');
		} else if ( (this.currentEvent.swipeAngle >= 135) && (this.currentEvent.swipeAngle <= 225) ) {
			return('right');
		} else if ( (this.currentEvent.swipeAngle > 45) && (this.currentEvent.swipeAngle < 135) ) {
			return('down');
		};
		return('up');
	};
	touchy.getType = function() {
		var cev = touchy.currentEvent;
		if(cev.swipeDirection=="left"||cev.swipeDirection=="right") return("swipe");
		else if(cev.swipeDirection=="up"||cev.swipeDirection=="down") return("scroll");
		else return(undefined);
	};
	touchy.getTarget = function(event) {
		return(event.currentTarget);
	};
	touchy.update = function(event,capture) {
		if(!touchy.currentEvent) touchy.newEvent();
		var tch = event["touches"][0] || event["changedTouches"][0], cev = touchy.currentEvent;
		cev.curX = tch.pageX;
		cev.curY = tch.pageY;
		cev.history = cev.history || [];
		cev.history.push([cev.curX,cev.curY]);
		if(!cev.fingerCount) cev.fingerCount = event["touches"].length;
		if(!cev.startX) cev.startX = cev.curX;
		if(!cev.startY) cev.startY = cev.curY;
		cev.deltaX = cev.curX - cev.startX;
		cev.deltaY = cev.curY - cev.startY;
		cev.horzDiff = cev.startX - cev.curX;
		cev.vertDiff = cev.curY - cev.startY;
		if(cev.deltaX > 0 || cev.deltaY > 0) {
			cev.swipeLength = touchy.swipeLength();
			if(cev.swipeLength >= touchy.config.minLength) {
				cev.swipeAngle = touchy.calculateAngle();
				cev.swipeDirection = touchy.swipeDirection();
				if(!cev.type) {
					cev.type = touchy.getType();
					if(cev.type) TouchEvent(cev.type+"start");
				};
			} else {
				cev.swipeAngle = undefined;
				cev.swipeDirection = undefined;
			};
		};
		if(capture && (!cev.type || touchy.config["capture"+cev.type]==true)) event.preventDefault();
		// if(cev.type) console.log(touchy.config["capture"+cev.type]+"");
	};
	touchy.newEvent = function() { delete touchy["currentEvent"]; touchy.currentEvent = touchy.clone(touchy.baseEvent); };
	touchy.cancel = function() { delete touchy["currentEvent"]; };
	touchy.currentEvent = false;
	touchy.hook(element);
	return(touchy);
};<commit_msg>touchy stuff works<commit_after>// /*
//  TouchyFeely
// 	Swipe controller library - handles swipes, touches, and pinches on any object, icnluding the body
// 	Created by John Bragg for Seabright Studios
// */

var TouchyFeely = function(element,options) {
	var touchy = this;
	var TouchHooks = {
		touchstart : function(event) {
			if(event.touches.length == 1) {
				touchy.update(event,true);
				touchy.currentEvent.target = touchy.getTarget(event);
			};
		},
		touchmove : function(event) {
			if(touchy.currentEvent) {
				touchy.update(event);
				if(touchy.currentEvent.type) { TouchEvent(touchy.currentEvent.type+"move"); };
				return(false);
			};
			return(true);
		},
		touchend : function(event) {
			if(touchy.currentEvent) {
				touchy.update(event);
				if(touchy.currentEvent.type) { TouchEvent(touchy.currentEvent.type+"end"); };
			};
			touchy.cancel();
		},
		touchcancel : function(event) { touchy.cancel(); }
	};
	var TouchEvent = function(type) {
		var evObj = document.createEvent('UIEvents');
		evObj.initUIEvent(type, true, true, window, 1);
		for(var i in touchy.currentEvent) { evObj[i] = touchy.currentEvent[i]; };
		touchy.element.dispatchEvent(evObj);
		// console.log("Event: "+type,evObj);
	};
	var baseEvent = {
		history : []
	};
	touchy.element = element;
	touchy.config = {
		minLength : 20,
		capturescroll : true,
		captureswipe : true
	};
	for(var o in (options||{})) {
		touchy.config[o] = options[o];
	};
	touchy.clone = function(obj) {
	  var newObj = (obj instanceof Array) ? [] : {};
	  for(i in obj) {
	    if(obj[i] && typeof obj[i] == "object") {
	      newObj[i] = touchy.clone(obj[i]);
	    } else newObj[i] = obj[i];
	  };
		return newObj;
	};
	touchy.hook = function(elem) { for(var i in TouchHooks) { elem.addEventListener(i, TouchHooks[i], true); }; };
	touchy.swipeLength = function() {
		return(Math.round(Math.sqrt(Math.pow(touchy.currentEvent.deltaX,2)+Math.pow(touchy.currentEvent.deltaY,2))));
	};
	touchy.calculateAngle = function() {
		var ang = Math.round((Math.atan2(touchy.currentEvent.vertDiff,touchy.currentEvent.horzDiff))*180/Math.PI); //angle in degrees
		if(ang < 0) ang = 360 - Math.abs(ang);
		return(ang);
	};
	touchy.swipeDirection = function() {
		if ( ((this.currentEvent.swipeAngle <= 45) && (this.currentEvent.swipeAngle >= 0)) || ((this.currentEvent.swipeAngle <= 360) && (this.currentEvent.swipeAngle >= 315)) ) {
			return('left');
		} else if ( (this.currentEvent.swipeAngle >= 135) && (this.currentEvent.swipeAngle <= 225) ) {
			return('right');
		} else if ( (this.currentEvent.swipeAngle > 45) && (this.currentEvent.swipeAngle < 135) ) {
			return('down');
		};
		return('up');
	};
	touchy.getType = function() {
		var cev = touchy.currentEvent;
		if(cev.swipeDirection=="left"||cev.swipeDirection=="right") return("swipe");
		else if(cev.swipeDirection=="up"||cev.swipeDirection=="down") return("scroll");
		else return(undefined);
	};
	touchy.getTarget = function(event) {
		return(event.currentTarget);
	};
	touchy.update = function(event,capture) {
		if(!touchy.currentEvent) touchy.newEvent();
		var tch = event["touches"][0] || event["changedTouches"][0], cev = touchy.currentEvent;
		cev.curX = tch.pageX;
		cev.curY = tch.pageY;
		cev.history = cev.history || [];
		cev.history.push([cev.curX,cev.curY]);
		if(!cev.fingerCount) cev.fingerCount = event["touches"].length;
		if(!cev.startX) cev.startX = cev.curX;
		if(!cev.startY) cev.startY = cev.curY;
		cev.deltaX = cev.curX - cev.startX;
		cev.deltaY = cev.curY - cev.startY;
		cev.horzDiff = cev.startX - cev.curX;
		cev.vertDiff = cev.curY - cev.startY;
		if(cev.deltaX > 0 || cev.deltaY > 0) {
			cev.swipeLength = touchy.swipeLength();
			if(cev.swipeLength >= touchy.config.minLength) {
				cev.swipeAngle = touchy.calculateAngle();
				cev.swipeDirection = touchy.swipeDirection();
				if(!cev.type) {
					cev.type = touchy.getType();
					if(cev.type) TouchEvent(cev.type+"start");
				};
			} else {
				cev.swipeAngle = undefined;
				cev.swipeDirection = undefined;
			};
		};
		if(capture && (!cev.type || touchy.config["capture"+cev.type]==true)) event.preventDefault();
		// if(cev.type) console.log(touchy.config["capture"+cev.type]+"");
	};
	touchy.newEvent = function() { delete touchy["currentEvent"]; touchy.currentEvent = touchy.clone(touchy.baseEvent); };
	touchy.cancel = function() { delete touchy["currentEvent"]; };
	touchy.currentEvent = false;
	touchy.hook(element);
	return(touchy);
};<|endoftext|>


<commit_before>var webpack = require('webpack');
var autoprefixer = require('autoprefixer');

module.exports = {
	devtool: 'cheap-module-eval-source-map',
	entry: [
		'./src/index.jsx'
	],
	module: {
		loaders: [
			{
				test: /\.jsx?$/,
				exclude: /node_modules/,
				loader: 'eslint!babel'
			}
		]
	},
	resolve: {
		extensions: ['', '.js', '.jsx'],
		modulesDirectories: ['node_modules']
	},
	output: {
		path: __dirname + '/build/',
		publicPath: '/',
		filename: 'index.js'
	},
	plugins: [
		new webpack.optimize.OccurenceOrderPlugin(),
		new webpack.NoErrorsPlugin()
	],
	postcss: function () {
        return {
            defaults: [autoprefixer],
            cleaner:  [autoprefixer({ browsers: [
				'> 1%', 'IE >= 10', 'last 2 versions', 'Android >= 5'
			] })]
        };
    }
};
<commit_msg>externals added for example<commit_after>var webpack = require('webpack');
var autoprefixer = require('autoprefixer');

module.exports = {
	devtool: 'cheap-module-eval-source-map',
	entry: [
		'./src/index.jsx'
	],
	module: {
		loaders: [
			{
				test: /\.jsx?$/,
				exclude: /node_modules/,
				loader: 'eslint!babel'
			}
		]
	},
	externals: [
		"react": "React",
        "react-dom": "ReactDOM"
	],
	resolve: {
		extensions: ['', '.js', '.jsx'],
		modulesDirectories: ['node_modules']
	},
	output: {
		path: __dirname + '/build/',
		publicPath: '/',
		filename: 'index.js'
	},
	plugins: [
		new webpack.optimize.OccurenceOrderPlugin(),
		new webpack.NoErrorsPlugin()
	],
	postcss: function () {
        return {
            defaults: [autoprefixer],
            cleaner:  [autoprefixer({ browsers: [
				'> 1%', 'IE >= 10', 'last 2 versions', 'Android >= 5'
			] })]
        };
    }
};
<|endoftext|>


<commit_before>var PROPERTY_SS_ID = 'SPREADSHEET_ID';
var RULE_KEY = 'MAILMAN_PROP_RULES';
var MAILMAN_VERSION = 'pre0.31';
var APP_NAME = 'Mailman';
var LAST_AUTH_KEY = 'MAILMAN_AUTH_EMAIL';

var SPREADSHEET_ID = null;
<commit_msg>Incremented the version.<commit_after>var PROPERTY_SS_ID = 'SPREADSHEET_ID';
var RULE_KEY = 'MAILMAN_PROP_RULES';
var MAILMAN_VERSION = 'pre0.32';
var APP_NAME = 'Mailman';
var LAST_AUTH_KEY = 'MAILMAN_AUTH_EMAIL';

var SPREADSHEET_ID = null;
<|endoftext|>


<commit_before>/******************************************************
 * PATTERN LAB NODE
 * EDITION-NODE-GULP
 * The gulp wrapper around patternlab-node core, providing tasks to interact with the core library.
 ******************************************************/
const gulp = require('gulp');
const argv = require('minimist')(process.argv.slice(2));

/******************************************************
 * PATTERN LAB  NODE WRAPPER TASKS with core library
 ******************************************************/
const config = require('./patternlab-config.json');
const patternlab = require('@pattern-lab/core')(config);

function build() {
  return patternlab
    .build({
      watch: argv.watch,
      cleanPublic: config.cleanPublic,
    })
    .then(() => {
      // do something else when this promise resolves
    });
}

function serve() {
  return patternlab
    .serve({
      cleanPublic: config.cleanPublic,
    })
    .then(() => {
      // do something else when this promise resolves
    });
}

gulp.task('patternlab:version', function() {
  console.log(patternlab.version());
});

gulp.task('patternlab:help', function() {
  patternlab.help();
});

gulp.task('patternlab:patternsonly', function() {
  patternlab.patternsonly(config.cleanPublic);
});

gulp.task('patternlab:liststarterkits', function() {
  patternlab.liststarterkits();
});

gulp.task('patternlab:loadstarterkit', function() {
  patternlab.loadstarterkit(argv.kit, argv.clean);
});

gulp.task('patternlab:build', function() {
  build().then(() => {
    // do something else when this promise resolves
  });
});

gulp.task('patternlab:serve', function() {
  serve().then(() => {
    // do something else when this promise resolves
  });
});

gulp.task('patternlab:installplugin', function() {
  patternlab.installplugin(argv.plugin);
});

gulp.task('default', ['patternlab:help']);
<commit_msg>feat(serve): change calling method<commit_after>/******************************************************
 * PATTERN LAB NODE
 * EDITION-NODE-GULP
 * The gulp wrapper around patternlab-node core, providing tasks to interact with the core library.
 ******************************************************/
const gulp = require('gulp');
const argv = require('minimist')(process.argv.slice(2));

/******************************************************
 * PATTERN LAB  NODE WRAPPER TASKS with core library
 ******************************************************/
const config = require('./patternlab-config.json');
const patternlab = require('@pattern-lab/core')(config);

function build() {
  return patternlab
    .build({
      watch: argv.watch,
      cleanPublic: config.cleanPublic,
    })
    .then(() => {
      // do something else when this promise resolves
    });
}

function serve() {
  return patternlab.server
    .serve({
      cleanPublic: config.cleanPublic,
    })
    .then(() => {
      // do something else when this promise resolves
    });
}

gulp.task('patternlab:version', function() {
  console.log(patternlab.version());
});

gulp.task('patternlab:help', function() {
  patternlab.help();
});

gulp.task('patternlab:patternsonly', function() {
  patternlab.patternsonly(config.cleanPublic);
});

gulp.task('patternlab:liststarterkits', function() {
  patternlab.liststarterkits();
});

gulp.task('patternlab:loadstarterkit', function() {
  patternlab.loadstarterkit(argv.kit, argv.clean);
});

gulp.task('patternlab:build', function() {
  build().then(() => {
    // do something else when this promise resolves
  });
});

gulp.task('patternlab:serve', function() {
  serve().then(() => {
    // do something else when this promise resolves
  });
});

gulp.task('patternlab:installplugin', function() {
  patternlab.installplugin(argv.plugin);
});

gulp.task('default', ['patternlab:help']);
<|endoftext|>


<commit_before>"use strict";
var os = require('os');
var md5 = require('MD5');

function chunkSubstr(str, size) {
  var numChunks = str.length / size + .5 | 0,
      chunks = new Array(numChunks);

  for(var i = 0, o = 0; i < numChunks; ++i, o += size) {
    chunks[i] = str.substr(o, size);
  }

  return chunks;
}

var bigrandom = function bigrandom(salt="s") {
    return md5(salt + Math.random() +
               Math.random() + Math.random() + Math.random() +
               new Date().getTime() +
               JSON.stringify(arguments) +
               os.hostname() +
               os.freemem() +
               JSON.stringify(os.cpus()) +
               JSON.stringify(os.networkInterfaces()) +
               JSON.stringify(os.loadavg()) +
               process.pid +
               process.hrtime() +
               process.memoryUsage() +
               os.uptime());
}

function randomString(salt = "random-guid") {
    return bigrandom(salt);
    }
exports.randomString = randomString;

function randomGuid(numberOfBlocks = 4,
        blockLength = 4,
        salt = "random-guid") {
    let strLength=numberOfBlocks * blockLength;
    let randomString = bigrandom();
    while(strLength > 32){
        randomString += bigrandom();
        strLength -= 32;
    }
    const chunks=chunkSubstr(randomString,blockLength);
    const chunkedArray = chunks.map(v => v.toString(16));
    let output=[chunkedArray[0]];
    let i = chunkedArray.length;

    for(let i = 1; i < numberOfBlocks; i++){
        output.push(chunkedArray[i]);
    }
    return output.join('-');
    //return chunks.map(v => v.toString(16)).join('-');
    }
exports.randomGuid = randomGuid;

//generate a guid that is tested unique against id's on the current doc
function domSafeRandomGuid(numberOfBlocks = 4) {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }

    var output = '';
    var num = numberOfBlocks;
    while (num > 0) {
        output += s4();
        if (num > 1) output += "-";
        num--;
    }

    if (null === document.getElementById(output)) {
        return output;
    } else {
        domSafeRandomGuid(numberOfBlocks);
    }
}
exports.domSafeRandomGuid = domSafeRandomGuid;<commit_msg>0.0.5<commit_after>"use strict";
var os = require('os');
var md5 = require('MD5');

function chunkSubstr(str, size) {
  var numChunks = str.length / size + 0.5 | 0,
      chunks = new Array(numChunks);

  for(var i = 0, o = 0; i < numChunks; ++i, o += size) {
    chunks[i] = str.substr(o, size);
  }

  return chunks;
}

var bigrandom = function bigrandom(salt="s") {
    return md5(salt + Math.random() +
               Math.random() + Math.random() + Math.random() +
               new Date().getTime() +
               JSON.stringify(arguments) +
               os.hostname() +
               os.freemem() +
               JSON.stringify(os.cpus()) +
               JSON.stringify(os.networkInterfaces()) +
               JSON.stringify(os.loadavg()) +
               process.pid +
               process.hrtime() +
               process.memoryUsage() +
               os.uptime());
}

function randomString(salt = "random-guid") {
    return bigrandom(salt);
    }
exports.randomString = randomString;

function randomGuid(numberOfBlocks = 4,
        blockLength = 4,
        salt = "random-guid") {
    let strLength=numberOfBlocks * blockLength;
    let rnd = bigrandom();
    while(strLength > 32){
        rnd += bigrandom();
        strLength -= 32;
    }
    const chunks=chunkSubstr(rnd,blockLength);
    const chunkedArray = chunks.map(v => v.toString(16));
    let output=[chunkedArray[0]];
    let i = chunkedArray.length;

    for(let i = 1; i < numberOfBlocks; i++){
        output.push(chunkedArray[i]);
    }
    return output.join('-');
    //return chunks.map(v => v.toString(16)).join('-');
    }
exports.randomGuid = randomGuid;

//generate a guid that is tested unique against id's on the current doc
function domSafeRandomGuid(numberOfBlocks = 4) {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }

    var output = '';
    var num = numberOfBlocks;
    while (num > 0) {
        output += s4();
        if (num > 1) output += "-";
        num--;
    }

    if (null === document.getElementById(output)) {
        return output;
    } else {
        return domSafeRandomGuid(numberOfBlocks);
    }
}
exports.domSafeRandomGuid = domSafeRandomGuid;<|endoftext|>


<commit_before>// Define Dependencies
var gulp = require('gulp')

// Deploy (gulp deploy)
gulp.task('deploy', ['deploy:rsync'])
<commit_msg>Update gulp deploy task<commit_after>// Define Dependencies
var gulp = require('gulp')

// Deploy (gulp deploy)
gulp.task('deploy', ['deploy:ghPages'])
<|endoftext|>


<commit_before>var initProductActions = function(){

  $("#add_product_name").product_autocomplete();

  $('.calculator-fields').each(function(){
    var $fields_container = $(this);
    var $type_select = $fields_container.find('.type-select');
    var $settings = $fields_container.find('.settings');
    var $warning = $fields_container.find('.warning');
    var originalType = $type_select.val();

    $warning.hide();
    $type_select.change(function(){
      if( $(this).val() == originalType ){
        $warning.hide();
        $settings.show();
        $settings.find('input').removeAttr('disabled');
      } else {
        $warning.show();
        $settings.hide();
        $settings.find('input').attr('disabled', 'disabled');
      }
    });
  });

  //
  // CreateLineItems Promotion Action
  //
  ( function(){
    var hideOrShowItemTables = function(){
      $('.promotion_action table').each(function(){
        if($(this).find('td').length == 0){
          $(this).hide();
        } else {
          $(this).show();
        }
      });
    };
    hideOrShowItemTables();

    // Remove line item
    var setupRemoveLineItems = function(){
      $(".remove_promotion_line_item").click(function(){
        line_items_el = $($('.line_items_string')[0])
        finder = RegExp($(this).data("variant-id") + "x\\d+")
        line_items_el.val(line_items_el.val().replace(finder, ""))
        $(this).parents('tr').remove();
        hideOrShowItemTables();
      });
    };

    setupRemoveLineItems();
    // Add line item to list
    $(".promotion_action.create_line_items button.add").unbind('click').click(function(e){
      var $container = $(this).parents('.promotion_action');
      var product_name = $container.find("input[name='add_product_name']").val();
      var variant_id = $container.find("input[name='add_variant_id']").val();
      var quantity = $container.find("input[name='add_quantity']").val();
      if(variant_id){
        // Add to the table
        var newRow = "
" + product_name + "	" + quantity + "
";
        $container.find('table').append(newRow);
        // Add to serialized string in hidden text field
        var $hiddenField = $container.find(".line_items_string");
        $hiddenField.val($hiddenField.val() + "," + variant_id + "x" + quantity);
        setupRemoveLineItems();
        hideOrShowItemTables();
      }
      return false;
    });

  } )();

}

$(document).ready(function() {
  initProductActions();

  // toggle fields for specific events
  $('#promotion_event_name').change(function() {
    $('#promotion_code_field').toggle($('#promotion_event_name').val() == 'spree.checkout.coupon_code_added');
    $('#promotion_path_field').toggle($('#promotion_event_name').val() == 'spree.content.visited');
  });
  $('#promotion_event_name').change();

});

<commit_msg>Refactor promotions.js<commit_after>$(document).ready(function () {
  $("#add_product_name").product_autocomplete();

  $('.calculator-fields').each(function(){
    var fields_container = $(this);
    var type_select = fields_container.find('.type-select');
    var settings = fields_container.find('.settings');
    var warning = fields_container.find('.warning');
    var originalType = type_select.val();

    warning.hide();
    type_select.change(function(){
      if($(this).val() == originalType){
        warning.hide();
        settings.show();
        settings.find('input').removeAttr('disabled');
      } else {
        warning.show();
        settings.hide();
        settings.find('input').attr('disabled', 'disabled');
      }
    });
  });

  $('.promotion_action table').each(function(){
    if($(this).find('td').length == 0){
      $(this).hide();
    } else {
      $(this).show();
    }
  });

  $(".remove_promotion_line_item").on("click", function(){
    line_items_el = $($('.line_items_string')[0])
    finder = RegExp($(this).data("variant-id") + "x\\d+")
    line_items_el.val(line_items_el.val().replace(finder, ""))
    $(this).parents('tr').remove();
    hideOrShowItemTables();
  });

  $(".promotion_action.create_line_items button.add").on("click", function(){
    var container = $(this).parents('.promotion_action');
    var product_name = container.find("input[name='add_product_name']").val();
    var variant_id = container.find("input[name='add_variant_id']").val();
    var quantity = container.find("input[name='add_quantity']").val();
    if(variant_id) {
      // Add to the table
      var newRow = "
" + product_name + "	" + quantity + "
";
      container.find('table').append(newRow);
      // Add to serialized string in hidden text field
      var hiddenField = container.find(".line_items_string");
      hiddenField.val(hiddenField.val() + "," + variant_id + "x" + quantity);
    }
    return false;
  });

  // toggle fields for specific events
  $('#promotion_event_name').change(function() {
    $('#promotion_code_field').toggle($('#promotion_event_name').val() == 'spree.checkout.coupon_code_added');
    $('#promotion_path_field').toggle($('#promotion_event_name').val() == 'spree.content.visited');
  });
  $('#promotion_event_name').change();

});

<|endoftext|>


<commit_before>// Exposes an Array of Linters, which can be accessed with `ghlint.linters`. Every Linter is an Object with a message field and a lint method.
//
// ## Linter Properties
// ### message (String)
// A short description of what went wrong (assuming the linter fails).
// ### lint (function)
// Must be given the reponse bodies of three GitHub API endpoints for a specific repository as parameters: [/repos/:owner](https://developer.github.com/v3/repos/#get), [/repos/:owner/:repo/commits](https://developer.github.com/v3/repos/commits/), and [/repos/:owner/:repo/contents](https://developer.github.com/v3/repos/contents/). These parameters are named repo, commits, and contents in the source respectively. Returns true if the Linter passes (if the repo satisfies the Linter's description) and false if it fails.
module.exports = [
  {
    message: 'missing commits',
    lint: function (repo, commits) {
      return commits.length > 0;
    }
  },

  {
    message: 'repository name should be lowercased',
    lint: function (repo) {
      // Name should only contain lowercase letters, numbers, dashes, and underscores.
      return /^[a-z\d\-_]+$/.test(repo.name);
    }
  },

  {
    message: 'missing description',
    lint: function (repo) {
      return Boolean(repo.description);
    }
  },

  {
    message: 'default branch should be master',
    lint: function (repo) {
      return repo.default_branch === 'master';
    }
  },

  {
    message: 'missing issues',
    lint: function (repo) {
      return Boolean(repo.has_issues);
    }
  },

  {
    message: 'uses GitHub Pages and is missing a homepage',
    lint: function (repo) {
      // This will always pass if the repo isn't using GitHub Pages.
      return repo.has_pages ? Boolean(repo.homepage) : true;
    }
  },

  {
    message: 'missing license',
    lint: function (repo, commits, contents) {
      // At least one file in the root directory should have "license" in its name (case insensitive).
      return Array.prototype.some.call(contents, function (content) {
        return content.type === 'file' && /license/i.test(content.name);
      });
    }
  },

  {
    message: 'missing readme',
    lint: function (repo, commits, contents) {
      // At least one file in the root directory should have "readme" in its name (case insensitive).
      return Array.prototype.some.call(contents, function (content) {
        return content.type === 'file' && /readme/i.test(content.name);
      });
    }
  }
];
<commit_msg>Extract a new function to check for patterns from files in the root directory<commit_after>// Returns true if at least one file in the root directory of `contents` has a name that matches `pattern`.
function matchingFileInRoot(contents, pattern) {
  return contents.some(function (content) {
    return content.type === 'file' && pattern.test(content.name);
  });
}

// Exposes an Array of Linters, which can be accessed with `ghlint.linters`. Every Linter is an Object with a message field and a lint method.
//
// ## Linter Properties
// ### message (String)
// A short description of what went wrong (assuming the linter fails).
// ### lint (function)
// Must be given the reponse bodies of three GitHub API endpoints for a specific repository as parameters: [/repos/:owner](https://developer.github.com/v3/repos/#get), [/repos/:owner/:repo/commits](https://developer.github.com/v3/repos/commits/), and [/repos/:owner/:repo/contents](https://developer.github.com/v3/repos/contents/). These parameters are named repo, commits, and contents in the source respectively. Returns true if the Linter passes (if the repo satisfies the Linter's description) and false if it fails.
module.exports = [
  {
    message: 'missing commits',
    lint: function (repo, commits) {
      return commits.length > 0;
    }
  },

  {
    message: 'repository name should be lowercased',
    lint: function (repo) {
      // Name should only contain lowercase letters, numbers, dashes, and underscores.
      return /^[a-z\d\-_]+$/.test(repo.name);
    }
  },

  {
    message: 'missing description',
    lint: function (repo) {
      return Boolean(repo.description);
    }
  },

  {
    message: 'default branch should be master',
    lint: function (repo) {
      return repo.default_branch === 'master';
    }
  },

  {
    message: 'missing issues',
    lint: function (repo) {
      return Boolean(repo.has_issues);
    }
  },

  {
    message: 'uses GitHub Pages and is missing a homepage',
    lint: function (repo) {
      // This will always pass if the repo isn't using GitHub Pages.
      return repo.has_pages ? Boolean(repo.homepage) : true;
    }
  },

  {
    message: 'missing license',
    lint: function (repo, commits, contents) {
      return matchingFileInRoot(contents, /license/i);
    }
  },

  {
    message: 'missing readme',
    lint: function (repo, commits, contents) {
      return matchingFileInRoot(contents, /readme/i);
    }
  }
];
<|endoftext|>


<commit_before>steal('can/util/can.js', function (can) {

	// event.js
	// ---------

	// can.extend(Class.prototype, can.event);
	// can.extend(Class.prototype, can.event, { __propagate: 'prop' });

	// can.extend(Class.prototype, can.event);
	// can.extend(Class.prototype, can.event, { __propagate: 'prop' });

	// return can.event;

	// _Basic event wrapper._
	can.addEvent = function (event, fn) {
		var allEvents = this.__bindEvents || (this.__bindEvents = {}),
			eventList = allEvents[event] || (allEvents[event] = []);
		eventList.push({
			handler: fn,
			name: event
		});
		return this;
	};

	// can.listenTo works without knowing how bind works
	// the API was heavily influenced by BackboneJS:
	// http://backbonejs.org/
	can.listenTo = function (other, event, handler) {
		var idedEvents = this.__listenToEvents;
		if (!idedEvents) {
			idedEvents = this.__listenToEvents = {};
		}
		var otherId = can.cid(other);
		var othersEvents = idedEvents[otherId];
		if (!othersEvents) {
			othersEvents = idedEvents[otherId] = {
				obj: other,
				events: {}
			};
		}
		var eventsEvents = othersEvents.events[event];
		if (!eventsEvents) {
			eventsEvents = othersEvents.events[event] = [];
		}
		eventsEvents.push(handler);
		can.bind.call(other, event, handler);
	};

	can.stopListening = function (other, event, handler) {
		var idedEvents = this.__listenToEvents,
			iterIdedEvents = idedEvents,
			i = 0;
		if (!idedEvents) {
			return this;
		}
		if (other) {
			var othercid = can.cid(other);
			(iterIdedEvents = {})[othercid] = idedEvents[othercid];
			// you might be trying to listen to something that is not there
			if (!idedEvents[othercid]) {
				return this;
			}
		}
		for (var cid in iterIdedEvents) {
			var othersEvents = iterIdedEvents[cid],
				eventsEvents;
			other = idedEvents[cid].obj;
			if (!event) {
				eventsEvents = othersEvents.events;
			} else {
				(eventsEvents = {})[event] = othersEvents.events[event];
			}
			for (var eventName in eventsEvents) {
				var handlers = eventsEvents[eventName] || [];
				i = 0;
				while (i < handlers.length) {
					if (handler && handler === handlers[i] || !handler) {
						can.unbind.call(other, eventName, handlers[i]);
						handlers.splice(i, 1);
					} else {
						i++;
					}
				}
				// no more handlers?
				if (!handlers.length) {
					delete othersEvents.events[eventName];
				}
			}
			if (can.isEmptyObject(othersEvents.events)) {
				delete idedEvents[cid];
			}
		}
		return this;
	};

	can.removeEvent = function (event, fn) {
		if (!this.__bindEvents) {
			return this;
		}
		var events = this.__bindEvents[event] || [],
			i = 0,
			ev, isFunction = typeof fn === 'function';
		while (i < events.length) {
			ev = events[i];
			if (isFunction && ev.handler === fn || !isFunction && ev.cid === fn) {
				events.splice(i, 1);
			} else {
				i++;
			}
		}
		return this;
	};

	can.dispatch = function (event, args) {
		if (!this.__bindEvents) {
			return;
		}
		if (typeof event === 'string') {
			event = {
				type: event
			};
		}
		var eventName = event.type,
			handlers = (this.__bindEvents[eventName] || [])
				.slice(0),
			ev;
		args = [event].concat(args || []);
		for (var i = 0, len = handlers.length; i < len; i++) {
			ev = handlers[i];
			ev.handler.apply(this, args);
		}
	};

	can.once = function(event, handler) {
		var once = function() {
			can.unbind.call(this, event, once);
			return handler.apply(this, arguments);
		};
		can.bind.call(this, event, once);
		return this;
	};

	can.event = {
		// __propagate: false,

		// Event method aliases
		on: can.addEvent,
		off: can.removeEvent,
		once: can.once,
		bind: can.addEvent,
		unbind: can.removeEvent,
		delegate: function(selector, event, handler) {
			return can.addEvent.call(event, handler);
		},
		undelegate: function(selector, event, handler) {
			return can.removeEvent.call(event, handler);
		},
		trigger: can.dispatch,

		// Normal can/event methods
		addEvent: can.addEvent,
		removeEvent: can.removeEvent,
		listenTo: can.listenTo,
		stopListening: can.stopListening,
		dispatch: can.dispatch
	};

	return can.event;
});
<commit_msg>can/event once method should be "one"<commit_after>steal('can/util/can.js', function (can) {

	// event.js
	// ---------

	// can.extend(Class.prototype, can.event);
	// can.extend(Class.prototype, can.event, { __propagate: 'prop' });

	// can.extend(Class.prototype, can.event);
	// can.extend(Class.prototype, can.event, { __propagate: 'prop' });

	// return can.event;

	// _Basic event wrapper._
	can.addEvent = function (event, fn) {
		var allEvents = this.__bindEvents || (this.__bindEvents = {}),
			eventList = allEvents[event] || (allEvents[event] = []);
		eventList.push({
			handler: fn,
			name: event
		});
		return this;
	};

	// can.listenTo works without knowing how bind works
	// the API was heavily influenced by BackboneJS:
	// http://backbonejs.org/
	can.listenTo = function (other, event, handler) {
		var idedEvents = this.__listenToEvents;
		if (!idedEvents) {
			idedEvents = this.__listenToEvents = {};
		}
		var otherId = can.cid(other);
		var othersEvents = idedEvents[otherId];
		if (!othersEvents) {
			othersEvents = idedEvents[otherId] = {
				obj: other,
				events: {}
			};
		}
		var eventsEvents = othersEvents.events[event];
		if (!eventsEvents) {
			eventsEvents = othersEvents.events[event] = [];
		}
		eventsEvents.push(handler);
		can.bind.call(other, event, handler);
	};

	can.stopListening = function (other, event, handler) {
		var idedEvents = this.__listenToEvents,
			iterIdedEvents = idedEvents,
			i = 0;
		if (!idedEvents) {
			return this;
		}
		if (other) {
			var othercid = can.cid(other);
			(iterIdedEvents = {})[othercid] = idedEvents[othercid];
			// you might be trying to listen to something that is not there
			if (!idedEvents[othercid]) {
				return this;
			}
		}
		for (var cid in iterIdedEvents) {
			var othersEvents = iterIdedEvents[cid],
				eventsEvents;
			other = idedEvents[cid].obj;
			if (!event) {
				eventsEvents = othersEvents.events;
			} else {
				(eventsEvents = {})[event] = othersEvents.events[event];
			}
			for (var eventName in eventsEvents) {
				var handlers = eventsEvents[eventName] || [];
				i = 0;
				while (i < handlers.length) {
					if (handler && handler === handlers[i] || !handler) {
						can.unbind.call(other, eventName, handlers[i]);
						handlers.splice(i, 1);
					} else {
						i++;
					}
				}
				// no more handlers?
				if (!handlers.length) {
					delete othersEvents.events[eventName];
				}
			}
			if (can.isEmptyObject(othersEvents.events)) {
				delete idedEvents[cid];
			}
		}
		return this;
	};

	can.removeEvent = function (event, fn) {
		if (!this.__bindEvents) {
			return this;
		}
		var events = this.__bindEvents[event] || [],
			i = 0,
			ev, isFunction = typeof fn === 'function';
		while (i < events.length) {
			ev = events[i];
			if (isFunction && ev.handler === fn || !isFunction && ev.cid === fn) {
				events.splice(i, 1);
			} else {
				i++;
			}
		}
		return this;
	};

	can.dispatch = function (event, args) {
		if (!this.__bindEvents) {
			return;
		}
		if (typeof event === 'string') {
			event = {
				type: event
			};
		}
		var eventName = event.type,
			handlers = (this.__bindEvents[eventName] || [])
				.slice(0),
			ev;
		args = [event].concat(args || []);
		for (var i = 0, len = handlers.length; i < len; i++) {
			ev = handlers[i];
			ev.handler.apply(this, args);
		}
	};

	can.once = function(event, handler) {
		var once = function() {
			can.unbind.call(this, event, once);
			return handler.apply(this, arguments);
		};
		can.bind.call(this, event, once);
		return this;
	};

	can.event = {
		// __propagate: false,

		// Event method aliases
		on: can.addEvent,
		off: can.removeEvent,
		one: can.one,
		bind: can.addEvent,
		unbind: can.removeEvent,
		delegate: function(selector, event, handler) {
			return can.addEvent.call(event, handler);
		},
		undelegate: function(selector, event, handler) {
			return can.removeEvent.call(event, handler);
		},
		trigger: can.dispatch,

		// Normal can/event methods
		addEvent: can.addEvent,
		removeEvent: can.removeEvent,
		listenTo: can.listenTo,
		stopListening: can.stopListening,
		dispatch: can.dispatch
	};

	return can.event;
});
<|endoftext|>


<commit_before>

(function(mousetouch){
   var mt; // private variables of mousetouch
   mt.current=-1;
   mt.justpressed=false;
   mt.justpnr=false; // just pressed and released
   mt.dbl=false; // in double click gesture;
   mt.outside=false; // outside of current element;
   mt.elements=[];
   mt.touches=[]; // last coordinates of touches
   mt.mouse={x:0,y:0}; // last coordinate of mouse

   // double click timings
   mt.dbl_t1=300; // timing for release
   mt.dbl_t2=500; // timing for next down

   // function for registering mousetouch events for an element, gestures is hash e.g. {doubleclick=>1,...}
   mousetouch.register=function(element,handler,gestures){
      var elnr=mt.elements.length;
      mt.elements[elnr].handler=handler;
      mt.elements[elnr].el=element;
      mt.elements[elnr].gestures=gestures;
      var down=function(e){
         mt.current=elnr;
         mt.outside=false;
         mt.dbl=mt.justpnr; // this is the second click of a double click if true
         mt.justpressed=false;
         mt.justpnr=false;
         if (mt.dbl){
            callhandler(e,'down');
         } else {
            if (mt.elements[elnr].gestures.doubleclick){ // does this element want double clicks?
               mt.justpressed=true;
               setTimeout(function(){
                  if (mt.justpressed){
                     call(e,'down'); // this is a delayed single click
                  }
                  mt.justpressed=false;
               },mt.dbl_t1);
            } else {
               callhandler(e,'down');
            }
         }
      }
      $(element).mousedown(down); // register down function to mousedown
      $(element).bind('touchstart',down); // and touchstart

      // events that simply register whether mouse / touch is outside element
      $(element).mouseleave(function(e)){
         if (elnr!=mt.current) return;
         mt.outside=true;
      }
      $(element).mouseenter(function(e)){
         if (elnr!=mt.current) return;
         mt.outside=false;
      }
   }

   // mouseup / touchend event; registered on global document to catch events outside of element
   var up=function(e){
      if (mt.current<0) return; // not a gesture of any registered element
      if (mt.justpressed){ // going to be a double click gesture (mouseup shortly after mousedown)
         mt.justpnr=true;
         mt.justpressed=false;
         var elnr=mousemove.current;
         setTimeout(function(){
            if (mt.justpnr){
               callhandler(e,'down'); // this is a delayed single click
               callhandler(e,'up'); // instantaneously end gesture (single click)
            }
            mt.justpnr=false;
         },mt.dbl_t2);
      } else {
         callhandler(e,'up');
      }
      mt.current=-1; // end gesture officially
   }

   // mousemove / touchmove event; registered on global document to catch events outside of element
   var move=function(e){
      if (mt.current<0) return; // not a gesture of any registered element
      if (mt.justpressed || mt.justpnr){ // this interrupts double click detection
         mt.justpnr=false;
         mt.justpressed=false;
         callhandler(e,'down'); // start of gesture
      }
      callhandler(e,'move');
   }

   // call the handler for the element; provide additional gesture information
   var callhandler=function(e,what){
      var gesture={doubleclick:mt.dbl,outside:mt.outside,first:(what=='down'),last:(what=='up')};
      if (e.originalEvent.touches){ // touch event
         if (e.originalEvent.touches.length){
            gesture.x=e.originalEvent.touches[0].pageX;
            gesture.y=e.originalEvent.touches[0].pageY;
            mt.touches[0].x=gesture.x;
            mt.touches[0].y=gesture.y;
         } else {
            gesture.x=mt.touches[0].x;
            gesture.y=mt.touches[0].y;
         }
      } else { // mouse event
         gesture.x=e.pageX;
         gesture.y=e.pageY;
      }
      mt.elements[mt.current].handler.call(mt.elements[mt.current].element,e,gesture);
   }

   // register document event handlers after DOM ready
   $(function(){
      $(document).mouseup(up);
      $(document).bind('touchend',up);
      $(document).mousemove(move);
      $(document).bind('touchmove',move);
   });
})(window.mousetouch={});<commit_msg>Fixes mouse touch.js<commit_after>
(function(mousetouch){
   var mt; // private variables of mousetouch
   mt.current=-1;
   mt.justpressed=false;
   mt.justpnr=false; // just pressed and released
   mt.dbl=false; // in double click gesture;
   mt.outside=false; // outside of current element;
   mt.elements=[];
   mt.touches=[]; // last coordinates of touches
   mt.mouse={x:0,y:0}; // last coordinate of mouse

   // double click timings
   mt.dbl_t1=300; // timing for release
   mt.dbl_t2=500; // timing for next down

   // function for registering mousetouch events for an element, gestures is hash e.g. {doubleclick=>1,...}
   mousetouch.register=function(element,handler,gestures){
      var elnr=mt.elements.length;
      mt.elements[elnr].handler=handler;
      mt.elements[elnr].el=element;
      mt.elements[elnr].gestures=gestures;
      var down=function(e){
         mt.current=elnr;
         mt.outside=false;
         mt.dbl=mt.justpnr; // this is the second click of a double click if true
         mt.justpressed=false;
         mt.justpnr=false;
         if (mt.dbl){
            callhandler(e,'down');
         } else {
            if (mt.elements[elnr].gestures.doubleclick){ // does this element want double clicks?
               mt.justpressed=true;
               setTimeout(function(){
                  if (mt.justpressed){
                     call(e,'down'); // this is a delayed single click
                  }
                  mt.justpressed=false;
               },mt.dbl_t1);
            } else {
               callhandler(e,'down');
            }
         }
      }
      $(element).mousedown(down); // register down function to mousedown
      $(element).bind('touchstart',down); // and touchstart

      // events that simply register whether mouse / touch is outside element
      $(element).mouseleave(function(e){
         if (elnr!=mt.current) return;
         mt.outside=true;
      });
      $(element).mouseenter(function(e){
         if (elnr!=mt.current) return;
         mt.outside=false;
      });
   }

   // mouseup / touchend event; registered on global document to catch events outside of element
   var up=function(e){
      if (mt.current<0) return; // not a gesture of any registered element
      if (mt.justpressed){ // going to be a double click gesture (mouseup shortly after mousedown)
         mt.justpnr=true;
         mt.justpressed=false;
         var elnr=mousemove.current;
         setTimeout(function(){
            if (mt.justpnr){
               callhandler(e,'down'); // this is a delayed single click
               callhandler(e,'up'); // instantaneously end gesture (single click)
            }
            mt.justpnr=false;
         },mt.dbl_t2);
      } else {
         callhandler(e,'up');
      }
      mt.current=-1; // end gesture officially
   }

   // mousemove / touchmove event; registered on global document to catch events outside of element
   var move=function(e){
      if (mt.current<0) return; // not a gesture of any registered element
      if (mt.justpressed || mt.justpnr){ // this interrupts double click detection
         mt.justpnr=false;
         mt.justpressed=false;
         callhandler(e,'down'); // start of gesture
      }
      callhandler(e,'move');
   }

   // call the handler for the element; provide additional gesture information
   var callhandler=function(e,what){
      var gesture={doubleclick:mt.dbl,outside:mt.outside,first:(what=='down'),last:(what=='up')};
      if (e.originalEvent.touches){ // touch event
         if (e.originalEvent.touches.length){
            gesture.x=e.originalEvent.touches[0].pageX;
            gesture.y=e.originalEvent.touches[0].pageY;
            mt.touches[0].x=gesture.x;
            mt.touches[0].y=gesture.y;
         } else {
            gesture.x=mt.touches[0].x;
            gesture.y=mt.touches[0].y;
         }
      } else { // mouse event
         gesture.x=e.pageX;
         gesture.y=e.pageY;
      }
      mt.elements[mt.current].handler.call(mt.elements[mt.current].element,e,gesture);
   }

   // register document event handlers after DOM ready
   $(function(){
      $(document).mouseup(up);
      $(document).bind('touchend',up);
      $(document).mousemove(move);
      $(document).bind('touchmove',move);
   });
})(window.mousetouch={});<|endoftext|>


<commit_before>
// to use this widget, just include this js file, and then call openaccessbutton_widget() in a script on the page
// If jquery is not already used on the site, jquery is required too.
// bootstrap can optionally be used to apply styling
// this can be done like so:
//
// <link rel="stylesheet" href="https://static.cottagelabs.com/bootstrap-3.0.3/css/bootstrap.min.css">
//
//

// need an input field called oabutton_url
// and an oabutton_find button to trigger it (although triggers on enter too)
// and oabutton_availability div required for inserting results
// and optional oabutton_loading

var openaccessbutton_widget = function(opts) {
  if (opts === undefined) opts = {};
  if (opts.data === undefined) opts.data = false;
  var api = opts.api ? opts.api : 'https://api.openaccessbutton.org';
  var site = opts.site ? opts.site : 'https://openaccessbutton.org';
  if (opts.element === undefined) opts.element = '#openaccessbutton_widget';
  if (opts.uid === undefined) opts.uid = 'anonymous';
  if ($(opts.element).length === 0) $('body').append('

');

  var w = '
\
    <textarea id="oabutton_url" class="form-control" style="min-height:40px;height:40px;font-size:1.1em;" placeholder="Skip the paywall using a URL, DOI, PMID, PMC ID, Title, or Citation"></textarea>\

\
      \

\

\

Powered by Open Access Button

\

';
  $(opts.element).html(w);

  var availability = function(e) {
    if ($(this).attr('id') === 'oabutton_find' || e === undefined || e.keyCode === 13) {
      if (e && $(this).attr('id') === 'oabutton_find') e.preventDefault();
      var url = $('#oabutton_url').val().trim();
      if (!url.length) {
        $('#oabutton_url').css('border-color','#f04717').focus();
        return;
      }
      if (url.lastIndexOf('.') === url.length-1) url = url.substring(0,url.length-1);
      $('#oabutton_loading').show();
      var avopts = {
        type:'POST',
        url:api+'/availability',
        cache: false,
        processData: false,
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify({url:url,from:opts.uid,plugin:'widget',embedded:window.location.href}),
        success: function(data) {
          $('#oabutton_loading').hide();
          $('#oabutton_availability').show();
          var has = {};
          if (data.data.availability.length > 0) {
            for ( var a in data.data.availability ) {
              has[data.data.availability[a].type] = {url:data.data.availability[a].url};
            }
          }
          if (data.data.requests.length > 0) {
            for ( var r in data.data.requests ) {
              if (!has[data.data.requests[r].type]) has[data.data.requests[r].type] = {id:data.data.requests[r]._id,ucreated:data.data.requests[r].ucreated,usupport:data.data.requests[r].usupport};
            }
          }
          if (data.data.match && data.data.match.indexOf('http') !== 0 && data.data.meta && data.data.meta.article && data.data.meta.article.doi) data.data.match = 'https://doi.org/' + data.data.meta.article.doi;
          if (JSON.stringify(has) === '{}') {
            if (data.data.match.indexOf('http') === 0) {
              var dr = {};
              try { dr.title = data.data.meta.article.title; } catch(err) {}
              try { dr.doi = data.data.meta.article.doi; } catch(err) {}
              try { dr.url = data.data.match; } catch(err) {}
              var ropts = {
                type:'POST',
                url: api+'/request?fast=true',
                cache:false,
                processData:false,
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify(dr),
                success: function(resp) {
                  window.location = site + '/request/' + resp._id;
                },
                error: function() {
                  window.location = site + '/request?url=' + encodeURIComponent(data.data.match);
                }
              }
              $.ajax(ropts);
            } else {
              $('#oabutton_availability').html('
Sorry, we couldn\'t find anything for ' + data.data.match + '.

Matching titles and citations can be tricky. Please find a URL, DOI, PMID or PMCID and try again.
');
            }
          } else if (has.article && !has.data) {
            var availability = '';
            if (has.article.id) {
              availability += '
';
              if (has.article.ucreated) {
                availability += 'You already created a request for this article View the request
';
              } else if (has.article.usupport) {
                availability += 'You already support a request for this article View the request
';
              } else {
                availability += 'Someone has requested access to the article Notify me
';
              }
            } else {
              availability += '
This article is available!
';
              availability += '
' + has.article.url + '
';
              availability += '
Not what you were expecting? Report an error.
';
              availability += '
 You can request it from the author if it isn\'t available.
';
            }
            if (opts.data) {
              availability += '
';
              availability += 'Want the data supporting the article? ';
              availability += 'Request it from the author
';
            }
            $('#oabutton_availability').html(availability);
          } else if (!has.article && has.data) {
            var availability = '
This article is not available
';
            availability += '
Start a request
';
            if (opts.data) {
              availability += '
';
              if (has.data.id) {
                  availability += 'Someone has requested access to the data. Notify me';
              } else {
                availability += 'However there is data available:
';
                availability += '
' + has.data.url;
              }
              availability += '
';
            }
            $('#oabutton_availability').html(availability);
          } else if (has.article && has.data) {
            if (has.article.id && has.data.id) {
              window.location = site + '/request/' + has.article.id + '?data=false';
            } else {
              var availability = '
';
              if (has.article.url) {
                availability += 'This article is available!
';
                availability += '<h>' + has.article.url;
              }
              if (has.article.id) {
                availability += 'Someone has requested access to the article. Notify me';
              }
              availability += '
';
              if (opts.data) {
                availability += '
';
                if (has.data.url) {
                  availability += 'And there is data available for this article:

';
                  availability += '' + has.data.url;
                }
                if (has.data.id) {
                  availability += 'Someone has requested access to the data. Notify me';
                }
                availability += '
';
              }
              $('#oabutton_availability').html(availability);
            }
          }
        },
        error: function() {
          $('#oabutton_loading').hide();
          $('#oabutton_loading').after('
Sorry, something went wrong with Open Access Button. Can you let them know?
');
        }
      };
      $.ajax(avopts);
    }
  }
  $('#oabutton_url').bind('keyup',availability);
  $('#oabutton_find').bind('click',availability);
}
<commit_msg>opening powered by link in new window<commit_after>
// to use this widget, just include this js file, and then call openaccessbutton_widget() in a script on the page
// If jquery is not already used on the site, jquery is required too.
// bootstrap can optionally be used to apply styling
// this can be done like so:
//
// <link rel="stylesheet" href="https://static.cottagelabs.com/bootstrap-3.0.3/css/bootstrap.min.css">
//
//

// need an input field called oabutton_url
// and an oabutton_find button to trigger it (although triggers on enter too)
// and oabutton_availability div required for inserting results
// and optional oabutton_loading

var openaccessbutton_widget = function(opts) {
  if (opts === undefined) opts = {};
  if (opts.data === undefined) opts.data = false;
  var api = opts.api ? opts.api : 'https://api.openaccessbutton.org';
  var site = opts.site ? opts.site : 'https://openaccessbutton.org';
  if (opts.element === undefined) opts.element = '#openaccessbutton_widget';
  if (opts.uid === undefined) opts.uid = 'anonymous';
  if ($(opts.element).length === 0) $('body').append('

');

  var w = '
\
    <textarea id="oabutton_url" class="form-control" style="min-height:40px;height:40px;font-size:1.1em;" placeholder="Skip the paywall using a URL, DOI, PMID, PMC ID, Title, or Citation"></textarea>\

\
      \

\

\

Powered by Open Access Button

\

';
  $(opts.element).html(w);

  var availability = function(e) {
    if ($(this).attr('id') === 'oabutton_find' || e === undefined || e.keyCode === 13) {
      if (e && $(this).attr('id') === 'oabutton_find') e.preventDefault();
      var url = $('#oabutton_url').val().trim();
      if (!url.length) {
        $('#oabutton_url').css('border-color','#f04717').focus();
        return;
      }
      if (url.lastIndexOf('.') === url.length-1) url = url.substring(0,url.length-1);
      $('#oabutton_loading').show();
      var avopts = {
        type:'POST',
        url:api+'/availability',
        cache: false,
        processData: false,
        contentType: 'application/json',
        dataType: 'json',
        data: JSON.stringify({url:url,from:opts.uid,plugin:'widget',embedded:window.location.href}),
        success: function(data) {
          $('#oabutton_loading').hide();
          $('#oabutton_availability').show();
          var has = {};
          if (data.data.availability.length > 0) {
            for ( var a in data.data.availability ) {
              has[data.data.availability[a].type] = {url:data.data.availability[a].url};
            }
          }
          if (data.data.requests.length > 0) {
            for ( var r in data.data.requests ) {
              if (!has[data.data.requests[r].type]) has[data.data.requests[r].type] = {id:data.data.requests[r]._id,ucreated:data.data.requests[r].ucreated,usupport:data.data.requests[r].usupport};
            }
          }
          if (data.data.match && data.data.match.indexOf('http') !== 0 && data.data.meta && data.data.meta.article && data.data.meta.article.doi) data.data.match = 'https://doi.org/' + data.data.meta.article.doi;
          if (JSON.stringify(has) === '{}') {
            if (data.data.match.indexOf('http') === 0) {
              var dr = {};
              try { dr.title = data.data.meta.article.title; } catch(err) {}
              try { dr.doi = data.data.meta.article.doi; } catch(err) {}
              try { dr.url = data.data.match; } catch(err) {}
              var ropts = {
                type:'POST',
                url: api+'/request?fast=true',
                cache:false,
                processData:false,
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify(dr),
                success: function(resp) {
                  window.location = site + '/request/' + resp._id;
                },
                error: function() {
                  window.location = site + '/request?url=' + encodeURIComponent(data.data.match);
                }
              }
              $.ajax(ropts);
            } else {
              $('#oabutton_availability').html('
Sorry, we couldn\'t find anything for ' + data.data.match + '.

Matching titles and citations can be tricky. Please find a URL, DOI, PMID or PMCID and try again.
');
            }
          } else if (has.article && !has.data) {
            var availability = '';
            if (has.article.id) {
              availability += '
';
              if (has.article.ucreated) {
                availability += 'You already created a request for this article View the request
';
              } else if (has.article.usupport) {
                availability += 'You already support a request for this article View the request
';
              } else {
                availability += 'Someone has requested access to the article Notify me
';
              }
            } else {
              availability += '
This article is available!
';
              availability += '
' + has.article.url + '
';
              availability += '
Not what you were expecting? Report an error.
';
              availability += '
 You can request it from the author if it isn\'t available.
';
            }
            if (opts.data) {
              availability += '
';
              availability += 'Want the data supporting the article? ';
              availability += 'Request it from the author
';
            }
            $('#oabutton_availability').html(availability);
          } else if (!has.article && has.data) {
            var availability = '
This article is not available
';
            availability += '
Start a request
';
            if (opts.data) {
              availability += '
';
              if (has.data.id) {
                  availability += 'Someone has requested access to the data. Notify me';
              } else {
                availability += 'However there is data available:
';
                availability += '
' + has.data.url;
              }
              availability += '
';
            }
            $('#oabutton_availability').html(availability);
          } else if (has.article && has.data) {
            if (has.article.id && has.data.id) {
              window.location = site + '/request/' + has.article.id + '?data=false';
            } else {
              var availability = '
';
              if (has.article.url) {
                availability += 'This article is available!
';
                availability += '<h>' + has.article.url;
              }
              if (has.article.id) {
                availability += 'Someone has requested access to the article. Notify me';
              }
              availability += '
';
              if (opts.data) {
                availability += '
';
                if (has.data.url) {
                  availability += 'And there is data available for this article:

';
                  availability += '' + has.data.url;
                }
                if (has.data.id) {
                  availability += 'Someone has requested access to the data. Notify me';
                }
                availability += '
';
              }
              $('#oabutton_availability').html(availability);
            }
          }
        },
        error: function() {
          $('#oabutton_loading').hide();
          $('#oabutton_loading').after('
Sorry, something went wrong with Open Access Button. Can you let them know?
');
        }
      };
      $.ajax(avopts);
    }
  }
  $('#oabutton_url').bind('keyup',availability);
  $('#oabutton_find').bind('click',availability);
}
<|endoftext|>


<commit_before>'use strict';

var Cli = require('../../lib/cli');

var path = require('path');

describe('cli', function() {

  describe('#parse', function() {

    it('parse Linux args', function() {

      // given
      var args = [ 'app', '--enable-logging', '--other-flag=1', '../fixtures/random.xml' ];

      // when
      var {
        files,
        flags
      } = Cli.parse(args, __dirname);

      // then
      expect(files).to.eql([
        path.resolve('app/test/fixtures/random.xml')
      ]);

      expect(flags).to.eql({
        'enable-logging': true,
        'other-flag': 1
      });
    });

    it('parse Linux args, just diagram file', function() {

      // given
      var args = [ 'app', '../fixtures/random.xml' ];

      // when
      var {
        files,
        flags
      } = Cli.parse(args, __dirname);

      // then
      expect(files).to.eql([
        path.resolve('app/test/fixtures/random.xml')
      ]);

      expect(flags).to.eql({ });
    });

    if (process.platform === 'win32') {

      it('parse Windows args', function() {

        // given
        var args = [ 'app', '--', '..\\fixtures\\random.xml' ];

        // when
        var {
          files,
          flags
        } = Cli.parse(args, __dirname);

        // then
        expect(files).to.eql([
          path.resolve('app/test/fixtures/random.xml')
        ]);

        expect(flags).to.eql({ });
      });

      it('parse Windows args, just diagram file', function() {

        // given
        var args = [ 'app', '..\\\\fixtures\\\\random.xml' ];

        // when
        var {
          files,
          flags
        } = Cli.parse(args, __dirname);

        // then
        expect(files).to.eql([
          path.resolve('app/test/fixtures/random.xml')
        ]);

        expect(flags).to.eql({ });
      });

      it('parse Windows args, double backslash', function() {

        // given
        var args = [ 'app', '--', '..\\\\fixtures\\\\random.xml' ];

        // when
        var {
          files,
          flags
        } = Cli.parse(args, __dirname);

        // then
        expect(files).to.eql([
          path.resolve('app/test/fixtures/random.xml')
        ]);

        expect(flags).to.eql({ });
      });

    } else {

      it.skip('parse Windows args');

      it.skip('parse Windows args, double backslash');

    }
  });

});<commit_msg>test(app): migrate cli-spec to ES6<commit_after>'use strict';

const Cli = require('../../lib/cli');

const path = require('path');

describe('cli', function() {

  describe('#parse', function() {

    it('parse Linux args', function() {

      // given
      const args = [ 'app', '--enable-logging', '--other-flag=1', '../fixtures/random.xml' ];

      // when
      const {
        files,
        flags
      } = Cli.parse(args, __dirname);

      // then
      expect(files).to.eql([
        path.resolve('app/test/fixtures/random.xml')
      ]);

      expect(flags).to.eql({
        'enable-logging': true,
        'other-flag': 1
      });
    });

    it('parse Linux args, just diagram file', function() {

      // given
      const args = [ 'app', '../fixtures/random.xml' ];

      // when
      const {
        files,
        flags
      } = Cli.parse(args, __dirname);

      // then
      expect(files).to.eql([
        path.resolve('app/test/fixtures/random.xml')
      ]);

      expect(flags).to.eql({ });
    });

    if (process.platform === 'win32') {

      it('parse Windows args', function() {

        // given
        const args = [ 'app', '--', '..\\fixtures\\random.xml' ];

        // when
        const {
          files,
          flags
        } = Cli.parse(args, __dirname);

        // then
        expect(files).to.eql([
          path.resolve('app/test/fixtures/random.xml')
        ]);

        expect(flags).to.eql({ });
      });

      it('parse Windows args, just diagram file', function() {

        // given
        const args = [ 'app', '..\\\\fixtures\\\\random.xml' ];

        // when
        const {
          files,
          flags
        } = Cli.parse(args, __dirname);

        // then
        expect(files).to.eql([
          path.resolve('app/test/fixtures/random.xml')
        ]);

        expect(flags).to.eql({ });
      });

      it('parse Windows args, double backslash', function() {

        // given
        const args = [ 'app', '--', '..\\\\fixtures\\\\random.xml' ];

        // when
        const {
          files,
          flags
        } = Cli.parse(args, __dirname);

        // then
        expect(files).to.eql([
          path.resolve('app/test/fixtures/random.xml')
        ]);

        expect(flags).to.eql({ });
      });

    } else {

      it.skip('parse Windows args');

      it.skip('parse Windows args, double backslash');

    }
  });

});<|endoftext|>


<commit_before>import React, { findDOMNode } from 'react';
import HashHistory from 'react-router/lib/HashHistory';
import { Router, Route, Link, Navigation } from 'react-router';
import auth from './auth';

var App = React.createClass({
  getInitialState() {
    return {
      loggedIn: auth.loggedIn()
    };
  },

  setStateOnAuth(loggedIn) {
    this.setState({
      loggedIn: loggedIn
    });
  },

  componentWillMount() {
    auth.onChange = this.setStateOnAuth;
    auth.login();
  },

  render() {
    return (

            {this.state.loggedIn ? (
              <Link to="/logout">Log out</Link>
            ) : (
              <Link to="/login">Sign in</Link>
            )}

<Link to="/about">About</Link>

<Link to="/dashboard">Dashboard</Link> (authenticated)

        {this.props.children}

    );
  }
});

var Dashboard = React.createClass({
  render() {
    var token = auth.getToken();
    return (

Dashboard

You made it!

{token}

    );
  }
});

var Login = React.createClass({

  mixins: [ Navigation ],

  getInitialState() {
    return {
      error: false
    };
  },

  handleSubmit(event) {
    event.preventDefault();

    var email = findDOMNode(this.refs.email).value;
    var pass = findDOMNode(this.refs.pass).value;

    auth.login(email, pass, (loggedIn) => {
      if (!loggedIn)
        return this.setState({ error: true });

      var { location } = this.props;

      if (location.query && location.query.nextPathname) {
        this.replaceWith(location.query.nextPathname);
      } else {
        this.replaceWith('/about');
      }
    });
  },

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input ref="email" placeholder="email" defaultValue="joe@example.com"/>
        <input ref="pass" placeholder="password"/> (hint: password1)

        <button type="submit">login</button>
        {this.state.error && (

Bad login information

        )}
      </form>
    );
  }
});

var About = React.createClass({
  render() {
    return
About
;
  }
});

var Logout = React.createClass({
  componentDidMount() {
    auth.logout();
  },

  render() {
    return
You are now logged out
;
  }
});

function requireAuth(nextState, router) {
  if (!auth.loggedIn())
    router.replaceWith('/login', { nextPathname: nextState.location.pathname });
}

React.render((
  <Router history={HashHistory}>
    <Route path="/" component={App}>
      <Route path="login" component={Login}/>
      <Route path="logout" component={Logout}/>
      <Route path="about" component={About}/>
      <Route path="dashboard" component={Dashboard} onEnter={requireAuth}/>
    </Route>
  </Router>
), document.getElementById('example'));
<commit_msg>update auth-flow to new transition objects<commit_after>import React, { findDOMNode } from 'react';
import HashHistory from 'react-router/lib/HashHistory';
import { Router, Route, Link, Navigation } from 'react-router';
import auth from './auth';

var App = React.createClass({
  getInitialState() {
    return {
      loggedIn: auth.loggedIn()
    };
  },

  setStateOnAuth(loggedIn) {
    this.setState({
      loggedIn: loggedIn
    });
  },

  componentWillMount() {
    auth.onChange = this.setStateOnAuth;
    auth.login();
  },

  render() {
    return (

            {this.state.loggedIn ? (
              <Link to="/logout">Log out</Link>
            ) : (
              <Link to="/login">Sign in</Link>
            )}

<Link to="/about">About</Link>

<Link to="/dashboard">Dashboard</Link> (authenticated)

        {this.props.children}

    );
  }
});

var Dashboard = React.createClass({
  render() {
    var token = auth.getToken();
    return (

Dashboard

You made it!

{token}

    );
  }
});

var Login = React.createClass({

  mixins: [ Navigation ],

  getInitialState() {
    return {
      error: false
    };
  },

  handleSubmit(event) {
    event.preventDefault();

    var email = findDOMNode(this.refs.email).value;
    var pass = findDOMNode(this.refs.pass).value;

    auth.login(email, pass, (loggedIn) => {
      if (!loggedIn)
        return this.setState({ error: true });

      var { location } = this.props;

      if (location.query && location.query.nextPathname) {
        this.replaceWith(location.query.nextPathname);
      } else {
        this.replaceWith('/about');
      }
    });
  },

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input ref="email" placeholder="email" defaultValue="joe@example.com"/>
        <input ref="pass" placeholder="password"/> (hint: password1)

        <button type="submit">login</button>
        {this.state.error && (

Bad login information

        )}
      </form>
    );
  }
});

var About = React.createClass({
  render() {
    return
About
;
  }
});

var Logout = React.createClass({
  componentDidMount() {
    auth.logout();
  },

  render() {
    return
You are now logged out
;
  }
});

function requireAuth(nextState, transition) {
  if (!auth.loggedIn())
    transition.to('/login', { nextPathname: nextState.location.pathname });
}

React.render((
  <Router history={HashHistory}>
    <Route path="/" component={App}>
      <Route path="login" component={Login}/>
      <Route path="logout" component={Logout}/>
      <Route path="about" component={About}/>
      <Route path="dashboard" component={Dashboard} onEnter={requireAuth}/>
    </Route>
  </Router>
), document.getElementById('example'));
<|endoftext|>


<commit_before>// For episode 3 ----------

// Number 數
0
1
1024
20.5
-17
-23.09

10 + 21
7 + 5.1
1 + 2 + 3
1 + 2 * 3
(1 + 2) * 3
20 - 10
20 - 10 / 2
12 % 5
12 - 2 % 5
(12 - 2) % 5

// String 字串
"hello"
'world'
"hello" + "world"
'how\'s it going?'

parseInt('100') // 分析看看這是甚麼整飾
parseInt('29.37')
parseFloat('29.37') // 分析看看這是甚麼小數
parseInt('-31')

// Boolean 布林值
true    // 真, 成立
false   // 假, 不成立

3 > 2
19 < 3
43 >= 17
43 <= 43

// 把數變成字串再相加
'5' + 3
'abc' + 321

// For episode 4 ----------

var a = 1;    // var 用來宣告變數, block-scope: let, const,... ECMAScript 6 之後補充
              // = 是指定的意思
var b = "shiba";
var c;    // undefined, 未定義，不知道是什麼值
c = true;
var d = null;    // 沒有值

a = a + 1;
a += 1;
a++;    // a = a + 1 回傳舊a值
++a;    // a = a + 1 回傳新a值

b += 'world';

var e = 17;
e /= 5; // e = e / 5
var f = 17;
f %= 5; // f = f % 5

// For episode 5 ----------

var t0 = true, t1 = true;
var f0 = false, f1 = false;
t0
!t0 // ! 為"否定"的意思
f0
!f0

t0 && t1 // "而且"，當所有條件都成立時才成立
t0 && f0
f0 && f1
t0 || f0 // "或者"，只要有一個條件成立就成立
f0 || f1
t0 || t1
// && 真正的意義是當先行的運算元可以被轉成 true 時回傳之後的運算元
//    否則回傳先行運算元
// || 當先行運算元可以被轉成 true 拾回傳先行運算元
//    否則回傳後運算元

var m = 20;
m == 20
m != 20
m == '20' // 由於資料型態的轉換 此行比較結果為真
m != '20'

// 比較嚴格的比較
m === 20
m !== 20
m === '20' // 由於不轉換資料型態 此行比較結果為假
m !== '20'

// For episode 6 ----------

// 印出東西到 JavaScript console
console.log('Just wanted to say hello');

var day = 1;

// if 就是"如果"的意思
// else 就是"不然"
// else if 是"不然如果""

if (day === 1) {
  // 這是星期一
  console.log('This is Monday');
}

if (day === 1) {
  console.log('This is Monday');
} else {
  console.log('This is not Monday');
}

if (day === 1) {
  console.log('This is Monday');
} else if (day === 2) {
  console.log('This is Tuesday');
} else if (day === 3) {
  console.log('This is Wednesday');
} else {
  console.log('Good day anyway');
}

if (day === 6 || day === 7) {
  console.log('Happy weekend!!!');
} else {
  console.log('Not so happy');
}

// For episode 7 ----------

var i = 0;
while (i < 10) {
  i = i + 1;
  console.log('Number of laps = ' + i);
}

var i = 0;
while (i < 10) {
  i = i + 1;
  console.log('Number of laps = ' + i);
  if (i === 5) {
    break;
  }
}

var i = 0;
while (i < 10) {
  i = i + 1;
  if (i === 7) {
    continue;
  }
  console.log('Number of laps = ' + i);
}

// 未介紹 do...while，有興趣的朋友請參考
// https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/do...while

for (var i = 0; i < 10; i++) {
  console.log('Number of laps = ' + i);
}

// For episode 8 ----------

// 陣列(Array) 條狀(1維)容器

var a = [];
var c = [6, 4, 2, 9];
var b = [5, 17];

// 容器使用方法 ----
// 1. 取特定位置的值 利用索引(index)
//console.log(c[3]);

// 2. 長度
//console.log(b.length);

// 3. 從尾巴新增項目
b.push(13);

// 4. 從尾巴抽取項目
b.pop();

// 5. 從頭新增項目
b.unshift(7);

// 6. 從頭抽取項目
b.shift();

// 7. 接合
b.splice(1, 1, 13, 3);
b.splice(1, 1);
b.splice(1, 0, 6, 29);

//console.log('b');
//console.log(b);

// 8. 求特定值之索引
//console.log(c.indexOf(29));
//console.log(b.indexOf(29));

// 9. 逐個讀出
for (var i = 0, len = b.length; i < len; i++) {
    console.log(b[i]);
}
<commit_msg>Add examples for episode 9<commit_after>// For episode 3 ----------

// Number 數
0
1
1024
20.5
-17
-23.09

10 + 21
7 + 5.1
1 + 2 + 3
1 + 2 * 3
(1 + 2) * 3
20 - 10
20 - 10 / 2
12 % 5
12 - 2 % 5
(12 - 2) % 5

// String 字串
"hello"
'world'
"hello" + "world"
'how\'s it going?'

parseInt('100') // 分析看看這是甚麼整飾
parseInt('29.37')
parseFloat('29.37') // 分析看看這是甚麼小數
parseInt('-31')

// Boolean 布林值
true    // 真, 成立
false   // 假, 不成立

3 > 2
19 < 3
43 >= 17
43 <= 43

// 把數變成字串再相加
'5' + 3
'abc' + 321

// For episode 4 ----------

var a = 1;    // var 用來宣告變數, block-scope: let, const,... ECMAScript 6 之後補充
              // = 是指定的意思
var b = "shiba";
var c;    // undefined, 未定義，不知道是什麼值
c = true;
var d = null;    // 沒有值

a = a + 1;
a += 1;
a++;    // a = a + 1 回傳舊a值
++a;    // a = a + 1 回傳新a值

b += 'world';

var e = 17;
e /= 5; // e = e / 5
var f = 17;
f %= 5; // f = f % 5

// For episode 5 ----------

var t0 = true, t1 = true;
var f0 = false, f1 = false;
t0
!t0 // ! 為"否定"的意思
f0
!f0

t0 && t1 // "而且"，當所有條件都成立時才成立
t0 && f0
f0 && f1
t0 || f0 // "或者"，只要有一個條件成立就成立
f0 || f1
t0 || t1
// && 真正的意義是當先行的運算元可以被轉成 true 時回傳之後的運算元
//    否則回傳先行運算元
// || 當先行運算元可以被轉成 true 拾回傳先行運算元
//    否則回傳後運算元

var m = 20;
m == 20
m != 20
m == '20' // 由於資料型態的轉換 此行比較結果為真
m != '20'

// 比較嚴格的比較
m === 20
m !== 20
m === '20' // 由於不轉換資料型態 此行比較結果為假
m !== '20'

// For episode 6 ----------

// 印出東西到 JavaScript console
console.log('Just wanted to say hello');

var day = 1;

// if 就是"如果"的意思
// else 就是"不然"
// else if 是"不然如果""

if (day === 1) {
  // 這是星期一
  console.log('This is Monday');
}

if (day === 1) {
  console.log('This is Monday');
} else {
  console.log('This is not Monday');
}

if (day === 1) {
  console.log('This is Monday');
} else if (day === 2) {
  console.log('This is Tuesday');
} else if (day === 3) {
  console.log('This is Wednesday');
} else {
  console.log('Good day anyway');
}

if (day === 6 || day === 7) {
  console.log('Happy weekend!!!');
} else {
  console.log('Not so happy');
}

// For episode 7 ----------

var i = 0;
while (i < 10) {
  i = i + 1;
  console.log('Number of laps = ' + i);
}

var i = 0;
while (i < 10) {
  i = i + 1;
  console.log('Number of laps = ' + i);
  if (i === 5) {
    break;
  }
}

var i = 0;
while (i < 10) {
  i = i + 1;
  if (i === 7) {
    continue;
  }
  console.log('Number of laps = ' + i);
}

// 未介紹 do...while，有興趣的朋友請參考
// https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/do...while

for (var i = 0; i < 10; i++) {
  console.log('Number of laps = ' + i);
}

// For episode 8 ----------

// 陣列(Array) 條狀(1維)容器

var a = [];
var c = [6, 4, 2, 9];
var b = [5, 17];

// 容器使用方法 ----
// 1. 取特定位置的值 利用索引(index)
//console.log(c[3]);

// 2. 長度
//console.log(b.length);

// 3. 從尾巴新增項目
b.push(13);

// 4. 從尾巴抽取項目
b.pop();

// 5. 從頭新增項目
b.unshift(7);

// 6. 從頭抽取項目
b.shift();

// 7. 接合
b.splice(1, 1, 13, 3);
b.splice(1, 1);
b.splice(1, 0, 6, 29);

//console.log('b');
//console.log(b);

// 8. 求特定值之索引
//console.log(c.indexOf(29));
//console.log(b.indexOf(29));

// 9. 逐個讀出
for (var i = 0, len = b.length; i < len; i++) {
    console.log(b[i]);
}

// For episode 9 ----------
// 1.
// make(製造商), numberOfWheels(輪子數),
// displacement(排氣量), habitat(棲息地)

// 2.
// rank(號碼), suit(花色),
// color(顏色), bloodType(血型)

// {}, {屬性名:值, 屬性名:值, .....}
var a = {};
var myCar = {
    make: 'Nissan',
    numberOfWheels: 4,
    displacement: 3800
};
var hisCard = {
    rank: 5,
    suit: 'spade',
    color: 'black'
};

/*
console.log('a');
console.log(a);
console.log('myCar');
console.log(myCar);
console.log('hisCard');
console.log(hisCard);
*/

// 如何取得物件某個屬性的值
//console.log(myCar.make);

// 改值
/*
hisCard.rank = 10;
hisCard.suit = 'heart';
hisCard.color = 'red';

console.log(hisCard);
*/
// 動態綁上新屬性
myCar.year = 2013;
myCar.model = 'GTR';

//console.log(myCar);

// 參考(reference)，可以想成是"把手"
var a = 17;
var b = a;
a = 29;

//console.log(a);
//console.log(b);
var herCard = hisCard;
hisCard.rank = 12;
hisCard.suit = 'diamond';
hisCard.red = 'red';

console.log(hisCard);
console.log(herCard);
<|endoftext|>


<commit_before>import {
  TOGGLE_COMPOSER,
  TOGGLE_GENERATING_KEY,
  SHOW_COMPOSER_WITH_TYPE,
  SELECT_KEY,
  CLEAR_SELECTED_KEYS,
  SET_ACTIVE_ALIAS,
  SET_OUTPUT
} from '../constants/UIConstants'

import { OrderedMap } from 'immutable'

const initialState = OrderedMap({
  isShowingComposer: false,
  composerType: '',
  selectedKeychain: OrderedMap({}),
  activeAlias: '',
  output: '',
  isGeneratingKey: false,
})

const uiReducer = (state = initialState, action) => {
  switch (action.type) {
    case TOGGLE_COMPOSER:
      return state.set('isShowingComposer', !state.get('isShowingComposer'))
    case TOGGLE_GENERATING_KEY:
      return state.set('isGeneratingKey', !state.get('isGeneratingKey'))
    case SHOW_COMPOSER_WITH_TYPE:
      return state.set('composerType', action.data).set('isShowingComposer', true)
    case SELECT_KEY:
      if (state.hasIn(['selectedKeychain', action.id]) && state.getIn(['selectedKeychain', action.id]) === true) {
        return state.setIn(['selectedKeychain', action.id], false)
      } else {
        return state.setIn(['selectedKeychain', action.id], true)
      }

    case CLEAR_SELECTED_KEYS:
      return state.setIn(['selectedKeychain'], OrderedMap({}))

    case SET_ACTIVE_ALIAS:
      return state.set('activeAlias', action.activeAlias)

    case SET_OUTPUT:
      console.log('seeeeeeting output!!!>>>>>>', action.output)
      return state.set('output', action.output)

    default:
      return state
  }
}

export default uiReducer
<commit_msg>Add isCopied to uiReducer<commit_after>import {
  TOGGLE_COMPOSER,
  TOGGLE_GENERATING_KEY,
  TOGGLE_IS_COPIED,
  SHOW_COMPOSER_WITH_TYPE,
  SELECT_KEY,
  CLEAR_SELECTED_KEYS,
  SET_ACTIVE_ALIAS,
  SET_OUTPUT
} from '../constants/UIConstants'

import { OrderedMap } from 'immutable'

const initialState = OrderedMap({
  isShowingComposer: false,
  composerType: '',
  selectedKeychain: OrderedMap({}),
  activeAlias: '',
  output: '',
  isGeneratingKey: false,
  isCopied: false,
})

const uiReducer = (state = initialState, action) => {
  switch (action.type) {
    case TOGGLE_COMPOSER:
      return state.set('isShowingComposer', !state.get('isShowingComposer'))
    case TOGGLE_GENERATING_KEY:
      return state.set('isGeneratingKey', !state.get('isGeneratingKey'))
    case TOGGLE_IS_COPIED:
      return state.set('isCopied', !state.get('isCopied'))
    case SHOW_COMPOSER_WITH_TYPE:
      return state.set('composerType', action.data).set('isShowingComposer', true)
    case SELECT_KEY:
      if (state.hasIn(['selectedKeychain', action.id]) && state.getIn(['selectedKeychain', action.id]) === true) {
        return state.setIn(['selectedKeychain', action.id], false)
      } else {
        return state.setIn(['selectedKeychain', action.id], true)
      }

    case CLEAR_SELECTED_KEYS:
      return state.setIn(['selectedKeychain'], OrderedMap({}))

    case SET_ACTIVE_ALIAS:
      return state.set('activeAlias', action.activeAlias)

    case SET_OUTPUT:
      console.log('seeeeeeting output!!!>>>>>>', action.output)
      return state.set('output', action.output)

    default:
      return state
  }
}

export default uiReducer
<|endoftext|>


<commit_before>var _ = require("lodash");
var linter = require("eslint").linter;
var through = require("through2");

var eslintWarningToHuman = function (file, warning) {
	var loc = file.replace(/^.*\/src\//, '') + ':' + warning.line + ',' + warning.column;
	return 'eslint: ' + warning.message + ' @ ' + loc;
};

var defaults = {
	ecmaFeatures: {
		//good parts
		blockBindings: true,
		destructuring: true,
		restParams: true,
		objectLiteralShorthandMethods: true,
		objectLiteralShorthandProperties: true,

		//gray area :)
		jsx: true,

		//bad parts (somewhat according to Douglas Crockford)
		arrowFunctions: false,//these can be good if there were more rules to specify a jslint style arrow function
		binaryLiterals: false,
		classes: false,
		defaultParams: false,
		forOf: false,
		generators: false,
		modules: false,//these are good if you only use a subset of its features. But we're using CommonJS modules so we don't need to turn these on now
		objectLiteralComputedProperties: false,
		objectLiteralDuplicateProperties: false,
		octalLiterals: false,
		regexUFlag: false,
		regexYFlag: false,
		spread: false,
		superInFunctions: false,
		templateStrings: false,
		unicodeCodePointEscapes: false,
		globalReturn: false
	},
	globals: {
		"console": true,
		"setTimeout": true,
		"setInterval": true,
		"clearTimeout": true,
		"clearInterval": true,

		//node (via browserify)
		"module": true,
		"process": true,
		"require": true,

		//browsers
		"window": true,
		"document": true
	},
	rules: {
		//language hazards
		"semi": 2,
		"radix": 2,
		"strict": [2, "never"],// b/c babelify takes care of this for us
		"no-eval": 2,
		"no-void": 2,//babelify will convert undefined into void 0; Other than that void shouldn't be used
		"no-with": 2,
		"no-undef": 2,
		"no-octal": 2,
		"no-caller": 2,
		"use-isnan": 2,
		"no-labels": 2,//too much like goto
		"no-multi-str": 2,
		"no-implied-eval": 2,
		"no-new-wrappers": 2,
		"no-self-compare": 2,
		"no-sparse-arrays": 2,
		"no-native-reassign": 2,
		"no-use-before-define": 2,

		//bad ideas
		"no-alert": 2,//make a bootstrap modal or use console.log
		"no-bitwise": 2,//if(a & b){... but what they really ment was if(a && b){...
		"no-plusplus": 2,//var i = 1, b = i++; is b 2 or 1? how about ++i? Just use i += 1;
		"no-script-url": 2,//just use react onClick handlers
		"no-cond-assign": 2,//if(a = b){... but what they really ment was if(a === b){...
		"no-new-require": 2,
		"no-unused-vars": [2, {
			vars: "all",
			args: "none"//unused arguments can provide good documentation about what is available
		}],

		//style consistency
		"wrap-iife": [2, "outside"],
		"consistent-this": [2, "self"],
		"no-trailing-spaces": 2
	}
};

module.exports = function(config_overrides){
	var eslint_config = _.defaultsDeep(defaults, config_overrides || {});
	return function(file){
		if (!/\.js$/i.test(file)){
			return through();
		}
		var js_code = '';
		return through(function (data, enc, done) {
			js_code += data;
			this.push(data);
			done();
		}, function(done){
			var warnings = linter.verify(js_code, eslint_config, file);

			if(_.size(warnings) === 0){
				return done();
			}
			done(eslintWarningToHuman(file, _.first(warnings)));
		});
	};
};
<commit_msg>fixing how _.defaultsDeep is used<commit_after>var _ = require("lodash");
var linter = require("eslint").linter;
var through = require("through2");

var eslintWarningToHuman = function (file, warning) {
	var loc = file.replace(/^.*\/src\//, '') + ':' + warning.line + ',' + warning.column;
	return 'eslint: ' + warning.message + ' @ ' + loc;
};

var defaults = {
	ecmaFeatures: {
		//good parts
		blockBindings: true,
		destructuring: true,
		restParams: true,
		objectLiteralShorthandMethods: true,
		objectLiteralShorthandProperties: true,

		//gray area :)
		jsx: true,

		//bad parts (somewhat according to Douglas Crockford)
		arrowFunctions: false,//these can be good if there were more rules to specify a jslint style arrow function
		binaryLiterals: false,
		classes: false,
		defaultParams: false,
		forOf: false,
		generators: false,
		modules: false,//these are good if you only use a subset of its features. But we're using CommonJS modules so we don't need to turn these on now
		objectLiteralComputedProperties: false,
		objectLiteralDuplicateProperties: false,
		octalLiterals: false,
		regexUFlag: false,
		regexYFlag: false,
		spread: false,
		superInFunctions: false,
		templateStrings: false,
		unicodeCodePointEscapes: false,
		globalReturn: false
	},
	globals: {
		"console": true,
		"setTimeout": true,
		"setInterval": true,
		"clearTimeout": true,
		"clearInterval": true,

		//node (via browserify)
		"module": true,
		"process": true,
		"require": true,

		//browsers
		"window": true,
		"document": true
	},
	rules: {
		//language hazards
		"semi": 2,
		"radix": 2,
		"strict": [2, "never"],// b/c babelify takes care of this for us
		"no-eval": 2,
		"no-void": 2,//babelify will convert undefined into void 0; Other than that void shouldn't be used
		"no-with": 2,
		"no-undef": 2,
		"no-octal": 2,
		"no-caller": 2,
		"use-isnan": 2,
		"no-labels": 2,//too much like goto
		"no-multi-str": 2,
		"no-implied-eval": 2,
		"no-new-wrappers": 2,
		"no-self-compare": 2,
		"no-sparse-arrays": 2,
		"no-native-reassign": 2,
		"no-use-before-define": 2,

		//bad ideas
		"no-alert": 2,//make a bootstrap modal or use console.log
		"no-bitwise": 2,//if(a & b){... but what they really ment was if(a && b){...
		"no-plusplus": 2,//var i = 1, b = i++; is b 2 or 1? how about ++i? Just use i += 1;
		"no-script-url": 2,//just use react onClick handlers
		"no-cond-assign": 2,//if(a = b){... but what they really ment was if(a === b){...
		"no-new-require": 2,
		"no-unused-vars": [2, {
			vars: "all",
			args: "none"//unused arguments can provide good documentation about what is available
		}],

		//style consistency
		"wrap-iife": [2, "outside"],
		"consistent-this": [2, "self"],
		"no-trailing-spaces": 2
	}
};

module.exports = function(config_overrides){
	var eslint_config = _.defaultsDeep({}, config_overrides || {}, defaults);//yep defaultsDeep mutates arg 1, and first one to define a property wins
	return function(file){
		if (!/\.js$/i.test(file)){
			return through();
		}
		var js_code = '';
		return through(function (data, enc, done) {
			js_code += data;
			this.push(data);
			done();
		}, function(done){
			var warnings = linter.verify(js_code, eslint_config, file);

			if(_.size(warnings) === 0){
				return done();
			}
			done(eslintWarningToHuman(file, _.first(warnings)));
		});
	};
};
<|endoftext|>


<commit_before>module.exports = {
  status: 'wip',
  collated: true,
  context: {
    arrowLeftActive: false,
    arrowRightActive: true,
    pages: [
      {
        pageNo: '1',
        active: true
      },
      {
        pageNo: 2,
        active: false
      },
      {
        pageNo: 3,
        active: false
      },
      {
        pageNo: 4,
        active: false
      },
      {
        pageNo: 5,
        active: false
      }
    ]
  },
  variants: [
    {
      name: 'both arrows',
      context: {
        arrowLeftActive: true,
        arrowRightActive: true,
        pages: [
          {
            pageNo: 1,
            active: false
          },
          {
            pageNo: 2,
            active: false
          },
          {
            pageNo: 3,
            active: true
          },
          {
            pageNo: 4,
            active: false
          },
          {
            pageNo: 5,
            active: false
          }
        ]
      }
    },
    {
      name: 'arrow left',
      context: {
        arrowLeftActive: true,
        arrowRightActive: false,
        pages: [
          {
            pageNo: 1,
            active: false
          },
          {
            pageNo: 2,
            active: false
          },
          {
            pageNo: 3,
            active: false
          },
          {
            pageNo: 4,
            active: false
          },
          {
            pageNo: 5,
            active: true
          }
        ]
      }
    },
    {
      name: 'more sites',
      context: {
        arrowLeftActive: true,
        arrowRightActive: true,
        pages: [
          {
            pageNo: 6,
            active: true
          },
          {
            pageNo: 7,
            active: false
          },
          {
            pageNo: '...',
            active: false
          },
          {
            pageNo: 17,
            active: false
          },
          {
            pageNo: 18,
            active: false
          }
        ]
      }
    },
    {
      name: 'arrow right',
      context: {
        arrowLeftActive: true,
        arrowRightActive: true,
        pages: [
          {
            pageNo: 13,
            active: true
          },
          {
            pageNo: 14,
            active: false
          },
          {
            pageNo: 15,
            active: false
          },
          {
            pageNo: 16,
            active: false
          },
          {
            pageNo: 17,
            active: false
          }
        ]
      }
    }
  ]
};
<commit_msg>#35795 Pager: Defining aria-labels in config.js<commit_after>module.exports = {
  status: 'wip',
  collated: true,
  context: {
    arrowLeftActive: false,
    arrowRightActive: true,
    ariaLabelLeft: 'Link to previous page, disabled',
    ariaLabelRight: 'Link to next page',
    pages: [
      {
        pageNo: '1',
        active: true
      },
      {
        pageNo: 2,
        active: false,
        ariaLabel: 'Link to page 2'
      },
      {
        pageNo: 3,
        active: false,
        ariaLabel: 'Link to page 3'
      },
      {
        pageNo: 4,
        active: false,
        ariaLabel: 'Link to page 4'
      },
      {
        pageNo: 5,
        active: false,
        ariaLabel: 'Link to page 5'
      }
    ]
  },
  variants: [
    {
      name: 'both arrows',
      context: {
        arrowLeftActive: true,
        arrowRightActive: true,
        ariaLabelLeft: 'Link to previous page',
        ariaLabelRight: 'Link to next page',
        pages: [
          {
            pageNo: 1,
            active: false,
            ariaLabel: 'Link to page 1'
          },
          {
            pageNo: 2,
            active: false,
            ariaLabel: 'Link to page 2'
          },
          {
            pageNo: 3,
            active: true,
            ariaLabel: 'Link to page 3'
          },
          {
            pageNo: 4,
            active: false,
            ariaLabel: 'Link to page 4'
          },
          {
            pageNo: 5,
            active: false,
            ariaLabel: 'Link to page 5'
          }
        ]
      }
    },
    {
      name: 'arrow left',
      context: {
        arrowLeftActive: true,
        arrowRightActive: false,
        ariaLabelLeft: 'Link to previous page',
        ariaLabelRight: 'Link to next page, disabled',
        pages: [
          {
            pageNo: 1,
            active: false,
            ariaLabel: 'Link to page 1'
          },
          {
            pageNo: 2,
            active: false,
            ariaLabel: 'Link to page 2'
          },
          {
            pageNo: 3,
            active: false,
            ariaLabel: 'Link to page 3'
          },
          {
            pageNo: 4,
            active: false,
            ariaLabel: 'Link to page 4'
          },
          {
            pageNo: 5,
            active: true
          }
        ]
      }
    },
    {
      name: 'more sites',
      context: {
        arrowLeftActive: true,
        arrowRightActive: true,
        ariaLabelLeft: 'Link to previous page',
        ariaLabelRight: 'Link to next page',
        pages: [
          {
            pageNo: 6,
            active: true
          },
          {
            pageNo: 7,
            active: false,
            ariaLabel: 'Link to page 7'
          },
          {
            pageNo: '...',
            active: false
          },
          {
            pageNo: 17,
            active: false,
            ariaLabel: 'Link to page 17'
          },
          {
            pageNo: 18,
            active: false,
            ariaLabel: 'Link to page 18'
          }
        ]
      }
    },
    {
      name: 'arrow right',
      context: {
        arrowLeftActive: true,
        arrowRightActive: true,
        ariaLabelLeft: 'Link to previous page',
        ariaLabelRight: 'Link to next page',
        pages: [
          {
            pageNo: 13,
            active: true
          },
          {
            pageNo: 14,
            active: false,
            ariaLabel: 'Link to page 14'
          },
          {
            pageNo: 15,
            active: false,
            ariaLabel: 'Link to page 15'
          },
          {
            pageNo: 16,
            active: false,
            ariaLabel: 'Link to page 16'
          },
          {
            pageNo: 17,
            active: false,
            ariaLabel: 'Link to page 17'
          }
        ]
      }
    }
  ]
};
<|endoftext|>