<commit_before>/*
 * Array utilities
 */

Array.prototype.compact = function() {
    var results = [];
    this.forEach(function(item) {
        item == null || item == undefined || results.push(item);
    });
    return results;
}

Array.prototype.detect = function(fn, thisObject) {
    for (var i = 0; i < this.length; i++)
        if (fn.call(thisObject, this[i], i, this))
            return this[i];
    return null;
}

Array.prototype.find = function(item) {
    for (var i = 0; i < this.length; i++)
        if (this[i] == item)
            return true;
    return false;
}

Array.prototype.contains = Array.prototype.find;

Array.prototype.invoke = function(name) {
    var result = new Array(this.length);
    var args = [].slice.call(arguments, 1);
    this.forEach(function(item, ix) {
        result[ix] = item[name].apply(item, args);
    });
    return result;
}

Array.prototype.pluck = function(name) {
    var result = new Array(this.length);
    this.forEach(function(item, ix) {
        result[ix] = item[name];
    });
    return result;
}

Array.prototype.select = function(fn, thisObject) {
    return this.filter(fn, thisObject);
}

Array.prototype.sum = function() {
    var sum = 0;
    this.forEach(function(n) {sum += n});
    return sum;
}

Array.prototype.without = function(item) {
    return this.filter(function(it) {
        return it != item;
    });
}

/*
 * Monadic Arrays
 */

Array.toList = function(ar) {
    return ar instanceof Array ? ar : [ar];
}

Array.fromList = function(ar) {
    return ar instanceof Array ? ar[0] : ar;
}

/*
 * JavaScript 1.6
 */

Array.prototype.indexOf = function(searchElement/*, fromIndex*/) {
    var len = this.length;
    for (var i = 0; i < len; i++)
        if (this[i] == searchElement)
            return i;
    return -1;
}

// lastIndexOf() - returns the index of the given item's last occurrence.

Array.prototype.every = function() {
    var len = this.length;
    for (var i = 0 ; i < len; i++)
        if (!fn.call(thisObject, this[i], i, this))
            return false;
    return true;
}

Array.prototype.some = function(fn, thisObject) {
    var len = this.length;
    for (var i = 0 ; i < len; i++)
        if (fn.call(thisObject, this[i], i, this))
            return true;
    return false;
}

Array.prototype.filter = function(fn, thisObject) {
    var len = this.length,
        results = [];
    for (var i = 0 ; i < len; i++)
        if (fn.call(thisObject, this[i], i, this))
            results.push(this[i]);
    return results;
}

Array.prototype.forEach = function(fn, thisObject) {
    var len = this.length;
    for (var i = 0 ; i < len; i++)
        if (typeof this[i] != 'undefined')
            fn.call(thisObject, this[i], i, this);
}

Array.prototype.map = function(fn, thisObject) {
    var len = this.length,
        result = new Array(len);
    for (var i = 0; i < len; i++)
        if (typeof this[i] != 'undefined')
            result[i] = fn.call(thisObject, this[i], i, this);
    return result;
}

/*
 * Prototype synonyms
 */

Array.prototype.each = Array.prototype.forEach;

/*
 * Hash utilities
 */

function $H(data) {
    return {
        each: function() {return Hash.each(data)},
        keys: function() {return Hash.keys(data)},
        merge: function(other) {return Hash.merge(data, other)},
        toQueryString: function() {return Hash.toQueryString(data)},
        values: function() {return Hash.values(data)}
    };
}

var Hash = {};

Hash.each = function(hash, fn) {
    for (var key in hash)
        fn(key, hash[key]);
}

Hash.keys = function(hash) {
    var keys = [];
    Hash.each(hash, function(key) {
        keys.push(key);
    });
    return keys;
}

Hash.merge = function(target, source) {
    for (var key in source)
        target[key] = source[key];
    return target;
}

Hash.toQueryString = function(hash) {
    var words = [];
    for (name in hash) {
        var value = hash[name];
        typeof value == 'function' ||
            words.push([name, '=', LzBrowser.urlEscape(value)].join(''));
    }
    words.sort();
    return words.join('&');
}

Hash.values = function(hash) {
    var values = [];
    Hash.each(hash, function(_, value) {
        values.push(value);
    });
    return values;
}

/*
 * String utilities
 */

String.prototype.escapeHTML = function() {
    return (this.replace('&', '&')
            .replace('<', '<')
            .replace('>', '>')
            .replace('"', '"'));
}

String.prototype.pluralize = function(count) {
    if (arguments.length && count == 1)
        return this;
    return this+'s';
}

// +pattern+ is required to be a string; there's therefore really no point in
// accepting a Function for +sub+.
String.prototype.replace = String.prototype['replace'] || function(pattern, sub) {
    var splits = this.split(pattern);
    var spans = new Array(splits.length*2-1);
    for (var i = 0, dst = 0; i < splits.length; i++) {
        i && (spans[dst++] = sub);
        spans[dst++] = splits[i];
    }
    return spans.join('');
}

String.prototype.strip = function() {
    var ws = " \t\n\r";
    for (j = this.length; --j >= 0 && ws.indexOf(this.charAt(j)) >= 0; )
        ;
    for (i = 0; i < j && ws.indexOf(this.charAt(i)) >= 0; i++)
        ;
    return 0 == i && j == this.length-1 ? this : this.slice(i, j+1);
}

String.prototype.truncate = function(length, ellipsis) {
    return (this.length <= length
            ? string
            : string.slice(0, length) + ellipsis);
}<commit_msg>add String.inflect, capitalize<commit_after>/*
 * Array utilities
 */

Array.prototype.compact = function() {
    var results = [];
    this.forEach(function(item) {
        item == null || item == undefined || results.push(item);
    });
    return results;
}

Array.prototype.detect = function(fn, thisObject) {
    for (var i = 0; i < this.length; i++)
        if (fn.call(thisObject, this[i], i, this))
            return this[i];
    return null;
}

Array.prototype.find = function(item) {
    for (var i = 0; i < this.length; i++)
        if (this[i] == item)
            return true;
    return false;
}

Array.prototype.contains = Array.prototype.find;

Array.prototype.invoke = function(name) {
    var result = new Array(this.length);
    var args = [].slice.call(arguments, 1);
    this.forEach(function(item, ix) {
        result[ix] = item[name].apply(item, args);
    });
    return result;
}

Array.prototype.pluck = function(name) {
    var result = new Array(this.length);
    this.forEach(function(item, ix) {
        result[ix] = item[name];
    });
    return result;
}

Array.prototype.select = function(fn, thisObject) {
    return this.filter(fn, thisObject);
}

Array.prototype.sum = function() {
    var sum = 0;
    this.forEach(function(n) {sum += n});
    return sum;
}

Array.prototype.without = function(item) {
    return this.filter(function(it) {
        return it != item;
    });
}

/*
 * Monadic Arrays
 */

Array.toList = function(ar) {
    return ar instanceof Array ? ar : [ar];
}

Array.fromList = function(ar) {
    return ar instanceof Array ? ar[0] : ar;
}

/*
 * JavaScript 1.6
 */

Array.prototype.indexOf = function(searchElement/*, fromIndex*/) {
    var len = this.length;
    for (var i = 0; i < len; i++)
        if (this[i] == searchElement)
            return i;
    return -1;
}

// lastIndexOf() - returns the index of the given item's last occurrence.

Array.prototype.every = function() {
    var len = this.length;
    for (var i = 0 ; i < len; i++)
        if (!fn.call(thisObject, this[i], i, this))
            return false;
    return true;
}

Array.prototype.some = function(fn, thisObject) {
    var len = this.length;
    for (var i = 0 ; i < len; i++)
        if (fn.call(thisObject, this[i], i, this))
            return true;
    return false;
}

Array.prototype.filter = function(fn, thisObject) {
    var len = this.length,
        results = [];
    for (var i = 0 ; i < len; i++)
        if (fn.call(thisObject, this[i], i, this))
            results.push(this[i]);
    return results;
}

Array.prototype.forEach = function(fn, thisObject) {
    var len = this.length;
    for (var i = 0 ; i < len; i++)
        if (typeof this[i] != 'undefined')
            fn.call(thisObject, this[i], i, this);
}

Array.prototype.map = function(fn, thisObject) {
    var len = this.length,
        result = new Array(len);
    for (var i = 0; i < len; i++)
        if (typeof this[i] != 'undefined')
            result[i] = fn.call(thisObject, this[i], i, this);
    return result;
}

/*
 * Prototype synonyms
 */

Array.prototype.each = Array.prototype.forEach;

/*
 * Hash utilities
 */

function $H(data) {
    return {
        each: function() {return Hash.each(data)},
        keys: function() {return Hash.keys(data)},
        merge: function(other) {return Hash.merge(data, other)},
        toQueryString: function() {return Hash.toQueryString(data)},
        values: function() {return Hash.values(data)}
    };
}

var Hash = {};

Hash.each = function(hash, fn) {
    for (var key in hash)
        fn(key, hash[key]);
}

Hash.keys = function(hash) {
    var keys = [];
    Hash.each(hash, function(key) {
        keys.push(key);
    });
    return keys;
}

Hash.merge = function(target, source) {
    for (var key in source)
        target[key] = source[key];
    return target;
}

Hash.toQueryString = function(hash) {
    var words = [];
    for (name in hash) {
        var value = hash[name];
        typeof value == 'function' ||
            words.push([name, '=', LzBrowser.urlEscape(value)].join(''));
    }
    words.sort();
    return words.join('&');
}

Hash.values = function(hash) {
    var values = [];
    Hash.each(hash, function(_, value) {
        values.push(value);
    });
    return values;
}

/*
 * String utilities
 */

String.prototype.capitalize = function() {
    return this.slice(0,1).toUpperCase() + this.slice(1);
}

String.prototype.escapeHTML = function() {
    return (this.replace('&', '&')
            .replace('<', '<')
            .replace('>', '>')
            .replace('"', '"'));
}

String.prototype.inflect = function(suffix) {
    var index = this.indexOf(' ');
    if (index >= 0)
        return this.slice(0, index).inflect(suffix) + this.slice(index);
    // pos == 'v', or vp has single word
    var inflections = {'ed': {'set': 'set'}};
    var key = this.toLowerCase();
    var value = (inflections[suffix]||{})[key];
    if (!value) {
        value = key;
        var lastChar = key.charAt(key.length-1);
        info(0, key);
        switch (lastChar) {
        case 'y':
            if (suffix == 'ed')
                value = value.slice(0, value.length-1) + 'i';
            break;
        case 'e':
            value = value.slice(0, value.length-1);
            break;
        }
        if (key == value &&
            "aeiou".indexOf(value.charAt(value.length-1)) < 0 &&
            "aeiou".indexOf(value.charAt(value.length-2)) >= 0)
            value += value.charAt(value.length-1);
        value += suffix;
    }
    // TODO: capitalize
    return value;
}

String.prototype.pluralize = function(count) {
    if (arguments.length && count == 1)
        return this;
    return this+'s';
}

// +pattern+ is required to be a string; there's therefore really no point in
// accepting a Function for +sub+.
String.prototype.replace = String.prototype['replace'] || function(pattern, sub) {
    var splits = this.split(pattern);
    var spans = new Array(splits.length*2-1);
    for (var i = 0, dst = 0; i < splits.length; i++) {
        i && (spans[dst++] = sub);
        spans[dst++] = splits[i];
    }
    return spans.join('');
}

String.prototype.strip = function() {
    var ws = " \t\n\r";
    for (j = this.length; --j >= 0 && ws.indexOf(this.charAt(j)) >= 0; )
        ;
    for (i = 0; i < j && ws.indexOf(this.charAt(i)) >= 0; i++)
        ;
    return 0 == i && j == this.length-1 ? this : this.slice(i, j+1);
}

String.prototype.truncate = function(length, ellipsis) {
    return (this.length <= length
            ? string
            : string.slice(0, length) + ellipsis);
}

<|endoftext|>


<commit_before>const gulp  = require('gulp');
const glob  = require('glob');
const Mocha = require('mocha');
const $     = require('./_shared');

/**
 * Clear cached module to enable to re-require the module.
 * @param {string} path - The module path.
 * @return {void}
 */
function clearModuleCache(path) {
  delete require.cache[path];
}

/**
 * Run tests by mocha.
 * @param {string} pattern - The pattern of test files.
 * @param {Object} options - The options passed to mocha.
 * @return {Promise} Will be resolved after running all tests.
 *     The argument is an exit code. If any runtime errors occured,
 *     this promise will be rejected.
 */
function runTests(pattern, options) {
  const mocha = new Mocha(options);
  const files = glob.sync(pattern, { realpath: true });
  files.forEach(file => {
    clearModuleCache(file);  // For watching
    mocha.addFile(file);
  });
  return new Promise((resolve, reject) => {
    try {
      mocha.run(resolve);
    } catch(e) {
      reject(e);
    }
  });
}

gulp.task('test:all', [
  'lint:all',
  'test:dest'
]);

// Test pre-transpiled sources directly.
gulp.task('test', ['test:prepare'], () => {
  return runTests($.GLOB.spec)
    .then(exitCode => process.exit(exitCode))
    .catch(e => { throw e; });
});

// Test transpiled sources.
gulp.task('test:dest', ['build', 'test:prepare:dest'], () => {
  return runTests($.GLOB.spec)
    .then(exitCode => process.exit(exitCode))
    .catch(e => { throw e; });
});

gulp.task('test:watch', ['test:prepare'], () => {
  function test() {
    runTests($.GLOB.spec, { reporter: 'dot' })
      .catch(e => console.log(e.stack));
  }

  gulp.watch($.GLOB.src, event => {
    clearModuleCache(event.path);
    test();
  });
  $.runAndWatch($.GLOB.test, null, () => test());
});

gulp.task('test:prepare', () => {
  registerBabelHook({
    plugins: [
      moduleAliasPlugin({ '$src': $.PATH.src })
    ]
  });
  loadTestHelpers();
});

gulp.task('test:prepare:dest', () => {
  registerBabelHook({
    plugins: [
      moduleAliasPlugin({ '$src': $.PATH.dest })
    ]
  });
  loadTestHelpers();
});

function loadTestHelpers() {
  require(`${$.root}/test/mocha-env`);
}

function registerBabelHook(options) {
  require('babel-core/register')(options || {});
}

function moduleAliasPlugin(modules) {
  const options = Object.keys(modules).map(alias => {
    return { src: modules[alias], expose: alias };
  });
  return ['module-alias', options];
}
<commit_msg>chore(gulp): Reload all sources everytime in 'test:watch'<commit_after>const gulp  = require('gulp');
const glob  = require('glob');
const Mocha = require('mocha');
const $     = require('./_shared');

/**
 * Clear cached module to enable to re-require the module.
 * @param {string} path - The module path.
 * @return {void}
 */
function clearModuleCache(path) {
  delete require.cache[path];
}

/**
 * Run tests by mocha.
 * @param {string} pattern - The pattern of test files.
 * @param {Object} options - The options passed to mocha.
 * @return {Promise} Will be resolved after running all tests.
 *     The argument is an exit code. If any runtime errors occured,
 *     this promise will be rejected.
 */
function runTests(pattern, options) {
  const mocha = new Mocha(options);
  const files = glob.sync(pattern, { realpath: true });
  files.forEach(file => {
    clearModuleCache(file);  // For watching
    mocha.addFile(file);
  });
  return new Promise((resolve, reject) => {
    try {
      mocha.run(resolve);
    } catch(e) {
      reject(e);
    }
  });
}

gulp.task('test:all', [
  'lint:all',
  'test:dest'
]);

// Test pre-transpiled sources directly.
gulp.task('test', ['test:prepare'], () => {
  return runTests($.GLOB.spec)
    .then(exitCode => process.exit(exitCode))
    .catch(e => { throw e; });
});

// Test transpiled sources.
gulp.task('test:dest', ['build', 'test:prepare:dest'], () => {
  return runTests($.GLOB.spec)
    .then(exitCode => process.exit(exitCode))
    .catch(e => { throw e; });
});

gulp.task('test:watch', ['test:prepare'], () => {
  function test() {
    runTests($.GLOB.spec, { reporter: 'dot' })
      .catch(e => console.log(e.stack));
  }

  const sourceFiles = glob.sync($.GLOB.src, { realpath: true });
  gulp.watch($.GLOB.src, () => {
    // Reload all source files.If we refresh only the changed file,
    // the files required in it don't be refreshed.
    sourceFiles.forEach(f => clearModuleCache(f));
    test();
  });
  $.runAndWatch($.GLOB.test, null, () => test());
});

gulp.task('test:prepare', () => {
  registerBabelHook({
    plugins: [
      moduleAliasPlugin({ '$src': $.PATH.src })
    ]
  });
  loadTestHelpers();
});

gulp.task('test:prepare:dest', () => {
  registerBabelHook({
    plugins: [
      moduleAliasPlugin({ '$src': $.PATH.dest })
    ]
  });
  loadTestHelpers();
});

function loadTestHelpers() {
  require(`${$.root}/test/mocha-env`);
}

function registerBabelHook(options) {
  require('babel-core/register')(options || {});
}

function moduleAliasPlugin(modules) {
  const options = Object.keys(modules).map(alias => {
    return { src: modules[alias], expose: alias };
  });
  return ['module-alias', options];
}
<|endoftext|>


<commit_before>/**
 * @file WidgetHeader component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';

class WidgetHeader extends Component {

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    render() {

        const {children, className, style, title} = this.props;

        return (
            <div className={`widget-header ${className}`}
                 style={style}>

                {title}

                    {children}

        );

    }
};

WidgetHeader.propTypes = {

    className: PropTypes.string,
    style: PropTypes.object,

    title: PropTypes.any

};

WidgetHeader.defaultProps = {

    className: '',
    style: null,

    title: ''

};

export default WidgetHeader;<commit_msg>update WidgetHeader<commit_after>/**
 * @file WidgetHeader component
 * @author liangxiaojun(liangxiaojun@derbysoft.com)
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

class WidgetHeader extends Component {

    constructor(props, ...restArgs) {
        super(props, ...restArgs);
    }

    render() {

        const {children, className, style, title} = this.props,

            headerClassName = classNames('widget-header', {
                [className]: className
            });

        return (

                {title}

                    {children}

        );

    }
};

WidgetHeader.propTypes = {

    className: PropTypes.string,
    style: PropTypes.object,

    title: PropTypes.any

};

WidgetHeader.defaultProps = {

    className: '',
    style: null,

    title: ''

};

export default WidgetHeader;<|endoftext|>


<commit_before>module.exports = [
	"Amer CREDI",
	"Alain DECY",
	"Alain STANMEM",
	"Alain VERSE",
	"Alex CEPTION",
	"Alonzo BALMASKER",
	"Alphonse PATAMOB",
	"Axel AIRE",
	"Denis DIRON-DAYLE",
	"Élie COPTERE",
	"Gaspard ALIZAN",
	"Géo GRAFF",
	"Harry COVER",
	"Henri COCHET",
	"Henri HENCOR",
	"Henri STOURNE",
	"Jacques CELAIR",
	"Jean AIMAR",
	"Jean TANRIEN",
	"John DEUFF",
	"José PALDIR",
	"Justin PTIPEU",
	"Karl AJUMIDE",
	"Larry GOLADE",
	"Laurent DEVOUX",
	"Louis FINE",
	"Luc SURIEUX",
	"Marc ASSIN",
	"Otto GRAF",
	"Paul ISSIER",
	"Pierre KIROUL",
	"Régis CIDE",
	"Sacha HUTTE",
	"Sacha TOUILLE",
	"Théo JASMIN",
	"Xavier KAFAIRGAF",
	"Yann AKEPOURLUI"
];
<commit_msg>Update funnyNamesM.js<commit_after>module.exports = [
	"Amer CREDI",
	"Alain DECY",
	"Alain STANMEM",
	"Alain VERSE",
	"Alex CEPTION",
	"Alonzo BALMASKER",
	"Alphonse PATAMOB",
	"Axel AIRE",
	"Denis DIRON-DAYLE",
	"Élie COPTERE",
	"Gaspard ALIZAN",
	"Géo GRAFF",
	"Harry COVER",
	"Henri COCHET",
	"Henri HENCOR",
	"Henri STOURNE",
	"Jacques CELAIR",
	"Jean AIMAR",
	"Jean TANRIEN",
	"John DEUFF",
	"José PALDIR",
	"Justin PTIPEU",
	"Karl AJUMIDE",
	"Larry GOLADE",
	"Laurent DEVOUX",
	"Louis FINE",
	"Luc SURIEUX",
	"Marc ASSIN",
	"Otto GRAF",
	"Paul ISSIER",
	"Pierre KIROUL",
	"Régis CIDE",
	"Sacha HUTTE",
	"Sacha TOUILLE",
	"Théo JASMIN",
	"Xavier KAFAIRGAF",
	"Yann AKEPOURLUI",
	"Jean PEUPLUT"
];
<|endoftext|>


<commit_before>process.env.NODE_ENV = 'test';

var chai = require('chai');
var chaiHttp = require('chai-http');
var mongoose = require('mongoose-q')(require('mongoose'));
var passportStub = require('passport-stub');

var app = require('../../src/server/app');
var Product = require('../../src/server/models/product.js');
var should = chai.should();

chai.use(chaiHttp);

describe('charge.js Routes', function(){

  before(function(done) {

    mongoose.connection.db.dropDatabase();

    var product = new Product({
      name: 'Coconut Water',
      amount: 5,
      currency: 'USD',
      forSale: true
    });

    product.saveQ()
    .then(function(){
      done();
    });

  });

  after(function(done) {
    mongoose.connection.db.dropDatabase();
    done();
  });

  describe('GET /stripe', function(){
    it('should return a view', function(done){
      chai.request(app)
      .get('/stripe')
      .end(function(err, res){
        res.should.have.status(200);
        res.should.be.html;  // jshint ignore:line
        res.text.should.contain.string('Scram!');
        done();
      });
    });
  });

  // describe('GET /products', function(){
  //   it('should return a view', function(done){
  //     chai.request(app)
  //     .get('/products')
  //     .end(function(err, res){
  //       res.should.have.status(200);
  //       res.should.be.html;  // jshint ignore:line
  //       res.text.should.contain.string('Coconut Water');
  //       done();
  //     });
  //   });
  // });

  describe('GET /product/:id', function(){
    it('should return a view', function(done){
      Product.findOne({}, function (err, results) {
        var productID = results._id;
        var productPrice = results.amount;
        chai.request(app)
        .get('/product/'+productID)
        .end(function(err, res){
          res.should.have.status(200);
          res.should.be.html;  // jshint ignore:line
          res.text.should.contain.string('Coconut Water');
          res.text.should.contain.string(productPrice);
          done();
        });
      });
    });
  });

  // describe('GET /charge', function(){
  //   it('should redirect if user is not logged in', function(done){
  //     Product.findOne({}, function (err, results) {
  //       var productID = results._id;
  //       chai.request(app)
  //       .get('/charge/' + productID)
  //       .end(function(err, res){
  //         res.should.have.status(200);
  //         res.redirects[0].should.contain('/auth/login');
  //         res.text.should.contain('
Login
\n');
  //         done();
  //       });
  //     });
  //   });
  // });

});

<commit_msg>increased test time<commit_after>process.env.NODE_ENV = 'test';

var chai = require('chai');
var chaiHttp = require('chai-http');
var mongoose = require('mongoose-q')(require('mongoose'));
var passportStub = require('passport-stub');

var app = require('../../src/server/app');
var Product = require('../../src/server/models/product.js');
var should = chai.should();

chai.use(chaiHttp);

describe('charge.js Routes', function(){

  before(function(done) {

    mongoose.connection.db.dropDatabase();

    var product = new Product({
      name: 'Coconut Water',
      amount: 5,
      currency: 'USD',
      forSale: true
    });

    product.saveQ()
    .then(function(){
      done();
    });

  });

  after(function(done) {
    mongoose.connection.db.dropDatabase();
    done();
  });

  describe('GET /stripe', function(){
    it('should return a view', function(done){
      chai.request(app)
      .get('/stripe')
      .end(function(err, res){
        res.should.have.status(200);
        res.should.be.html;  // jshint ignore:line
        res.text.should.contain.string('Scram!');
        done();
      });
    });
  });

  // describe('GET /products', function(){
  //   it('should return a view', function(done){
  //     chai.request(app)
  //     .get('/products')
  //     .end(function(err, res){
  //       res.should.have.status(200);
  //       res.should.be.html;  // jshint ignore:line
  //       res.text.should.contain.string('Coconut Water');
  //       done();
  //     });
  //   });
  // });

  // describe('GET /product/:id', function(){
  //   it('should return a view', function(done){
  //     Product.findOne({}, function (err, results) {
  //       var productID = results._id;
  //       var productPrice = results.amount;
  //       chai.request(app)
  //       .get('/product/'+productID)
  //       .end(function(err, res){
  //         res.should.have.status(200);
  //         res.should.be.html;  // jshint ignore:line
  //         res.text.should.contain.string('Coconut Water');
  //         res.text.should.contain.string(productPrice);
  //         done();
  //       });
  //     });
  //   });
  // });

  // describe('GET /charge', function(){
  //   it('should redirect if user is not logged in', function(done){
  //     Product.findOne({}, function (err, results) {
  //       var productID = results._id;
  //       chai.request(app)
  //       .get('/charge/' + productID)
  //       .end(function(err, res){
  //         res.should.have.status(200);
  //         res.redirects[0].should.contain('/auth/login');
  //         res.text.should.contain('
Login
\n');
  //         done();
  //       });
  //     });
  //   });
  // });

});

<|endoftext|>


<commit_before>"use strict";

var
    esPhinx;

(function ($module) {

    const
        CSS_CLASS = "esphinx ui",
        CSS_CLASS_QUERY = "." + CSS_CLASS.replace(/ +/g, ".");

    var
        $ = esPhinx;

    $module.extend({

        panels: {

            autocomplete: {

                // new: function (searchTextBox, originalList, options,
                //     callback) {
                new: function (searchTextBox, originalList, options = {},
                    callback) {
                    var
                        ConstructorReference = $module.panels.autocomplete.new,
                        self = this,
                        nodeListFound,
                        referenceNode,
                        created = false,

                        spanize = function (mapped) {
                            var
                                spanizedSliceFound;

                            Object.keys(mapped).forEach(function (i) {
                                spanizedSliceFound = $("");
                                spanizedSliceFound
                                    .addClass(CSS_CLASS + " slice-found");
                                spanizedSliceFound.text(mapped[i]);
                                mapped[i] = spanizedSliceFound;
                            });

                            return mapped;
                        },

                        resolveAnswer = function (found, maps) {
                            var
                                resolved = $(),
                                composed,
                                tagName = found.tagName().toLowerCase(),
                                nodeText,
                                nodeTextAsArr,
                                mapped;

                            found.each(function (node, i) {
                                nodeText = $(node).text().toLowerCase().trim();
                                nodeTextAsArr = nodeText.split(" ");
                                mapped = spanize(maps[i]);
                                composed = composeMatch(mapped, nodeText,
                                    nodeTextAsArr);
                                resolved.concat(true, composeName(composed,
                                    node));
                            });

                            return resolved;
                        },

                        composeMatch = function (mapped, nodeText,
                            nodeTextAsArr) {
                            var
                                composedArr = [],
                                leftUnitName,
                                rightUnitName,
                                searchIndex,
                                sliceFound,
                                itemAsLower,
                                span;

                            nodeTextAsArr.spaceOut().capitalize()
                            .forEach(function (value, i) {
                                if (mapped.hasOwnProperty(i)) {
                                    span = mapped[i];
                                    itemAsLower = value.toLowerCase();
                                    sliceFound = span.text();
                                    searchIndex = itemAsLower
                                        .search(sliceFound);
                                    leftUnitName = itemAsLower
                                        .slice(0, searchIndex);
                                    rightUnitName = itemAsLower
                                        .slice(searchIndex + sliceFound.length,
                                        itemAsLower.length);

                                    if (!leftUnitName.empty()) {
                                        composedArr
                                            .push(capitalizeIf(leftUnitName,
                                            nodeText));
                                    } else {
                                        span.text(capitalizeIf(span.text(),
                                            nodeText));
                                    }

                                    composedArr.push(span.asNode());

                                    if (!rightUnitName.empty()) {
                                        composedArr.push(rightUnitName);
                                    }
                                } else {
                                    composedArr.push(value);
                                }

                            });

                            return composedArr;
                        },

                        capitalizeIf = function (word, nodeText) {
                            var
                                searchIndex;

                            searchIndex = nodeText.toLowerCase().trim()
                                .search(word);

                            if (searchIndex >= 0) {
                                return word.capitalize();
                            } else {
                                return word;
                            }
                        },

                        composeName = function (composedArr, node) {
                            var
                                copy = $(node).clone();

                            composedArr.forEach(function (v) {
                                copy.append(v);
                            });

                            return copy;
                        },

                        create = function (referenceNode) {
                            var
                                nodeListFound = $("

")
                                    .addClass(CSS_CLASS + " list-built-found"),
                                width,
                                borderBottom,
                                border,
                                marginBottom,

                                hitTarget = function (target) {
                                    if (target
                                        .is(nodeListFound.childElements())
                                        || target.is(referenceNode)) {
                                        return true;
                                    }
                                    return false;
                                };

                            if (referenceNode.instanceOf(HTMLInputElement)) {

                                // referenceNode.on("blur", function (e) {
                                //     var
                                //         selection = document.getSelection(),
                                //         focused = document.getSelection()
                                //             .focusNode;

                                //     if (!focused.instanceOf(HTMLInputElement)
                                //     && !focused.constructorIs(HTMLLIElement)) {
                                //         focused = focused
                                //             .parent("ol" + CSS_CLASS_QUERY
                                //             + ".list-built-found li");
                                //     }
                                //     // relatedTarget still doesn't work in FF
                                //     // self.hide();
                                // });

                                $(document).on("mouseup", function (e) {
                                    var
                                        target = $(e.target);

                                    if (!target.instanceOf(HTMLInputElement)
                                        && !target
                                            .constructorIs(HTMLLIElement)) {
                                        target = target
                                            .parent("ol" + CSS_CLASS_QUERY
                                            + ".list-built-found li");
                                    }

                                    if (!hitTarget(target)) {
                                        self.hide();
                                    } else if (target
                                        .constructorIs(HTMLLIElement)) {
                                        if (target.hasClass("selected")) {
                                            target.removeClass("selected");
                                        } else {
                                            target.addClass("selected");
                                        }
                                    }

                                });

                                referenceNode.on("keydown", function (e) {
                                    if (e.key == "Tab") {
                                        self.hide();
                                    }
                                });

                                referenceNode.on("focus", function () {
                                    if (nodeListFound.childElements().some()) {
                                        nodeListFound.show();
                                    }
                                });

                                marginBottom = referenceNode
                                    .css("margin-bottom");
                                width = referenceNode.width();
                                borderBottom = referenceNode
                                    .css("border-bottom");
                                border = referenceNode.css("border");

                                nodeListFound
                                    .css("margin-top", -marginBottom + "px");

                                // only after set width, otherwise doesn't can get your border
                                nodeListFound.insertAfter(referenceNode);
                                if (width) {
                                    nodeListFound.css("position", "absolute");
                                    // nodeListFound.width(width);
                                    nodeListFound.css("min-width", width);
                                }

                                nodeListFound.show();
                            } else {
                                nodeListFound.insertAfter(referenceNode);
                            }

                            return nodeListFound;
                        },

                        show = function (autocompletedList) {
                            nodeListFound.deflate();

                            if (searchTextBox.value()) {
                                if (originalList instanceof $) {
                                    originalList.hide();
                                }
                                // debugger
                                // whats criteria?
                                autocompletedList.each(function (li) {
                                    nodeListFound.append(li);
                                });

                                if (nodeListFound.childElements().some()) {
                                    nodeListFound.show();
                                } else {
                                    nodeListFound.hide();
                                }
                            } else {
                                if (originalList instanceof $) {
                                    originalList.show();
                                }
                                self.hide();
                            }

                            return nodeListFound.childElements();
                        };

                    if (!(this instanceof ConstructorReference)) {
                        return new ConstructorReference(searchTextBox,
                            originalList, options, callback);
                    }

                    if (Object.getPrototypeOf(originalList)
                        === Object.getPrototypeOf({})) {
                        referenceNode = searchTextBox;
                        callback = options;
                        options = undefined;
                    } else {
                        referenceNode = originalList;
                    }

                    searchTextBox.autocomplete(originalList, options,
                    function (found, mapped) {
                        var
                            resolvedAnswer;

                        if (!created) {
                            created = true;

                            nodeListFound = create(referenceNode);
                        }

                        if (!callback || !callback instanceof Function) {
                            callback = function () {};
                        }

                        resolvedAnswer = resolveAnswer(found, mapped);
                        callback.call(self, show(resolvedAnswer));
                    });

                    this.hide = function () {
                        nodeListFound.hide();
                    };

                }

            }

        }

    });

})(esPhinx.ui);
<commit_msg>adequation<commit_after>"use strict";

var
    esPhinx;

(function ($module) {

    const
        CSS_CLASS = "esphinx ui",
        CSS_CLASS_QUERY = "." + CSS_CLASS.replace(/ +/g, ".");

    var
        $ = esPhinx;

    $module.extend({

        panels: {

            autocomplete: {

                new: function (searchTextBox, originalList, options,
                    callback) {
                // new: function (searchTextBox, originalList, options = {},
                    // callback) {
                    var
                        ConstructorReference = $module.panels.autocomplete.new,
                        self = this,
                        nodeListFound,
                        referenceNode,
                        created = false,

                        spanize = function (mapped) {
                            var
                                spanizedSliceFound;

                            Object.keys(mapped).forEach(function (i) {
                                spanizedSliceFound = $("");
                                spanizedSliceFound
                                    .addClass(CSS_CLASS + " slice-found");
                                spanizedSliceFound.text(mapped[i]);
                                mapped[i] = spanizedSliceFound;
                            });

                            return mapped;
                        },

                        resolveAnswer = function (found, maps) {
                            var
                                resolved = $(),
                                composed,
                                tagName = found.tagName().toLowerCase(),
                                nodeText,
                                nodeTextAsArr,
                                mapped;

                            found.each(function (node, i) {
                                nodeText = $(node).text().toLowerCase().trim();
                                nodeTextAsArr = nodeText.split(" ");
                                mapped = spanize(maps[i]);
                                composed = composeMatch(mapped, nodeText,
                                    nodeTextAsArr);
                                resolved.concat(true, composeName(composed,
                                    node));
                            });

                            return resolved;
                        },

                        composeMatch = function (mapped, nodeText,
                            nodeTextAsArr) {
                            var
                                composedArr = [],
                                leftUnitName,
                                rightUnitName,
                                searchIndex,
                                sliceFound,
                                itemAsLower,
                                span;

                            nodeTextAsArr.spaceOut().capitalize()
                            .forEach(function (value, i) {
                                if (mapped.hasOwnProperty(i)) {
                                    span = mapped[i];
                                    itemAsLower = value.toLowerCase();
                                    sliceFound = span.text();
                                    searchIndex = itemAsLower
                                        .search(sliceFound);
                                    leftUnitName = itemAsLower
                                        .slice(0, searchIndex);
                                    rightUnitName = itemAsLower
                                        .slice(searchIndex + sliceFound.length,
                                        itemAsLower.length);

                                    if (!leftUnitName.empty()) {
                                        composedArr
                                            .push(capitalizeIf(leftUnitName,
                                            nodeText));
                                    } else {
                                        span.text(capitalizeIf(span.text(),
                                            nodeText));
                                    }

                                    composedArr.push(span.asNode());

                                    if (!rightUnitName.empty()) {
                                        composedArr.push(rightUnitName);
                                    }
                                } else {
                                    composedArr.push(value);
                                }

                            });

                            return composedArr;
                        },

                        capitalizeIf = function (word, nodeText) {
                            var
                                searchIndex;

                            searchIndex = nodeText.toLowerCase().trim()
                                .search(word);

                            if (searchIndex >= 0) {
                                return word.capitalize();
                            } else {
                                return word;
                            }
                        },

                        composeName = function (composedArr, node) {
                            var
                                copy = $(node).clone();

                            composedArr.forEach(function (v) {
                                copy.append(v);
                            });

                            return copy;
                        },

                        create = function (referenceNode) {
                            var
                                nodeListFound = $("

")
                                    .addClass(CSS_CLASS + " list-built-found"),
                                width,
                                borderBottom,
                                border,
                                marginBottom,

                                hitTarget = function (target) {
                                    if (target
                                        .is(nodeListFound.childElements())
                                        || target.is(referenceNode)) {
                                        return true;
                                    }
                                    return false;
                                };

                            if (referenceNode.instanceOf(HTMLInputElement)) {

                                // referenceNode.on("blur", function (e) {
                                //     var
                                //         selection = document.getSelection(),
                                //         focused = document.getSelection()
                                //             .focusNode;

                                //     if (!focused.instanceOf(HTMLInputElement)
                                //     && !focused.constructorIs(HTMLLIElement)) {
                                //         focused = focused
                                //             .parent("ol" + CSS_CLASS_QUERY
                                //             + ".list-built-found li");
                                //     }
                                //     // relatedTarget still doesn't work in FF
                                //     // self.hide();
                                // });

                                $(document).on("mouseup", function (e) {
                                    var
                                        target = $(e.target);

                                    if (!target.instanceOf(HTMLInputElement)
                                        && !target
                                            .constructorIs(HTMLLIElement)) {
                                        target = target
                                            .parent("ol" + CSS_CLASS_QUERY
                                            + ".list-built-found li");
                                    }

                                    if (!hitTarget(target)) {
                                        self.hide();
                                    } else if (target
                                        .constructorIs(HTMLLIElement)) {
                                        if (target.hasClass("selected")) {
                                            target.removeClass("selected");
                                        } else {
                                            target.addClass("selected");
                                        }
                                    }

                                });

                                referenceNode.on("keydown", function (e) {
                                    if (e.key == "Tab") {
                                        self.hide();
                                    }
                                });

                                referenceNode.on("focus", function () {
                                    if (nodeListFound.childElements().some()) {
                                        nodeListFound.show();
                                    }
                                });

                                marginBottom = referenceNode
                                    .css("margin-bottom");
                                width = referenceNode.width();
                                borderBottom = referenceNode
                                    .css("border-bottom");
                                border = referenceNode.css("border");

                                nodeListFound
                                    .css("margin-top", -marginBottom + "px");

                                // only after set width, otherwise doesn't can get your border
                                nodeListFound.insertAfter(referenceNode);
                                if (width) {
                                    nodeListFound.css("position", "absolute");
                                    // nodeListFound.width(width);
                                    nodeListFound.css("min-width", width);
                                }

                                nodeListFound.show();
                            } else {
                                nodeListFound.insertAfter(referenceNode);
                            }

                            return nodeListFound;
                        },

                        show = function (autocompletedList) {
                            nodeListFound.deflate();

                            if (searchTextBox.value()) {
                                if (originalList instanceof $) {
                                    originalList.hide();
                                }
                                // debugger
                                // whats criteria?
                                autocompletedList.each(function (li) {
                                    nodeListFound.append(li);
                                });

                                if (nodeListFound.childElements().some()) {
                                    nodeListFound.show();
                                } else {
                                    nodeListFound.hide();
                                }
                            } else {
                                if (originalList instanceof $) {
                                    originalList.show();
                                }
                                self.hide();
                            }

                            return nodeListFound.childElements();
                        };

                    if (!(this instanceof ConstructorReference)) {
                        return new ConstructorReference(searchTextBox,
                            originalList, options, callback);
                    }

                    if (Object.getPrototypeOf(originalList)
                        === Object.getPrototypeOf({})) {
                        referenceNode = searchTextBox;
                        callback = options;
                        options = undefined;
                    } else {
                        referenceNode = originalList;
                    }

                    searchTextBox.autocomplete(originalList, options,
                    function (found, mapped) {
                        var
                            resolvedAnswer;

                        if (!created) {
                            created = true;

                            nodeListFound = create(referenceNode);
                        }

                        if (!callback || !callback instanceof Function) {
                            callback = function () {};
                        }

                        resolvedAnswer = resolveAnswer(found, mapped);
                        callback.call(self, show(resolvedAnswer));
                    });

                    this.hide = function () {
                        nodeListFound.hide();
                    };

                }

            }

        }

    });

})(esPhinx.ui);
<|endoftext|>


<commit_before>/* jshint strict: false */
/* globals configData */

/*
 * Doo reads this file from classpath runners/karma.conf.js
 * This sets up junit reporter.
 */

var path = require('path');

// Doo writes this file to /tmp, so can't use relative require directly
var logger = require(process.cwd() + '/node_modules/karma/lib/logger.js');

module.exports = function(config) {

  var suite = path.basename(process.cwd());

  // Hide two unncessary warnings
  logger.create('web-server', 'error');
  logger.create('watcher', 'error');

  configData.plugins = ['karma-*'];

  configData.logLevel = config.LOG_WARN;

  configData.reporters = ['dots', 'junit'];
  configData.junitReporter = {
    outputDir: (process.env.CIRCLE_TEST_REPORTS || 'junit'),
    outputFile: suite + '.xml',
    suite: suite, // suite will become the package name attribute in xml testsuite element
    useBrowserName: false // add browser name to report and classes names
  };

  config.set(configData);
};
<commit_msg>Remove Karma logger hack which doesn't work with 2.0<commit_after>/* jshint strict: false */
/* globals configData */

/*
 * Doo reads this file from classpath runners/karma.conf.js
 * This sets up junit reporter.
 */

var path = require('path');

module.exports = function(config) {

  var suite = path.basename(process.cwd());

  configData.plugins = ['karma-*'];

  configData.logLevel = config.LOG_WARN;

  configData.reporters = ['dots', 'junit'];
  configData.junitReporter = {
    outputDir: (process.env.CIRCLE_TEST_REPORTS || 'junit'),
    outputFile: suite + '.xml',
    suite: suite, // suite will become the package name attribute in xml testsuite element
    useBrowserName: false // add browser name to report and classes names
  };

  config.set(configData);
};
<|endoftext|>


<commit_before>/* @flow */
'use strict'

import Relay from 'react-relay'
import React from 'react'
import { StyleSheet, Dimensions, View, Text, TouchableWithoutFeedback, NativeModules } from 'react-native'
const { ARTemporaryAPIModule } = NativeModules

import Events from '../../../native_modules/events'

import SerifText from '../../text/serif'
import colors from '../../../../data/colors'
import Button from '../../buttons/inverted_button'
import fragments from './relay_fragments'
import SectionTitle from '../section_title'

const isPad = Dimensions.get('window').width > 700

const additionalContentRails = [
  'followed_artists',
  'saved_works',
  'live_auctions',
  'current_fairs',
  'genes',
  'generic_gene',
]

class ArtworkRailHeader extends React.Component {
  state: {
    following: boolean
  };

  constructor(props) {
    super(props)

    let following = false
    console.log('props.rail.key', props.rail.key )
    if (props.rail.key === 'followed_artist') {
      following = true
    }

    this.state = { following: following }
  }

  render() {
    return (
      <TouchableWithoutFeedback onPress={this.props.handleViewAll}>
        <View style={styles.container}>
          { this.props.rail.context && this.followAnnotation() }
          <SectionTitle>
          { this.props.rail.title }
          </SectionTitle>
          { this.actionButton() }
        </View>
      </TouchableWithoutFeedback>
    )
  }

  followAnnotation() {
    if (this.props.rail.key === 'related_artists') {
      return <SerifText style={styles.followAnnotation}>{ 'Based on ' + this.props.rail.context.based_on.name }</SerifText>
    }
  }

  hasAdditionalContent() {
    const moduleKey = this.props.rail.key
    return additionalContentRails.indexOf(moduleKey) > -1
  }

  actionButton() {
    if (this.hasAdditionalContent()) {
      return <Text style={styles.viewAllButton}> { 'View All'.toUpperCase() } </Text>
    } else if (this.props.rail.key === 'related_artists' || this.props.rail.key === 'followed_artist') {
        return (
          <View style={styles.followButton}>
            <Button text={this.state.following ? 'Following' : 'Follow'}
                    selected={this.state.following}
                    onPress={this.handleFollowChange} />
          </View>
        )
    }
  }

  handleFollowChange = () => {
    const context = this.props.rail.context
    ARTemporaryAPIModule.setFollowArtistStatus(!this.state.following, context.artist.id, (error, following) => {
      if (error) {
        console.error(error)
      } else {
        Events.postEvent(this, {
          name: following ? 'Follow artist' : 'Unfollow artist',
          artist_id: context.artist.id,
          artist_slug: context.artist.id,
          source_screen: 'artist page',
        })
      }
      this.setState({ following: following })
    })
  }
}

const styles = StyleSheet.create({
  container: {
    marginTop: isPad ? 50 : 40,
    marginBottom: 20,
    marginLeft: 30,
    marginRight: 30,
  },
  title: {
    marginTop: 10,
    fontSize: isPad ? 30 : 26,
    alignSelf: 'center',
    textAlign: 'center',
  },
  viewAllButton: {
    fontFamily: 'Avant Garde Gothic ITCW01Dm',
    fontSize: isPad ? 14 : 12,
    color: colors['gray-medium'],
    textAlign: 'center',
    letterSpacing: 0.5,
  },
  followButton: {
    marginTop: 10,
    marginBottom: 0,
    alignSelf: 'center',
    height: 30,
    width: 90,
  },
  followAnnotation: {
    fontStyle: 'italic',
    alignSelf: 'center',
    fontSize: 16,
  }
})

export default Relay.createContainer(ArtworkRailHeader, {
  fragments: {
    rail: () => Relay.QL`
      fragment on HomePageArtworkModule {
        title
        key
        context {
          ${fragments.relatedArtistFragment}
          ${fragments.geneFragment}
          ${fragments.auctionFragment}
          ${fragments.fairFragment}
          ${fragments.followedArtistFragment}
        }
      }
    `,
  }
})
<commit_msg>Remove console<commit_after>/* @flow */
'use strict'

import Relay from 'react-relay'
import React from 'react'
import { StyleSheet, Dimensions, View, Text, TouchableWithoutFeedback, NativeModules } from 'react-native'
const { ARTemporaryAPIModule } = NativeModules

import Events from '../../../native_modules/events'

import SerifText from '../../text/serif'
import colors from '../../../../data/colors'
import Button from '../../buttons/inverted_button'
import fragments from './relay_fragments'
import SectionTitle from '../section_title'

const isPad = Dimensions.get('window').width > 700

const additionalContentRails = [
  'followed_artists',
  'saved_works',
  'live_auctions',
  'current_fairs',
  'genes',
  'generic_gene',
]

class ArtworkRailHeader extends React.Component {
  state: {
    following: boolean
  };

  constructor(props) {
    super(props)

    let following = false
    if (props.rail.key === 'followed_artist') {
      following = true
    }

    this.state = { following: following }
  }

  render() {
    return (
      <TouchableWithoutFeedback onPress={this.props.handleViewAll}>
        <View style={styles.container}>
          { this.props.rail.context && this.followAnnotation() }
          <SectionTitle>
          { this.props.rail.title }
          </SectionTitle>
          { this.actionButton() }
        </View>
      </TouchableWithoutFeedback>
    )
  }

  followAnnotation() {
    if (this.props.rail.key === 'related_artists') {
      return <SerifText style={styles.followAnnotation}>{ 'Based on ' + this.props.rail.context.based_on.name }</SerifText>
    }
  }

  hasAdditionalContent() {
    const moduleKey = this.props.rail.key
    return additionalContentRails.indexOf(moduleKey) > -1
  }

  actionButton() {
    if (this.hasAdditionalContent()) {
      return <Text style={styles.viewAllButton}> { 'View All'.toUpperCase() } </Text>
    } else if (this.props.rail.key === 'related_artists' || this.props.rail.key === 'followed_artist') {
        return (
          <View style={styles.followButton}>
            <Button text={this.state.following ? 'Following' : 'Follow'}
                    selected={this.state.following}
                    onPress={this.handleFollowChange} />
          </View>
        )
    }
  }

  handleFollowChange = () => {
    const context = this.props.rail.context
    ARTemporaryAPIModule.setFollowArtistStatus(!this.state.following, context.artist.id, (error, following) => {
      if (error) {
        console.error(error)
      } else {
        Events.postEvent(this, {
          name: following ? 'Follow artist' : 'Unfollow artist',
          artist_id: context.artist.id,
          artist_slug: context.artist.id,
          source_screen: 'artist page',
        })
      }
      this.setState({ following: following })
    })
  }
}

const styles = StyleSheet.create({
  container: {
    marginTop: isPad ? 50 : 40,
    marginBottom: 20,
    marginLeft: 30,
    marginRight: 30,
  },
  title: {
    marginTop: 10,
    fontSize: isPad ? 30 : 26,
    alignSelf: 'center',
    textAlign: 'center',
  },
  viewAllButton: {
    fontFamily: 'Avant Garde Gothic ITCW01Dm',
    fontSize: isPad ? 14 : 12,
    color: colors['gray-medium'],
    textAlign: 'center',
    letterSpacing: 0.5,
  },
  followButton: {
    marginTop: 10,
    marginBottom: 0,
    alignSelf: 'center',
    height: 30,
    width: 90,
  },
  followAnnotation: {
    fontStyle: 'italic',
    alignSelf: 'center',
    fontSize: 16,
  }
})

export default Relay.createContainer(ArtworkRailHeader, {
  fragments: {
    rail: () => Relay.QL`
      fragment on HomePageArtworkModule {
        title
        key
        context {
          ${fragments.relatedArtistFragment}
          ${fragments.geneFragment}
          ${fragments.auctionFragment}
          ${fragments.fairFragment}
          ${fragments.followedArtistFragment}
        }
      }
    `,
  }
})
<|endoftext|>


<commit_before>module.exports = [
	{
		description: 'rewrites `a = a + 1` as `a+=1`',
		input: `a = a + 1`,
		output: `a+=1`
	},

	{
		description: 'rewrites `a = a + a` as `a+=a`',
		input: `a = a + a`,
		output: `a+=a`
	},

	{
		description: 'does not rewrite `a = 1 + a` as `a+=1`, because it\'s not commutative',
		input: `a = 1 + a`,
		output: `a=1+a`
	},

	{
		description: 'rewrites `a = a - 1` as `a-=1`',
		input: `a = a - 1`,
		output: `a-=1`
	},

	{
		description: 'does not rewrite `a = 1 - a` as `a-=1`',
		input: `a = 1 - a`,
		output: `a=1-a`
	},

	{
		description: 'rewrites arithmetic expression with value',
		input: `a = 1 + 2 * 3`,
		output: `a=7`
	},

	{
		description: 'preserves space before --x expression',
		input: `Math.sqrt(1 - --t * t)`,
		output: `Math.sqrt(1- --t*t)`
	},

	{
		description: 'preserves space before parenthesised --x expression',
		input: `Math.sqrt(1 - ((--t)) * t)`,
		output: `Math.sqrt(1- --t*t)`
	},

	{
		description: 'preserves space before parenthesised rewritten ternary --x expression',
		input: `Math.sqrt(1 - (true ? --t : t) * t)`,
		output: `Math.sqrt(1- --t*t)`
	}
];
<commit_msg>Add a couple of test-cases that would've failed before<commit_after>module.exports = [
	{
		description: 'rewrites `a = a + 1` as `a+=1`',
		input: `a = a + 1`,
		output: `a+=1`
	},

	{
		description: 'rewrites `a = a + a` as `a+=a`',
		input: `a = a + a`,
		output: `a+=a`
	},

	{
		description: 'does not rewrite `a = 1 + a` as `a+=1`, because it\'s not commutative',
		input: `a = 1 + a`,
		output: `a=1+a`
	},

	{
		description: 'rewrites `a = a - 1` as `a-=1`',
		input: `a = a - 1`,
		output: `a-=1`
	},

	{
		description: 'does not rewrite `a = 1 - a` as `a-=1`',
		input: `a = 1 - a`,
		output: `a=1-a`
	},

	{
		description: 'rewrites arithmetic expression with value',
		input: `a = 1 + 2 * 3`,
		output: `a=7`
	},

	{
		description: 'rewrites arithmetic with non-simple values',
		input: `a = [ 1 ] + 2`,
		output: `a="12"`
	},

	{
		description: 'does not rewrite arithmetic with unknown but truthy values',
		input: `a = [ b ] + 2`,
		output: `a=[b]+2`
	},

	{
		description: 'preserves space before --x expression',
		input: `Math.sqrt(1 - --t * t)`,
		output: `Math.sqrt(1- --t*t)`
	},

	{
		description: 'preserves space before parenthesised --x expression',
		input: `Math.sqrt(1 - ((--t)) * t)`,
		output: `Math.sqrt(1- --t*t)`
	},

	{
		description: 'preserves space before parenthesised rewritten ternary --x expression',
		input: `Math.sqrt(1 - (true ? --t : t) * t)`,
		output: `Math.sqrt(1- --t*t)`
	}
];
<|endoftext|>


<commit_before>// base.js
// 141211
// - initial version

// Disable enter to submit form
// http://stackoverflow.com/a/587575
function checkEnter(e){
	e = e || event;
	var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
	return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
}

var $overlay,
	$tooltip,
	$menu,
	csrftoken = $.cookie('csrftoken'),
	browser = {
		can : {
			placeholder: function() { return 'placeholder' in document.createElement('input'); }
		}
	},
	taggingJS_options = {
		'case-sensitive': true,
		'forbidden-chars': [','],
		'forbidden-chars-text': '이하의 문자는 사용할 수 없습니다:\n',
		'forbidden-words-text': '이하의 단어는 사용할 수 없습니다:\n',
		'no-duplicate-text': '이하의 태그는 이미 선택되어 있습니다:\n',
		'tag-char': '',
		'no-spacebar': true,
		'tag-on-blur': false
	},
	autocomplete_options = {
		'serviceUrl': '/x/t',
		'type': 'POST',
		'minChars': 2,
		'lookupLimit': 5,
		'preserveInput': true,
		'formatResult': function(suggestion, currentValue) {
			return '' + $.Autocomplete.formatResult(suggestion, currentValue) + '' + suggestion.data + '';
		},
		'onSelect': function(suggestion) { this.focus(); },
		'zIndex': 1050
	}

$(function() {

	$window = $(window);
	$document = $(document);
	$body = $('body');
	$overlay = $('#overlay');
	$tooltip = $('#tooltip');
	$menu = $('.dropdown.container');

	$document
		.one('touchstart', function() {
			$('html').removeClass('no-touch');

			$document
				.off('mouseenter mouseleave', '.th')
				.off('mouseenter', '*[title]');

			$('.pscroll')
				.perfectScrollbar('destroy')
				.css('overflow', 'auto');
		})

		.on('keypress', '.type-zone', checkEnter)

		.on('click', '.dropdown.container .handle', function(e) {
			var $container = $(this).closest('.container');
			if(!$container.hasClass('open')) { $container.addClass('open');
			} else { $container.removeClass('open'); }
		})
		.on('mouseleave', '.dropdown.container', function() { if($(this).hasClass('open')) $(this).removeClass('open'); })
		.on('click', '.dropdown.container .handle[href=#]', function(e) { e.preventDefault(); })
		.on('mousedown', '.dropdown.container .close', function(e) {
			e.preventDefault();
			var $container = $(this).closest('.container');
			$container.removeClass('open');
		})

		.on('click', 'a.checkbox', function(e) {
			if($(this).attr('href') != '#') return true;

			e.preventDefault();

			if($(this).hasClass('radio')) {
				var $container = $(this).closest('.radio-container'),
					$input = $container.find('input[name=' + $container.data('input-name') + ']');

				$container.find('a.radio').removeClass('checked');
				$(this).addClass('checked');
				$input.val($(this).data('input-value'));
			} else {
				var $checkbox = $(this).prev('input[type=checkbox]');

				$(this).toggleClass('checked');
				$checkbox.prop('checked', !$checkbox.prop('checked'));
			}
		})

		.on('mouseenter', '.th', showTooltip)
		.on('mouseleave scroll', '.th', hideTooltip)
		.on('mouseenter', '*[title]', function(e) {
			if($(this).closest('.note-editor').length) return false;
			$(this)
				.data('title', $(this).attr('title'))
				.removeAttr('title')
				.addClass('th');
			showTooltip(e);
		});

	$('.article img').each(function() {
		if($(this).parents('a').length > 0) { return false; } else {
			var a = $('');

			a
				.addClass('imagecontainer')
				.attr('href', $(this).attr('src'))
				.attr('target', '_blank');

			$(this).wrap(a);
		}
	});

	$('input[type=checkbox]').each(function() {
		var $label;

		$label = $(this).closest('label').length ? $(this).closest('label') : $label;
		$label = $(this).next('label').length ? $(this).next('label') : $label;
		$label = $(this).prev('label').length ? $(this).prev('label') : $label;

		var $a = $('')
			.attr('href', '#')
			.addClass('checkbox')
			.html('')

		if($(this).prop('checked')) $a.addClass('checked');

		$a
			.insertAfter($label)
			.find('.label').append('' + $.trim($label.text()) + '');
		$(this).insertAfter($label);

		$(this).hide();
		$label.remove();
	});

	$('.post.item .label.meta.comments')
		.on('mouseenter', function() {
			var $item = $(this).closest('a.post.item');

			$item.attr('href', $item.attr('href') + '#comments');
		})
		.on('mouseleave', function() {
			var $item = $(this).closest('a.post.item');

			$item.attr('href', $item.attr('href').replace('#comments', ''));
		});

	$('.section.article.form form')
		.on('submit', function() {
			$('#tagbox').tagging('add');
			$tags.val($tagbox.tagging('getTags').join(','));
		})
		.find('.category')
			.on('click', 'a.option', function(e) {
				e.preventDefault();
				$('.section.article.form .category option').filter('[value='+$(this).data('value')+']').prop('selected', true).trigger('change');
				$('.section.article.form .category .text').text($(this).text());
				$(this).closest('.dropdown.container').removeClass('open');
			})
			.each(function() {
				var option, $handle = $(''), $dropdown = $('
'), $ul = $('
');

				option = $(this).find('select option');

				$('')
					.html(''+$(this).data('text')+'')
					.addClass('text')
					.appendTo($handle);

				$('')
					.addClass('icon')
					.appendTo($handle);

				$handle
					.attr('href', '#')
					.addClass('handle label meta')
					.appendTo($(this));

				$('')
					.addClass('close')
					.attr('href', '#')
					.appendTo($dropdown);

				$('
')
					.addClass('tip top')
					.html('')
					.appendTo($dropdown);

				option.each(function() {
					var $li = $('
'), $a = $(''), value = $(this).attr('value');

					if(value == '') return true;

					if($(this).prop('selected')) $(this).closest('.dropdown.container').find('.handle .text span').text($(this).text());

					$('')
						.text($(this).text())
						.appendTo($a);

					$a
						.attr('href', '#')
						.addClass('option')
						.data('value', value)
						.appendTo($li);

					switch($(this).text()) {
						case '번역':
							$li.addClass('scanlation');
							break;
						case '자막':
							$li.addClass('subtitles');
							break;
						case '정보':
							$li.addClass('news');
							break;
					}

					$li.appendTo($ul);
				});

				$('
')
					.append($ul)
					.appendTo($dropdown);

				$dropdown
					.addClass('dropdown menu')
					.appendTo($(this));

				$(this).find('select').hide();
			});

	if(!browser.can.placeholder()) {
		$('#form_login .field input').each(function() {
			$('')
				.attr('for', $(this).attr('id'))
				.append(''+$(this).attr('placeholder')+'')
				.insertAfter($(this).addClass('noplaceholder'));
		});
	}

	$('#form_login')
		.on('load focusin focusout', '.field input.noplaceholder', function() {
			if(this.value == '') { $(this).next('label').show();
			} else { $(this).next('label').hide(); }
		})
		.on('keypress', '.field input.noplaceholder', function() {
			$(this).next('label').hide();
		});

	$('.vote a').on('click', function(e) {
		e.preventDefault();
		vote('p', $(this).parent('.vote').data('target-id'), $(this));
	});

	$('.section.board')
		.on('click', '.search.button .label.meta.search', function(e) {
			e.preventDefault();

			var $nav = $(this).closest('.nav.bottom');

			$nav
				.addClass('open')
				.removeClass('close');

		})
		.on('click', '.search.button .label.meta.delete', function(e) {
			e.preventDefault();

			var $nav = $(this).closest('.nav.bottom');

			$nav
				.removeClass('open')
				.addClass('close');
		});

	$('.tabs')
		.on('click', '.tab.header a:not(.current)', function() {
			var $container = $(this).closest('.tabs'),
				target = $(this).attr('href').replace('#', '.');

			$container.find('.section').hide();
			$container.find(target).show();

			$container.find('.tab.header a').removeClass('current');
			$(this).addClass('current');

		})
});

function csrfSafeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); }

$.ajaxSetup({
	beforeSend: function(xhr, settings) {
		if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
			xhr.setRequestHeader("X-CSRFToken", csrftoken);
		}
	}
});

function showTooltip(e) {
	var $target = $(e.target).closest('.th');
	var position = $target.offset();

	var targetHeight = $target.outerHeight();
	var targetWidth = $target.outerWidth();

	var offsetY = 0;
	var offsetX = 0;

	var top;
	var left;

	var height;
	var width;

	var margin = 10;

	$tooltip.find('.container p').html($target.data('title').replace(/\\n/gi, '
'));
	$tooltip.find('.tip').removeAttr('style');

	top = position.top + targetHeight;
	left = position.left + targetWidth/2;

	height = $tooltip.height();
	width = $tooltip.width();

	if(top + height + margin > $window.height() + $window.scrollTop()) offsetY = -1*(targetHeight + height);

	offsetX = $window.width() + $window.scrollLeft() - left;

	if(offsetX - (width/2 + margin) < 0) {
		offsetX = offsetX - (width/2 + margin);
		if(width/2 + offsetX < 0 ) return false;
	} else if(offsetX + (width/2 + margin) > 0) {
		offsetX = offsetX + width/2 + margin - $window.width();
		if(offsetX < 0) offsetX = 0;
		if(width/2 - offsetX < 0 ) return false;
	} else { offsetX = 0; }

	$('.th-active').removeClass('th-active');
	$target.addClass('th-active');

	$tooltip
		.css({
			'top': top + offsetY,
			'left': left - width/2 + offsetX
		})
		.show()
		.stop()
		.animate({'opacity': 1}, 100)
		.find('.tip')
			.hide()
			.css('margin-left', -2*offsetX)
			.filter((offsetY >= 0) ? '.top' : '.bottom').show();
}

function hideTooltip() {
	$('.th-active').removeClass('th-active');

	$tooltip
		.stop()
		.animate({'opacity': 0}, 100, function() { $tooltip.hide(); });
}

function vote(type, target, button) {
	var vote, avote, work,
		$sibling_voted = button.siblings('.voted'),
		databox = {
			type: type,
			target: target,
			vote: null
		};

	work = button.hasClass('voted') ? '-' : '+';
	vote = button.hasClass('upvote') ? '+' : '-';
	avote = (vote == '+') ? '-' : '+';

	if(work == '+' && $sibling_voted.length) {
		$ajax_vote({type: type, target: target, vote: '-' + avote}, $sibling_voted)
			.done(function(data, status, xhr) {
				$ajax_vote({type: type, target: target, vote: work + vote})
					.done(function(data) { vote_callback(data, work, button); });

				vote_callback(data, '-', $sibling_voted);
			});
	} else { $ajax_vote({type: type, target: target, vote: work + vote}).done(function(data) { vote_callback(data, work, button); }); };
}

function vote_callback(data, work, button) {
	if(work == '+') { button.addClass('voted');
	} else { button.removeClass('voted'); }

	var $score = button.closest('.item').find('.meta.score');

	if(button.parents('.comment').length && data.current.total  >= 0) data.current.total = '+' + data.current.total;

	$score
		.attr('title', '+'+data.current.upvote+' / -'+data.current.downvote)
		.find('.text span').text(data.current.total);
}

function $ajax_vote(databox) {
	return $.ajax({
			type: 'POST',
			url: VOTE_AJAX_ENDPOINT,
			data: databox
		})
			.fail(function(xhr, status, error) {
				var response = xhr.responseJSON.status;
				switch(response) {
					case 'notauthenticated':
						alert('로그인한 사용자만 사용 가능한 기능입니다.');
						break;

					case 'alreadyhave':
						alert('이미 추천한 게시글 또는 댓글입니다.');
						break;

					default:
						alert('알 수 없는 문제가 발생하였습니다.');
						console.log(databox);
						console.log(xhr);
						console.log(status);
						console.log(error);
				}
			});
}
<commit_msg>Remove preserveInput from jQuery autocomplete options<commit_after>// base.js
// 141211
// - initial version

// Disable enter to submit form
// http://stackoverflow.com/a/587575
function checkEnter(e){
	e = e || event;
	var txtArea = /textarea/i.test((e.target || e.srcElement).tagName);
	return txtArea || (e.keyCode || e.which || e.charCode || 0) !== 13;
}

var $overlay,
	$tooltip,
	$menu,
	csrftoken = $.cookie('csrftoken'),
	browser = {
		can : {
			placeholder: function() { return 'placeholder' in document.createElement('input'); }
		}
	},
	taggingJS_options = {
		'case-sensitive': true,
		'forbidden-chars': [','],
		'forbidden-chars-text': '이하의 문자는 사용할 수 없습니다:\n',
		'forbidden-words-text': '이하의 단어는 사용할 수 없습니다:\n',
		'no-duplicate-text': '이하의 태그는 이미 선택되어 있습니다:\n',
		'tag-char': '',
		'no-spacebar': true,
		'tag-on-blur': false
	},
	autocomplete_options = {
		'serviceUrl': '/x/t',
		'type': 'POST',
		'minChars': 2,
		'lookupLimit': 5,
		'formatResult': function(suggestion, currentValue) {
			return '' + $.Autocomplete.formatResult(suggestion, currentValue) + '' + suggestion.data + '';
		},
		'onSelect': function(suggestion) { this.focus(); },
		'zIndex': 1050
	}

$(function() {

	$window = $(window);
	$document = $(document);
	$body = $('body');
	$overlay = $('#overlay');
	$tooltip = $('#tooltip');
	$menu = $('.dropdown.container');

	$document
		.one('touchstart', function() {
			$('html').removeClass('no-touch');

			$document
				.off('mouseenter mouseleave', '.th')
				.off('mouseenter', '*[title]');

			$('.pscroll')
				.perfectScrollbar('destroy')
				.css('overflow', 'auto');
		})

		.on('keypress', '.type-zone', checkEnter)

		.on('click', '.dropdown.container .handle', function(e) {
			var $container = $(this).closest('.container');
			if(!$container.hasClass('open')) { $container.addClass('open');
			} else { $container.removeClass('open'); }
		})
		.on('mouseleave', '.dropdown.container', function() { if($(this).hasClass('open')) $(this).removeClass('open'); })
		.on('click', '.dropdown.container .handle[href=#]', function(e) { e.preventDefault(); })
		.on('mousedown', '.dropdown.container .close', function(e) {
			e.preventDefault();
			var $container = $(this).closest('.container');
			$container.removeClass('open');
		})

		.on('click', 'a.checkbox', function(e) {
			if($(this).attr('href') != '#') return true;

			e.preventDefault();

			if($(this).hasClass('radio')) {
				var $container = $(this).closest('.radio-container'),
					$input = $container.find('input[name=' + $container.data('input-name') + ']');

				$container.find('a.radio').removeClass('checked');
				$(this).addClass('checked');
				$input.val($(this).data('input-value'));
			} else {
				var $checkbox = $(this).prev('input[type=checkbox]');

				$(this).toggleClass('checked');
				$checkbox.prop('checked', !$checkbox.prop('checked'));
			}
		})

		.on('mouseenter', '.th', showTooltip)
		.on('mouseleave scroll', '.th', hideTooltip)
		.on('mouseenter', '*[title]', function(e) {
			if($(this).closest('.note-editor').length) return false;
			$(this)
				.data('title', $(this).attr('title'))
				.removeAttr('title')
				.addClass('th');
			showTooltip(e);
		});

	$('.article img').each(function() {
		if($(this).parents('a').length > 0) { return false; } else {
			var a = $('');

			a
				.addClass('imagecontainer')
				.attr('href', $(this).attr('src'))
				.attr('target', '_blank');

			$(this).wrap(a);
		}
	});

	$('input[type=checkbox]').each(function() {
		var $label;

		$label = $(this).closest('label').length ? $(this).closest('label') : $label;
		$label = $(this).next('label').length ? $(this).next('label') : $label;
		$label = $(this).prev('label').length ? $(this).prev('label') : $label;

		var $a = $('')
			.attr('href', '#')
			.addClass('checkbox')
			.html('')

		if($(this).prop('checked')) $a.addClass('checked');

		$a
			.insertAfter($label)
			.find('.label').append('' + $.trim($label.text()) + '');
		$(this).insertAfter($label);

		$(this).hide();
		$label.remove();
	});

	$('.post.item .label.meta.comments')
		.on('mouseenter', function() {
			var $item = $(this).closest('a.post.item');

			$item.attr('href', $item.attr('href') + '#comments');
		})
		.on('mouseleave', function() {
			var $item = $(this).closest('a.post.item');

			$item.attr('href', $item.attr('href').replace('#comments', ''));
		});

	$('.section.article.form form')
		.on('submit', function() {
			$('#tagbox').tagging('add');
			$tags.val($tagbox.tagging('getTags').join(','));
		})
		.find('.category')
			.on('click', 'a.option', function(e) {
				e.preventDefault();
				$('.section.article.form .category option').filter('[value='+$(this).data('value')+']').prop('selected', true).trigger('change');
				$('.section.article.form .category .text').text($(this).text());
				$(this).closest('.dropdown.container').removeClass('open');
			})
			.each(function() {
				var option, $handle = $(''), $dropdown = $('
'), $ul = $('
');

				option = $(this).find('select option');

				$('')
					.html(''+$(this).data('text')+'')
					.addClass('text')
					.appendTo($handle);

				$('')
					.addClass('icon')
					.appendTo($handle);

				$handle
					.attr('href', '#')
					.addClass('handle label meta')
					.appendTo($(this));

				$('')
					.addClass('close')
					.attr('href', '#')
					.appendTo($dropdown);

				$('
')
					.addClass('tip top')
					.html('')
					.appendTo($dropdown);

				option.each(function() {
					var $li = $('
'), $a = $(''), value = $(this).attr('value');

					if(value == '') return true;

					if($(this).prop('selected')) $(this).closest('.dropdown.container').find('.handle .text span').text($(this).text());

					$('')
						.text($(this).text())
						.appendTo($a);

					$a
						.attr('href', '#')
						.addClass('option')
						.data('value', value)
						.appendTo($li);

					switch($(this).text()) {
						case '번역':
							$li.addClass('scanlation');
							break;
						case '자막':
							$li.addClass('subtitles');
							break;
						case '정보':
							$li.addClass('news');
							break;
					}

					$li.appendTo($ul);
				});

				$('
')
					.append($ul)
					.appendTo($dropdown);

				$dropdown
					.addClass('dropdown menu')
					.appendTo($(this));

				$(this).find('select').hide();
			});

	if(!browser.can.placeholder()) {
		$('#form_login .field input').each(function() {
			$('')
				.attr('for', $(this).attr('id'))
				.append(''+$(this).attr('placeholder')+'')
				.insertAfter($(this).addClass('noplaceholder'));
		});
	}

	$('#form_login')
		.on('load focusin focusout', '.field input.noplaceholder', function() {
			if(this.value == '') { $(this).next('label').show();
			} else { $(this).next('label').hide(); }
		})
		.on('keypress', '.field input.noplaceholder', function() {
			$(this).next('label').hide();
		});

	$('.vote a').on('click', function(e) {
		e.preventDefault();
		vote('p', $(this).parent('.vote').data('target-id'), $(this));
	});

	$('.section.board')
		.on('click', '.search.button .label.meta.search', function(e) {
			e.preventDefault();

			var $nav = $(this).closest('.nav.bottom');

			$nav
				.addClass('open')
				.removeClass('close');

		})
		.on('click', '.search.button .label.meta.delete', function(e) {
			e.preventDefault();

			var $nav = $(this).closest('.nav.bottom');

			$nav
				.removeClass('open')
				.addClass('close');
		});

	$('.tabs')
		.on('click', '.tab.header a:not(.current)', function() {
			var $container = $(this).closest('.tabs'),
				target = $(this).attr('href').replace('#', '.');

			$container.find('.section').hide();
			$container.find(target).show();

			$container.find('.tab.header a').removeClass('current');
			$(this).addClass('current');

		})
});

function csrfSafeMethod(method) { return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); }

$.ajaxSetup({
	beforeSend: function(xhr, settings) {
		if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
			xhr.setRequestHeader("X-CSRFToken", csrftoken);
		}
	}
});

function showTooltip(e) {
	var $target = $(e.target).closest('.th');
	var position = $target.offset();

	var targetHeight = $target.outerHeight();
	var targetWidth = $target.outerWidth();

	var offsetY = 0;
	var offsetX = 0;

	var top;
	var left;

	var height;
	var width;

	var margin = 10;

	$tooltip.find('.container p').html($target.data('title').replace(/\\n/gi, '
'));
	$tooltip.find('.tip').removeAttr('style');

	top = position.top + targetHeight;
	left = position.left + targetWidth/2;

	height = $tooltip.height();
	width = $tooltip.width();

	if(top + height + margin > $window.height() + $window.scrollTop()) offsetY = -1*(targetHeight + height);

	offsetX = $window.width() + $window.scrollLeft() - left;

	if(offsetX - (width/2 + margin) < 0) {
		offsetX = offsetX - (width/2 + margin);
		if(width/2 + offsetX < 0 ) return false;
	} else if(offsetX + (width/2 + margin) > 0) {
		offsetX = offsetX + width/2 + margin - $window.width();
		if(offsetX < 0) offsetX = 0;
		if(width/2 - offsetX < 0 ) return false;
	} else { offsetX = 0; }

	$('.th-active').removeClass('th-active');
	$target.addClass('th-active');

	$tooltip
		.css({
			'top': top + offsetY,
			'left': left - width/2 + offsetX
		})
		.show()
		.stop()
		.animate({'opacity': 1}, 100)
		.find('.tip')
			.hide()
			.css('margin-left', -2*offsetX)
			.filter((offsetY >= 0) ? '.top' : '.bottom').show();
}

function hideTooltip() {
	$('.th-active').removeClass('th-active');

	$tooltip
		.stop()
		.animate({'opacity': 0}, 100, function() { $tooltip.hide(); });
}

function vote(type, target, button) {
	var vote, avote, work,
		$sibling_voted = button.siblings('.voted'),
		databox = {
			type: type,
			target: target,
			vote: null
		};

	work = button.hasClass('voted') ? '-' : '+';
	vote = button.hasClass('upvote') ? '+' : '-';
	avote = (vote == '+') ? '-' : '+';

	if(work == '+' && $sibling_voted.length) {
		$ajax_vote({type: type, target: target, vote: '-' + avote}, $sibling_voted)
			.done(function(data, status, xhr) {
				$ajax_vote({type: type, target: target, vote: work + vote})
					.done(function(data) { vote_callback(data, work, button); });

				vote_callback(data, '-', $sibling_voted);
			});
	} else { $ajax_vote({type: type, target: target, vote: work + vote}).done(function(data) { vote_callback(data, work, button); }); };
}

function vote_callback(data, work, button) {
	if(work == '+') { button.addClass('voted');
	} else { button.removeClass('voted'); }

	var $score = button.closest('.item').find('.meta.score');

	if(button.parents('.comment').length && data.current.total  >= 0) data.current.total = '+' + data.current.total;

	$score
		.attr('title', '+'+data.current.upvote+' / -'+data.current.downvote)
		.find('.text span').text(data.current.total);
}

function $ajax_vote(databox) {
	return $.ajax({
			type: 'POST',
			url: VOTE_AJAX_ENDPOINT,
			data: databox
		})
			.fail(function(xhr, status, error) {
				var response = xhr.responseJSON.status;
				switch(response) {
					case 'notauthenticated':
						alert('로그인한 사용자만 사용 가능한 기능입니다.');
						break;

					case 'alreadyhave':
						alert('이미 추천한 게시글 또는 댓글입니다.');
						break;

					default:
						alert('알 수 없는 문제가 발생하였습니다.');
						console.log(databox);
						console.log(xhr);
						console.log(status);
						console.log(error);
				}
			});
}
<|endoftext|>


<commit_before>// The Statistics strategy uses the measure of each end-start time for each
// query executed against the db to calculate the mean, variance and standard deviation
// and pick the server which the lowest mean and deviation
var StatisticsStrategy = exports.StatisticsStrategy = function(replicaset) {
  this.replicaset = replicaset;
}

// Starts any needed code
StatisticsStrategy.prototype.start = function(callback) {
  callback(null, null);
}

StatisticsStrategy.prototype.stop = function(callback) {
  callback && callback(null, null);
}

StatisticsStrategy.prototype.checkoutSecondary = function(tags, secondaryCandidates) {
  // Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS
  // Create a list of candidat servers, containing the primary if available
  var candidateServers = [];

  // If we have not provided a list of candidate servers use the default setup
  if(!Array.isArray(secondaryCandidates)) {
    candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : [];
    // Add all the secondaries
    var keys = Object.keys(this.replicaset._state.secondaries);
    for(var i = 0; i < keys.length; i++) {
      candidateServers.push(this.replicaset._state.secondaries[keys[i]])
    }
  } else {
    candidateServers = secondaryCandidates;
  }

  // Final list of eligable server
  var finalCandidates = [];

  // If we have tags filter by tags
  if(tags != null && typeof tags == 'object') {
    // If we have an array or single tag selection
    var tagObjects = Array.isArray(tags) ? tags : [tags];
    // Iterate over all tags until we find a candidate server
    for(var _i = 0; _i < tagObjects.length; _i++) {
      // Grab a tag object
      var tagObject = tagObjects[_i];
      // Matching keys
      var matchingKeys = Object.keys(tagObject);
      // Remove any that are not tagged correctly
      for(var i = 0; i < candidateServers.length; i++) {
        var server = candidateServers[i];
        // If we have tags match
        if(server.tags != null) {
          var matching = true;

          // Ensure we have all the values
          for(var j = 0; j < matchingKeys.length; j++) {
            if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) {
              matching = false;
              break;
            }
          }

          // If we have a match add it to the list of matching servers
          if(matching) {
            finalCandidates.push(server);
          }
        }
      }
    }
  } else {
    // Final array candidates
    var finalCandidates = candidateServers;
  }

  // If no candidates available return an error
  if(finalCandidates.length == 0) return new Error("No replica set members available for query");
  // Pick a random server
  return finalCandidates[Math.round(Math.random(1000000) * (finalCandidates.length - 1))].checkoutReader();
}
<commit_msg>fixed; make statistics start() behave same as ping<commit_after>// The Statistics strategy uses the measure of each end-start time for each
// query executed against the db to calculate the mean, variance and standard deviation
// and pick the server which the lowest mean and deviation
var StatisticsStrategy = exports.StatisticsStrategy = function(replicaset) {
  this.replicaset = replicaset;
}

// Starts any needed code
StatisticsStrategy.prototype.start = function(callback) {
  callback && callback(null, null);
}

StatisticsStrategy.prototype.stop = function(callback) {
  callback && callback(null, null);
}

StatisticsStrategy.prototype.checkoutSecondary = function(tags, secondaryCandidates) {
  // Servers are picked based on the lowest ping time and then servers that lower than that + secondaryAcceptableLatencyMS
  // Create a list of candidat servers, containing the primary if available
  var candidateServers = [];

  // If we have not provided a list of candidate servers use the default setup
  if(!Array.isArray(secondaryCandidates)) {
    candidateServers = this.replicaset._state.master != null ? [this.replicaset._state.master] : [];
    // Add all the secondaries
    var keys = Object.keys(this.replicaset._state.secondaries);
    for(var i = 0; i < keys.length; i++) {
      candidateServers.push(this.replicaset._state.secondaries[keys[i]])
    }
  } else {
    candidateServers = secondaryCandidates;
  }

  // Final list of eligable server
  var finalCandidates = [];

  // If we have tags filter by tags
  if(tags != null && typeof tags == 'object') {
    // If we have an array or single tag selection
    var tagObjects = Array.isArray(tags) ? tags : [tags];
    // Iterate over all tags until we find a candidate server
    for(var _i = 0; _i < tagObjects.length; _i++) {
      // Grab a tag object
      var tagObject = tagObjects[_i];
      // Matching keys
      var matchingKeys = Object.keys(tagObject);
      // Remove any that are not tagged correctly
      for(var i = 0; i < candidateServers.length; i++) {
        var server = candidateServers[i];
        // If we have tags match
        if(server.tags != null) {
          var matching = true;

          // Ensure we have all the values
          for(var j = 0; j < matchingKeys.length; j++) {
            if(server.tags[matchingKeys[j]] != tagObject[matchingKeys[j]]) {
              matching = false;
              break;
            }
          }

          // If we have a match add it to the list of matching servers
          if(matching) {
            finalCandidates.push(server);
          }
        }
      }
    }
  } else {
    // Final array candidates
    var finalCandidates = candidateServers;
  }

  // If no candidates available return an error
  if(finalCandidates.length == 0) return new Error("No replica set members available for query");
  // Pick a random server
  return finalCandidates[Math.round(Math.random(1000000) * (finalCandidates.length - 1))].checkoutReader();
}
<|endoftext|>