<commit_before>/*jslint node: true*/

var exports;
(function () {
  'use strict';
  var deferred = require('deferred'),
    promisify = deferred.promisify,
    fs = require('fs'),
    path = require('path'),
    http = require('http'),
    iconv = require('iconv-lite'),
    exists = promisify(fs.exists),
    readFile = promisify(fs.readFile),
    bone,
    log,
    modPac;

  function shExpMatch(url, pattern) {
    url = url || '';
    var pChar,
      isAggressive = false,
      pIndex,
      urlIndex = 0,
      patternLength = pattern.length,
      urlLength = url.length;
    for (pIndex = 0; pIndex < patternLength; pIndex += 1) {
      pChar = pattern[pIndex];
      switch (pChar) {
      case "?":
        isAggressive = false;
        urlIndex += 1;
        break;
      case "*":
        if (pIndex === patternLength - 1) {
          urlIndex = urlLength;
        } else {
          isAggressive = true;
        }
        break;
      default:
        if (isAggressive) {
          urlIndex = url.indexOf(pChar, urlIndex);
          if (urlIndex < 0) {
            return false;
          }
          isAggressive = false;
        } else {
          if (urlIndex >= urlLength || url[urlIndex] !== pChar) {
            return false;
          }
        }
        urlIndex += 1;
      }
    }
    return urlIndex === urlLength;
  }

  modPac = {
    pacReady : deferred(),

    strBrowserPac : '',

    findProxyFromPac : function () {
      return 'DIRECT';
    },

    findProxyForURL : function (url, host) {
      var i, j, len, rule, matched,
        rules = this.conf.proxyRules;

      for (i in rules) {
        if (rules.hasOwnProperty(i)) {
          rule = rules[i];
          len = rule.length;
          for (j = 0; j < len; j++) {
            matched = rule[j].indexOf('/') > -1 ?
                shExpMatch(url, rule[j]) :
                shExpMatch(host, rule[j]);
            if (matched) {
              return i;
            }
          }
        }
      }

      return this.findProxyFromPac(url, host);
    },

    getBrowserPac : function () {
      var browserPacPath = this.browserPacPath,
        that = this,
        def = deferred();

      if (this.strBrowserPac) {
        def.resolve(this.strBrowserPac);
      } else {
        exists(browserPacPath)(function (exists) {
          if (exists) {
            readFile(browserPacPath, 'utf8')(function (content) {
              that.strBrowserPac = content;
              def.resolve(content);
            });
          } else {
            that.pacReady.promise()(function () {
              def.resolve(that.strBrowserPac);
            });
          }
        });
      }

      return def.promise();
    },

    makePac : function () {
      var that = this,
        req,
        pacURI = this.originalPacURI,
        enc = this.conf.pacEncoding,
        cachedPacPath = this.cachedPacPath,

        writer = bone.fs.createWriteStream(cachedPacPath, {
          flags : 'w',
          encoding : enc,
          focus: true
        });

      writer.on('finish', function () {
        that.updateProxyPolicy();
      });

      if (pacURI.indexOf('http://') === 0) {
        req = http.get(pacURI, function (res) {
          res.pipe(writer);
        });
        req.on('socket', function (socket) {
          socket.setTimeout(8000);
          socket.on('timeout', function() {
            req.abort();
          });
        });
        req.on('error', function () {
          log('Error: Fail to load pac: ' + pacURI);
          writer.end();
        });
      } else {
        exists(pacURI)(function (fileExist) {
          if (fileExist) {
            fs.createReadStream(pacURI).pipe(writer);
          } else {
            if (pacURI) {
              log('Error: Fail to load pac: ' + pacURI);
            }
            writer.end();
          }
        });
      }
    },

    updateProxyPolicy : function () {
      var enc = this.conf.pacEncoding,
        browserPacTmpl = this.browserPacTmpl,
        proxyPacTmpl = this.proxyPacTmpl,
        policyPath = this.proxyPolicyPath,
        browserPacPath = this.browserPacPath,
        that = this,
        defProxyPac = deferred(),
        defBrowserPac = deferred(),
        filterFn = this.conf.pacFilter;

      if(filterFn == 'auto') {
        filterFn = this.makeDefaultFilter();
      }

      readFile(this.cachedPacPath).done(function (content) {
        content = iconv.decode(content, enc).trim();
        if (content === '') {
          content = 'var FindProxyForURL;';
        }
        readFile(proxyPacTmpl, 'utf8').done(function (tmpl) {
          var writer;
          tmpl = tmpl.replace('{$realPac}', content);

          writer = fs.createWriteStream(policyPath, {
            flags : 'w',
            encoding : enc
          });

          writer.on('finish', function () {
            that.findProxyFromPac = require(policyPath).findProxyFromPac;
            defProxyPac.resolve();
          });
          writer.end(tmpl);
        });

        readFile(browserPacTmpl, 'utf8').done(function (tmpl) {
          var writer,
            strFilter = filterFn.toString().
              replace('function (url, host)', 'function filter(url, host)');

          tmpl = tmpl.
            replace('{$realPac}', content).
            replace('{$filterFn}', strFilter).
            replace('{$proxyRules}', JSON.stringify(that.conf.proxyRules)).
            replace('{$proxyIp}', that.conf.ip).
            replace('{$proxyPort}', that.conf.port);

          that.strBrowserPac = tmpl;
          defBrowserPac.resolve();

          writer = fs.createWriteStream(browserPacPath, {
            flags : 'w',
            encoding : enc
          });

          writer.end(tmpl);
        });
      });

      deferred(defProxyPac.promise(), defBrowserPac.promise())(function () {
        that.pacReady.resolve();
        log('Info: Proxy started at : ' + that.conf.ip + ':' + that.conf.port +
            ', set your browser pac to: http://' + that.conf.ip +
            ':' + that.conf.port + '/pac');
      });
    },

    defaultConf : {
      proxyRules : {
      },
      replaceRules : {},
      pacFilter : function (url, host) {
        return true;
      },
      ip : '127.0.0.1',
      port : '8080',
      pac : '',
      pacEncoding : 'utf8'
    },

    makeDefaultFilter : function() {
      var conf = this.conf;
      var condition = [];
      if(Array.isArray(conf.replaceRules)) {
        for(var i in conf.replaceRules) {
          if(conf.replaceRules.hasOwnProperty(i)) {
            if(conf.replaceRules[i][0] instanceof RegExp) {
              condition.push(conf.replaceRules[i][0].toString()+'.test(url)');
            }
          }
        }

        if(condition.length) {
          var fn = ['function (url, host) {'];
          fn.push('if(');
          fn.push(condition.join('||'));
          fn.push('){return true}');
          fn.push('}');
          return fn.join('');
        }
      }
      return this.defaultConf.pacFilter;
    },

    init : function (macFiddler) {
      bone = macFiddler.bone;

      this.originalPacURI = this.conf.pac;
      this.cachedPacPath = path.join(__dirname, '../../', '/runtime/origin.pac');
      this.browserPacPath = path.join(__dirname, '../../', '/runtime/browser.pac');
      this.proxyPolicyPath = path.join(__dirname, '../../', '/runtime/policy.js');
      this.proxyPacTmpl = path.join(__dirname, '../../', '/lib/proxyPacTemplate.js');
      this.browserPacTmpl = path.join(__dirname, '../../', '/lib/browserPacTemplate.js');

      log = macFiddler.log;
      if(this.originalPacURI) {
        this.makePac();
        console.log('pac module enabled. visit http://0.0.0.0:'+this.conf.port+'/pac');
      }
    }
  };

  if (exports === undefined) {
    exports = {};
  }
  exports.pac = modPac;

}());

<commit_msg>modify the fs.exists call<commit_after>/*jslint node: true*/

var exports;
(function () {
  'use strict';
  var deferred = require('deferred'),
    promisify = deferred.promisify,
    fs = require('fs'),
    path = require('path'),
    http = require('http'),
    iconv = require('iconv-lite'),
    exists = promisify(fs.exists),
    readFile = promisify(fs.readFile),
    bone,
    log,
    modPac;

  function shExpMatch(url, pattern) {
    url = url || '';
    var pChar,
      isAggressive = false,
      pIndex,
      urlIndex = 0,
      patternLength = pattern.length,
      urlLength = url.length;
    for (pIndex = 0; pIndex < patternLength; pIndex += 1) {
      pChar = pattern[pIndex];
      switch (pChar) {
      case "?":
        isAggressive = false;
        urlIndex += 1;
        break;
      case "*":
        if (pIndex === patternLength - 1) {
          urlIndex = urlLength;
        } else {
          isAggressive = true;
        }
        break;
      default:
        if (isAggressive) {
          urlIndex = url.indexOf(pChar, urlIndex);
          if (urlIndex < 0) {
            return false;
          }
          isAggressive = false;
        } else {
          if (urlIndex >= urlLength || url[urlIndex] !== pChar) {
            return false;
          }
        }
        urlIndex += 1;
      }
    }
    return urlIndex === urlLength;
  }

  modPac = {
    pacReady : deferred(),

    strBrowserPac : '',

    findProxyFromPac : function () {
      return 'DIRECT';
    },

    findProxyForURL : function (url, host) {
      var i, j, len, rule, matched,
        rules = this.conf.proxyRules;

      for (i in rules) {
        if (rules.hasOwnProperty(i)) {
          rule = rules[i];
          len = rule.length;
          for (j = 0; j < len; j++) {
            matched = rule[j].indexOf('/') > -1 ?
                shExpMatch(url, rule[j]) :
                shExpMatch(host, rule[j]);
            if (matched) {
              return i;
            }
          }
        }
      }

      return this.findProxyFromPac(url, host);
    },

    getBrowserPac : function () {
      var browserPacPath = this.browserPacPath,
        that = this,
        def = deferred();

      if (this.strBrowserPac) {
        def.resolve(this.strBrowserPac);
      } else {
        // deferred 有bug，暂时先这么处理
        fs.exists(browserPacPath, function(err, exists) {
          if(err) {
            log('Error: fail to execute exists: ' + browserPacPath);
          } else {
            if (exists) {
              readFile(browserPacPath, 'utf8')(function (content) {
                that.strBrowserPac = content;
                def.resolve(content);
              });
            } else {
              that.pacReady.promise()(function () {
                def.resolve(that.strBrowserPac);
              });
            }
          }
        });
        /*exists(browserPacPath)(function (exists) {
          if (exists) {
            readFile(browserPacPath, 'utf8')(function (content) {
              that.strBrowserPac = content;
              def.resolve(content);
            });
          } else {
            that.pacReady.promise()(function () {
              def.resolve(that.strBrowserPac);
            });
          }
        });*/
      }

      return def.promise();
    },

    makePac : function () {
      var that = this,
        req,
        pacURI = this.originalPacURI || '',
        enc = this.conf.pacEncoding,
        cachedPacPath = this.cachedPacPath,

        writer = bone.fs.createWriteStream(cachedPacPath, {
          flags : 'w',
          encoding : enc,
          focus: true
        });

      writer.on('finish', function () {
        that.updateProxyPolicy();
      });

      if (pacURI.indexOf('http://') === 0) {
        req = http.get(pacURI, function (res) {
          res.pipe(writer);
        });
        req.on('socket', function (socket) {
          socket.setTimeout(8000);
          socket.on('timeout', function() {
            req.abort();
          });
        });
        req.on('error', function () {
          log('Error: Fail to load pac: ' + pacURI);
          writer.end();
        });
      } else {
        // deferred 有bug，暂时先这么处理
        fs.exists(pacURI, function(err, fileExist) {
          if(err) {
            log('Error: Fail to execute exists: ' + pacURI);
          } else {
            if (fileExist) {
              fs.createReadStream(pacURI).pipe(writer);
            } else {
              if (pacURI) {
                log('Error: Fail to load pac: ' + pacURI);
              }
              writer.end();
            }
          }
        });
        /*exists(pacURI)(function (fileExist) {
          if (fileExist) {
            fs.createReadStream(pacURI).pipe(writer);
          } else {
            if (pacURI) {
              log('Error: Fail to load pac: ' + pacURI);
            }
            writer.end();
          }
        });*/
      }
    },

    updateProxyPolicy : function () {
      var enc = this.conf.pacEncoding,
        browserPacTmpl = this.browserPacTmpl,
        proxyPacTmpl = this.proxyPacTmpl,
        policyPath = this.proxyPolicyPath,
        browserPacPath = this.browserPacPath,
        that = this,
        defProxyPac = deferred(),
        defBrowserPac = deferred(),
        filterFn = this.conf.pacFilter;

      if(filterFn == 'auto') {
        filterFn = this.makeDefaultFilter();
      }

      readFile(this.cachedPacPath).done(function (content) {
        content = iconv.decode(content, enc).trim();
        if (content === '') {
          content = 'var FindProxyForURL;';
        }
        readFile(proxyPacTmpl, 'utf8').done(function (tmpl) {
          var writer;
          tmpl = tmpl.replace('{$realPac}', content);

          writer = fs.createWriteStream(policyPath, {
            flags : 'w',
            encoding : enc
          });

          writer.on('finish', function () {
            that.findProxyFromPac = require(policyPath).findProxyFromPac;
            defProxyPac.resolve();
          });
          writer.end(tmpl);
        });

        readFile(browserPacTmpl, 'utf8').done(function (tmpl) {
          var writer,
            strFilter = filterFn.toString().
              replace('function (url, host)', 'function filter(url, host)');

          tmpl = tmpl.
            replace('{$realPac}', content).
            replace('{$filterFn}', strFilter).
            replace('{$proxyRules}', JSON.stringify(that.conf.proxyRules)).
            replace('{$proxyIp}', that.conf.ip).
            replace('{$proxyPort}', that.conf.port);

          that.strBrowserPac = tmpl;
          defBrowserPac.resolve();

          writer = fs.createWriteStream(browserPacPath, {
            flags : 'w',
            encoding : enc
          });

          writer.end(tmpl);
        });
      });

      deferred(defProxyPac.promise(), defBrowserPac.promise())(function () {
        that.pacReady.resolve();
        log('Info: Proxy started at : ' + that.conf.ip + ':' + that.conf.port +
            ', set your browser pac to: http://' + that.conf.ip +
            ':' + that.conf.port + '/pac');
      });
    },

    defaultConf : {
      proxyRules : {
      },
      replaceRules : {},
      pacFilter : function (url, host) {
        return true;
      },
      ip : '127.0.0.1',
      port : '8080',
      pac : '',
      pacEncoding : 'utf8'
    },

    makeDefaultFilter : function() {
      var conf = this.conf;
      var condition = [];
      if(Array.isArray(conf.replaceRules)) {
        for(var i in conf.replaceRules) {
          if(conf.replaceRules.hasOwnProperty(i)) {
            if(conf.replaceRules[i][0] instanceof RegExp) {
              condition.push(conf.replaceRules[i][0].toString()+'.test(url)');
            }
          }
        }

        if(condition.length) {
          var fn = ['function (url, host) {'];
          fn.push('if(');
          fn.push(condition.join('||'));
          fn.push('){return true}');
          fn.push('}');
          return fn.join('');
        }
      }
      return this.defaultConf.pacFilter;
    },

    init : function (macFiddler) {
      bone = macFiddler.bone;

      this.originalPacURI = this.conf.pac;
      this.cachedPacPath = path.join(__dirname, '../../', '/runtime/origin.pac');
      this.browserPacPath = path.join(__dirname, '../../', '/runtime/browser.pac');
      this.proxyPolicyPath = path.join(__dirname, '../../', '/runtime/policy.js');
      this.proxyPacTmpl = path.join(__dirname, '../../', '/lib/proxyPacTemplate.js');
      this.browserPacTmpl = path.join(__dirname, '../../', '/lib/browserPacTemplate.js');

      log = macFiddler.log;
      if(this.originalPacURI) {
        this.makePac();
        console.log('pac module enabled. visit http://0.0.0.0:'+this.conf.port+'/pac');
      }
    }
  };

  if (exports === undefined) {
    exports = {};
  }
  exports.pac = modPac;

}());

<|endoftext|>


<commit_before>var Repository = (function (Object) {
    "use strict";

    function Repository() {
        this.dict = {};
    }

    Repository.prototype.add = function (item, fn, dependencies) {
        this.dict[item.id] = {
            fn: fn,
            dependencies: dependencies
        };
    };

    Repository.prototype.has = function (item) {
        return this.dict[item.id] !== undefined;
    };

    Repository.prototype.remove = function (item) {
        delete this.dict[item.id];
    };

    Repository.prototype.call = function (arg1, arg2) {
        var self = this;
        var alreadyCalledMap = {};

        Object.keys(this.dict).forEach(function (key) {
            var wrapper = this.dict[key];
            callItem(key, wrapper.fn, wrapper.dependencies);
        }, this);

        function callItem(id, fn, dependencies) {
            alreadyCalledMap[id] = true;
            if (dependencies) {
                dependencies.forEach(function (dependency) {
                    var dependencyNotAlreadyCalled = dependency && !alreadyCalledMap[dependency.id];
                    if (dependencyNotAlreadyCalled) {
                        var wrapper = self.dict[dependency.id];
                        callItem(dependency.id, wrapper.fn, wrapper.dependencies);
                    }
                });
            }

            fn(arg1, arg2);
        }
    };

    return Repository;
})(Object);<commit_msg>fixes missing dependency bug refs #60 #core (cherry picked from commit 25891e2)<commit_after>var Repository = (function (Object) {
    "use strict";

    function Repository() {
        this.dict = {};
    }

    Repository.prototype.add = function (item, fn, dependencies) {
        this.dict[item.id] = {
            fn: fn,
            dependencies: dependencies
        };
    };

    Repository.prototype.has = function (item) {
        return this.dict[item.id] !== undefined;
    };

    Repository.prototype.remove = function (item) {
        delete this.dict[item.id];
    };

    Repository.prototype.call = function (arg1, arg2) {
        var self = this;
        var alreadyCalledMap = {};

        Object.keys(this.dict).forEach(function (key) {
            var wrapper = this.dict[key];
            callItem(key, wrapper.fn, wrapper.dependencies);
        }, this);

        function callItem(id, fn, dependencies) {
            alreadyCalledMap[id] = true;
            if (dependencies) {
                dependencies.forEach(function (dependency) {
                    var dependencyNotAlreadyCalled = dependency && !alreadyCalledMap[dependency.id];
                    if (dependencyNotAlreadyCalled) {
                        var wrapper = self.dict[dependency.id];
                        if (wrapper)
                            callItem(dependency.id, wrapper.fn, wrapper.dependencies);
                    }
                });
            }

            fn(arg1, arg2);
        }
    };

    return Repository;
})(Object);<|endoftext|>


<commit_before>angular.module('codebrag.commits')

    .factory('filesWithCommentsService', function (commitFilesService, Comments) {

        function loadAll(commitId, generalComments) {
            return commitFilesService.loadFilesForCommit(commitId).$then(function (files) {
                Comments.query({id: commitId}, function (comments) {
                    _.forEach(comments.comments, function(comment) {generalComments.push(comment)});
                    putInlineCommentsInFiles(files, comments.inlineComments);
                });
                return files.data;
            });
        }

        function putInlineCommentsInFiles(files, allComments) {

            _.forEach(files.data, _putCommentsInFile);

            function _putCommentsInFile(file) {
                var inlineCommentsForFile = _.find(allComments, _isCommentListForFile);
                file.commentCount = 0;

                _.forEach(file.lines, _putCommentsInLine);

                function _putCommentsInLine(line, index) {
                    line.commentCount = 0;
                    line.comments = [];
                    if (inlineCommentsForFile != undefined) {
                        var commentsForLine = _.find(inlineCommentsForFile.lineComments, function (commentList) {
                            return commentList.lineNumber == index;
                        });
                        if (commentsForLine != undefined) {
                            line.commentCount = commentsForLine.comments.length;
                            file.commentCount += line.commentCount;
                            line.comments = commentsForLine.comments;
                        }
                    }
                    line.hasComments = line.commentCount > 0;
                    line.showCommentForm = false;
                }

                function _isCommentListForFile(commentList) {
                    return commentList.fileName == file.filename;
                }

            }
        }

        return {
            loadAll: loadAll,
            putInlineCommentsInFiles: putInlineCommentsInFiles
        }

    });<commit_msg>Fix checks if variable is undefined<commit_after>angular.module('codebrag.commits')

    .factory('filesWithCommentsService', function (commitFilesService, Comments) {

        function loadAll(commitId, generalComments) {
            return commitFilesService.loadFilesForCommit(commitId).$then(function (files) {
                Comments.query({id: commitId}, function (comments) {
                    _.forEach(comments.comments, function(comment) {generalComments.push(comment)});
                    putInlineCommentsInFiles(files, comments.inlineComments);
                });
                return files.data;
            });
        }

        function putInlineCommentsInFiles(files, allComments) {

            _.forEach(files.data, _putCommentsInFile);

            function _putCommentsInFile(file) {
                var inlineCommentsForFile = _.find(allComments, _isCommentListForFile);
                file.commentCount = 0;

                _.forEach(file.lines, _putCommentsInLine);

                function _putCommentsInLine(line, index) {
                    line.commentCount = 0;
                    line.comments = [];
                    if (!_.isUndefined(inlineCommentsForFile)) {
                        var commentsForLine = _.find(inlineCommentsForFile.lineComments, function (commentList) {
                            return commentList.lineNumber == index;
                        });
                        if (!_.isUndefined(commentsForLine)) {
                            line.commentCount = commentsForLine.comments.length;
                            file.commentCount += line.commentCount;
                            line.comments = commentsForLine.comments;
                        }
                    }
                    line.hasComments = line.commentCount > 0;
                    line.showCommentForm = false;
                }

                function _isCommentListForFile(commentList) {
                    return commentList.fileName == file.filename;
                }

            }
        }

        return {
            loadAll: loadAll,
            putInlineCommentsInFiles: putInlineCommentsInFiles
        }

    });<|endoftext|>


<commit_before>var langs = require( 'languages' );
var countries = require( 'i18n-iso-countries' );
var states = require( 'us-states' );
var airports = require( 'airport-lookup' );
var currencies = require( 'currency-codes' );

module.exports = {
	commands: {
		airport: {
			help: 'Looks up an IATA airport code',
			usage: [ 'code' ],
			command: function ( bot, msg ) {
				var data = airports( msg.args.code );
				if ( data ) {
					var datum = [ data.size, countries.getName( data.iso, 'en' ), data.type ];
					return data.iata + ': ' + data.name + ' (' + datum.join( ' ' ) + ')';
				}
				return 'Unable to find an airport with IATA code ' + msg.args.code;
			}
		},
		currency: {
			help: 'Looks up an ISO 4217 currency code',
			usage: [ 'currency' ],
			command: function ( bot, msg ) {
				var code = currencies.code( msg.args.currency );
				if ( code ) {
					if ( code.countries ) {
						return code.code + ' → ' + code.currency + ' (' + code.countries.join( ', ' ) + ')';
					}
					return code.code + ' → ' + code.currency;
				}
				return 'ISO code not found.';
			}
		},
		lang: {
			help: 'Looks up an ISO 369-1 language code',
			aliases: [ 'language' ],
			usage: [ 'lang' ],
			command: function ( bot, msg ) {
				msg.args.lang = msg.args.lang.toLowerCase();
				if ( langs.isValid( msg.args.lang ) ) {
					var info = langs.getLanguageInfo( msg.args.lang );
					return msg.args.lang + ' → ' + info.name + ' · ' + info.nativeName;
				}
				return 'Invalid ISO 639-1 code.';
			}
		},
		country: {
			help: 'Looks up an ISO 3166 alpha2 country code',
			usage: [ 'country' ],
			command: function ( bot, msg ) {
				var code = msg.args.country.toUpperCase();
				if ( countries.getName( code, 'en' ) ) {
					return code + ' → ' + countries.getName( code, 'en' ) + ' · ' + countries.getName( code, 'de' );
				}
				return 'ISO 3166-alpha2 code not found.';
			}
		},
		state: {
			help: 'Looks up the postal abbbreviation for a US state',
			usage: [ 'code' ],
			command: function ( bot, msg ) {
				var code = msg.args.code.toUpperCase();
				if ( states[code] ) {
					return code + ' → ' + states[code];
				}
				return 'USPS code not found';
			}
		}
	}
};
<commit_msg>Alias cc to country<commit_after>var langs = require( 'languages' );
var countries = require( 'i18n-iso-countries' );
var states = require( 'us-states' );
var airports = require( 'airport-lookup' );
var currencies = require( 'currency-codes' );

module.exports = {
	commands: {
		airport: {
			help: 'Looks up an IATA airport code',
			usage: [ 'code' ],
			command: function ( bot, msg ) {
				var data = airports( msg.args.code );
				if ( data ) {
					var datum = [ data.size, countries.getName( data.iso, 'en' ), data.type ];
					return data.iata + ': ' + data.name + ' (' + datum.join( ' ' ) + ')';
				}
				return 'Unable to find an airport with IATA code ' + msg.args.code;
			}
		},
		currency: {
			help: 'Looks up an ISO 4217 currency code',
			usage: [ 'currency' ],
			command: function ( bot, msg ) {
				var code = currencies.code( msg.args.currency );
				if ( code ) {
					if ( code.countries ) {
						return code.code + ' → ' + code.currency + ' (' + code.countries.join( ', ' ) + ')';
					}
					return code.code + ' → ' + code.currency;
				}
				return 'ISO code not found.';
			}
		},
		lang: {
			help: 'Looks up an ISO 369-1 language code',
			aliases: [ 'language' ],
			usage: [ 'lang' ],
			command: function ( bot, msg ) {
				msg.args.lang = msg.args.lang.toLowerCase();
				if ( langs.isValid( msg.args.lang ) ) {
					var info = langs.getLanguageInfo( msg.args.lang );
					return msg.args.lang + ' → ' + info.name + ' · ' + info.nativeName;
				}
				return 'Invalid ISO 639-1 code.';
			}
		},
		country: {
			help: 'Looks up an ISO 3166 alpha2 country code',
			usage: [ 'country' ],
			aliases: [ 'cc' ],
			command: function ( bot, msg ) {
				var code = msg.args.country.toUpperCase();
				if ( countries.getName( code, 'en' ) ) {
					return code + ' → ' + countries.getName( code, 'en' ) + ' · ' + countries.getName( code, 'de' );
				}
				return 'ISO 3166-alpha2 code not found.';
			}
		},
		state: {
			help: 'Looks up the postal abbbreviation for a US state',
			usage: [ 'code' ],
			command: function ( bot, msg ) {
				var code = msg.args.code.toUpperCase();
				if ( states[code] ) {
					return code + ' → ' + states[code];
				}
				return 'USPS code not found';
			}
		}
	}
};
<|endoftext|>


<commit_before>(function() {
  'use strict';

  if (self.fetch) {
    return
  }

  function Headers(headers) {
    this.map = {}

    var self = this
    if (headers instanceof Headers) {
      headers.forEach(function(name, values) {
        values.forEach(function(value) {
          self.append(name, value)
        })
      })

    } else if (headers) {
      Object.getOwnPropertyNames(headers).forEach(function(name) {
        self.append(name, headers[name])
      })
    }
  }

  Headers.prototype.append = function(name, value) {
    name = name.toLowerCase()
    var list = this.map[name]
    if (!list) {
      list = []
      this.map[name] = list
    }
    list.push(value)
  }

  Headers.prototype['delete'] = function(name) {
    delete this.map[name.toLowerCase()]
  }

  Headers.prototype.get = function(name) {
    var values = this.map[name.toLowerCase()]
    return values ? values[0] : null
  }

  Headers.prototype.getAll = function(name) {
    return this.map[name.toLowerCase()] || []
  }

  Headers.prototype.has = function(name) {
    return this.map.hasOwnProperty(name.toLowerCase())
  }

  Headers.prototype.set = function(name, value) {
    this.map[name.toLowerCase()] = [value]
  }

  // Instead of iterable for now.
  Headers.prototype.forEach = function(callback) {
    var self = this
    Object.getOwnPropertyNames(this.map).forEach(function(name) {
      callback(name, self.map[name])
    })
  }

  function consumed(body) {
    if (body.bodyUsed) {
      return Promise.reject(new TypeError('Already read'))
    }
    body.bodyUsed = true
  }

  function fileReaderReady(reader) {
    return new Promise(function(resolve, reject) {
      reader.onload = function() {
        resolve(reader.result)
      }
      reader.onerror = function() {
        reject(reader.error)
      }
    })
  }

  function readBlobAsArrayBuffer(blob) {
    var reader = new FileReader()
    reader.readAsArrayBuffer(blob)
    return fileReaderReady(reader)
  }

  function readBlobAsText(blob) {
    var reader = new FileReader()
    reader.readAsText(blob)
    return fileReaderReady(reader)
  }

  var blobSupport = 'FileReader' in self && 'Blob' in self && (function() {
    try {
      new Blob();
      return true
    } catch(e) {
      return false
    }
  })();
  var formDataSupport = 'FormData' in self;

  function Body() {
    this.bodyUsed = false

    if (blobSupport) {
      this._initBody = function(body) {
        this._bodyInit = body
        if (typeof body === 'string') {
          this._bodyText = body
        } else if (blobSupport && Blob.prototype.isPrototypeOf(body)) {
          this._bodyBlob = body
        } else if (formDataSupport && FormData.prototype.isPrototypeOf(body)) {
          this._bodyFormData = body
        } else if (!body) {
          this._bodyText = ''
        } else {
          throw new Error('unsupported BodyInit type')
        }
      }

      this.blob = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return Promise.resolve(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as blob')
        } else {
          return Promise.resolve(new Blob([this._bodyText]))
        }
      }

      this.arrayBuffer = function() {
        return this.blob().then(readBlobAsArrayBuffer)
      }

      this.text = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return readBlobAsText(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as text')
        } else {
          return Promise.resolve(this._bodyText)
        }
      }
    } else {
      this._initBody = function(body) {
        this._bodyInit = body
        if (typeof body === 'string') {
          this._bodyText = body
        } else if (formDataSupport && FormData.prototype.isPrototypeOf(body)) {
          this._bodyFormData = body
        } else if (!body) {
          this._bodyText = ''
        } else {
          throw new Error('unsupported BodyInit type')
        }
      }

      this.text = function() {
        var rejected = consumed(this)
        return rejected ? rejected : Promise.resolve(this._bodyText)
      }
    }

    if (formDataSupport) {
      this.formData = function() {
        return this.text().then(decode)
      }
    }

    this.json = function() {
      return this.text().then(JSON.parse)
    }

    return this
  }

  // HTTP methods whose capitalization should be normalized
  var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']

  function normalizeMethod(method) {
    var upcased = method.toUpperCase()
    return (methods.indexOf(upcased) > -1) ? upcased : method
  }

  function Request(url, options) {
    options = options || {}
    this.url = url

    this.credentials = options.credentials || 'omit'
    this.headers = new Headers(options.headers)
    this.method = normalizeMethod(options.method || 'GET')
    this.mode = options.mode || null
    this.referrer = null

    if ((this.method === 'GET' || this.method === 'HEAD') && options.body) {
      throw new TypeError('Body not allowed for GET or HEAD requests')
    }
    this._initBody(options.body)
  }

  function decode(body) {
    var form = new FormData()
    body.trim().split('&').forEach(function(bytes) {
      if (bytes) {
        var split = bytes.split('=')
        var name = split.shift().replace(/\+/g, ' ')
        var value = split.join('=').replace(/\+/g, ' ')
        form.append(decodeURIComponent(name), decodeURIComponent(value))
      }
    })
    return form
  }

  function headers(xhr) {
    var head = new Headers()
    var pairs = xhr.getAllResponseHeaders().trim().split('\n')
    pairs.forEach(function(header) {
      var split = header.trim().split(':')
      var key = split.shift().trim()
      var value = split.join(':').trim()
      head.append(key, value)
    })
    return head
  }

  Request.prototype.fetch = function() {
    var self = this

    return new Promise(function(resolve, reject) {
      var xhr = new XMLHttpRequest()
      if (self.credentials === 'cors') {
        xhr.withCredentials = true;
      }

      function responseURL() {
        if ('responseURL' in xhr) {
          return xhr.responseURL
        }

        // Avoid security warnings on getResponseHeader when not allowed by CORS
        if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
          return xhr.getResponseHeader('X-Request-URL')
        }

        return;
      }

      xhr.onload = function() {
        var status = (xhr.status === 1223) ? 204 : xhr.status
        if (status < 100 || status > 599) {
          reject(new TypeError('Network request failed'))
          return
        }
        var options = {
          status: status,
          statusText: xhr.statusText,
          headers: headers(xhr),
          url: responseURL()
        }
        var body = 'response' in xhr ? xhr.response : xhr.responseText;
        resolve(new Response(body, options))
      }

      xhr.onerror = function() {
        reject(new TypeError('Network request failed'))
      }

      xhr.open(self.method, self.url, true)
      if ('responseType' in xhr && blobSupport) {
        xhr.responseType = 'blob'
      }

      self.headers.forEach(function(name, values) {
        values.forEach(function(value) {
          xhr.setRequestHeader(name, value)
        })
      })

      xhr.send(typeof self._bodyInit === 'undefined' ? null : self._bodyInit)
    })
  }

  Body.call(Request.prototype)

  function Response(bodyInit, options) {
    if (!options) {
      options = {}
    }

    this._initBody(bodyInit)
    this.type = 'default'
    this.url = null
    this.status = options.status
    this.statusText = options.statusText
    this.headers = options.headers
    this.url = options.url || ''
  }

  Body.call(Response.prototype)

  self.Headers = Headers;
  self.Request = Request;
  self.Response = Response;

  self.fetch = function (url, options) {
    return new Request(url, options).fetch()
  }
  self.fetch.polyfill = true
})();
<commit_msg>Bundle up support checks into a single object<commit_after>(function() {
  'use strict';

  if (self.fetch) {
    return
  }

  function Headers(headers) {
    this.map = {}

    var self = this
    if (headers instanceof Headers) {
      headers.forEach(function(name, values) {
        values.forEach(function(value) {
          self.append(name, value)
        })
      })

    } else if (headers) {
      Object.getOwnPropertyNames(headers).forEach(function(name) {
        self.append(name, headers[name])
      })
    }
  }

  Headers.prototype.append = function(name, value) {
    name = name.toLowerCase()
    var list = this.map[name]
    if (!list) {
      list = []
      this.map[name] = list
    }
    list.push(value)
  }

  Headers.prototype['delete'] = function(name) {
    delete this.map[name.toLowerCase()]
  }

  Headers.prototype.get = function(name) {
    var values = this.map[name.toLowerCase()]
    return values ? values[0] : null
  }

  Headers.prototype.getAll = function(name) {
    return this.map[name.toLowerCase()] || []
  }

  Headers.prototype.has = function(name) {
    return this.map.hasOwnProperty(name.toLowerCase())
  }

  Headers.prototype.set = function(name, value) {
    this.map[name.toLowerCase()] = [value]
  }

  // Instead of iterable for now.
  Headers.prototype.forEach = function(callback) {
    var self = this
    Object.getOwnPropertyNames(this.map).forEach(function(name) {
      callback(name, self.map[name])
    })
  }

  function consumed(body) {
    if (body.bodyUsed) {
      return Promise.reject(new TypeError('Already read'))
    }
    body.bodyUsed = true
  }

  function fileReaderReady(reader) {
    return new Promise(function(resolve, reject) {
      reader.onload = function() {
        resolve(reader.result)
      }
      reader.onerror = function() {
        reject(reader.error)
      }
    })
  }

  function readBlobAsArrayBuffer(blob) {
    var reader = new FileReader()
    reader.readAsArrayBuffer(blob)
    return fileReaderReady(reader)
  }

  function readBlobAsText(blob) {
    var reader = new FileReader()
    reader.readAsText(blob)
    return fileReaderReady(reader)
  }

  var support = {
    blob: 'FileReader' in self && 'Blob' in self && (function() {
      try {
        new Blob();
        return true
      } catch(e) {
        return false
      }
    })(),
    formData: 'FormData' in self
  }

  function Body() {
    this.bodyUsed = false

    if (support.blob) {
      this._initBody = function(body) {
        this._bodyInit = body
        if (typeof body === 'string') {
          this._bodyText = body
        } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
          this._bodyBlob = body
        } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
          this._bodyFormData = body
        } else if (!body) {
          this._bodyText = ''
        } else {
          throw new Error('unsupported BodyInit type')
        }
      }

      this.blob = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return Promise.resolve(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as blob')
        } else {
          return Promise.resolve(new Blob([this._bodyText]))
        }
      }

      this.arrayBuffer = function() {
        return this.blob().then(readBlobAsArrayBuffer)
      }

      this.text = function() {
        var rejected = consumed(this)
        if (rejected) {
          return rejected
        }

        if (this._bodyBlob) {
          return readBlobAsText(this._bodyBlob)
        } else if (this._bodyFormData) {
          throw new Error('could not read FormData body as text')
        } else {
          return Promise.resolve(this._bodyText)
        }
      }
    } else {
      this._initBody = function(body) {
        this._bodyInit = body
        if (typeof body === 'string') {
          this._bodyText = body
        } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
          this._bodyFormData = body
        } else if (!body) {
          this._bodyText = ''
        } else {
          throw new Error('unsupported BodyInit type')
        }
      }

      this.text = function() {
        var rejected = consumed(this)
        return rejected ? rejected : Promise.resolve(this._bodyText)
      }
    }

    if (support.formData) {
      this.formData = function() {
        return this.text().then(decode)
      }
    }

    this.json = function() {
      return this.text().then(JSON.parse)
    }

    return this
  }

  // HTTP methods whose capitalization should be normalized
  var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']

  function normalizeMethod(method) {
    var upcased = method.toUpperCase()
    return (methods.indexOf(upcased) > -1) ? upcased : method
  }

  function Request(url, options) {
    options = options || {}
    this.url = url

    this.credentials = options.credentials || 'omit'
    this.headers = new Headers(options.headers)
    this.method = normalizeMethod(options.method || 'GET')
    this.mode = options.mode || null
    this.referrer = null

    if ((this.method === 'GET' || this.method === 'HEAD') && options.body) {
      throw new TypeError('Body not allowed for GET or HEAD requests')
    }
    this._initBody(options.body)
  }

  function decode(body) {
    var form = new FormData()
    body.trim().split('&').forEach(function(bytes) {
      if (bytes) {
        var split = bytes.split('=')
        var name = split.shift().replace(/\+/g, ' ')
        var value = split.join('=').replace(/\+/g, ' ')
        form.append(decodeURIComponent(name), decodeURIComponent(value))
      }
    })
    return form
  }

  function headers(xhr) {
    var head = new Headers()
    var pairs = xhr.getAllResponseHeaders().trim().split('\n')
    pairs.forEach(function(header) {
      var split = header.trim().split(':')
      var key = split.shift().trim()
      var value = split.join(':').trim()
      head.append(key, value)
    })
    return head
  }

  Request.prototype.fetch = function() {
    var self = this

    return new Promise(function(resolve, reject) {
      var xhr = new XMLHttpRequest()
      if (self.credentials === 'cors') {
        xhr.withCredentials = true;
      }

      function responseURL() {
        if ('responseURL' in xhr) {
          return xhr.responseURL
        }

        // Avoid security warnings on getResponseHeader when not allowed by CORS
        if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
          return xhr.getResponseHeader('X-Request-URL')
        }

        return;
      }

      xhr.onload = function() {
        var status = (xhr.status === 1223) ? 204 : xhr.status
        if (status < 100 || status > 599) {
          reject(new TypeError('Network request failed'))
          return
        }
        var options = {
          status: status,
          statusText: xhr.statusText,
          headers: headers(xhr),
          url: responseURL()
        }
        var body = 'response' in xhr ? xhr.response : xhr.responseText;
        resolve(new Response(body, options))
      }

      xhr.onerror = function() {
        reject(new TypeError('Network request failed'))
      }

      xhr.open(self.method, self.url, true)
      if ('responseType' in xhr && support.blob) {
        xhr.responseType = 'blob'
      }

      self.headers.forEach(function(name, values) {
        values.forEach(function(value) {
          xhr.setRequestHeader(name, value)
        })
      })

      xhr.send(typeof self._bodyInit === 'undefined' ? null : self._bodyInit)
    })
  }

  Body.call(Request.prototype)

  function Response(bodyInit, options) {
    if (!options) {
      options = {}
    }

    this._initBody(bodyInit)
    this.type = 'default'
    this.url = null
    this.status = options.status
    this.statusText = options.statusText
    this.headers = options.headers
    this.url = options.url || ''
  }

  Body.call(Response.prototype)

  self.Headers = Headers;
  self.Request = Request;
  self.Response = Response;

  self.fetch = function (url, options) {
    return new Request(url, options).fetch()
  }
  self.fetch.polyfill = true
})();
<|endoftext|>


<commit_before>const webpack = require('webpack')
const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

module.exports = {
  entry: {
    adhocracy4: [
      'shariff/dist/shariff.min.css',
      'select2/dist/css/select2.min.css',
      'slick-carousel/slick/slick.css',
      './meinberlin/assets/extra_css/_slick-theme.css',
      './meinberlin/assets/scss/style.scss',
      './meinberlin/assets/js/app.js'
    ],
    vendor: [
      'classnames',
      '@fortawesome/fontawesome-free/scss/fontawesome.scss',
      '@fortawesome/fontawesome-free/scss/brands.scss',
      '@fortawesome/fontawesome-free/scss/regular.scss',
      '@fortawesome/fontawesome-free/scss/solid.scss',
      'js-cookie',
      'react',
      'immutability-helper',
      'react-dom',
      'react-flip-move',
      'react-sticky-box'
    ],
    captcheck: [
      './meinberlin/apps/captcha/assets/captcheck.js'
    ],
    datepicker: [
      './meinberlin/assets/js/init-picker.js',
      'datepicker/css/datepicker.min.css'
    ],
    embed: [
      'bootstrap/js/dist/modal.js',
      './meinberlin/apps/embed/assets/embed.js'
    ],
    unload_warning: [
      './meinberlin/assets/js/unload_warning.js'
    ],
    dsgvo_video_embed: [
      'dsgvo-video-embed/dist/dsgvo-video-embed.min.css',
      'dsgvo-video-embed/dist/dsgvo-video-embed.min.js'
    ],
    // A4 dependencies - we want all of them to go through webpack
    mb_plans_map: [
      'leaflet/dist/leaflet.css',
      'mapbox-gl/dist/mapbox-gl.css',
      'leaflet.markercluster/dist/MarkerCluster.css',
      'react-bootstrap-typeahead/css/Typeahead.css',
      './meinberlin/apps/plans/assets/plans_map.jsx'
    ],
    a4maps_display_point: [
      'leaflet/dist/leaflet.css',
      'mapbox-gl/dist/mapbox-gl.css',
      'adhocracy4/adhocracy4/maps/static/a4maps/a4maps_display_point.js'
    ],
    a4maps_display_points: [
      'leaflet/dist/leaflet.css',
      'mapbox-gl/dist/mapbox-gl.css',
      'leaflet.markercluster/dist/MarkerCluster.css',
      'adhocracy4/adhocracy4/maps/static/a4maps/a4maps_display_points.js'
    ],
    a4maps_choose_point: [
      'leaflet/dist/leaflet.css',
      'mapbox-gl/dist/mapbox-gl.css',
      'adhocracy4/adhocracy4/maps/static/a4maps/a4maps_choose_point.js'
    ],
    a4maps_choose_polygon: [
      'leaflet/dist/leaflet.css',
      'mapbox-gl/dist/mapbox-gl.css',
      'leaflet-draw/dist/leaflet.draw.css',
      './meinberlin/apps/maps/assets/map_choose_polygon_with_preset.js'
    ],
    category_formset: [
      'adhocracy4/adhocracy4/categories/assets/category_formset.js'
    ],
    image_uploader: [
      'adhocracy4/adhocracy4/images/assets/image_uploader.js'
    ],
    select_dropdown_init: [
      'adhocracy4/adhocracy4/categories/assets/select_dropdown_init.js'
    ]
  },
  output: {
    libraryTarget: 'this',
    library: '[name]',
    path: path.resolve('./meinberlin/static/'),
    publicPath: '/static/',
    filename: '[name].js'
  },
  externals: {
    django: 'django'
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules\/(?!(adhocracy4)\/).*/, // exclude most dependencies
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env', '@babel/preset-react'].map(require.resolve),
          plugins: ['@babel/plugin-transform-runtime', '@babel/plugin-transform-modules-commonjs']
        }
      },
      {
        test: /\.s?css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader
          },
          {
            loader: 'css-loader',
            options: {
              url: url => !url.startsWith('/')
            }
          },
          {
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                plugins: [
                  require('autoprefixer')
                ]
              }
            }
          },
          {
            loader: 'sass-loader'
          }
        ]
      },
      {
        test: /fonts\/.*\.(svg|woff2?|ttf|eot)(\?.*)?$/,
        loader: 'file-loader',
        options: {
          name: 'fonts/[name].[ext]'
        }
      },
      {
        test: /\.svg$|\.png$/,
        loader: 'file-loader',
        options: {
          name: 'images/[name].[ext]'
        }
      }
    ]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx', '.scss', '.css'],
    alias: {
      a4maps_common$: 'adhocracy4/adhocracy4/maps/static/a4maps/a4maps_common.js',
      bootstrap$: 'bootstrap/dist/js/bootstrap.bundle.min.js',
      jquery$: 'jquery/dist/jquery.min.js',
      select2$: 'select2/dist/js/select2.min.js',
      shariff$: 'shariff/dist/shariff.min.js',
      shpjs$: 'shpjs/dist/shp.min.js',
      tether$: 'tether/dist/js/tether.min.js',
      'slick-carousel$': 'slick-carousel/slick/slick.min.js'
    },
    // when using `npm link`, dependencies are resolved against the linked
    // folder by default. This may result in dependencies being included twice.
    // Setting `resolve.root` forces webpack to resolve all dependencies
    // against the local directory.
    modules: [path.resolve('./node_modules')]
  },
  plugins: [
    new webpack.ProvidePlugin({
      timeago: 'timeago.js',
      $: 'jquery',
      jQuery: 'jquery',
      Promise: ['es6-promise', 'Promise'],
      fetch: ['whatwg-fetch', 'fetch']
    }),
    new webpack.optimize.SplitChunksPlugin({
      name: 'vendor',
      filename: 'vendor.js'
    }),
    new MiniCssExtractPlugin({
      filename: '[name].css',
      chunkFilename: '[name].css'
    }),
    new CopyWebpackPlugin({
      patterns: [{
        from: './meinberlin/assets/images/**/*',
        to: 'images/',
        flatten: true
      }]
    })
  ]
}
<commit_msg>Revert "webpack: Use optimized static files for dsgvo-embed"<commit_after>const webpack = require('webpack')
const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')

module.exports = {
  entry: {
    adhocracy4: [
      'shariff/dist/shariff.min.css',
      'select2/dist/css/select2.min.css',
      'slick-carousel/slick/slick.css',
      './meinberlin/assets/extra_css/_slick-theme.css',
      './meinberlin/assets/scss/style.scss',
      './meinberlin/assets/js/app.js'
    ],
    vendor: [
      'classnames',
      '@fortawesome/fontawesome-free/scss/fontawesome.scss',
      '@fortawesome/fontawesome-free/scss/brands.scss',
      '@fortawesome/fontawesome-free/scss/regular.scss',
      '@fortawesome/fontawesome-free/scss/solid.scss',
      'js-cookie',
      'react',
      'immutability-helper',
      'react-dom',
      'react-flip-move',
      'react-sticky-box'
    ],
    captcheck: [
      './meinberlin/apps/captcha/assets/captcheck.js'
    ],
    datepicker: [
      './meinberlin/assets/js/init-picker.js',
      'datepicker/css/datepicker.min.css'
    ],
    embed: [
      'bootstrap/js/dist/modal.js',
      './meinberlin/apps/embed/assets/embed.js'
    ],
    unload_warning: [
      './meinberlin/assets/js/unload_warning.js'
    ],
    dsgvo_video_embed: [
      'dsgvo-video-embed/css/dsgvo-video-embed.css',
      'dsgvo-video-embed/js/dsgvo-video-embed.js'
    ],
    // A4 dependencies - we want all of them to go through webpack
    mb_plans_map: [
      'leaflet/dist/leaflet.css',
      'mapbox-gl/dist/mapbox-gl.css',
      'leaflet.markercluster/dist/MarkerCluster.css',
      'react-bootstrap-typeahead/css/Typeahead.css',
      './meinberlin/apps/plans/assets/plans_map.jsx'
    ],
    a4maps_display_point: [
      'leaflet/dist/leaflet.css',
      'mapbox-gl/dist/mapbox-gl.css',
      'adhocracy4/adhocracy4/maps/static/a4maps/a4maps_display_point.js'
    ],
    a4maps_display_points: [
      'leaflet/dist/leaflet.css',
      'mapbox-gl/dist/mapbox-gl.css',
      'leaflet.markercluster/dist/MarkerCluster.css',
      'adhocracy4/adhocracy4/maps/static/a4maps/a4maps_display_points.js'
    ],
    a4maps_choose_point: [
      'leaflet/dist/leaflet.css',
      'mapbox-gl/dist/mapbox-gl.css',
      'adhocracy4/adhocracy4/maps/static/a4maps/a4maps_choose_point.js'
    ],
    a4maps_choose_polygon: [
      'leaflet/dist/leaflet.css',
      'mapbox-gl/dist/mapbox-gl.css',
      'leaflet-draw/dist/leaflet.draw.css',
      './meinberlin/apps/maps/assets/map_choose_polygon_with_preset.js'
    ],
    category_formset: [
      'adhocracy4/adhocracy4/categories/assets/category_formset.js'
    ],
    image_uploader: [
      'adhocracy4/adhocracy4/images/assets/image_uploader.js'
    ],
    select_dropdown_init: [
      'adhocracy4/adhocracy4/categories/assets/select_dropdown_init.js'
    ]
  },
  output: {
    libraryTarget: 'this',
    library: '[name]',
    path: path.resolve('./meinberlin/static/'),
    publicPath: '/static/',
    filename: '[name].js'
  },
  externals: {
    django: 'django'
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules\/(?!(adhocracy4)\/).*/, // exclude most dependencies
        loader: 'babel-loader',
        options: {
          presets: ['@babel/preset-env', '@babel/preset-react'].map(require.resolve),
          plugins: ['@babel/plugin-transform-runtime', '@babel/plugin-transform-modules-commonjs']
        }
      },
      {
        test: /\.s?css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader
          },
          {
            loader: 'css-loader',
            options: {
              url: url => !url.startsWith('/')
            }
          },
          {
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                plugins: [
                  require('autoprefixer')
                ]
              }
            }
          },
          {
            loader: 'sass-loader'
          }
        ]
      },
      {
        test: /fonts\/.*\.(svg|woff2?|ttf|eot)(\?.*)?$/,
        loader: 'file-loader',
        options: {
          name: 'fonts/[name].[ext]'
        }
      },
      {
        test: /\.svg$|\.png$/,
        loader: 'file-loader',
        options: {
          name: 'images/[name].[ext]'
        }
      }
    ]
  },
  resolve: {
    extensions: ['*', '.js', '.jsx', '.scss', '.css'],
    alias: {
      a4maps_common$: 'adhocracy4/adhocracy4/maps/static/a4maps/a4maps_common.js',
      bootstrap$: 'bootstrap/dist/js/bootstrap.bundle.min.js',
      jquery$: 'jquery/dist/jquery.min.js',
      select2$: 'select2/dist/js/select2.min.js',
      shariff$: 'shariff/dist/shariff.min.js',
      shpjs$: 'shpjs/dist/shp.min.js',
      tether$: 'tether/dist/js/tether.min.js',
      'slick-carousel$': 'slick-carousel/slick/slick.min.js'
    },
    // when using `npm link`, dependencies are resolved against the linked
    // folder by default. This may result in dependencies being included twice.
    // Setting `resolve.root` forces webpack to resolve all dependencies
    // against the local directory.
    modules: [path.resolve('./node_modules')]
  },
  plugins: [
    new webpack.ProvidePlugin({
      timeago: 'timeago.js',
      $: 'jquery',
      jQuery: 'jquery',
      Promise: ['es6-promise', 'Promise'],
      fetch: ['whatwg-fetch', 'fetch']
    }),
    new webpack.optimize.SplitChunksPlugin({
      name: 'vendor',
      filename: 'vendor.js'
    }),
    new MiniCssExtractPlugin({
      filename: '[name].css',
      chunkFilename: '[name].css'
    }),
    new CopyWebpackPlugin({
      patterns: [{
        from: './meinberlin/assets/images/**/*',
        to: 'images/',
        flatten: true
      }]
    })
  ]
}
<|endoftext|>


<commit_before>var mongoURL = 'mongodb://127.0.0.1:27017/search45';

var MongoClient = require('mongodb').MongoClient;
var fs = require('fs');
var _ = require('lodash');

var filename = process.argv[2];

function modifyGeneDocs(genetreeLUT) {
  require('readline').createInterface({
    input: fs.createReadStream(filename),
    terminal: false
  }).on('line', function (line) { // one JSON object per line
    var obj = JSON.parse(line);
    if(obj.epl_gene_tree) {
      obj.epl_gene_tree_root_taxon_id = genetreeLUT[obj.epl_gene_tree].node_taxon_id;
    }
    console.log(JSON.stringify(obj));
  });
}

// connect to the ontologies database
MongoClient.connect(mongoURL, function(err, db) {
  if (err) throw err;
  db.collection('genetree').find({}, {node_taxon_id: 1}).toArray(function(err, docs) {
    if (err) throw err;
    modifyGeneDocs(_.indexBy(docs, '_id'));
    db.close();
  });
});
<commit_msg>add updated genetree data to gene docs<commit_after>var mongoURL = 'mongodb://127.0.0.1:27017/search45';

var MongoClient = require('mongodb').MongoClient;
var fs = require('fs');
var _ = require('lodash');

var filename = process.argv[2];

function modifyGeneDocs(genetreeLUT) {
  require('readline').createInterface({
    input: fs.createReadStream(filename),
    terminal: false
  }).on('line', function (line) { // one JSON object per line
    var obj = JSON.parse(line);
    if(obj.epl_gene_tree) {
      var tree = genetreeLUT[obj.epl_gene_tree];
      obj.grm_gene_tree = tree.tree_id;
      obj.grm_gene_tree_root_taxon_id = tree.node_taxon_id;
      if(tree.stableIds.length > 1) {
        obj.epl_sibling_trees = _.filter(tree.stableIds, function(id) { return id !== obj.epl_gene_tree; });
      }
    }
    console.log(JSON.stringify(obj));
  });
}

// connect to the ontologies database
MongoClient.connect(mongoURL, function(err, db) {
  if (err) throw err;
  db.collection('genetree').find({}, {node_taxon_id: 1, stableIds: 1, tree_id: 1}).toArray(function(err, docs) {
    if (err) throw err;
    var lut = _.reduce(docs, function(acc, doc) {
      _.forEach(doc.stableIds, function(stableId) {
        acc[stableId] = doc;
      });
      return acc;
    }, {});

    modifyGeneDocs(lut);
    db.close();
  });
});
<|endoftext|>


<commit_before>/* globals testsuite */
(function() {
    var mediaIns = null;
    testsuite('toast.Media', 'getInstance()', function(report) {
        try {
            mediaIns = toast.Media.getInstance();
            report('Success: toast.Media.getInstance()');
        } catch (err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'open()', function(report) {
        try {
            mediaIns.open('http://media.w3.org/2010/05/sintel/trailer.mp4');
            report('Success: toast.Media.open(\'http://media.w3.org/2010/05/sintel/trailer.mp4\')');
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'getContainerElement()', function(report) {
        try {
            var elContainer = mediaIns.getContainerElement();
            elContainer.style.left = '0px';
            elContainer.style.top = '0px';
            elContainer.style.width = '320px';
            elContainer.style.height = '180px';
            report('Success: getContainerElement()');
            report.append(elContainer);
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }

    });
    testsuite('toast.Media', 'setListener()', function(report) {
        try {
            mediaIns.setListener({
                onevent: function (evt) {
                     switch(evt.type) {
                         case 'STATE':
                             report('Success: Media State changed: ' + evt.data.oldState + ' -> ' + evt.data.state);
                             break;
                         case 'DURATION':
                             report('Success: Media duration updated: ' + evt.data.duration + 'ms');
                             break;
                         case 'POSITION':
                             report('Success: Media position updated: ' + evt.data.position + 'ms');
                             break;
                         case 'BUFFERINGPROGRESS' :
                             report('Success: Media buffering in progress: ' + evt.data.bufferingPercentage + '%');
                             if(evt.data.bufferingPercentage >= 100) {
                                 report('Success: Buffering completed');
                             }
                             break;
                     }
                 },
                 onerror: function (err) {
                     report('Error : MediaError occured: ' + JSON.stringify(err));
                 }
            });
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'unsetListener()', function(report) {
        try {
            mediaIns.unsetListener();
            report('Success: toast.Media.unsetListener()');
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'play()', function(report) {
        try {
            mediaIns.play();
            report('Success: toast.Media.play()');
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'pause()', function(report) {
        try {
            mediaIns.pause();
            report('Success: toast.Media.pause()');
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'seekTo() to \'FF 3s\'', function(report) {
        try {
            var curPosition = mediaIns.getCurrentPosition();
            mediaIns.seekTo(curPosition + 3000);
            report('Success: FF 3s');
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'getDuration()', function(report) {
        try {
            var duration = mediaIns.getDuration();
            report('Success: ' + duration);
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'getCurrentPosition()', function(report) {
        try {
            var position = mediaIns.getCurrentPosition();
            report('Success: ' + position);
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'stop()', function(report) {
        try {
            mediaIns.stop();
            report('Success: toast.Media.stop()');
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
})();<commit_msg>#15 add media audio sample test<commit_after>/* globals testsuite */
(function() {
    var mediaIns = null;
    testsuite('toast.Media', 'getInstance()', function(report) {
        try {
            mediaIns = toast.Media.getInstance();
            report('Success: toast.Media.getInstance()');
        } catch (err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'open() -> \'SampleVideo\' ', function(report) {
        try {
            mediaIns.open('http://media.w3.org/2010/05/sintel/trailer.mp4');
            report('Success: toast.Media.open(\'http://media.w3.org/2010/05/sintel/trailer.mp4\')');
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'open() -> \'SampleAudio\' ', function(report) {
        try {
            mediaIns.open('http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.mp3');
            report('Success: toast.Media.open(\'http://media.w3.org/2010/07/bunny/04-Death_Becomes_Fur.mp3\')');
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'getContainerElement()', function(report) {
        try {
            var elContainer = mediaIns.getContainerElement();
            elContainer.style.left = '0px';
            elContainer.style.top = '0px';
            elContainer.style.width = '320px';
            elContainer.style.height = '180px';
            report('Success: getContainerElement()');
            report.append(elContainer);
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }

    });
    testsuite('toast.Media', 'setListener()', function(report) {
        try {
            mediaIns.setListener({
                onevent: function (evt) {
                     switch(evt.type) {
                         case 'STATE':
                             report('Success: Media State changed: ' + evt.data.oldState + ' -> ' + evt.data.state);
                             break;
                         case 'DURATION':
                             report('Success: Media duration updated: ' + evt.data.duration + 'ms');
                             break;
                         case 'POSITION':
                             report('Success: Media position updated: ' + evt.data.position + 'ms');
                             break;
                         case 'BUFFERINGPROGRESS' :
                             report('Success: Media buffering in progress: ' + evt.data.bufferingPercentage + '%');
                             if(evt.data.bufferingPercentage >= 100) {
                                 report('Success: Buffering completed');
                             }
                             break;
                     }
                 },
                 onerror: function (err) {
                     report('Error : MediaError occured: ' + JSON.stringify(err));
                 }
            });
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'unsetListener()', function(report) {
        try {
            mediaIns.unsetListener();
            report('Success: toast.Media.unsetListener()');
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'play()', function(report) {
        try {
            mediaIns.play();
            report('Success: toast.Media.play()');
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'pause()', function(report) {
        try {
            mediaIns.pause();
            report('Success: toast.Media.pause()');
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'seekTo() to \'FF 3s\'', function(report) {
        try {
            var curPosition = mediaIns.getCurrentPosition();
            mediaIns.seekTo(curPosition + 3000);
            report('Success: FF 3s');
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'getDuration()', function(report) {
        try {
            var duration = mediaIns.getDuration();
            report('Success: ' + duration);
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'getCurrentPosition()', function(report) {
        try {
            var position = mediaIns.getCurrentPosition();
            report('Success: ' + position);
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
    testsuite('toast.Media', 'stop()', function(report) {
        try {
            mediaIns.stop();
            report('Success: toast.Media.stop()');
        } catch(err){
            report('Error: ' + JSON.stringify(err));
        }
    });
})();<|endoftext|>


<commit_before>/* =============================================================

    Slider v3.1
    A simple, responsive, touch-enabled image slider, forked from Swipe.

    Script by Brad Birdsall.
    http://swipejs.com/

    Forked by Chris Ferdinandi.
    http://gomakethings.com

    Code contributed by Ron Ilan.
    https://github.com/bradbirdsall/Swipe/pull/277

    Licensed under the MIT license.
    http://gomakethings.com/mit/

 * ============================================================= */

if ( 'querySelector' in document && 'addEventListener' in window ) {

    var Swipe = function (container, options) {

      "use strict";

      // utilities
      var noop = function() {}; // simple no operation function
      var offloadFn = function(fn) { setTimeout(fn || noop, 0) }; // offload a functions execution

      // check browser capabilities
      var browser = {
        addEventListener: !!window.addEventListener,
        touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
        transitions: (function(temp) {
          var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
          for ( var i in props ) if (temp.style[ props[i] ] !== undefined) return true;
          return false;
        })(document.createElement('swipe'))
      };

      // quit if no root element
      if (!container) return;
      var element = container.children[0];
      var slides, slidePos, width, length;
      options = options || {};
      var index = parseInt(options.startSlide - 1, 10) || 0;
      var speed = options.speed || 300;
      options.continuous = options.continuous !== undefined ? options.continuous : true;

      var setup = function () {

        // cache slides
        slides = element.children;
        length = slides.length;

        // set continuous to false if only one slide
        if (slides.length < 2) options.continuous = false;

        // create an array to store current positions of each slide
        slidePos = new Array(slides.length);

        // determine width of each slide
        width = container.getBoundingClientRect().width || container.offsetWidth;

        element.style.width = (slides.length * width) + 'px';

        // stack elements
        var pos = slides.length;
        while(pos--) {

          var slide = slides[pos];

          slide.style.width = width + 'px';
          slide.setAttribute('data-index', pos);

          if (browser.transitions) {
            slide.style.left = (pos * -width) + 'px';
            move(pos, index > pos ? -width : (index < pos ? width : 0), 0);
          }

        }

        // reposition elements before and after index
        if (options.continuous && browser.transitions) {
          move(circle(index-1), -width, 0);
          move(circle(index+1), width, 0);
        }

        if (!browser.transitions) element.style.left = (index * -width) + 'px';

        visibleThree(index, slides);

        container.style.visibility = 'visible';

      };

      var prev = function () {

        if (options.continuous) slide(index-1);
        else if (index) slide(index-1);

      };

      var next = function () {

        if (options.continuous) slide(index+1);
        else if (index < slides.length - 1) slide(index+1);

      };

      var circle = function (index) {

        // a simple positive modulo using slides.length
        return (slides.length + (index % slides.length)) % slides.length;

      };

      var slide = function (to, slideSpeed) {

        // do nothing if already on requested slide
        if (index == to) return;

        if (browser.transitions) {

          var direction = Math.abs(index-to) / (index-to); // 1: backward, -1: forward

          // get the actual position of the slide
          if (options.continuous) {
            var natural_direction = direction;
            direction = -slidePos[circle(to)] / width;

            // if going forward but to < index, use to = slides.length + to
            // if going backward but to > index, use to = -slides.length + to
            if (direction !== natural_direction) to =  -direction * slides.length + to;

          }

          var diff = Math.abs(index-to) - 1;

          // move all the slides between index and to in the right direction
          while (diff--) move( circle((to > index ? to : index) - diff - 1), width * direction, 0);

          to = circle(to);

          move(index, width * direction, slideSpeed || speed);
          move(to, 0, slideSpeed || speed);

          if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place

        } else {

          to = circle(to);
          animate(index * -width, to * -width, slideSpeed || speed);
          //no fallback for a circular continuous if the browser does not accept transitions
        }

        index = to;
        visibleThree(index, slides);
        offloadFn(options.callback && options.callback(index, slides[index]));
      };

      var move = function (index, dist, speed) {

        translate(index, dist, speed);
        slidePos[index] = dist;

      };

      var translate = function (index, dist, speed) {

        var slide = slides[index];
        var style = slide && slide.style;

        if (!style) return;

        style.webkitTransitionDuration =
        style.MozTransitionDuration =
        style.msTransitionDuration =
        style.OTransitionDuration =
        style.transitionDuration = speed + 'ms';

        style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
        style.msTransform =
        style.MozTransform =
        style.OTransform = 'translateX(' + dist + 'px)';

      };

      var animate = function (from, to, speed) {

        // if not an animation, just reposition
        if (!speed) {

          element.style.left = to + 'px';
          return;

        }

        var start = +new Date;

        var timer = setInterval(function() {

          var timeElap = +new Date - start;

          if (timeElap > speed) {

            element.style.left = to + 'px';

            if (delay) begin();

            options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);

            clearInterval(timer);
            return;

          }

          element.style.left = (( (to - from) * (Math.floor((timeElap / speed) * 100) / 100) ) + from) + 'px';

        }, 4);

      };

      // hide all slides then show only current, next and prev
      function visibleThree(index, slides) {

        var pos = slides.length;

        while(pos--) {

          slides[pos].style.visibility = 'hidden';

          if(pos === circle(index) || pos === circle(index-1) || pos === circle(index+1)){
            slides[pos].style.visibility = 'visible';
          }

        }

      }

      // setup auto slideshow
      var delay = options.auto || 0;
      var interval;

      var begin = function () {

        interval = setTimeout(next, delay);

      };

      var stop = function () {

        delay = 0;
        clearTimeout(interval);

      };

      // setup initial vars
      var start = {};
      var delta = {};
      var isScrolling;

      // setup event capturing
      var events = {

        handleEvent: function(event) {

          switch (event.type) {
            case 'touchstart': this.start(event); break;
            case 'touchmove': this.move(event); break;
            case 'touchend': offloadFn(this.end(event)); break;
            case 'webkitTransitionEnd':
            case 'msTransitionEnd':
            case 'oTransitionEnd':
            case 'otransitionend':
            case 'transitionend': offloadFn(this.transitionEnd(event)); break;
            case 'resize': offloadFn(setup.call()); break;
          }

          if (options.stopPropagation) event.stopPropagation();

        },
        start: function(event) {

          var touches = event.touches[0];

          // measure start values
          start = {

            // get initial touch coords
            x: touches.pageX,
            y: touches.pageY,

            // store time to determine touch duration
            time: +new Date

          };

          // used for testing first move event
          isScrolling = undefined;

          // reset delta and end measurements
          delta = {};

          // attach touchmove and touchend listeners
          element.addEventListener('touchmove', this, false);
          element.addEventListener('touchend', this, false);

        },
        move: function(event) {

          // ensure swiping with one touch and not pinching
          if ( event.touches.length > 1 || event.scale && event.scale !== 1) return;

          if (options.disableScroll) event.preventDefault();

          var touches = event.touches[0];

          // measure change in x and y
          delta = {
            x: touches.pageX - start.x,
            y: touches.pageY - start.y
          };

          // determine if scrolling test has run - one time test
          if ( typeof isScrolling == 'undefined') {
            isScrolling = !!( isScrolling || Math.abs(delta.x) < Math.abs(delta.y) );
          }

          // if user is not trying to scroll vertically
          if (!isScrolling) {

            // prevent native scrolling
            event.preventDefault();

            // stop slideshow
            stop();

            // increase resistance if first or last slide
            if (options.continuous) { // we don't add resistance at the end

              translate(circle(index-1), delta.x + slidePos[circle(index-1)], 0);
              translate(index, delta.x + slidePos[index], 0);
              translate(circle(index+1), delta.x + slidePos[circle(index+1)], 0);

            } else {

              delta.x =
                delta.x /
                  ( (!index && delta.x > 0               // if first slide and sliding left
                  || index == slides.length - 1        // or if last slide and sliding right
                  && delta.x < 0                       // and if sliding at all
                  ) ?
                  ( Math.abs(delta.x) / width + 1 )      // determine resistance level
                  : 1 );                                 // no resistance if false

              // translate 1:1
              translate(index-1, delta.x + slidePos[index-1], 0);
              translate(index, delta.x + slidePos[index], 0);
              translate(index+1, delta.x + slidePos[index+1], 0);
            }

          }

        },
        end: function(event) {

          // measure duration
          var duration = +new Date - start.time;

          // determine if slide attempt triggers next/prev slide
          var isValidSlide =
                Number(duration) < 250               // if slide duration is less than 250ms
                && Math.abs(delta.x) > 20            // and if slide amt is greater than 20px
                || Math.abs(delta.x) > width/2;      // or if slide amt is greater than half the width

          // determine if slide attempt is past start and end
          var isPastBounds =
                !index && delta.x > 0                            // if first slide and slide amt is greater than 0
                || index == slides.length - 1 && delta.x < 0;    // or if last slide and slide amt is less than 0

          if (options.continuous) isPastBounds = false;

          // determine direction of swipe (true:right, false:left)
          var direction = delta.x < 0;

          // if not scrolling vertically
          if (!isScrolling) {

            if (isValidSlide && !isPastBounds) {

              if (direction) {

                if (options.continuous) { // we need to get the next in this direction in place

                  move(circle(index-1), -width, 0);
                  move(circle(index+2), width, 0);

                } else {
                  move(index-1, -width, 0);
                }

                move(index, slidePos[index]-width, speed);
                move(circle(index+1), slidePos[circle(index+1)]-width, speed);
                index = circle(index+1);

              } else {
                if (options.continuous) { // we need to get the next in this direction in place

                  move(circle(index+1), width, 0);
                  move(circle(index-2), -width, 0);

                } else {
                  move(index+1, width, 0);
                }

                move(index, slidePos[index]+width, speed);
                move(circle(index-1), slidePos[circle(index-1)]+width, speed);
                index = circle(index-1);

              }

              visibleThree(index, slides);
              options.callback && options.callback(index, slides[index]);

            } else {

              if (options.continuous) {

                move(circle(index-1), -width, speed);
                move(index, 0, speed);
                move(circle(index+1), width, speed);

              } else {

                move(index-1, -width, speed);
                move(index, 0, speed);
                move(index+1, width, speed);
              }

            }

          }

          // kill touchmove and touchend event listeners until touchstart called again
          element.removeEventListener('touchmove', events, false);
          element.removeEventListener('touchend', events, false);

        },
        transitionEnd: function(event) {

          if (parseInt(event.target.getAttribute('data-index'), 10) == index) {

            if (delay) begin();

            options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);

          }

        }

      };

      // trigger setup
      setup();

      // start auto slideshow if applicable
      if (delay) begin();

      // add event listeners
      if (browser.addEventListener) {

        // set touchstart event on element
        if (browser.touch) element.addEventListener('touchstart', events, false);

        if (browser.transitions) {
          element.addEventListener('webkitTransitionEnd', events, false);
          element.addEventListener('msTransitionEnd', events, false);
          element.addEventListener('oTransitionEnd', events, false);
          element.addEventListener('otransitionend', events, false);
          element.addEventListener('transitionend', events, false);
        }

        // set resize event on window
        window.addEventListener('resize', events, false);

      } else {

        window.onresize = function () { setup() }; // to play nice with old IE

      }

      // expose the Swipe API
      return {
        setup: function() {

          setup();

        },
        slide: function(to, speed) {

          // cancel slideshow
          stop();

          slide(to, speed);

        },
        prev: function() {

          // cancel slideshow
          stop();

          prev();

        },
        next: function() {

          // cancel slideshow
          stop();

          next();

        },
        getPos: function() {

          // return current index position
          return index + 1;

        },
        getNumSlides: function() {

          // return total number of slides
          return length;
        },
        kill: function() {

          // cancel slideshow
          stop();

          // reset element
          element.style.width = 'auto';
          element.style.left = 0;

          // reset slides
          var pos = slides.length;
          while(pos--) {

            var slide = slides[pos];
            slide.style.width = '100%';
            slide.style.left = 0;

            if (browser.transitions) translate(pos, 0, 0);

          }

          // removed event listeners
          if (browser.addEventListener) {

            // remove current event listeners
            element.removeEventListener('touchstart', events, false);
            element.removeEventListener('webkitTransitionEnd', events, false);
            element.removeEventListener('msTransitionEnd', events, false);
            element.removeEventListener('oTransitionEnd', events, false);
            element.removeEventListener('otransitionend', events, false);
            element.removeEventListener('transitionend', events, false);
            window.removeEventListener('resize', events, false);

          }
          else {

            window.onresize = null;

          }

        }
      };

    };

}<commit_msg>transitionEnd bug fix<commit_after>/* =============================================================

		Slider v3.3
		A simple, responsive, touch-enabled image slider, forked from Swipe.

		Script by Brad Birdsall.
		http://swipejs.com/

		Forked by Chris Ferdinandi.
		http://gomakethings.com

		Code contributed by Ron Ilan.
		https://github.com/bradbirdsall/Swipe/pull/277

		Licensed under the MIT license.
		http://gomakethings.com/mit/

 * ============================================================= */

if ( 'querySelector' in document && 'addEventListener' in window ) {

	var Swipe = function (container, options) {

		"use strict";

		// utilities
		var noop = function() {}; // simple no operation function
		var offloadFn = function(fn) { setTimeout(fn || noop, 0) }; // offload a functions execution

		// check browser capabilities
		var browser = {
			addEventListener: !!window.addEventListener,
			touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
			transitions: (function(temp) {
				var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
				for ( var i in props ) if (temp.style[ props[i] ] !== undefined) return true;
				return false;
			})(document.createElement('swipe'))
		};

		// quit if no root element
		if (!container) return;
		var element = container.children[0];
		var slides, slidePos, width, length;
		options = options || {};
		var index = parseInt(options.startSlide - 1, 10) || 0;
		var speed = options.speed || 300;
		options.continuous = options.continuous !== undefined ? options.continuous : true;

		var setup = function () {

			// cache slides
			slides = element.children;
			length = slides.length;

			// set continuous to false if only one slide
			if (slides.length < 2) options.continuous = false;

			// create an array to store current positions of each slide
			slidePos = new Array(slides.length);

			// determine width of each slide
			width = container.getBoundingClientRect().width || container.offsetWidth;

			element.style.width = (slides.length * width) + 'px';

			// stack elements
			var pos = slides.length;
			while(pos--) {

				var slide = slides[pos];

				slide.style.width = width + 'px';
				slide.setAttribute('data-index', pos);

				if (browser.transitions) {
					slide.style.left = (pos * -width) + 'px';
					move(pos, index > pos ? -width : (index < pos ? width : 0), 0);
				}

			}

			// reposition elements before and after index
			if (options.continuous && browser.transitions) {
				move(circle(index-1), -width, 0);
				move(circle(index+1), width, 0);
			}

			if (!browser.transitions) element.style.left = (index * -width) + 'px';

			visibleThree(index, slides);

			container.style.visibility = 'visible';

		};

		var prev = function () {

			if (options.continuous) slide(index-1);
			else if (index) slide(index-1);

		};

		var next = function () {

			if (options.continuous) slide(index+1);
			else if (index < slides.length - 1) slide(index+1);

		};

		var circle = function (index) {

			// a simple positive modulo using slides.length
			return (slides.length + (index % slides.length)) % slides.length;

		};

		var slide = function (to, slideSpeed) {

			// do nothing if already on requested slide
			if (index == to) return;

			if (browser.transitions) {

				var direction = Math.abs(index-to) / (index-to); // 1: backward, -1: forward

				// get the actual position of the slide
				if (options.continuous) {
					var natural_direction = direction;
					direction = -slidePos[circle(to)] / width;

					// if going forward but to < index, use to = slides.length + to
					// if going backward but to > index, use to = -slides.length + to
					if (direction !== natural_direction) to =  -direction * slides.length + to;

				}

				var diff = Math.abs(index-to) - 1;

				// move all the slides between index and to in the right direction
				while (diff--) move( circle((to > index ? to : index) - diff - 1), width * direction, 0);

				to = circle(to);

				move(index, width * direction, slideSpeed || speed);
				move(to, 0, slideSpeed || speed);

				if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place

			} else {

				to = circle(to);
				animate(index * -width, to * -width, slideSpeed || speed);
				//no fallback for a circular continuous if the browser does not accept transitions
			}

			index = to;
			offloadFn(options.callback && options.callback(index, slides[index]));
		};

		var move = function (index, dist, speed) {

			translate(index, dist, speed);
			slidePos[index] = dist;

		};

		var translate = function (index, dist, speed) {

			var slide = slides[index];
			var style = slide && slide.style;

			if (!style) return;

			style.webkitTransitionDuration =
			style.MozTransitionDuration =
			style.msTransitionDuration =
			style.OTransitionDuration =
			style.transitionDuration = speed + 'ms';

			style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
			style.msTransform =
			style.MozTransform =
			style.OTransform = 'translateX(' + dist + 'px)';

		};

		var animate = function (from, to, speed) {

			// if not an animation, just reposition
			if (!speed) {

				element.style.left = to + 'px';
				return;

			}

			var start = +new Date;

			var timer = setInterval(function() {

				var timeElap = +new Date - start;

				if (timeElap > speed) {

					element.style.left = to + 'px';

					if (delay) begin();

					options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);

					clearInterval(timer);
					return;

				}

				element.style.left = (( (to - from) * (Math.floor((timeElap / speed) * 100) / 100) ) + from) + 'px';

			}, 4);

		};

		// hide all slides other than current one
		function visibleThree(index, slides) {

			var pos = slides.length;

			// first make this one visible
			slides[index].style.visibility = 'visible';

			// then check all others for hiding
			while(pos--) {

				if(pos === circle(index) || pos === circle(index-1) || pos === circle(index+1)){
					slides[pos].style.visibility = 'visible';
				} else {
					slides[pos].style.visibility = 'hidden';
				}

			}

		}

		// setup auto slideshow
		var delay = options.auto || 0;
		var interval;

		var begin = function () {

			interval = setTimeout(next, delay);

		};

		var stop = function () {

			delay = 0;
			clearTimeout(interval);

		};

		// setup initial vars
		var start = {};
		var delta = {};
		var isScrolling;

		// setup event capturing
		var events = {

			handleEvent: function(event) {

				switch (event.type) {
					case 'touchstart': this.start(event); break;
					case 'touchmove': this.move(event); break;
					case 'touchend': offloadFn(this.end(event)); break;
					case 'webkitTransitionEnd':
					case 'msTransitionEnd':
					case 'oTransitionEnd':
					case 'otransitionend':
					case 'transitionend': offloadFn(this.transitionEnd(event)); break;
					case 'resize': offloadFn(setup.call()); break;
				}

				if (options.stopPropagation) event.stopPropagation();

			},
			start: function(event) {

				var touches = event.touches[0];

				// measure start values
				start = {

					// get initial touch coords
					x: touches.pageX,
					y: touches.pageY,

					// store time to determine touch duration
					time: +new Date

				};

				// used for testing first move event
				isScrolling = undefined;

				// reset delta and end measurements
				delta = {};

				// attach touchmove and touchend listeners
				element.addEventListener('touchmove', this, false);
				element.addEventListener('touchend', this, false);

			},
			move: function(event) {

				// ensure swiping with one touch and not pinching
				if ( event.touches.length > 1 || event.scale && event.scale !== 1) return;

				if (options.disableScroll) event.preventDefault();

				var touches = event.touches[0];

				// measure change in x and y
				delta = {
					x: touches.pageX - start.x,
					y: touches.pageY - start.y
				};

				// determine if scrolling test has run - one time test
				if ( typeof isScrolling == 'undefined') {
					isScrolling = !!( isScrolling || Math.abs(delta.x) < Math.abs(delta.y) );
				}

				// if user is not trying to scroll vertically
				if (!isScrolling) {

					// prevent native scrolling
					event.preventDefault();

					// stop slideshow
					stop();

					// increase resistance if first or last slide
					if (options.continuous) { // we don't add resistance at the end

						translate(circle(index-1), delta.x + slidePos[circle(index-1)], 0);
						translate(index, delta.x + slidePos[index], 0);
						translate(circle(index+1), delta.x + slidePos[circle(index+1)], 0);

					} else {

						delta.x =
							delta.x /
								( (!index && delta.x > 0               // if first slide and sliding left
								|| index == slides.length - 1        // or if last slide and sliding right
								&& delta.x < 0                       // and if sliding at all
								) ?
								( Math.abs(delta.x) / width + 1 )      // determine resistance level
								: 1 );                                 // no resistance if false

						// translate 1:1
						translate(index-1, delta.x + slidePos[index-1], 0);
						translate(index, delta.x + slidePos[index], 0);
						translate(index+1, delta.x + slidePos[index+1], 0);
					}

				}

			},
			end: function(event) {

				// measure duration
				var duration = +new Date - start.time;

				// determine if slide attempt triggers next/prev slide
				var isValidSlide =
							Number(duration) < 250               // if slide duration is less than 250ms
							&& Math.abs(delta.x) > 20            // and if slide amt is greater than 20px
							|| Math.abs(delta.x) > width/2;      // or if slide amt is greater than half the width

				// determine if slide attempt is past start and end
				var isPastBounds =
							!index && delta.x > 0                            // if first slide and slide amt is greater than 0
							|| index == slides.length - 1 && delta.x < 0;    // or if last slide and slide amt is less than 0

				if (options.continuous) isPastBounds = false;

				// determine direction of swipe (true:right, false:left)
				var direction = delta.x < 0;

				// if not scrolling vertically
				if (!isScrolling) {

					if (isValidSlide && !isPastBounds) {

						if (direction) {

							if (options.continuous) { // we need to get the next in this direction in place

								move(circle(index-1), -width, 0);
								move(circle(index+2), width, 0);

							} else {
								move(index-1, -width, 0);
							}

							move(index, slidePos[index]-width, speed);
							move(circle(index+1), slidePos[circle(index+1)]-width, speed);
							index = circle(index+1);

						} else {
							if (options.continuous) { // we need to get the next in this direction in place

								move(circle(index+1), width, 0);
								move(circle(index-2), -width, 0);

							} else {
								move(index+1, width, 0);
							}

							move(index, slidePos[index]+width, speed);
							move(circle(index-1), slidePos[circle(index-1)]+width, speed);
							index = circle(index-1);

						}

						options.callback && options.callback(index, slides[index]);

					} else {

						if (options.continuous) {

							move(circle(index-1), -width, speed);
							move(index, 0, speed);
							move(circle(index+1), width, speed);

						} else {

							move(index-1, -width, speed);
							move(index, 0, speed);
							move(index+1, width, speed);
						}

					}

				}

				// kill touchmove and touchend event listeners until touchstart called again
				element.removeEventListener('touchmove', events, false);
				element.removeEventListener('touchend', events, false);

			},
			transitionEnd: function(event) {

				visibleThree(index, slides);

				if (parseInt(event.target.getAttribute('data-index'), 10) == index) {

					if (delay) begin();

					options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);

				}

			}

		};

		// trigger setup
		setup();

		// start auto slideshow if applicable
		if (delay) begin();

		// add event listeners
		if (browser.addEventListener) {

			// set touchstart event on element
			if (browser.touch) element.addEventListener('touchstart', events, false);

			if (browser.transitions) {
				element.addEventListener('webkitTransitionEnd', events, false);
				element.addEventListener('msTransitionEnd', events, false);
				element.addEventListener('oTransitionEnd', events, false);
				element.addEventListener('otransitionend', events, false);
				element.addEventListener('transitionend', events, false);
			}

			// set resize event on window
			window.addEventListener('resize', events, false);

		} else {

			window.onresize = function () { setup() }; // to play nice with old IE

		}

		// expose the Swipe API
		return {
			setup: function() {

				setup();

			},
			slide: function(to, speed) {

				// cancel slideshow
				stop();

				slide(to, speed);

			},
			prev: function() {

				// cancel slideshow
				stop();

				prev();

			},
			next: function() {

				// cancel slideshow
				stop();

				next();

			},
			getPos: function() {

				// return current index position
				return index + 1;

			},
			getNumSlides: function() {

				// return total number of slides
				return length;
			},
			kill: function() {

				// cancel slideshow
				stop();

				// reset element
				element.style.width = 'auto';
				element.style.left = 0;

				// reset slides
				var pos = slides.length;
				while(pos--) {

					var slide = slides[pos];
					slide.style.width = '100%';
					slide.style.left = 0;

					if (browser.transitions) translate(pos, 0, 0);

				}

				// removed event listeners
				if (browser.addEventListener) {

					// remove current event listeners
					element.removeEventListener('touchstart', events, false);
					element.removeEventListener('webkitTransitionEnd', events, false);
					element.removeEventListener('msTransitionEnd', events, false);
					element.removeEventListener('oTransitionEnd', events, false);
					element.removeEventListener('otransitionend', events, false);
					element.removeEventListener('transitionend', events, false);
					window.removeEventListener('resize', events, false);

				}
				else {

					window.onresize = null;

				}

			}
		};

	};

}<|endoftext|>