<commit_before>var parse = require('css-tree').parse;
var compress = require('./compressor');
var translate = require('css-tree').translate;
var translateWithSourceMap = require('css-tree').translateWithSourceMap;
var walk = require('css-tree').walk;
var walkRules = require('css-tree').walkRules;
var walkRulesRight = require('css-tree').walkRulesRight;
var clone = require('css-tree').clone;
var List = require('css-tree').List;

function debugOutput(name, options, startTime, data) {
    if (options.debug) {
        console.error('## ' + name + ' done in %d ms\n', Date.now() - startTime);
    }

    return data;
}

function createDefaultLogger(level) {
    var lastDebug;

    return function logger(title, ast) {
        var line = title;

        if (ast) {
            line = '[' + ((Date.now() - lastDebug) / 1000).toFixed(3) + 's] ' + line;
        }

        if (level > 1 && ast) {
            var css = translate(ast, true);

            // when level 2, limit css to 256 symbols
            if (level === 2 && css.length > 256) {
                css = css.substr(0, 256) + '...';
            }

            line += '\n  ' + css + '\n';
        }

        console.error(line);
        lastDebug = Date.now();
    };
}

function copy(obj) {
    var result = {};

    for (var key in obj) {
        result[key] = obj[key];
    }

    return result;
}

function buildCompressOptions(options) {
    options = copy(options);

    if (typeof options.logger !== 'function' && options.debug) {
        options.logger = createDefaultLogger(options.debug);
    }

    return options;
}

function runPlugins(ast, options, plugin) {
    var plugins = [];
    if (Array.isArray(plugin)) {
        plugins = plugin;
    } else if (typeof plugin === 'function') {
        plugins = [plugin];
    }
    plugins.forEach(function(plugin) {
        plugin(ast, options);
    });
}

function minify(context, source, options) {
    options = options || {};

    var filename = options.filename || '<unknown>';
    var result;

    // parse
    var ast = debugOutput('parsing', options, Date.now(),
        parse(source, {
            context: context,
            filename: filename,
            positions: Boolean(options.sourceMap)
        })
    );

    // after parse plugins
    if (options.beforeCompress) {
        debugOutput('beforeCompress', options, Date.now(),
            runPlugins(ast, options, options.beforeCompress)
        );
    }

    // compress
    var compressResult = debugOutput('compress', options, Date.now(),
        compress(ast, buildCompressOptions(options))
    );

    // after compress plugins
    if (options.afterCompress) {
        debugOutput('afterCompress', options, Date.now(),
            runPlugins(compressResult, options, options.afterCompress)
        );
    }

    // translate
    if (options.sourceMap) {
        result = debugOutput('translateWithSourceMap', options, Date.now(), (function() {
            var tmp = translateWithSourceMap(compressResult.ast);
            tmp.map._file = filename; // since other tools can relay on file in source map transform chain
            tmp.map.setSourceContent(filename, source);
            return tmp;
        })());
    } else {
        result = debugOutput('translate', options, Date.now(), {
            css: translate(compressResult.ast),
            map: null
        });
    }

    return result;
}

function minifyStylesheet(source, options) {
    return minify('stylesheet', source, options);
};

function minifyBlock(source, options) {
    return minify('block', source, options);
}

module.exports = {
    version: require('../package.json').version,

    // classes
    List: List,

    // main methods
    minify: minifyStylesheet,
    minifyBlock: minifyBlock,

    // step by step
    parse: parse,
    compress: compress,
    translate: translate,
    translateWithSourceMap: translateWithSourceMap,

    // walkers
    walk: walk,
    walkRules: walkRules,
    walkRulesRight: walkRulesRight,

    // utils
    clone: clone
};
<commit_msg>before/afterCompress refactoring<commit_after>var parse = require('css-tree').parse;
var compress = require('./compressor');
var translate = require('css-tree').translate;
var translateWithSourceMap = require('css-tree').translateWithSourceMap;
var walk = require('css-tree').walk;
var walkRules = require('css-tree').walkRules;
var walkRulesRight = require('css-tree').walkRulesRight;
var clone = require('css-tree').clone;
var List = require('css-tree').List;

function debugOutput(name, options, startTime, data) {
    if (options.debug) {
        console.error('## ' + name + ' done in %d ms\n', Date.now() - startTime);
    }

    return data;
}

function createDefaultLogger(level) {
    var lastDebug;

    return function logger(title, ast) {
        var line = title;

        if (ast) {
            line = '[' + ((Date.now() - lastDebug) / 1000).toFixed(3) + 's] ' + line;
        }

        if (level > 1 && ast) {
            var css = translate(ast, true);

            // when level 2, limit css to 256 symbols
            if (level === 2 && css.length > 256) {
                css = css.substr(0, 256) + '...';
            }

            line += '\n  ' + css + '\n';
        }

        console.error(line);
        lastDebug = Date.now();
    };
}

function copy(obj) {
    var result = {};

    for (var key in obj) {
        result[key] = obj[key];
    }

    return result;
}

function buildCompressOptions(options) {
    options = copy(options);

    if (typeof options.logger !== 'function' && options.debug) {
        options.logger = createDefaultLogger(options.debug);
    }

    return options;
}

function runHandler(ast, options, handlers) {
    if (!Array.isArray(handlers)) {
        handlers = [handlers];
    }

    handlers.forEach(function(fn) {
        fn(ast, options);
    });
}

function minify(context, source, options) {
    options = options || {};

    var filename = options.filename || '<unknown>';
    var result;

    // parse
    var ast = debugOutput('parsing', options, Date.now(),
        parse(source, {
            context: context,
            filename: filename,
            positions: Boolean(options.sourceMap)
        })
    );

    // before compress handlers
    if (options.beforeCompress) {
        debugOutput('beforeCompress', options, Date.now(),
            runHandler(ast, options, options.beforeCompress)
        );
    }

    // compress
    var compressResult = debugOutput('compress', options, Date.now(),
        compress(ast, buildCompressOptions(options))
    );

    // after compress handlers
    if (options.afterCompress) {
        debugOutput('afterCompress', options, Date.now(),
            runHandler(compressResult, options, options.afterCompress)
        );
    }

    // translate
    if (options.sourceMap) {
        result = debugOutput('translateWithSourceMap', options, Date.now(), (function() {
            var tmp = translateWithSourceMap(compressResult.ast);
            tmp.map._file = filename; // since other tools can relay on file in source map transform chain
            tmp.map.setSourceContent(filename, source);
            return tmp;
        })());
    } else {
        result = debugOutput('translate', options, Date.now(), {
            css: translate(compressResult.ast),
            map: null
        });
    }

    return result;
}

function minifyStylesheet(source, options) {
    return minify('stylesheet', source, options);
};

function minifyBlock(source, options) {
    return minify('block', source, options);
}

module.exports = {
    version: require('../package.json').version,

    // classes
    List: List,

    // main methods
    minify: minifyStylesheet,
    minifyBlock: minifyBlock,

    // step by step
    parse: parse,
    compress: compress,
    translate: translate,
    translateWithSourceMap: translateWithSourceMap,

    // walkers
    walk: walk,
    walkRules: walkRules,
    walkRulesRight: walkRulesRight,

    // utils
    clone: clone
};
<|endoftext|>


<commit_before>/**
 * Determines if a value is a function.
 *
 * @param {*} candidate the candidate to test
 * @returns {boolean} true, if candidate is a Function
 */
export function isFunction(candidate) {
    return 'function' === typeof candidate;
}

/**
 * Determines if a value is an object.
 *
 * @param {*} candidate the candidate to test
 * @returns {boolean} true, if candidate is an object
 */
export function isObject(candidate) {
    return null !== candidate && 'object' === typeof candidate && !isArray(candidate);
}

/**
 * Determines if a value is an array.
 *
 * @param {*} candidate the candidate to test
 * @returns {boolean} true, if candidate is an array
 */
export function isArray(candidate) {
    return Array.isArray(candidate);
}

/**
 * Merges two objects; members of the second object take precedence over the first object.
 *
 * @param {Object} target an object to merge to
 * @returns {Object} the target object, populated with the source object's members
 */
export function merge(target, source) {
    // Merge algorithm adapted from:
    // From (http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically)

    let array = isArray(source),
        dest = array && [] || {};

    if (array) {
        target = target || [];
        dest = dest.concat(target);
        source.forEach(function onItem(e, i) {
            if ('undefined' === typeof dest[i]) {
                dest[i] = e;
            } else if ('object' === typeof e) {
                dest[i] = merge(target[i], e);
            } else {
                if (target.indexOf(e) === -1) {
                    dest.push(e);
                }
            }
        });
    } else {
        if (isObject(target)) {
            Object.keys(target || {}).forEach(function (key) {
                dest[key] = target[key];
            });
        }
        Object.keys(source || {}).forEach(function (key) {
            if (!isObject(source[key]) || !source[key]) {
                dest[key] = source[key];
            }
            else {
                if (!target[key]) {
                    dest[key] = source[key];
                } else {
                    dest[key] = merge(target[key], source[key]);
                }
            }
        });
    }

    return dest;
}

/**
 * Executes a function.
 *
 * @param {Function} fn the function to execute
 * @param {*[]} args an array of arguments to execute the function with
 * @param {Object} [context] the optional context
 * @returns {*} the return value of the function execution, or null if no function is provided
 */
export function execute(fn, args, context) {
    if (isFunction(fn)) {
        return fn.apply(context || {}, args);
    }
    return null;
}

/**
 * Executes a function asynchronously.
 *
 * @param {Function} fn the function to execute
 * @param {*[]} args an array of arguments to execute the function with
 * @param {Object} [context] the optional context
 */
export function executeAsync(fn, args, context) {
    if (isFunction(fn)) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                try {
                    resolve(fn.apply(context || {}, args));
                } catch (error) {
                    reject(error);
                }
            });
        });
    }
    return null;
}

/**
 * A store implementation in memory.
 */
export class InMemoryStore {

    //this.settings = {};

    /**
     * Creates an instance.
     */
    constructor() {
        this.settings = {};
    }

    /**
     * Loads values.
     *
     * @param {Function} successCallback the callback invoked on success (with parameter {})
     */
    load(successCallback) {
        executeAsync(successCallback, [merge({}, this.settings)]);
    };

    /**
     * Saves values.
     *
     * @param {Object} settings the settings to save
     * @param {Function} successCallback the success callback to invoke on success
     */
    save(settings, successCallback) {
        // Assign the settings
        this.settings = merge(this.settings, settings);

        // Invoke the callback
        executeAsync(successCallback, [merge({}, this.settings)]);
    };

    /**
     * Clears values.
     *
     * @param {Function} successCallback the success callback to invoke on success
     */
    clear(successCallback) {
        this.settings = {};

        executeAsync(successCallback, [{}]);
    };

};

/**
 * Implementation for SettingsManager, a class for storing settings.
 *
 * @param {Object} [backingStore] optional backing store to wrap
 */
export class SettingsManager {

    // The backing store to use
    // backingStore;

    /**
     * Creates a SettingsManager instance backed by an optional store.
     *
     * @param {Store} [backingStore] optional store implementation to use
     */
    constructor(backingStore) {
        this.backingStore = backingStore || new InMemoryStore();
    }

    /**
     * Loads values.
     *
     * @param {Function} [successCallback] the callback invoked on success (invoked with the settings)
     * @param {Function} [errorCallback] the error callback, invoked on failure
     */
    load(successCallback, errorCallback) {
        this.backingStore.load(function onLoad(settings) {
            execute(successCallback, [settings], this.backingStore);
        }, errorCallback);
    };

    /**
     * Saves values.
     *
     * @param {Object} settings the settings to save
     * @param {Function} [successCallback] the callback invoked on success
     * @param {Function} [errorCallback] the error callback, invoked on failure
     */
    save(settings, successCallback, errorCallback) {
        if (!settings) {
            executeAsync(successCallback, [{}]);
        } else if (isObject(settings)) {
            execute(this.backingStore.save, [settings, successCallback, errorCallback], this.backingStore);
        } else {
            executeAsync(errorCallback, ['"settings" is not an object']);
        }
    };

    /**
     * Clears values.
     *
     * @param {Function} successCallback the success callback to invoke on success
     * @param {Function} [errorCallback] the error callback, invoked on failure
     */
    clear(successCallback, errorCallback) {
        executeAsync(this.backingStore.clear, [successCallback, errorCallback], this.backingStore);
    };

}
<commit_msg>Removed obsolete code<commit_after>/**
 * Determines if a value is a function.
 *
 * @param {*} candidate the candidate to test
 * @returns {boolean} true, if candidate is a Function
 */
export function isFunction(candidate) {
    return 'function' === typeof candidate;
}

/**
 * Determines if a value is an object.
 *
 * @param {*} candidate the candidate to test
 * @returns {boolean} true, if candidate is an object
 */
export function isObject(candidate) {
    return null !== candidate && 'object' === typeof candidate && !isArray(candidate);
}

/**
 * Determines if a value is an array.
 *
 * @param {*} candidate the candidate to test
 * @returns {boolean} true, if candidate is an array
 */
export function isArray(candidate) {
    return Array.isArray(candidate);
}

/**
 * Merges two objects; members of the second object take precedence over the first object.
 *
 * @param {Object} target an object to merge to
 * @returns {Object} the target object, populated with the source object's members
 */
export function merge(target, source) {
    // Merge algorithm adapted from:
    // From (http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically)

    let array = isArray(source),
        dest = array && [] || {};

    if (array) {
        target = target || [];
        dest = dest.concat(target);
        source.forEach(function onItem(e, i) {
            if ('undefined' === typeof dest[i]) {
                dest[i] = e;
            } else if ('object' === typeof e) {
                dest[i] = merge(target[i], e);
            } else {
                if (target.indexOf(e) === -1) {
                    dest.push(e);
                }
            }
        });
    } else {
        if (isObject(target)) {
            Object.keys(target || {}).forEach(function (key) {
                dest[key] = target[key];
            });
        }
        Object.keys(source || {}).forEach(function (key) {
            if (!isObject(source[key]) || !source[key]) {
                dest[key] = source[key];
            }
            else {
                if (!target[key]) {
                    dest[key] = source[key];
                } else {
                    dest[key] = merge(target[key], source[key]);
                }
            }
        });
    }

    return dest;
}

/**
 * Executes a function.
 *
 * @param {Function} fn the function to execute
 * @param {*[]} args an array of arguments to execute the function with
 * @param {Object} [context] the optional context
 * @returns {*} the return value of the function execution, or null if no function is provided
 */
export function execute(fn, args, context) {
    if (isFunction(fn)) {
        return fn.apply(context || {}, args);
    }
    return null;
}

/**
 * Executes a function asynchronously.
 *
 * @param {Function} fn the function to execute
 * @param {*[]} args an array of arguments to execute the function with
 * @param {Object} [context] the optional context
 */
export function executeAsync(fn, args, context) {
    if (isFunction(fn)) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                try {
                    resolve(fn.apply(context || {}, args));
                } catch (error) {
                    reject(error);
                }
            });
        });
    }
    return null;
}

/**
 * A store implementation in memory.
 */
export class InMemoryStore {

    //this.settings = {};

    /**
     * Creates an instance.
     */
    constructor() {
        this.settings = {};
    }

    /**
     * Loads values.
     *
     * @param {Function} successCallback the callback invoked on success (with parameter {})
     */
    load(successCallback) {
        executeAsync(successCallback, [merge({}, this.settings)]);
    };

    /**
     * Saves values.
     *
     * @param {Object} settings the settings to save
     * @param {Function} successCallback the success callback to invoke on success
     */
    save(settings, successCallback) {
        // Assign the settings
        this.settings = merge(this.settings, settings);

        // Invoke the callback
        executeAsync(successCallback, [merge({}, this.settings)]);
    };

    /**
     * Clears values.
     *
     * @param {Function} successCallback the success callback to invoke on success
     */
    clear(successCallback) {
        this.settings = {};

        executeAsync(successCallback, [{}]);
    };

};

/**
 * Implementation for SettingsManager, a class for storing settings.
 *
 * @param {Object} [backingStore] optional backing store to wrap
 */
export class SettingsManager {

    /**
     * Creates a SettingsManager instance backed by an optional store.
     *
     * @param {Store} [backingStore] optional store implementation to use
     */
    constructor(backingStore) {
        this.backingStore = backingStore || new InMemoryStore();
    }

    /**
     * Loads values.
     *
     * @param {Function} [successCallback] the callback invoked on success (invoked with the settings)
     * @param {Function} [errorCallback] the error callback, invoked on failure
     */
    load(successCallback, errorCallback) {
        this.backingStore.load(function onLoad(settings) {
            execute(successCallback, [settings], this.backingStore);
        }, errorCallback);
    };

    /**
     * Saves values.
     *
     * @param {Object} settings the settings to save
     * @param {Function} [successCallback] the callback invoked on success
     * @param {Function} [errorCallback] the error callback, invoked on failure
     */
    save(settings, successCallback, errorCallback) {
        if (!settings) {
            executeAsync(successCallback, [{}]);
        } else if (isObject(settings)) {
            execute(this.backingStore.save, [settings, successCallback, errorCallback], this.backingStore);
        } else {
            executeAsync(errorCallback, ['"settings" is not an object']);
        }
    };

    /**
     * Clears values.
     *
     * @param {Function} successCallback the success callback to invoke on success
     * @param {Function} [errorCallback] the error callback, invoked on failure
     */
    clear(successCallback, errorCallback) {
        executeAsync(this.backingStore.clear, [successCallback, errorCallback], this.backingStore);
    };

}
<|endoftext|>


<commit_before>/*
 * post-hover.js
 * https://github.com/savetheinternet/Tinyboard-Tools/blob/master/js/post-hover.js
 *
 * Released under the MIT license
 * Copyright (c) 2012 Michael Save <savetheinternet@tinyboard.org>
 *
 * Usage:
 *   $config['additional_javascript'][] = 'js/jquery.min.js';
 *   $config['additional_javascript'][] = 'js/post-hover.js';
 *
 */

$(document).ready(function(){
	var dont_fetch_again = [];
	$('p.body a:not([rel="nofollow"])').each(function() {
		var id;

		if(id = $(this).text().match(/^>>(\d+)$/)) {
			id = id[1];
		}

		var post = false;
		$(this).hover(function(e) {
			var start_hover = function(link) {
				if(post.is(':visible') && $(window).scrollTop() <= post.offset().top + post.height()) {
					// post is in view
					post.attr('style', 'border-style: none dashed dashed none; background: ' + post.css('border-right-color'));
				} else {
					var top = e.pageY - post.height() - 15;

					post.clone()
						.attr('id', 'post-hover-' + id)
						.addClass('post-hover')
						.css('position', 'absolute')
						.css('border-style', 'solid')
						.css('box-shadow', '1px 1px 1px #999')
						.css('display', 'block')
						.css('left', e.pageX)
						.css('top', top > $(window).scrollTop() ? top : $(window).scrollTop())
						.insertAfter($(link).parent());
					$(link).trigger('mousemove');
				}
			};

			post = $('div.post#reply_' + id);
			if(post.length > 0) {
				start_hover(this);
			} else {
				var link = this;

				if($.inArray($(this).attr('href'), dont_fetch_again) != -1) {
					return;
				}

				dont_fetch_again.push($(this).attr('href'));
				$.ajax({
					url: $(this).attr('href'),
					context: document.body,
					success: function(data) {
						post = $('div.post:first')
								.prepend($(data).find('div.post#reply_' + id).css('display', 'none').addClass('hidden'))
								.find('div.post#reply_' + id);
						if(typeof window.enable_fa == 'function' && localStorage['forcedanon'])
							enable_fa();
						start_hover(link);
					}
				});
			}
		}, function() {
			if(!post)
				return;
			post.attr('style', '');
			if(post.hasClass('hidden'))
				post.css('display', 'none');
			$('.post-hover').remove();
		}).mousemove(function(e) {
			if(!post)
				return;
			var top = e.pageY - post.height() - 15;
			$('#post-hover-' + id)
				.css('left', e.pageX)
				.css('top', top > $(window).scrollTop() ? top : $(window).scrollTop());
		});
	});
});

<commit_msg>Check if post is below viewable region.<commit_after>/*
 * post-hover.js
 * https://github.com/savetheinternet/Tinyboard-Tools/blob/master/js/post-hover.js
 *
 * Released under the MIT license
 * Copyright (c) 2012 Michael Save <savetheinternet@tinyboard.org>
 *
 * Usage:
 *   $config['additional_javascript'][] = 'js/jquery.min.js';
 *   $config['additional_javascript'][] = 'js/post-hover.js';
 *
 */

$(document).ready(function(){
	var dont_fetch_again = [];
	$('p.body a:not([rel="nofollow"])').each(function() {
		var id;

		if(id = $(this).text().match(/^>>(\d+)$/)) {
			id = id[1];
		}

		var post = false;
		var hovering = false;
		$(this).hover(function(e) {
			hovering = true;

			var start_hover = function(link) {
				if(post.is(':visible') &&
						post.offset().top + post.height() >= $(window).scrollTop() &&
						post.offset().top <= $(window).scrollTop() + $(window).height()
						) {
					// post is in view
					post.attr('style', 'border-style: none dashed dashed none; background: ' + post.css('border-right-color'));
				} else {
					var top = e.pageY - post.height() - 15;

					post.clone()
						.attr('id', 'post-hover-' + id)
						.addClass('post-hover')
						.css('position', 'absolute')
						.css('border-style', 'solid')
						.css('box-shadow', '1px 1px 1px #999')
						.css('display', 'block')
						.css('left', e.pageX)
						.css('top', top > $(window).scrollTop() ? top : $(window).scrollTop())
						.insertAfter($(link).parent());
					$(link).trigger('mousemove');
				}
			};

			post = $('div.post#reply_' + id);
			console.log(post);
			if(post.length > 0) {
				start_hover(this);
			} else {
				var link = this;

				if($.inArray($(this).attr('href'), dont_fetch_again) != -1) {
					return;
				}

				dont_fetch_again.push($(this).attr('href'));
				$.ajax({
					url: $(this).attr('href'),
					context: document.body,
					success: function(data) {
						post = $('div.post:first')
								.prepend($(data).find('div.post#reply_' + id).css('display', 'none').addClass('hidden'))
								.find('div.post#reply_' + id);
						if(typeof window.enable_fa == 'function' && localStorage['forcedanon'])
							enable_fa();
						if(hovering)
							start_hover(link);
					}
				});
			}
		}, function() {
			hovering = false;
			if(!post)
				return;

			post.attr('style', '');
			if(post.hasClass('hidden'))
				post.css('display', 'none');
			$('.post-hover').remove();
		}).mousemove(function(e) {
			if(!post)
				return;
			var top = e.pageY - post.height() - 15;
			$('#post-hover-' + id)
				.css('left', e.pageX)
				.css('top', top > $(window).scrollTop() ? top : $(window).scrollTop());
		});
	});
});

<|endoftext|>


<commit_before>/*jshint node:true*/
module.exports = {
  description: 'Installs config',

  afterInstall: function(options) {
    return this.addAddonToProject({ name: 'flexi-config' });
  }
};
<commit_msg>fix(blueprint) include normalizeEntityName()<commit_after>/*jshint node:true*/
module.exports = {
  normalizeEntityName: function() {},

  afterInstall: function(options) {
    return this.addAddonToProject({ name: 'flexi-config' });
  }
};
<|endoftext|>


<commit_before>"use strict";

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');

//  ---------------------------------------------------------------------------

module.exports = class quadrigacx extends Exchange {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'quadrigacx',
            'name': 'QuadrigaCX',
            'countries': 'CA',
            'rateLimit': 1000,
            'version': 'v2',
            'hasCORS': true,
            // obsolete metainfo interface
            'hasWithdraw': true,
            // new metainfo interface
            'has': {
                'withdraw': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766825-98a6d0de-5ee7-11e7-9fa4-38e11a2c6f52.jpg',
                'api': 'https://api.quadrigacx.com',
                'www': 'https://www.quadrigacx.com',
                'doc': 'https://www.quadrigacx.com/api_info',
            },
            'requiredCredentials': {
                'apiKey': true,
                'secret': true,
                'uid': true,
            },
            'api': {
                'public': {
                    'get': [
                        'order_book',
                        'ticker',
                        'transactions',
                    ],
                },
                'private': {
                    'post': [
                        'balance',
                        'bitcoin_deposit_address',
                        'bitcoin_withdrawal',
                        'buy',
                        'cancel_order',
                        'ether_deposit_address',
                        'ether_withdrawal',
                        'lookup_order',
                        'open_orders',
                        'sell',
                        'user_transactions',
                    ],
                },
            },
            'markets': {
                'BTC/CAD': { 'id': 'btc_cad', 'symbol': 'BTC/CAD', 'base': 'BTC', 'quote': 'CAD', 'maker': 0.005, 'taker': 0.005 },
                'BTC/USD': { 'id': 'btc_usd', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD', 'maker': 0.005, 'taker': 0.005 },
                'ETH/BTC': { 'id': 'eth_btc', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC', 'maker': 0.002, 'taker': 0.002 },
                'ETH/CAD': { 'id': 'eth_cad', 'symbol': 'ETH/CAD', 'base': 'ETH', 'quote': 'CAD', 'maker': 0.005, 'taker': 0.005 },
                'LTC/CAD': { 'id': 'ltc_cad', 'symbol': 'LTC/CAD', 'base': 'LTC', 'quote': 'CAD', 'maker': 0.005, 'taker': 0.005 },
                'BCH/CAD': { 'id': 'bch_cad', 'symbol': 'BCH/CAD', 'base': 'BCH', 'quote': 'CAD', 'maker': 0.005, 'taker': 0.005 },
                'BTG/CAD': { 'id': 'btg_cad', 'symbol': 'BTG/CAD', 'base': 'BTG', 'quote': 'CAD', 'maker': 0.005, 'taker': 0.005 },
            },
        });
    }

    async fetchBalance (params = {}) {
        let balances = await this.privatePostBalance ();
        let result = { 'info': balances };
        let currencies = Object.keys (this.currencies);
        for (let i = 0; i < currencies.length; i++) {
            let currency = currencies[i];
            let lowercase = currency.toLowerCase ();
            let account = {
                'free': parseFloat (balances[lowercase + '_available']),
                'used': parseFloat (balances[lowercase + '_reserved']),
                'total': parseFloat (balances[lowercase + '_balance']),
            };
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, params = {}) {
        let orderbook = await this.publicGetOrderBook (this.extend ({
            'book': this.marketId (symbol),
        }, params));
        let timestamp = parseInt (orderbook['timestamp']) * 1000;
        return this.parseOrderBook (orderbook, timestamp);
    }

    async fetchTicker (symbol, params = {}) {
        let ticker = await this.publicGetTicker (this.extend ({
            'book': this.marketId (symbol),
        }, params));
        let timestamp = parseInt (ticker['timestamp']) * 1000;
        let vwap = parseFloat (ticker['vwap']);
        let baseVolume = parseFloat (ticker['volume']);
        let quoteVolume = baseVolume * vwap;
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': parseFloat (ticker['high']),
            'low': parseFloat (ticker['low']),
            'bid': parseFloat (ticker['bid']),
            'ask': parseFloat (ticker['ask']),
            'vwap': vwap,
            'open': undefined,
            'close': undefined,
            'first': undefined,
            'last': parseFloat (ticker['last']),
            'change': undefined,
            'percentage': undefined,
            'average': undefined,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        };
    }

    parseTrade (trade, market) {
        let timestamp = parseInt (trade['date']) * 1000;
        return {
            'info': trade,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'id': trade['tid'].toString (),
            'order': undefined,
            'type': undefined,
            'side': trade['side'],
            'price': parseFloat (trade['price']),
            'amount': parseFloat (trade['amount']),
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        let market = this.market (symbol);
        let response = await this.publicGetTransactions (this.extend ({
            'book': market['id'],
        }, params));
        return this.parseTrades (response, market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        let method = 'privatePost' + this.capitalize (side);
        let order = {
            'amount': amount,
            'book': this.marketId (symbol),
        };
        if (type == 'limit')
            order['price'] = price;
        let response = await this[method] (this.extend (order, params));
        return {
            'info': response,
            'id': response['id'].toString (),
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        return await this.privatePostCancelOrder (this.extend ({
            'id': id,
        }, params));
    }

    async fetchDepositAddress (currency, params = {}) {
        let method = 'privatePost' + this.getCurrencyName (currency) + 'DepositAddress';
        let response = await this[method] (params);
        let address = undefined;
        let status = undefined;
        // [E|e]rror
        if (response.indexOf ('rror') >= 0) {
            status = 'error';
        } else {
            address = response;
            status = 'ok';
        }
        return {
            'currency': currency,
            'address': address,
            'status': status,
            'info': this.last_http_response,
        };
    }

    getCurrencyName (currency) {
        if (currency == 'ETH')
            return 'Ether';
        if (currency == 'BTC')
            return 'Bitcoin';
    }

    async withdraw (currency, amount, address, params = {}) {
        await this.loadMarkets ();
        let request = {
            'amount': amount,
            'address': address,
        };
        let method = 'privatePost' + this.getCurrencyName (currency) + 'Withdrawal';
        let response = await this[method] (this.extend (request, params));
        return {
            'info': response,
            'id': undefined,
        };
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'] + '/' + this.version + '/' + path;
        if (api == 'public') {
            url += '?' + this.urlencode (params);
        } else {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ();
            let request = [ nonce.toString (), this.uid, this.apiKey ].join ('');
            let signature = this.hmac (this.encode (request), this.encode (this.secret));
            let query = this.extend ({
                'key': this.apiKey,
                'nonce': nonce,
                'signature': signature,
            }, params);
            body = this.json (query);
            headers = {
                'Content-Type': 'application/json',
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if (typeof response === 'string')
            return response;
        if ('error' in response)
            throw new ExchangeError (this.id + ' ' + this.json (response));
        return response;
    }
}
<commit_msg>quadrigacx withdraw tag and linting #1313<commit_after>'use strict';

//  ---------------------------------------------------------------------------

const Exchange = require ('./base/Exchange');
const { ExchangeError } = require ('./base/errors');

//  ---------------------------------------------------------------------------

module.exports = class quadrigacx extends Exchange {

    describe () {
        return this.deepExtend (super.describe (), {
            'id': 'quadrigacx',
            'name': 'QuadrigaCX',
            'countries': 'CA',
            'rateLimit': 1000,
            'version': 'v2',
            'hasCORS': true,
            // obsolete metainfo interface
            'hasWithdraw': true,
            // new metainfo interface
            'has': {
                'withdraw': true,
            },
            'urls': {
                'logo': 'https://user-images.githubusercontent.com/1294454/27766825-98a6d0de-5ee7-11e7-9fa4-38e11a2c6f52.jpg',
                'api': 'https://api.quadrigacx.com',
                'www': 'https://www.quadrigacx.com',
                'doc': 'https://www.quadrigacx.com/api_info',
            },
            'requiredCredentials': {
                'apiKey': true,
                'secret': true,
                'uid': true,
            },
            'api': {
                'public': {
                    'get': [
                        'order_book',
                        'ticker',
                        'transactions',
                    ],
                },
                'private': {
                    'post': [
                        'balance',
                        'bitcoin_deposit_address',
                        'bitcoin_withdrawal',
                        'buy',
                        'cancel_order',
                        'ether_deposit_address',
                        'ether_withdrawal',
                        'lookup_order',
                        'open_orders',
                        'sell',
                        'user_transactions',
                    ],
                },
            },
            'markets': {
                'BTC/CAD': { 'id': 'btc_cad', 'symbol': 'BTC/CAD', 'base': 'BTC', 'quote': 'CAD', 'maker': 0.005, 'taker': 0.005 },
                'BTC/USD': { 'id': 'btc_usd', 'symbol': 'BTC/USD', 'base': 'BTC', 'quote': 'USD', 'maker': 0.005, 'taker': 0.005 },
                'ETH/BTC': { 'id': 'eth_btc', 'symbol': 'ETH/BTC', 'base': 'ETH', 'quote': 'BTC', 'maker': 0.002, 'taker': 0.002 },
                'ETH/CAD': { 'id': 'eth_cad', 'symbol': 'ETH/CAD', 'base': 'ETH', 'quote': 'CAD', 'maker': 0.005, 'taker': 0.005 },
                'LTC/CAD': { 'id': 'ltc_cad', 'symbol': 'LTC/CAD', 'base': 'LTC', 'quote': 'CAD', 'maker': 0.005, 'taker': 0.005 },
                'BCH/CAD': { 'id': 'bch_cad', 'symbol': 'BCH/CAD', 'base': 'BCH', 'quote': 'CAD', 'maker': 0.005, 'taker': 0.005 },
                'BTG/CAD': { 'id': 'btg_cad', 'symbol': 'BTG/CAD', 'base': 'BTG', 'quote': 'CAD', 'maker': 0.005, 'taker': 0.005 },
            },
        });
    }

    async fetchBalance (params = {}) {
        let balances = await this.privatePostBalance ();
        let result = { 'info': balances };
        let currencies = Object.keys (this.currencies);
        for (let i = 0; i < currencies.length; i++) {
            let currency = currencies[i];
            let lowercase = currency.toLowerCase ();
            let account = {
                'free': parseFloat (balances[lowercase + '_available']),
                'used': parseFloat (balances[lowercase + '_reserved']),
                'total': parseFloat (balances[lowercase + '_balance']),
            };
            result[currency] = account;
        }
        return this.parseBalance (result);
    }

    async fetchOrderBook (symbol, params = {}) {
        let orderbook = await this.publicGetOrderBook (this.extend ({
            'book': this.marketId (symbol),
        }, params));
        let timestamp = parseInt (orderbook['timestamp']) * 1000;
        return this.parseOrderBook (orderbook, timestamp);
    }

    async fetchTicker (symbol, params = {}) {
        let ticker = await this.publicGetTicker (this.extend ({
            'book': this.marketId (symbol),
        }, params));
        let timestamp = parseInt (ticker['timestamp']) * 1000;
        let vwap = parseFloat (ticker['vwap']);
        let baseVolume = parseFloat (ticker['volume']);
        let quoteVolume = baseVolume * vwap;
        return {
            'symbol': symbol,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'high': parseFloat (ticker['high']),
            'low': parseFloat (ticker['low']),
            'bid': parseFloat (ticker['bid']),
            'ask': parseFloat (ticker['ask']),
            'vwap': vwap,
            'open': undefined,
            'close': undefined,
            'first': undefined,
            'last': parseFloat (ticker['last']),
            'change': undefined,
            'percentage': undefined,
            'average': undefined,
            'baseVolume': baseVolume,
            'quoteVolume': quoteVolume,
            'info': ticker,
        };
    }

    parseTrade (trade, market) {
        let timestamp = parseInt (trade['date']) * 1000;
        return {
            'info': trade,
            'timestamp': timestamp,
            'datetime': this.iso8601 (timestamp),
            'symbol': market['symbol'],
            'id': trade['tid'].toString (),
            'order': undefined,
            'type': undefined,
            'side': trade['side'],
            'price': parseFloat (trade['price']),
            'amount': parseFloat (trade['amount']),
        };
    }

    async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
        let market = this.market (symbol);
        let response = await this.publicGetTransactions (this.extend ({
            'book': market['id'],
        }, params));
        return this.parseTrades (response, market, since, limit);
    }

    async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
        let method = 'privatePost' + this.capitalize (side);
        let order = {
            'amount': amount,
            'book': this.marketId (symbol),
        };
        if (type === 'limit')
            order['price'] = price;
        let response = await this[method] (this.extend (order, params));
        return {
            'info': response,
            'id': response['id'].toString (),
        };
    }

    async cancelOrder (id, symbol = undefined, params = {}) {
        return await this.privatePostCancelOrder (this.extend ({
            'id': id,
        }, params));
    }

    async fetchDepositAddress (currency, params = {}) {
        let method = 'privatePost' + this.getCurrencyName (currency) + 'DepositAddress';
        let response = await this[method] (params);
        let address = undefined;
        let status = undefined;
        // [E|e]rror
        if (response.indexOf ('rror') >= 0) {
            status = 'error';
        } else {
            address = response;
            status = 'ok';
        }
        return {
            'currency': currency,
            'address': address,
            'status': status,
            'info': this.last_http_response,
        };
    }

    getCurrencyName (currency) {
        if (currency === 'ETH')
            return 'Ether';
        if (currency === 'BTC')
            return 'Bitcoin';
    }

    async withdraw (currency, amount, address, tag = undefined, params = {}) {
        await this.loadMarkets ();
        let request = {
            'amount': amount,
            'address': address,
        };
        let method = 'privatePost' + this.getCurrencyName (currency) + 'Withdrawal';
        let response = await this[method] (this.extend (request, params));
        return {
            'info': response,
            'id': undefined,
        };
    }

    sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let url = this.urls['api'] + '/' + this.version + '/' + path;
        if (api === 'public') {
            url += '?' + this.urlencode (params);
        } else {
            this.checkRequiredCredentials ();
            let nonce = this.nonce ();
            let request = [ nonce.toString (), this.uid, this.apiKey ].join ('');
            let signature = this.hmac (this.encode (request), this.encode (this.secret));
            let query = this.extend ({
                'key': this.apiKey,
                'nonce': nonce,
                'signature': signature,
            }, params);
            body = this.json (query);
            headers = {
                'Content-Type': 'application/json',
            };
        }
        return { 'url': url, 'method': method, 'body': body, 'headers': headers };
    }

    async request (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
        let response = await this.fetch2 (path, api, method, params, headers, body);
        if (typeof response === 'string')
            return response;
        if ('error' in response)
            throw new ExchangeError (this.id + ' ' + this.json (response));
        return response;
    }
}
<|endoftext|>


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

    var React = require('react'),
        ReactIntl = require('react-intl'),
        IntlMixin = ReactIntl.IntlMixin,
        FormattedMessage = ReactIntl.FormattedMessage;

    module.exports = React.createClass({
        mixins: [IntlMixin],
        propTypes: {
            value: React.PropTypes.number,
            onChange: React.PropTypes.func,
            showClear: React.PropTypes.bool
        },

        getDefaultProps: function () {
            return {
                value: 0,
                size: 5,
                showClear: true,
                messages: {
                    'react-star-rating-input': {
                        clear: 'Clear',
                        reset: 'Reset value to no stars'
                    }
                }
            };
        },

        getInitialState: function () {
            return {prospectiveValue: 0};
        },

        render: function () {
            return React.DOM.div(
                {className: 'star-rating-input'},
                [this.clearingItem()].concat(this.starItems())
            );
        },

        clearingItem: function () {
            return React.DOM.div(
                {className: 'star-rating-clear-container', key: 0},

                React.DOM.a({
                    className: 'star-rating-clear',
                    title: React.createElement(FormattedMessage, {
                        message: this.getIntlMessage('react-star-rating-input.reset')
                    }),
                    href: '',
                    ref: 's0',
                    style: this.props.showClear ? null : {display: 'none'},

                    onClick: function (e) {
                        e.preventDefault();
                        this.setState({prospectiveValue: 0});
                        this.props.onChange(0);
                    }.bind(this)
                }, React.createElement(FormattedMessage, {
                    message: this.getIntlMessage('react-star-rating-input.clear')
                }))
            );
        },

        starItems: function () {
            var stars = [],
                i;
            for (i = 1; i <= this.props.size; i += 1) {
                stars.push(this.starItem(i, this.anchorMode(i)));
            }
            return stars;
        },

        starItem: function (value, mode) {
            return React.DOM.div(
                {className: 'star-rating-star-container', key: value},

                React.DOM.a({
                    className: 'star-rating-star ' + mode,
                    title: value,
                    href: '',
                    ref: 's' + value,

                    onMouseEnter: function () {
                        this.setState({prospectiveValue: value});
                    }.bind(this),

                    onMouseLeave: function () {
                        this.setState({prospectiveValue: 0});
                    }.bind(this),

                    onClick: function (e) {
                        e.preventDefault();
                        this.setState({prospectiveValue: 0});
                        this.props.onChange(value);
                    }.bind(this)
                }, value)
            );
        },

        anchorMode: function (value) {
            if (this.state.prospectiveValue > 0) {
                return (value <= this.state.prospectiveValue ? 'suggested' : 'off');
            }

            return (value <= this.props.value ? 'on' : 'off');
        }
    });
}());
<commit_msg>Fixed translation of title<commit_after>(function () {
    'use strict';

    var React = require('react'),
        ReactIntl = require('react-intl'),
        IntlMixin = ReactIntl.IntlMixin,
        FormattedMessage = ReactIntl.FormattedMessage;

    module.exports = React.createClass({
        mixins: [IntlMixin],
        propTypes: {
            value: React.PropTypes.number,
            onChange: React.PropTypes.func,
            showClear: React.PropTypes.bool
        },

        getDefaultProps: function () {
            return {
                value: 0,
                size: 5,
                showClear: true,
                messages: {
                    'react-star-rating-input': {
                        clear: 'Clear',
                        reset: 'Reset value to no stars'
                    }
                }
            };
        },

        getInitialState: function () {
            return {prospectiveValue: 0};
        },

        render: function () {
            return React.DOM.div(
                {className: 'star-rating-input'},
                [this.clearingItem()].concat(this.starItems())
            );
        },

        clearingItem: function () {
            return React.DOM.div(
                {className: 'star-rating-clear-container', key: 0},

                React.DOM.a({
                    className: 'star-rating-clear',
                    title: this.getIntlMessage('react-star-rating-input.reset'),
                    href: '',
                    ref: 's0',
                    style: this.props.showClear ? null : {display: 'none'},

                    onClick: function (e) {
                        e.preventDefault();
                        this.setState({prospectiveValue: 0});
                        this.props.onChange(0);
                    }.bind(this)
                }, React.createElement(FormattedMessage, {
                    message: this.getIntlMessage('react-star-rating-input.clear')
                }))
            );
        },

        starItems: function () {
            var stars = [],
                i;
            for (i = 1; i <= this.props.size; i += 1) {
                stars.push(this.starItem(i, this.anchorMode(i)));
            }
            return stars;
        },

        starItem: function (value, mode) {
            return React.DOM.div(
                {className: 'star-rating-star-container', key: value},

                React.DOM.a({
                    className: 'star-rating-star ' + mode,
                    title: value,
                    href: '',
                    ref: 's' + value,

                    onMouseEnter: function () {
                        this.setState({prospectiveValue: value});
                    }.bind(this),

                    onMouseLeave: function () {
                        this.setState({prospectiveValue: 0});
                    }.bind(this),

                    onClick: function (e) {
                        e.preventDefault();
                        this.setState({prospectiveValue: 0});
                        this.props.onChange(value);
                    }.bind(this)
                }, value)
            );
        },

        anchorMode: function (value) {
            if (this.state.prospectiveValue > 0) {
                return (value <= this.state.prospectiveValue ? 'suggested' : 'off');
            }

            return (value <= this.props.value ? 'on' : 'off');
        }
    });
}());
<|endoftext|>


<commit_before>(function() {
  'use strict';
  window.Whisper = window.Whisper || {};
  Whisper.ReadSyncs = new (Backbone.Collection.extend({
    forMessage: function(message) {
      var receipt = this.findWhere({
        sender: message.get('source'),
        timestamp: message.get('sent_at'),
      });
      if (receipt) {
        console.log('Found early read sync for message');
        this.remove(receipt);
        return receipt;
      }
    },
    onReceipt: function(receipt) {
      var messages = new Whisper.MessageCollection();
      return messages.fetchSentAt(receipt.get('timestamp')).then(
        function() {
          var message = messages.find(function(message) {
            return (
              message.isIncoming() &&
              message.isUnread() &&
              message.get('source') === receipt.get('sender')
            );
          });
          if (message) {
            Whisper.Notifications.remove(message);
            return message.markRead(receipt.get('read_at')).then(
              function() {
                this.notifyConversation(message);
                this.remove(receipt);
              }.bind(this)
            );
          } else {
            console.log(
              'No message for read sync',
              receipt.get('sender'),
              receipt.get('timestamp')
            );
          }
        }.bind(this)
      );
    },
    notifyConversation: function(message) {
      var conversation = ConversationController.get({
        id: message.get('conversationId'),
      });

      if (conversation) {
        conversation.onReadMessage(message);
      }
    },
  }))();
})();
<commit_msg>Log read sync reception and remove notification<commit_after>(function() {
  'use strict';
  window.Whisper = window.Whisper || {};
  Whisper.ReadSyncs = new (Backbone.Collection.extend({
    forMessage: function(message) {
      var receipt = this.findWhere({
        sender: message.get('source'),
        timestamp: message.get('sent_at'),
      });
      if (receipt) {
        console.log('Found early read sync for message');
        this.remove(receipt);
        return receipt;
      }
    },
    onReceipt: function(receipt) {
      var messages = new Whisper.MessageCollection();
      return messages.fetchSentAt(receipt.get('timestamp')).then(
        function() {
          var message = messages.find(function(message) {
            return (
              message.isIncoming() &&
              message.isUnread() &&
              message.get('source') === receipt.get('sender')
            );
          });
          const notificationForMessage = message
            ? Whisper.Notifications.findWhere({ messageId: message.id })
            : null;
          const removedNotification = Whisper.Notifications.remove(
            notificationForMessage
          );
          const receiptSender = receipt.get('sender');
          const receiptTimestamp = receipt.get('timestamp');
          const wasMessageFound = Boolean(message);
          const wasNotificationFound = Boolean(notificationForMessage);
          const wasNotificationRemoved = Boolean(removedNotification);
          console.log('Receive read sync:', {
            receiptSender,
            receiptTimestamp,
            wasMessageFound,
            wasNotificationFound,
            wasNotificationRemoved,
          });
          return message
            ? message.markRead(receipt.get('read_at')).then(
                function() {
                  this.notifyConversation(message);
                  this.remove(receipt);
                }.bind(this)
              )
            : Promise.resolve();
        }.bind(this)
      );
    },
    notifyConversation: function(message) {
      var conversation = ConversationController.get({
        id: message.get('conversationId'),
      });

      if (conversation) {
        conversation.onReadMessage(message);
      }
    },
  }))();
})();
<|endoftext|>


<commit_before>$(document).ready(function (){
    // Get window size
    var width = $(window).width(),
        height = $(window).height(),
    // Minimized the width
        costumizedWidth = width - 32,
        minimizedHeight = height -  300,
    // Get image by their class
        image = $('.artis-img'),
        headline = $('.headline-img'),
        ads = $('.ads'),
        artisAds = $('.artis-ads'),
        imagePost = $('.artis-image-post'),
        hottest = $('.hottest'),
        secondHottest = $('.secondhot'),
        thirdHottest = $('.thirdhot'),
        tristan = $('.tristan');

    if(navigator.userAgent.toLowerCase().indexOf("android") > -1) {
      // Set the width css
      image.css('width', width - 35);
      headline.css('width', costumizedWidth);
      ads.css('width', costumizedWidth);
      artisAds.css('height', minimizedHeight);
      artisAds.css('width', costumizedWidth);
      imagePost.css('width', costumizedWidth);
      hottest.css('width', width - 57);
      secondHottest.css('width', costumizedWidth);
      thirdHottest.css('width', costumizedWidth);
      tristan.css('width', costumizedWidth);
    }
    else if (navigator.userAgent.toLowerCase().indexOf("iphone") > -1 ){
      // Set the width css
      image.css('width', width - 35);
      headline.css('width', costumizedWidth);
      ads.css('width', costumizedWidth);
      artisAds.css('height', minimizedHeight);
      artisAds.css('width', costumizedWidth);
      imagePost.css('width', costumizedWidth);
      hottest.css('width', width - 57);
      secondHottest.css('width', costumizedWidth);
      thirdHottest.css('width', costumizedWidth);
      tristan.css('width', costumizedWidth);
    }
});
<commit_msg>Responsive meme image<commit_after>$(document).ready(function (){
    // Get window size
    var width = $(window).width(),
        height = $(window).height(),
    // Minimized the width
        costumizedWidth = width - 32,
        minimizedHeight = height -  300,
    // Get image by their class
        image = $('.artis-img'),
        headline = $('.headline-img'),
        ads = $('.ads'),
        artisAds = $('.artis-ads'),
        imagePost = $('.artis-image-post'),
        hottest = $('.hottest'),
        secondHottest = $('.secondhot'),
        thirdHottest = $('.thirdhot'),
        meme = $('.meme'),
        tristan = $('.tristan');

    if(navigator.userAgent.toLowerCase().indexOf("android") > -1) {
      // Set the width css
      image.css('width', width - 35);
      headline.css('width', costumizedWidth);
      ads.css('width', costumizedWidth);
      artisAds.css('height', minimizedHeight);
      artisAds.css('width', costumizedWidth);
      imagePost.css('width', costumizedWidth);
      hottest.css('width', width - 57);
      secondHottest.css('width', costumizedWidth);
      thirdHottest.css('width', costumizedWidth);
      meme.css('width', costumizedWidth);
      tristan.css('width', costumizedWidth);
    }
    else if (navigator.userAgent.toLowerCase().indexOf("iphone") > -1 ){
      // Set the width css
      image.css('width', width - 35);
      headline.css('width', costumizedWidth);
      ads.css('width', costumizedWidth);
      artisAds.css('height', minimizedHeight);
      artisAds.css('width', costumizedWidth);
      imagePost.css('width', costumizedWidth);
      hottest.css('width', width - 57);
      secondHottest.css('width', costumizedWidth);
      thirdHottest.css('width', costumizedWidth);
      meme.css('width', costumizedWidth);
      tristan.css('width', costumizedWidth);
    }
});
<|endoftext|>


<commit_before>"use strict";

var BIGGulp = {
	utilities: require("auto-loader").load(__dirname + "/utilities/")
};

BIGGulp.load = function() {
	console.log("loading");
};

module.exports = BIGGulp;<commit_msg>updated main bootstrapper<commit_after>"use strict";

var BIGGulp = require("./core");

function load() {
	var Loader = new BIGGulp.Loader();
	return Loader.load();
}

module.exports = {
	utilities: require("./utilities"),
	load: load
};<|endoftext|>


<commit_before>/*
    Date: 2016-01-06
*/
//
var currentFeed = {
    // reset when click('.feedLink')
    RSS           : "https://cordova.apache.org/feed.xml",
    entries       : [],
    // reset when getFeed();
    title         : "",
    description   : "",
    length        : "",
    lastBuildDate : "",
    selectedStory : ""
};

var readerApp = {
    self : {},
    needFeed : true,
    //
    init : function () {
        console.log("readerApp.init");
    },
    getFeed : function(externalElements) {
        externalElements['status']('Contacting Server ...');
        $.get(currentFeed.RSS, function(data, errorCode) {
              externalElements['status']('Got Feed.');
            var xml           = $( data );
              externalElements['status']('xml make object okay');
            var title         = xml.find( "title" );
              externalElements['status']('xml title okay');
            var description   = xml.find( "description" );
              externalElements['status']('xml description okay');
            var items         = xml.find( "item" );
              externalElements['status']('xml items okay');
            var lastBuildDate = xml.find( "lastBuildDate" );
              externalElements['status']('xml parse okay');
            currentFeed.title         = title.text();
            currentFeed.description   = description.text();
            currentFeed.lastBuildDate = lastBuildDate.text();
            currentFeed.length        = items.length;
            externalElements['status']('title:' + title.text() + ":" + items.length);
            // Parse our object
            currentFeed.entries = [];
            $.each(items, function(i, v) {
                entry = {
                    title:$(v).find("title").text(),
                    link:$(v).find("link").text(),
                    description:$.trim($(v).find("description").text())
                };
                currentFeed.entries.push(entry);
            });
            externalElements['draw'](currentFeed);
            externalElements['status']('Done.');
        });
    },
    getStory : function (displayFunc) {
        var theStory = currentFeed.entries[currentFeed.selectedStory];
        // fire only if we have a valid reference for theStory and a displayFunc.
        if (theStory && displayFunc) {
            displayFunc(theStory);
        }
    },
}
<commit_msg>update<commit_after>/*
    Date: 2016-01-06
*/
//
var currentFeed = {
    // reset when click('.feedLink')
    RSS           : "https://cordova.apache.org/feed.xml",
    entries       : [],
    // reset when getFeed();
    title         : "",
    description   : "",
    length        : "",
    lastBuildDate : "",
    selectedStory : ""
};

var readerApp = {
    self : {},
    needFeed : true,
    //
    init : function () {
        console.log("readerApp.init");
    },
    getFeed : function(externalElements) {
        externalElements['status']('Contacting Server ...');
        $.get(currentFeed.RSS, function(data, errorCode) {
            externalElements['status']('Got Feed.');
            // let's see if it will parse
            try {
                var xml           = $( data );
                externalElements['status']('xml make object okay');
            }
            catch(err) {
                externalElements['status']('Cannot create xml Object.');
                return;
            }
            //
            var title         = xml.find( "title" );
            var description   = xml.find( "description" );
            var items         = xml.find( "item" );
            var lastBuildDate = xml.find( "lastBuildDate" );
            // assign
            currentFeed.title         = title.text();
            currentFeed.description   = description.text();
            currentFeed.lastBuildDate = lastBuildDate.text();
            currentFeed.length        = items.length;
            externalElements['status']('title:' + title.text() + ":" + items.length);
            // Parse our object
            currentFeed.entries = [];
            $.each(items, function(i, v) {
                entry = {
                    title:$(v).find("title").text(),
                    link:$(v).find("link").text(),
                    description:$.trim($(v).find("description").text())
                };
                currentFeed.entries.push(entry);
            });
            externalElements['draw'](currentFeed);
            externalElements['status']('Done.');
        });
    },
    getStory : function (displayFunc) {
        var theStory = currentFeed.entries[currentFeed.selectedStory];
        // fire only if we have a valid reference for theStory and a displayFunc.
        if (theStory && displayFunc) {
            displayFunc(theStory);
        }
    },
}
<|endoftext|>


<commit_before>export default heapsort;

function ascendantComparator(a, b){
	return a - b;
}

function heapsort(array, comparator=ascendantComparator) {
	// TODO: implement heapsort
}
<commit_msg>styles misc<commit_after>export default heapsort;

function ascendantComparator(a, b) {
	return a - b;
}

function heapsort(array, comparator=ascendantComparator) {
	// TODO: implement heapsort
	return array;
}
<|endoftext|>


<commit_before>var gulp = require('gulp');
var webpack = require('webpack-stream');
var watch = require('gulp-watch');
var batch = require('gulp-batch');
var connect = require('gulp-connect');
var copy = require('gulp-copy');
var runSeq = require('run-sequence');

// Run webpack
gulp.task('webpack', function(){
  gulp.src('src/customer/main.js')
    .pipe(webpack( require('./customer_webpack.config.js') ))
    .pipe(gulp.dest('dist/customer/js/'))
    .pipe(connect.reload());
  gulp.src('src/bussiness/main.js')
    .pipe(webpack( require('./bussiness_webpack.config.js') ))
    .pipe(gulp.dest('dist/bussiness/js/'))
    .pipe(connect.reload());
  gulp.src('src/admin/main.js')
    .pipe(webpack( require('./admin_webpack.config.js') ))
    .pipe(gulp.dest('dist/admin/js/'))
    .pipe(connect.reload());
});

// Run the webserver
gulp.task('webserver_customer', function() {
  connect.server({
    port: 8080,
    livereload: {port: 35750},
    root: 'dist/customer'
  });
});

gulp.task('webserver_bussiness', function() {
  connect.server({
    port: 8081,
    livereload: {port: 35751},
    root: 'dist/bussiness'
  });
});

gulp.task('webserver_admin', function() {
  connect.server({
    port: 8082,
    livereload: {port: 35752},
    root: 'dist/admin'
  });
});

// Copy index.html file
gulp.task('build.index', function(){
  gulp.src('./src/customer/index.html')
    .pipe(gulp.dest('./dist/customer/'));
  gulp.src('./src/bussiness/index.html')
    .pipe(gulp.dest('./dist/bussiness/'));
  gulp.src('./src/admin/index.html')
    .pipe(gulp.dest('./dist/admin/'));
});

// Default task
gulp.task('default', function(callback) {
    runSeq('webserver_customer', 'webserver_bussiness', 'webserver_admin', ['webpack', 'build.index'], callback);
});
<commit_msg>debug the livereload<commit_after>var gulp = require('gulp');
var webpack = require('webpack-stream');
var watch = require('gulp-watch');
var batch = require('gulp-batch');
//var connect = require('gulp-connect');
var copy = require('gulp-copy');
var runSeq = require('run-sequence');
//var watch = require('gulp-watch');
var server = require('gulp-server-livereload');

// Run webpack
gulp.task('webpack', function() {
  gulp.src('src/customer/main.js')
    .pipe(webpack( require('./customer_webpack.config.js') ))
    .pipe(gulp.dest('dist/customer/js/'))
  gulp.src('src/bussiness/main.js')
    .pipe(webpack( require('./bussiness_webpack.config.js') ))
    .pipe(gulp.dest('dist/bussiness/js/'))
  gulp.src('src/admin/main.js')
    .pipe(webpack( require('./admin_webpack.config.js') ))
    .pipe(gulp.dest('dist/admin/js/'))
});

// Run the webserver
gulp.task('webserver_customer', function() {
  gulp.src('dist/customer')
    .pipe(server({
      livereload: {
        enable: true,
        port: 35729
      },
      port: 8080
    }));
});

gulp.task('webserver_bussiness', function() {
  gulp.src('dist/bussiness')
    .pipe(server({
      livereload: {
        enable: true,
        port: 35730
      },
      port: 8081
    }));
});

gulp.task('webserver_admin', function() {
  gulp.src('dist/admin')
    .pipe(server({
      livereload: {
        enable: true,
        port: 35731
      },
      port: 8082
    }));
});

// Copy index.html file
gulp.task('build.index', function(){
  gulp.src('src/customer/index.html')
    .pipe(gulp.dest('dist/customer/'));
  gulp.src('src/bussiness/index.html')
    .pipe(gulp.dest('dist/bussiness/'));
  gulp.src('src/admin/index.html')
    .pipe(gulp.dest('dist/admin/'))
});

// Watch changes in index.html file && main.js file
gulp.task('watch', function() {
  gulp.watch(['src/**/index.html'], ['build.index']);
  gulp.watch(['src/**/main.js'], ['webpack']);
});

// Default task
gulp.task('default', function(callback) {
  runSeq(['webpack', 'build.index', 'watch'], 'webserver_customer', 'webserver_bussiness', 'webserver_admin');
});<|endoftext|>


<commit_before>var express = require('express');
var _ = require('lodash');
var bodyParser = require('body-parser');
var morgan = require('morgan');

var config = require('./config');
var twilio = require('./twilio');
var middlewares = require('./middlewares');
var routes = require('./routes');

var app = express();

app.use(morgan('combined'));
app.use(bodyParser.json())

app.get('/', function(req, res) {
	res.send('hello world');
});

routes(app);

module.exports = {
	start: function () {
		var server = app.listen(config.port, function () {
			var host = server.address().address;
			var port = server.address().port;
			console.log('Listening at http://%s:%s', host, port);
		});
	}
}
<commit_msg>Log error<commit_after>var express = require('express');
var _ = require('lodash');
var bodyParser = require('body-parser');
var morgan = require('morgan');

var config = require('./config');
var twilio = require('./twilio');
var middlewares = require('./middlewares');
var routes = require('./routes');

var app = express();

app.use(morgan('combined'));
app.use(bodyParser.json())

app.get('/', function(req, res) {
	res.send('hello world');
});

routes(app);

app.use(function(error, req, res, next) {
	console.log("Error:", error.stack || error.message || error);
	res.status(500).send({
		error: error.message || error
	});
})

module.exports = {
	start: function () {
		var server = app.listen(config.port, function () {
			var host = server.address().address;
			var port = server.address().port;
			console.log('Listening at http://%s:%s', host, port);
		});
	}
}
<|endoftext|>


<commit_before>'use strict';

var Vue = require('vue'),
    Core = require('./core.js');

require('./filter.js');
var vueSettings = require('./settings.js');

Vue.config.debug = true;

var vue = new Vue({
    el: '#application',
    data: {
        tags: [],
        things: [],
        busyThings: true,
        busyFetchMore: false,
        search: '',
        username: '',
        password: '',
        settings: Core.settings.data,
        mainView: '',
        thingContent: '',
        activeThing: {},
        shareThingLink: '',
        importFile: null
    },
    methods: {
        giveAddFocus: function () {
            this.$els.addinput.focus();
        },
        addThing: function () {
            Core.things.add(this.thingContent, function (error) {
                if (error) return console.error(error);
                vue.thingContent = '';
                vue.refresh();
            });
        },
        showThingEdit: function (thing) {
            thing.edit = true;

            Vue.nextTick(function() {
                $('#editThingTextarea' + thing.id).focus();
            });
        },
        saveEdit: function (thing) {
            Core.things.edit(thing, function (error) {
                if (error) return console.error(error);
                thing.edit = false;
                vue.refresh();
            });
        },
        cancelEdit: function (thing) {
            thing.edit = false;
        },
        showThingDel: function (thing) {
            this.activeThing = thing;
            $('#modalDel').modal('show');
        },
        deleteThing: function () {
            if (!this.activeThing) return;

            Core.things.del(this.activeThing, function (error) {
                if (error) return console.error(error);

                vue.activeThing = null;
                vue.refresh();

                $('#modalDel').modal('hide');
            });
        },
        showThingShare: function (thing) {
            Core.things.publicLink(thing, function (error, publicLinkId) {
                if (error) return console.error(error);

                vue.shareThingLink = location.origin + '/thing.html?id=' + publicLinkId;

                $('#modalShare').modal('show');
            });
        },
        saveSettings: function () {
            Core.settings.set(this.settings);
            Core.settings.save(function (error) {
                if (error) return console.error(error);

                $('#modalSettings').modal('hide');
            });
        },
        showLogin: function () {
            this.mainView = 'login';
            setTimeout(function () {
                $('#inputUsername').focus();
            }, 0);
        },
        logout: function () {
            Core.session.logout();
        },
        doLogin: function () {
            Core.session.login(this.username, this.password, function (error) {
                if (error) {
                    vue.username = '';
                    vue.password = '';
                    $('#inputUsername').focus();

                    return console.error('Login failed:', error.status ? error.status : error);
                }

                main();
            });
        },
        refresh: function () {
            refresh();
        },
        doSearch: function () {
            window.location.href = '/#search?' + encodeURIComponent(this.search);
        },
        tagSearch: function (tag) {
            window.location.href = '/#search?#' + encodeURIComponent(tag.name);
        },
        clearSearch: function () {
            vue.search = '';
            refresh();
            $('#inputSearch').focus();
        },
        exportThings: function () {
            Core.things.export();
        },
        importFileChanged: function () {
            this.importFile = this.$els.importfile.files[0];
        },
        importThings: function () {
            var data = new FormData();
            data.append('import', this.$els.importfile.files[0]);

            Core.things.import(data, function (error) {
                if (error) console.error(error);

                // vueSettings.hide();
                vue.importFile = null;

                // TODO refresh
            });
        },
        importThingsCancel: function () {
            this.importFile = null;
        },
        triggerImportInput: function () {
            this.$els.importfile.click();
        }
    }
});

Core.settings.onChanged(function (data) {
    if (data.title) window.document.title = data.title;
    if (data.backgroundUrl) window.document.body.style.backgroundImage = 'url("' + data.backgroundUrl + '")';
});

function hashChangeHandler() {
    var action = window.location.hash.split('?')[0];
    var params = window.location.hash.indexOf('?') > 0 ? decodeURIComponent(window.location.hash.slice(window.location.hash.indexOf('?') + 1)) : null;

    if (action === '#add') {
        vue.showThingAdd();
    } else if (action === '#settings') {
        vueSettings.show();
    } else if (action === '#search' && params !== null) {
        vue.search = params;
        refresh(vue.search);
    } else {
        refresh(vue.search);
    }
}

window.addEventListener('hashchange', hashChangeHandler, false);

function reset() {
    vue.mainView = '';
    vue.things = [];
    vue.tags = [];
    vue.search = '';
    vue.username = '';
    vue.password = '';
    Core.settings.reset();
}

function main() {
    Core.settings.get(function (error) {
        if (error) return console.error(error);

        Core.tags.get(function (error, tags) {
            if (error) return console.error(error);

            vue.tags = tags;
            vue.mainView = 'content';

            window.setTimeout(function () { vue.$els.addinput.focus(); }, 0);

            hashChangeHandler();
        });
    });
}

function refresh(search) {
    vue.busyThings = true;

    window.location.href = '/#search?' + (search ? encodeURIComponent(search) : '');

    Core.things.get(search || '', function (error, data) {
        if (error) return console.error(error);

        vue.things = data;
        vue.busyThings = false;

        // add global object for browser extensions
        document.getElementById('guacamoly-settings-node').textContent = JSON.stringify({
            origin: Core.origin(),
            token: Core.token(),
            title: Core.settings.data.title
        });
    });
}

Core.things.onAdded(refresh);
Core.things.onEdited(refresh);
Core.things.onDeleted(refresh);

Core.loginFailed = vue.showLogin;
Core.onLogout = function () {
    reset();
    vue.showLogin();
};

// Main
main();

window.addEventListener('scroll', function () {
    // add 1 full pixel to be on the safe side for zoom settings, where pixel values might be floats
    if ($(window).height() + $(window).scrollTop() + 1 >= $(document).height()) {
        vue.busyFetchMore = true;

        Core.things.fetchMore(function (error, result) {
            vue.busyFetchMore = false;

            if (error) return console.error(error);

            vue.things = vue.things.concat(result);
        });
    }
});
<commit_msg>Do not use settings.js<commit_after>'use strict';

var Vue = require('vue'),
    Core = require('./core.js');

require('./filter.js');

Vue.config.debug = true;

var vue = new Vue({
    el: '#application',
    data: {
        tags: [],
        things: [],
        busyThings: true,
        busyFetchMore: false,
        search: '',
        username: '',
        password: '',
        settings: Core.settings.data,
        mainView: '',
        thingContent: '',
        activeThing: {},
        shareThingLink: '',
        importFile: null
    },
    methods: {
        giveAddFocus: function () {
            this.$els.addinput.focus();
        },
        addThing: function () {
            Core.things.add(this.thingContent, function (error) {
                if (error) return console.error(error);
                vue.thingContent = '';
                vue.refresh();
            });
        },
        showThingEdit: function (thing) {
            thing.edit = true;

            Vue.nextTick(function() {
                $('#editThingTextarea' + thing.id).focus();
            });
        },
        saveEdit: function (thing) {
            Core.things.edit(thing, function (error) {
                if (error) return console.error(error);
                thing.edit = false;
                vue.refresh();
            });
        },
        cancelEdit: function (thing) {
            thing.edit = false;
        },
        showThingDel: function (thing) {
            this.activeThing = thing;
            $('#modalDel').modal('show');
        },
        deleteThing: function () {
            if (!this.activeThing) return;

            Core.things.del(this.activeThing, function (error) {
                if (error) return console.error(error);

                vue.activeThing = null;
                vue.refresh();

                $('#modalDel').modal('hide');
            });
        },
        showThingShare: function (thing) {
            Core.things.publicLink(thing, function (error, publicLinkId) {
                if (error) return console.error(error);

                vue.shareThingLink = location.origin + '/thing.html?id=' + publicLinkId;

                $('#modalShare').modal('show');
            });
        },
        saveSettings: function () {
            Core.settings.set(this.settings);
            Core.settings.save(function (error) {
                if (error) return console.error(error);

                $('#modalSettings').modal('hide');
            });
        },
        showLogin: function () {
            this.mainView = 'login';
            setTimeout(function () {
                $('#inputUsername').focus();
            }, 0);
        },
        logout: function () {
            Core.session.logout();
        },
        doLogin: function () {
            Core.session.login(this.username, this.password, function (error) {
                if (error) {
                    vue.username = '';
                    vue.password = '';
                    $('#inputUsername').focus();

                    return console.error('Login failed:', error.status ? error.status : error);
                }

                main();
            });
        },
        refresh: function () {
            refresh();
        },
        doSearch: function () {
            window.location.href = '/#search?' + encodeURIComponent(this.search);
        },
        tagSearch: function (tag) {
            window.location.href = '/#search?#' + encodeURIComponent(tag.name);
        },
        clearSearch: function () {
            vue.search = '';
            refresh();
            $('#inputSearch').focus();
        },
        exportThings: function () {
            Core.things.export();
        },
        importFileChanged: function () {
            this.importFile = this.$els.importfile.files[0];
        },
        importThings: function () {
            var data = new FormData();
            data.append('import', this.$els.importfile.files[0]);

            Core.things.import(data, function (error) {
                if (error) console.error(error);

                // vueSettings.hide();
                vue.importFile = null;

                // TODO refresh
            });
        },
        importThingsCancel: function () {
            this.importFile = null;
        },
        triggerImportInput: function () {
            this.$els.importfile.click();
        }
    }
});

Core.settings.onChanged(function (data) {
    if (data.title) window.document.title = data.title;
    if (data.backgroundUrl) window.document.body.style.backgroundImage = 'url("' + data.backgroundUrl + '")';
});

function hashChangeHandler() {
    var action = window.location.hash.split('?')[0];
    var params = window.location.hash.indexOf('?') > 0 ? decodeURIComponent(window.location.hash.slice(window.location.hash.indexOf('?') + 1)) : null;

    if (action === '#add') {
        vue.showThingAdd();
    } else if (action === '#search' && params !== null) {
        vue.search = params;
        refresh(vue.search);
    } else {
        refresh(vue.search);
    }
}

window.addEventListener('hashchange', hashChangeHandler, false);

function reset() {
    vue.mainView = '';
    vue.things = [];
    vue.tags = [];
    vue.search = '';
    vue.username = '';
    vue.password = '';
    Core.settings.reset();
}

function main() {
    Core.settings.get(function (error) {
        if (error) return console.error(error);

        Core.tags.get(function (error, tags) {
            if (error) return console.error(error);

            vue.tags = tags;
            vue.mainView = 'content';

            window.setTimeout(function () { vue.$els.addinput.focus(); }, 0);

            hashChangeHandler();
        });
    });
}

function refresh(search) {
    vue.busyThings = true;

    window.location.href = '/#search?' + (search ? encodeURIComponent(search) : '');

    Core.things.get(search || '', function (error, data) {
        if (error) return console.error(error);

        vue.things = data;
        vue.busyThings = false;

        // add global object for browser extensions
        document.getElementById('guacamoly-settings-node').textContent = JSON.stringify({
            origin: Core.origin(),
            token: Core.token(),
            title: Core.settings.data.title
        });
    });
}

Core.things.onAdded(refresh);
Core.things.onEdited(refresh);
Core.things.onDeleted(refresh);

Core.loginFailed = vue.showLogin;
Core.onLogout = function () {
    reset();
    vue.showLogin();
};

// Main
main();

window.addEventListener('scroll', function () {
    // add 1 full pixel to be on the safe side for zoom settings, where pixel values might be floats
    if ($(window).height() + $(window).scrollTop() + 1 >= $(document).height()) {
        vue.busyFetchMore = true;

        Core.things.fetchMore(function (error, result) {
            vue.busyFetchMore = false;

            if (error) return console.error(error);

            vue.things = vue.things.concat(result);
        });
    }
});
<|endoftext|>


<commit_before>// parseHash retrives the access_token from the URL hash
function parseHash() {
  var accessTokenregex = /access_token=([\s\S]{64})&(?:token_type=\S*)&(uid=\d*)/;
  var regexResult;
  if (regexResult = accessTokenregex.exec(window.location.hash), !!regexResult && regexResult.length === 3) {
    return {
      accessToken: regexResult[1],
      uid: regexResult[2]
    };
  }
}

function openDropBoxAuth() {
  var DropboxAuthURL = 'https://www.dropbox.com/1/oauth2/authorize';
  window.location.href = DropboxAuthURL + '?client_id=pe3r68lcz7jt12e' + '&response_type=token' + '&redirect_uri=' + window.location.href;
}

// entry point
document.addEventListener('DOMContentLoaded', function (evt) {
  var h1 = document.getElementById('jsMessage');
  var authBtn = document.getElementById('chiAuth');
  // In case the page has an hash, check if it's valid
  if (window.location.hash !== '') {
    if (AT = parseHash(), !!AT) {
      h1.textContent = 'Access Token received!';
      // TODO: call server!
      reqwest({
        url: '/api/hello',
        data: {
          dropboxUser: AT.accessToken,
          dropboxUid: AT.uid
        }
      }).then(function (resp) {
        h1.textContent = 'Chinchilla approved!';
      })
      .fail(function (err, msg) {
        h1.textContent = 'Chinchilla disapproves: ' + err;
      });
    } else { // bad hash, clear it
      window.location.hash = '';
      h1.textContent = 'Access Token provided was BAD :(';
      setTimeout(function () { h1.textContent = ''; }, 5000);
    }
  }

  var chiUserID;
  if (chiUserID = localStorage.getItem('user'), !!chiUserID) {
    // TODO: AJAX TO VALIDATE chiUserID
    h1.text('Wow you\'re an actual user, that\'s.. just...WOW!');
  }
  authBtn.addEventListener('click', openDropBoxAuth);
});
<commit_msg>frontend: fixed user registration<commit_after>// parseHash retrives the access_token from the URL hash
function parseHash() {
  var accessTokenregex = /access_token=([\s\S]{64})&(?:token_type=\S*)&(uid=\d*)/;
  var regexResult;
  if (regexResult = accessTokenregex.exec(window.location.hash), !!regexResult && regexResult.length === 3) {
    return {
      accessToken: regexResult[1],
      uid: regexResult[2]
    };
  }
}

function openDropBoxAuth() {
  var DropboxAuthURL = 'https://www.dropbox.com/1/oauth2/authorize';
  window.location.href = DropboxAuthURL + '?client_id=pe3r68lcz7jt12e' + '&response_type=token' + '&redirect_uri=' + window.location.href;
}

// entry point
document.addEventListener('DOMContentLoaded', function (evt) {
  var h1 = document.getElementById('jsMessage');
  var authBtn = document.getElementById('chiAuth');
  // In case the page has an hash, check if it's valid
  if (window.location.hash !== '') {
    if (AT = parseHash(), !!AT) {
      h1.textContent = 'Access Token received!';
      // TODO: call server!
      reqwest({
        url: '/api/hello',
        method: 'POST',
        type: 'json',
        contentType: 'application/json',
        data: JSON.stringify({
          dropboxUser: AT.accessToken,
          dropboxUid: AT.uid
        })
      }).then(function (resp) {
        if (resp.status === 201) {
          h1.textContent = 'Chinchilla user created.';
        }
        if (resp.status === 200) {
          h1.textContent = 'Welcome Back!';
        }
      })
      .fail(function (err, msg) {
        h1.textContent = 'Chinchilla disapproves: check console for err';
        console.log(err);
      });
    } else { // bad hash, clear it
      window.location.hash = '';
      h1.textContent = 'Access Token provided was BAD :(';
      setTimeout(function () { h1.textContent = ''; }, 5000);
    }
  }

  var chiUserID;
  if (chiUserID = localStorage.getItem('user'), !!chiUserID) {
    // TODO: AJAX TO VALIDATE chiUserID
    h1.text('Wow you\'re an actual user, that\'s.. just...WOW!');
  }
  authBtn.addEventListener('click', openDropBoxAuth);
});
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var util = require('util');
var Transform = require('stream').Transform;

// Matches: 00:00:17,810 --> 00:00:20,330
var timeMatch = new RegExp(/\d+\:\d+\:\d+\,\d+\s\-\-\>\s\d+\:\d+\:\d+\,\d+/);
// Matches: "0:00:00.180,0:00:02.230"
var altTimeMatch = new RegExp(/\d+\:\d+\:\d+\.\d+\,\d+\:\d+\:\d+\.\d+/);

function Parser(opts) {
  // if no instance, call new
  if (!(this instanceof Parser)) {
    return new Parser(opts);
  }
  this.fileName = opts.fileName;
  Transform.call(this);
}

util.inherits(Parser, Transform);

Parser.prototype._transform = function _transform(data, enc, cb) {
  var buf = new Buffer(data);
  var str = buf.toString('utf-8');
  var begin = ['\n\n###', this.fileName.split('.')[0], '\n'];
  var parsed = begin.concat(str.split('\r\n')).filter(function(line) {
    return !timeMatch.test(line) &&
      !altTimeMatch.test(line) &&
      line != (line.match(/\d+/) && line.match(/\d+/)[0]);
  }).join(' ').replace(/\>\>/, '\n\n');
  this.push(parsed);
  cb();
};

var writeEnabled = false;

function frListener(fr) {
  fr.on('end', function() {
    writeEnabled = true;
  });
}

function write(pipe, fw) {
  frListener(pipe.fr);
  return pipe.fr
    .pipe(pipe.parser)
    .pipe(fw, { end: false });
}

function writing(filePipes, fileWriter) {
  if (filePipes.length == 1 ) {
    var pipe = filePipes.shift();
    return pipe.fr
      .pipe(pipe.parser)
      .pipe(fileWriter, { end: true });
  }

  // Setup recursion
  if (writeEnabled) {
    writeEnabled = false;
    write(filePipes.shift(), fileWriter);
    writing(filePipes, fileWriter);
  } else {
    setImmediate(function() {
      writing(filePipes, fileWriter);
    });
  }
}

module.exports = function(dirName, fileName) {
  var dir = process.argv[2] || dirName;
  if (!dir) throw new Error('Directory required');

  var file = process.argv[3] || fileName || path.join(dir, 'parsed-srt.txt');

  var title = '# ' + dir.split('/').pop() + '\n\n';

  var fileWriter = fs.createWriteStream(file);
  fileWriter.setMaxListeners(0);
  fileWriter.write(title);

  fs.readdir(dir, function(err, files) {
    var srtFiles = files.filter(function(file) {
      return /\.srt/.test(file);
    });
    var len = srtFiles.length;

    var pipes = srtFiles.map(function(srtFile) {
      var filePath = path.join(dir, srtFile);
      var fileReader = fs.createReadStream(filePath);
      var parseSrtFile = new Parser({ fileName: srtFile });

      return {
        fr: fileReader,
        parser: parseSrtFile
      };
    });
    writeEnabled = true;
    writing(pipes, fileWriter);
  });
};

<commit_msg>updated title<commit_after>var fs = require('fs');
var path = require('path');
var util = require('util');
var Transform = require('stream').Transform;

// Matches: 00:00:17,810 --> 00:00:20,330
var timeMatch = new RegExp(/\d+\:\d+\:\d+\,\d+\s\-\-\>\s\d+\:\d+\:\d+\,\d+/);
// Matches: "0:00:00.180,0:00:02.230"
var altTimeMatch = new RegExp(/\d+\:\d+\:\d+\.\d+\,\d+\:\d+\:\d+\.\d+/);

function Parser(opts) {
  // if no instance, call new
  if (!(this instanceof Parser)) {
    return new Parser(opts);
  }
  this.fileName = opts.fileName;
  Transform.call(this);
}

util.inherits(Parser, Transform);

Parser.prototype._transform = function _transform(data, enc, cb) {
  var buf = new Buffer(data);
  var str = buf.toString('utf-8');
  var begin = ['\n\n###', this.fileName.split('.')[0], '\n'];
  var parsed = begin.concat(str.split('\r\n')).filter(function(line) {
    return !timeMatch.test(line) &&
      !altTimeMatch.test(line) &&
      line != (line.match(/\d+/) && line.match(/\d+/)[0]);
  }).join(' ').replace(/\>\>/, '\n\n');
  this.push(parsed);
  cb();
};

var writeEnabled = false;

function frListener(fr) {
  fr.on('end', function() {
    writeEnabled = true;
  });
}

function write(pipe, fw) {
  frListener(pipe.fr);
  return pipe.fr
    .pipe(pipe.parser)
    .pipe(fw, { end: false });
}

function writing(filePipes, fileWriter) {
  if (filePipes.length == 1 ) {
    var pipe = filePipes.shift();
    return pipe.fr
      .pipe(pipe.parser)
      .pipe(fileWriter, { end: true });
  }

  // Setup recursion
  if (writeEnabled) {
    writeEnabled = false;
    write(filePipes.shift(), fileWriter);
    writing(filePipes, fileWriter);
  } else {
    setImmediate(function() {
      writing(filePipes, fileWriter);
    });
  }
}

module.exports = function(dirName, fileName) {
  var dir = process.argv[2] || dirName;
  if (!dir) throw new Error('Directory required');

  var file = process.argv[3] || fileName || path.join(dir, 'parsed-srt.txt');

  var title =  dir.split('/').filter(function(w) { return w; }).pop();
  var compiledTitle = '# ' + title + '\n\n';

  var fileWriter = fs.createWriteStream(file);
  fileWriter.setMaxListeners(0);
  fileWriter.write(compiledTitle);

  fs.readdir(dir, function(err, files) {
    var srtFiles = files.filter(function(file) {
      return /\.srt/.test(file);
    });
    var len = srtFiles.length;

    var pipes = srtFiles.map(function(srtFile) {
      var filePath = path.join(dir, srtFile);
      var fileReader = fs.createReadStream(filePath);
      var parseSrtFile = new Parser({ fileName: srtFile });

      return {
        fr: fileReader,
        parser: parseSrtFile
      };
    });
    writeEnabled = true;
    writing(pipes, fileWriter);
  });
};

<|endoftext|>


<commit_before>// Dependencies
var ReadJson = require("r-json");

/**
 * Namy
 * Gets the name of the exported function.
 *
 * @name Namy
 * @function
 * @param {String} input The path to the package.json, directory or the file.
 * @param {Function} callback The callback function.
 */
function Namy(input, callback) {
    if (/package.json$/.test(input)) {
        return ReadJson(input, function (err, data) {
            if (err) { return callback(err); }
            if (!data.main) {
                return callback(new Error("Cannot find the main field in package.json"));
            }
            Namy(data.main, callback);
        });
    }

    var path = require.resolve(input)
      , isInCache = !!require.cache[path]
      , res = require(input) // TODO Make this async
      , name = null
      ;

    if (typeof res === "function") {
        name = res.name || null;
    } else {
        return callback(new Error("The module does not export a function."));
    }

    if (!isInCache) {
        delete require.cache[path];
    }

    if (!name) {
        return callback(new Error("The function does not have a name."));
    }

    callback(null, name);
}

module.exports = Namy;
<commit_msg>Wrapping with try-catch<commit_after>// Dependencies
var ReadJson = require("r-json");

/**
 * Namy
 * Gets the name of the exported function.
 *
 * @name Namy
 * @function
 * @param {String} input The path to the package.json, directory or the file.
 * @param {Function} callback The callback function.
 */
function Namy(input, callback) {
    if (/package.json$/.test(input)) {
        return ReadJson(input, function (err, data) {
            if (err) { return callback(err); }
            if (!data.main) {
                return callback(new Error("Cannot find the main field in package.json"));
            }
            Namy(data.main, callback);
        });
    }

    var path = null
      , isInCache = null
      , res = null
      , name = null
      ;

    try {
        path = require.resolve(input)
        isInCache = !!require.cache[path]
        // TODO Make this async
        res = require(input)
    } catch (err) {
        return callback(err);
    }

    if (typeof res === "function") {
        name = res.name || null;
    } else {
        return callback(new Error("The module does not export a function."));
    }

    if (!isInCache) {
        delete require.cache[path];
    }

    if (!name) {
        return callback(new Error("The function does not have a name."));
    }

    callback(null, name);
}

module.exports = Namy;
<|endoftext|>