<commit_before>/* globals Meteor, Tracker, RocketChat */
'use strict';

var IPC = require('electron').ipcRenderer;

class Notification extends window.Notification {
	get onclick() {
		return super.onclick;
	}

	set onclick(fn) {
		var result = super.onclick = () => {
			IPC.sendToHost('focus');
			fn.apply(this, arguments);
		};
		return result;
	}
}

window.Notification = Notification;

var events = ['unread-changed'];

events.forEach(function(e) {
	window.addEventListener(e, function(event) {
		IPC.sendToHost(e, event.detail);
	});
});

window.addEventListener('load', function() {
	Meteor.startup(function() {
		Tracker.autorun(function() {
			var siteName = RocketChat.settings.get('Site_Name');
			if (siteName) {
				IPC.sendToHost('title-changed', siteName);
			}
		});
	});
});

var shell = require('shell');

var supportExternalLinks = function(e) {
	var href;
	var isExternal = false;

	var checkDomElement = function(element) {
		if (element.nodeName === 'A') {
			if (element.classList.contains('swipebox') === false) {
				href = element.getAttribute('href') || '';
			}
		}

		if (/^https?:\/\/.+/.test(href) === true /*&& RegExp('^https?:\/\/'+location.host).test(href) === false*/ ) {
			isExternal = true;
		}

		if (href && isExternal) {
			shell.openExternal(href);
			e.preventDefault();
		} else if (element.parentElement) {
			checkDomElement(element.parentElement);
		}
	};

	checkDomElement(e.target);
};

document.addEventListener('click', supportExternalLinks, false);

var webFrame = require('web-frame');
var remote = require('remote');
var webContents = remote.getCurrentWebContents();
var Menu = remote.require('menu');
var menu = new Menu();

var path = remote.require('path');

// set the initial context menu so that a context menu exists even before spellcheck is called
var getTemplate = function() {
	return [
		{
			label: 'Undo',
			role: 'undo'
		},
		{
			label: 'Redo',
			role: 'redo'
		},
		{
			type: 'separator'
		},
		{
			label: 'Cut',
			role: 'cut'
		},
		{
			label: 'Copy',
			role: 'copy'
		},
		{
			label: 'Paste',
			role: 'paste'
		},
		{
			label: 'Select All',
			role: 'selectall'
		}
	];
};

let languagesMenu;
let checker;
const enabledDictionaries = [];
let availableDictionaries = [];
let dictionariesPath;

if (localStorage.getItem('spellcheckerDictionaries')) {
	let spellcheckerDictionaries = JSON.parse(localStorage.getItem('spellcheckerDictionaries'));
	if (Array.isArray(spellcheckerDictionaries)) {
		enabledDictionaries.push.apply(enabledDictionaries, spellcheckerDictionaries);
	}
}

if (localStorage.getItem('userLanguage') && enabledDictionaries.indexOf(localStorage.getItem('userLanguage')) === -1) {
	enabledDictionaries.push(localStorage.getItem('userLanguage'));
}

const saveEnabledDictionaries = function() {
	localStorage.setItem('spellcheckerDictionaries', JSON.stringify(enabledDictionaries));
};

const isCorrect = function(text) {
	if (!checker) {
		return true;
	}

	let isCorrect = false;
	enabledDictionaries.forEach(function(enabledDictionary) {
		if (availableDictionaries.indexOf(enabledDictionary) === -1) {
			return;
		}

		checker.setDictionary(enabledDictionary, dictionariesPath);
		if (!checker.isMisspelled(text)) {
			isCorrect = true;
		}
	});

	return isCorrect;
};

const getCorrections = function(text) {
	// Create an array of arrays of corrections
	// One array of corrections per language
	let allCorrections = [];
	enabledDictionaries.forEach(function(enabledDictionary) {
		if (availableDictionaries.indexOf(enabledDictionary) === -1) {
			return;
		}

		checker.setDictionary(enabledDictionary, dictionariesPath);
		const languageCorrections = checker.getCorrectionsForMisspelling(text);
		if (languageCorrections.length > 0) {
			allCorrections.push(languageCorrections);
		}
	});

	// Get the size of biggest array
	let length = 0;
	allCorrections.forEach(function(items) {
		length = Math.max(length, items.length);
	});

	// Merge all arrays until the size of the biggest array
	// To get the best suggestions of each language first
	// Ex: [[1,2,3], [a,b]] => [1,a,2,b,3]
	const corrections = [];
	for (let i = 0; i < length; i++) {
		for (var j = 0; j < allCorrections.length; j++) {
			if (allCorrections[j][i]) {
				corrections.push(allCorrections[j][i]);
			}
		}
	}

	// Remove duplicateds
	corrections.forEach(function(item, index) {
		const dupIndex = corrections.indexOf(item, index+1);
		if (dupIndex > -1) {
			corrections.splice(dupIndex, 1);
		}
	});

	return corrections;
};

try {
	checker = require('spellchecker');

	availableDictionaries = checker.getAvailableDictionaries();

	if (availableDictionaries.length === 0) {
		dictionariesPath = path.join(remote.app.getAppPath(), '../dictionaries');
		console.log('dictionariesPath', dictionariesPath);
		availableDictionaries = [
			'en_US',
			'es_ES',
			'pt_BR'
		];
	}

	languagesMenu = {
		label: 'Spelling languages',
		submenu: []
	};

	availableDictionaries.forEach((dictionary) => {
		const menu = {
			label: dictionary,
			type: 'checkbox',
			checked: enabledDictionaries.indexOf(dictionary) > -1,
			click: function(menuItem) {
				menu.checked = menuItem.checked;
				if (menuItem.checked) {
					enabledDictionaries.push(dictionary);
				} else {
					enabledDictionaries.splice(enabledDictionaries.indexOf(dictionary), 1);
				}
				saveEnabledDictionaries();
			}
		};
		languagesMenu.submenu.push(menu);
	});

	webFrame.setSpellCheckProvider('', false, {
		spellCheck: function(text) {
			return isCorrect(text);
		}
	});
} catch(e) {
	console.log('Spellchecker unavailble');
}

window.addEventListener('contextmenu', function(event){
	event.preventDefault();

	const template = getTemplate();

	if (languagesMenu) {
		template.unshift({ type: 'separator' });
		template.unshift(languagesMenu);
	}

	setTimeout(function() {
		if (['TEXTAREA', 'INPUT'].indexOf(event.target.nodeName) > -1) {
			const text = window.getSelection().toString().trim();
			if (text !== '' && !isCorrect(text)) {
				const options = getCorrections(text);
				const maxItems = Math.min(options.length, 6);

				if (maxItems > 0) {
					const suggestions = [];
					const onClick = function(menuItem) {
						webContents.replaceMisspelling(menuItem.label);
					};

					for (let i = 0; i < options.length; i++) {
						const item = options[i];
						suggestions.push({ label: item, click: onClick });
					}

					template.unshift({ type: 'separator' });

					if (suggestions.length > maxItems) {
						const morSuggestions = {
							label: 'More spelling suggestions',
							submenu: suggestions.slice(maxItems)
						};
						template.unshift(morSuggestions);
					}

					template.unshift.apply(template, suggestions.slice(0, maxItems));
				} else {
					template.unshift({ label: 'no suggestions', click: function() { } });
				}
			}
		}

		menu = Menu.buildFromTemplate(template);
		menu.popup(remote.getCurrentWindow());
	}, 0);
}, false);
<commit_msg>Improve set of initial language<commit_after>/* globals Meteor, Tracker, RocketChat */
'use strict';

var IPC = require('electron').ipcRenderer;

class Notification extends window.Notification {
	get onclick() {
		return super.onclick;
	}

	set onclick(fn) {
		var result = super.onclick = () => {
			IPC.sendToHost('focus');
			fn.apply(this, arguments);
		};
		return result;
	}
}

window.Notification = Notification;

var events = ['unread-changed'];

events.forEach(function(e) {
	window.addEventListener(e, function(event) {
		IPC.sendToHost(e, event.detail);
	});
});

window.addEventListener('load', function() {
	Meteor.startup(function() {
		Tracker.autorun(function() {
			var siteName = RocketChat.settings.get('Site_Name');
			if (siteName) {
				IPC.sendToHost('title-changed', siteName);
			}
		});
	});
});

var shell = require('shell');

var supportExternalLinks = function(e) {
	var href;
	var isExternal = false;

	var checkDomElement = function(element) {
		if (element.nodeName === 'A') {
			if (element.classList.contains('swipebox') === false) {
				href = element.getAttribute('href') || '';
			}
		}

		if (/^https?:\/\/.+/.test(href) === true /*&& RegExp('^https?:\/\/'+location.host).test(href) === false*/ ) {
			isExternal = true;
		}

		if (href && isExternal) {
			shell.openExternal(href);
			e.preventDefault();
		} else if (element.parentElement) {
			checkDomElement(element.parentElement);
		}
	};

	checkDomElement(e.target);
};

document.addEventListener('click', supportExternalLinks, false);

var webFrame = require('web-frame');
var remote = require('remote');
var webContents = remote.getCurrentWebContents();
var Menu = remote.require('menu');
var menu = new Menu();

var path = remote.require('path');

// set the initial context menu so that a context menu exists even before spellcheck is called
var getTemplate = function() {
	return [
		{
			label: 'Undo',
			role: 'undo'
		},
		{
			label: 'Redo',
			role: 'redo'
		},
		{
			type: 'separator'
		},
		{
			label: 'Cut',
			role: 'cut'
		},
		{
			label: 'Copy',
			role: 'copy'
		},
		{
			label: 'Paste',
			role: 'paste'
		},
		{
			label: 'Select All',
			role: 'selectall'
		}
	];
};

let languagesMenu;
let checker;
const enabledDictionaries = [];
let availableDictionaries = [];
let dictionariesPath;

if (localStorage.getItem('spellcheckerDictionaries')) {
	let spellcheckerDictionaries = JSON.parse(localStorage.getItem('spellcheckerDictionaries'));
	if (Array.isArray(spellcheckerDictionaries)) {
		enabledDictionaries.push.apply(enabledDictionaries, spellcheckerDictionaries);
	}
}

if (enabledDictionaries.length === 0 && localStorage.getItem('userLanguage')) {
	enabledDictionaries.push(localStorage.getItem('userLanguage'));
}

if (enabledDictionaries.length === 0) {
	enabledDictionaries.push(navigator.language.replace('-', '_'));
}

const saveEnabledDictionaries = function() {
	localStorage.setItem('spellcheckerDictionaries', JSON.stringify(enabledDictionaries));
};

const isCorrect = function(text) {
	if (!checker) {
		return true;
	}

	let isCorrect = false;
	enabledDictionaries.forEach(function(enabledDictionary) {
		if (availableDictionaries.indexOf(enabledDictionary) === -1) {
			return;
		}

		checker.setDictionary(enabledDictionary, dictionariesPath);
		if (!checker.isMisspelled(text)) {
			isCorrect = true;
		}
	});

	return isCorrect;
};

const getCorrections = function(text) {
	// Create an array of arrays of corrections
	// One array of corrections per language
	let allCorrections = [];
	enabledDictionaries.forEach(function(enabledDictionary) {
		if (availableDictionaries.indexOf(enabledDictionary) === -1) {
			return;
		}

		checker.setDictionary(enabledDictionary, dictionariesPath);
		const languageCorrections = checker.getCorrectionsForMisspelling(text);
		if (languageCorrections.length > 0) {
			allCorrections.push(languageCorrections);
		}
	});

	// Get the size of biggest array
	let length = 0;
	allCorrections.forEach(function(items) {
		length = Math.max(length, items.length);
	});

	// Merge all arrays until the size of the biggest array
	// To get the best suggestions of each language first
	// Ex: [[1,2,3], [a,b]] => [1,a,2,b,3]
	const corrections = [];
	for (let i = 0; i < length; i++) {
		for (var j = 0; j < allCorrections.length; j++) {
			if (allCorrections[j][i]) {
				corrections.push(allCorrections[j][i]);
			}
		}
	}

	// Remove duplicateds
	corrections.forEach(function(item, index) {
		const dupIndex = corrections.indexOf(item, index+1);
		if (dupIndex > -1) {
			corrections.splice(dupIndex, 1);
		}
	});

	return corrections;
};

try {
	checker = require('spellchecker');

	availableDictionaries = checker.getAvailableDictionaries();

	if (availableDictionaries.length === 0) {
		dictionariesPath = path.join(remote.app.getAppPath(), '../dictionaries');
		console.log('dictionariesPath', dictionariesPath);
		availableDictionaries = [
			'en_US',
			'es_ES',
			'pt_BR'
		];
	}

	languagesMenu = {
		label: 'Spelling languages',
		submenu: []
	};

	availableDictionaries.forEach((dictionary) => {
		const menu = {
			label: dictionary,
			type: 'checkbox',
			checked: enabledDictionaries.indexOf(dictionary) > -1,
			click: function(menuItem) {
				menu.checked = menuItem.checked;
				if (menuItem.checked) {
					enabledDictionaries.push(dictionary);
				} else {
					enabledDictionaries.splice(enabledDictionaries.indexOf(dictionary), 1);
				}
				saveEnabledDictionaries();
			}
		};
		languagesMenu.submenu.push(menu);
	});

	webFrame.setSpellCheckProvider('', false, {
		spellCheck: function(text) {
			return isCorrect(text);
		}
	});
} catch(e) {
	console.log('Spellchecker unavailble');
}

window.addEventListener('contextmenu', function(event){
	event.preventDefault();

	const template = getTemplate();

	if (languagesMenu) {
		template.unshift({ type: 'separator' });
		template.unshift(languagesMenu);
	}

	setTimeout(function() {
		if (['TEXTAREA', 'INPUT'].indexOf(event.target.nodeName) > -1) {
			const text = window.getSelection().toString().trim();
			if (text !== '' && !isCorrect(text)) {
				const options = getCorrections(text);
				const maxItems = Math.min(options.length, 6);

				if (maxItems > 0) {
					const suggestions = [];
					const onClick = function(menuItem) {
						webContents.replaceMisspelling(menuItem.label);
					};

					for (let i = 0; i < options.length; i++) {
						const item = options[i];
						suggestions.push({ label: item, click: onClick });
					}

					template.unshift({ type: 'separator' });

					if (suggestions.length > maxItems) {
						const morSuggestions = {
							label: 'More spelling suggestions',
							submenu: suggestions.slice(maxItems)
						};
						template.unshift(morSuggestions);
					}

					template.unshift.apply(template, suggestions.slice(0, maxItems));
				} else {
					template.unshift({ label: 'no suggestions', click: function() { } });
				}
			}
		}

		menu = Menu.buildFromTemplate(template);
		menu.popup(remote.getCurrentWindow());
	}, 0);
}, false);
<|endoftext|>


<commit_before>var request = require('request'),
    async = require('async');

module.exports = function () {
    var self = this,
        flatten = function(arrayOfArray) {
            return [].concat.apply([], arrayOfArray);
        },
        buildProjectUrl = function(projectId) {
            return self.config.url + '/api/v4/projects/' + projectId;
        },
        buildProjectPipelinesUrl = function(projectId, ref) {
            var url = self.config.url + '/api/v4/projects/' + projectId + '/pipelines';
            if(ref) { url = url + '?ref=' + ref; }
            return url;
        },
        buildPipelineDetailsUrl = function(projectId, pipelineId) {
            return self.config.url + '/api/v4/projects/' + projectId + '/pipelines/' + pipelineId;
        },
        buildJobUrl = function(projectId, pipelineId) {
            return self.config.url + '/api/v4/projects/' + projectId + '/pipelines/' + pipelineId + '/jobs/';
        },
        getProjectsApiUrl = function(page, perPage) {
            var query = '?page=' + page + '&per_page=' + perPage + self.config.additional_query;
            return self.config.url + '/api/v4/projects' + query;
        },
        getRequestHeaders = function() {
            return { 'PRIVATE-TOKEN': self.config.token };
        },
        makeRequest = function (url, callback) {
            request({
                headers: getRequestHeaders(),
                'url': url,
                json: true
            }, function(err, response, body) {
                callback(err, body);
            });
        },
        getProjectPipelines = function(project, callback) {
            makeRequest(buildProjectPipelinesUrl(project.id, project.ref), function(err, pipelines) {
                if(err) {
                    callback(err);
                    return;
                }
                async.map(pipelines, function(pipeline, callback) {
                    getPipelineDetails(project, pipeline.id, callback);
                }, callback);
            });
        },
        getPipelineDetails = function(project, pipelineId, callback) {
            async.waterfall([
                function(callback) {
                    makeRequest(buildPipelineDetailsUrl(project.id, pipelineId), callback);
                },
                function(pipeline, callback) {
                    makeRequest(buildJobUrl(project.id, pipelineId), function(err, jobs) {
                        pipeline.jobs = jobs;
                        callback(err, simplifyBuild(project, pipeline));
                    });
                }
            ], callback);
        },
        getBuilds = function(callback) {
            async.map(self.projects, getProjectPipelines, function(err, builds) {
                if(err) {
                    callback(err);
                    return;
                }
                callback(err, flatten(builds));
            });
        },
        simplifyBuild = function(project, build) {
            return {
                id: project.id + '|' + build.id,
                number: build.id,
                project: project.name + '/' + build.ref,
                isRunning: ['running', 'pending'].includes(build.status),
                startedAt: getDateTime(build.started_at),
                finishedAt: getDateTime(build.finished_at),
                requestedFor: getBuildRequestedFor(build),
                status: getBuildStatus(build.status),
                statusText: build.status,
                reason: getBuildRequestedFor(build),
                hasErrors: false,
                hasWarnings: false,
                url: getBuildUrl(project, build)
            };
        },
        getDateTime = function(dateTime) {
            return dateTime ? new Date(dateTime) : dateTime;
        },
        getBuildRequestedFor = function(build) {
            var job = build.jobs && build.jobs[0];
            return job && (job.commit.message + ' | ' + job.commit.author_name);
        },
        getBuildStatus = function(status) {
            switch (status) {
                case 'pending':
                    return '#ffa500';
                case 'running':
                    return 'Blue';
                case 'failed':
                    return 'Red';
                case 'success':
                    return 'Green';
                default:
                    return 'Gray';
            }
        },
        getBuildUrl = function(project, build) {
            if(build.jobs && build.jobs[0]) {
                var base = self.config.url + '/';
                return base + project.path_with_namespace + '/-/jobs/' + build.jobs[0].id; //Not sure whether this works
            } else {
                return "";
            }
        },
        getAllProjects = function(callback) {
            request({
                headers: getRequestHeaders(),
                'url': getProjectsApiUrl(1, 100),
                json: true
            }, function(err, response, body) {
                if (!err && response.statusCode == 200) {
                    var urls = [], pages = Math.ceil(
                        parseInt(response.headers['x-total-pages'], 10));
                    for (var i = 1; i <= pages; i = i + 1) {
                        urls.push(getProjectsApiUrl(i, 100));
                    }

                    async.map(urls, makeRequest, function(err, projects){
                        callback(err, flatten(projects));
                    });
                }
            });
        },
        loadProjects = function() {
            var slugs = self.config.slugs,
                matchers = slugs.map(slug => slug.project);
            getAllProjects(function(err, projects){
                if(err) return;
                var indexOfAllMatch = matchers.indexOf('*/*');
                projects.forEach(function(project){
                    var indexOfNamespace = matchers.indexOf(project.namespace.name + "/*"),
                        indexOfProject = matchers.indexOf(project.path_with_namespace),
                        index = indexOfAllMatch > -1 ? indexOfAllMatch : (
                            indexOfNamespace > -1 ? indexOfNamespace : (
                            indexOfProject > -1 ? indexOfProject : null));

                    if(index !== null) {
                        if(slugs[index].ref) {
                            project.ref = slugs[index].ref;
                        }
                        self.projects.push(project);
                    }
                });
            });
        };

    self.configure = function (config) {
        self.config = config;
        self.projects = [];
        if (typeof self.config.slugs === 'undefined') {
            self.config.slugs = [{project: '*/*'}];
        }
        if (typeof self.config.additional_query === 'undefined') {
          self.config.additional_query = "";
        }
        if (typeof process.env.GITLAB_TOKEN !== 'undefined') {
            self.config.token = process.env.GITLAB_TOKEN;
        }
        if (typeof self.config.caPath !== 'undefined') {
            request = request.defaults({
                agentOptions: {
                    ca: require('fs').readFileSync(self.config.caPath).toString().split("\n\n")
                }
            });
        }
        loadProjects();
    };

    self.check = getBuilds;
};
<commit_msg>gitlab: fixed tests<commit_after>var request = require('request'),
    async = require('async');

module.exports = function () {
    var self = this,
        flatten = function(arrayOfArray) {
            return [].concat.apply([], arrayOfArray);
        },
        buildProjectUrl = function(projectId) {
            return self.config.url + '/api/v4/projects/' + projectId;
        },
        buildProjectPipelinesUrl = function(projectId, ref) {
            var url = self.config.url + '/api/v4/projects/' + projectId + '/pipelines';
            if(ref) { url = url + '?ref=' + ref; }
            return url;
        },
        buildPipelineDetailsUrl = function(projectId, pipelineId) {
            return self.config.url + '/api/v4/projects/' + projectId + '/pipelines/' + pipelineId;
        },
        buildJobUrl = function(projectId, pipelineId) {
            return self.config.url + '/api/v4/projects/' + projectId + '/pipelines/' + pipelineId + '/jobs/';
        },
        getProjectsApiUrl = function(page, perPage) {
            var query = '?page=' + page + '&per_page=' + perPage + self.config.additional_query;
            return self.config.url + '/api/v4/projects' + query;
        },
        getRequestHeaders = function() {
            return { 'PRIVATE-TOKEN': self.config.token };
        },
        makeRequest = function (url, callback) {
            request({
                headers: getRequestHeaders(),
                'url': url,
                json: true
            }, function(err, response, body) {
                callback(err, body);
            });
        },
        getProjectPipelines = function(project, callback) {
            makeRequest(buildProjectPipelinesUrl(project.id, project.ref), function(err, pipelines) {
                if(err) {
                    callback(err);
                    return;
                }
                async.map(pipelines, function(pipeline, callback) {
                    getPipelineDetails(project, pipeline.id, callback);
                }, callback);
            });
        },
        getPipelineDetails = function(project, pipelineId, callback) {
            async.waterfall([
                function(callback) {
                    makeRequest(buildPipelineDetailsUrl(project.id, pipelineId), callback);
                },
                function(pipeline, callback) {
                    makeRequest(buildJobUrl(project.id, pipelineId), function(err, jobs) {
                        pipeline.jobs = jobs;
                        callback(err, simplifyBuild(project, pipeline));
                    });
                }
            ], callback);
        },
        getBuilds = function(callback) {
            if(self.projects.length === 0) {
                loadProjects();
            }
            async.map(self.projects, getProjectPipelines, function(err, builds) {
                if(err) {
                    callback(err);
                    return;
                }
                callback(err, flatten(builds));
            });
        },
        simplifyBuild = function(project, build) {
            return {
                id: project.id + '|' + build.id,
                number: build.id,
                project: project.name + '/' + build.ref,
                isRunning: ['running', 'pending'].includes(build.status),
                startedAt: getDateTime(build.started_at),
                finishedAt: getDateTime(build.finished_at),
                requestedFor: getBuildRequestedFor(build),
                status: getBuildStatus(build.status),
                statusText: build.status,
                reason: getBuildRequestedFor(build),
                hasErrors: false,
                hasWarnings: false,
                url: getBuildUrl(project, build)
            };
        },
        getDateTime = function(dateTime) {
            return dateTime ? new Date(dateTime) : dateTime;
        },
        getBuildRequestedFor = function(build) {
            var job = build.jobs && build.jobs[0];
            return job && (job.commit.message + ' | ' + job.commit.author_name);
        },
        getBuildStatus = function(status) {
            switch (status) {
                case 'pending':
                    return '#ffa500';
                case 'running':
                    return 'Blue';
                case 'failed':
                    return 'Red';
                case 'success':
                    return 'Green';
                default:
                    return 'Gray';
            }
        },
        getBuildUrl = function(project, build) {
            if(build.jobs && build.jobs[0]) {
                var base = self.config.url + '/';
                return base + project.path_with_namespace + '/-/jobs/' + build.jobs[0].id; //Not sure whether this works
            } else {
                return "";
            }
        },
        getAllProjects = function(callback) {
            request({
                headers: getRequestHeaders(),
                'url': getProjectsApiUrl(1, 100),
                json: true
            }, function(err, response, body) {
                if (!err && response.statusCode == 200) {
                    var urls = [], pages = Math.ceil(
                        parseInt(response.headers['x-total-pages'], 10));
                    for (var i = 1; i <= pages; i = i + 1) {
                        urls.push(getProjectsApiUrl(i, 100));
                    }

                    async.map(urls, makeRequest, function(err, projects){
                        callback(err, flatten(projects));
                    });
                }
            });
        },
        loadProjects = function() {
            var slugs = self.config.slugs,
                matchers = slugs.map(slug => slug.project);
            getAllProjects(function(err, projects){
                if(err) return;
                var indexOfAllMatch = matchers.indexOf('*/*');
                projects.forEach(function(project){
                    var indexOfNamespace = matchers.indexOf(project.namespace.name + "/*"),
                        indexOfProject = matchers.indexOf(project.path_with_namespace),
                        index = indexOfAllMatch > -1 ? indexOfAllMatch : (
                            indexOfNamespace > -1 ? indexOfNamespace : (
                            indexOfProject > -1 ? indexOfProject : null));

                    if(index !== null) {
                        if(slugs[index].ref) {
                            project.ref = slugs[index].ref;
                        }
                        self.projects.push(project);
                    }
                });
            });
        };

    self.configure = function (config) {
        self.config = config;
        self.projects = [];
        if (typeof self.config.slugs === 'undefined') {
            self.config.slugs = [{project: '*/*'}];
        }
        if (typeof self.config.additional_query === 'undefined') {
          self.config.additional_query = "";
        }
        if (typeof process.env.GITLAB_TOKEN !== 'undefined') {
            self.config.token = process.env.GITLAB_TOKEN;
        }
        if (typeof self.config.caPath !== 'undefined') {
            request = request.defaults({
                agentOptions: {
                    ca: require('fs').readFileSync(self.config.caPath).toString().split("\n\n")
                }
            });
        }
    };

    self.check = getBuilds;
};
<|endoftext|>


<commit_before>// Scroll effects for the page

// Top bar text changes from white to black after scrolling a certain amount
function adjustTopBar(scroll) {
  const topBar = document.getElementsByClassName('top-bar')[0];

  // Scroll distance at which everything will switch from black to white
  const threshold = window.innerWidth > window.innerHeight
                        ? window.innerHeight * 1.25
                        : window.innerHeight * 0.95;

  // Text color changes suddenly at threshold
  if (scroll > threshold) {
    topBar.style.color = 'black';
  } else {
    topBar.style.color = 'white';
  }
}

// Main scroll handler

function scrollHandler() {
  const scroll = window.scrollY;
  adjustTopBar(scroll);
}

window.addEventListener('scroll', scrollHandler);
document.addEventListener('DOMContentLoaded', scrollHandler);
<commit_msg>Parallax on headline<commit_after>// Scroll effects for the page

// Top bar text changes from white to black after scrolling a certain amount
function adjustTopBar(scroll) {
  const topBar = document.getElementsByClassName('top-bar')[0];

  // Scroll distance at which everything will switch from black to white
  const threshold = window.innerWidth > window.innerHeight
                        ? window.innerHeight * 1.25
                        : window.innerHeight * 0.95;

  // Text color changes suddenly at threshold
  if (scroll > threshold) {
    topBar.style.color = 'black';
  } else {
    topBar.style.color = 'white';
  }
}

function headlineParallax(scroll) {
  requestAnimationFrame(() => {
    const headline = document.getElementsByClassName('headline')[0];
    headline.style.transform = `translateY(calc( -50% - ${scroll / 50}vh ))`;
  });
}

// Main scroll handler

function scrollHandler() {
  const scroll = window.scrollY;
  adjustTopBar(scroll);
  headlineParallax(scroll);
}

window.addEventListener('scroll', scrollHandler);
document.addEventListener('DOMContentLoaded', scrollHandler);
<|endoftext|>


<commit_before>let sections = [
  {depth: 0, title: 'Getting Started', slug: 'start'},
  {depth: 1, title: 'Babel', slug: 'babel'},
  {depth: 1, title: 'JSX', slug: 'jsx'},
  {depth: 1, title: 'ES6', slug: 'es6'},
  {depth: 1, title: 'ES6 Continued', slug: 'es6_continued'},
  {depth: 1, title: 'ES7 and Beyond', slug: 'es7_and_beyond'},

  {depth: 0, title: 'React Components', slug: 'components'},
  {depth: 1, title: 'Component API', slug: 'component_api'},
  {depth: 1, title: 'Lifecycle API', slug: 'lifecycle_api'},

  {depth: 0, title: 'Core Components', slug: 'core_components'},
  {depth: 1, title: 'Flexbox', slug: 'flexbox'},
  {depth: 1, title: 'View', slug: 'view'},
  {depth: 1, title: 'Text', slug: 'text'},
  {depth: 1, title: 'Image', slug: 'image'},
  {depth: 1, title: 'ScrollView', slug: 'scrollview'},
  {depth: 1, title: 'ListView', slug: 'listview'},

  {depth: 0, title: 'Data Management', slug: 'data'},
  {depth: 1, title: 'Component State', slug: 'data_component_state'},
  {depth: 1, title: 'Redux', slug: 'redux'},
  {depth: 2, title: 'React Redux', slug: 'react_redux'},
  // {depth: 2, title: 'Async Control Flow', slug: 'redux_async'},
  {depth: 1, title: 'Realm', slug: 'realm'},
  // {depth: 1, title: 'Firebase', slug: 'firebase_data'},
  //
  {depth: 0, title: 'Persistence', slug: 'persistence'},
  {depth: 1, title: 'AsyncStorage', slug: 'asyncstorage'},
  // {depth: 1, title: 'Redux Persist', slug: 'redux_persist'},

  // {depth: 0, title: 'Navigation', slug: 'navigation'},
  // {depth: 1, title: 'React Native Router Flux', slug: 'react_native_router_flux'},
  // {depth: 1, title: 'React Native Navigation', slug: 'react_native_navigation'},
  //
  {depth: 0, title: 'Animation', slug: 'animation'},
  {depth: 1, title: 'Animated', slug: 'animated'},
  {depth: 1, title: 'RN Animatable', slug: 'react_native_animatable'},
  {depth: 1, title: 'Gestures', slug: 'gestures'},

  {depth: 0, title: 'Exercises', slug: 'exercises'},

  {depth: 1, title: 'Todo List', slug: 'todo_list'},
  {depth: 2, title: 'App Layout', slug: 'todo_list_1'},
  {depth: 2, title: 'Input & Adding', slug: 'todo_list_2'},
  {depth: 2, title: 'List and Checkbox', slug: 'todo_list_3'},
  {depth: 2, title: 'Removal & Styling', slug: 'todo_list_4'},

  // {depth: 1, title: 'Reddit', slug: 'reddit'},

  {depth: 1, title: 'Uber', slug: 'uber'},
  {depth: 2, title: 'Search Header', slug: 'uber_1'},
  {depth: 2, title: 'Results List', slug: 'uber_2'},
  {depth: 2, title: 'Map & Geolocation', slug: 'uber_3'},
  {depth: 2, title: 'UI Polish', slug: 'uber_4'},
  //
  // {depth: 0, title: 'Boilerplates', slug: 'boilerplates'},
  // {depth: 1, title: 'Ignite', slug: 'ignite'},
  //
  // {depth: 0, title: 'Projects', slug: 'boilerplates'},
  // {depth: 1, title: 'Twitter Clone', slug: 'project_twitter'},
  // {depth: 2, title: 'Project Setup', slug: 'project_twitter_setup'},
  // {depth: 2, title: 'Item Component', slug: 'project_twitter_list_item'},
  // {depth: 2, title: 'List Component', slug: 'project_twitter_list'},
  // {depth: 2, title: 'Images', slug: 'project_twitter_images'},
  // {depth: 2, title: 'Video', slug: 'project_twitter_video'},
  // {depth: 2, title: 'Performance', slug: 'project_twitter_performance'},
  // {depth: 2, title: 'Bonus: Compose', slug: 'project_twitter_compose'},
  // {depth: 1, title: 'Uber Clone', slug: 'project_uber'},
  // {depth: 2, title: 'Project Setup', slug: 'project_uber'},
  // {depth: 2, title: 'Item Component', slug: 'project_uber'},
  // {depth: 2, title: 'List Component', slug: 'project_uber'},
  // {depth: 2, title: 'Images', slug: 'project_uber'},
  // {depth: 2, title: 'Video', slug: 'project_uber'},
  // {depth: 2, title: 'Performance', slug: 'project_uber'},
  // {depth: 2, title: 'Bonus: Compose', slug: 'project_uber'},
]

sections = sections.reduce((acc, section) => {
  let {major, minor, patch} = acc
  const {depth} = section

  if (depth === 0) {
    major++
    minor = 0
    patch = 0
  } else if (depth === 1) {
    minor++
    patch = 0
  } else {
    patch++
  }

  acc.sections.push({...section, major, minor, patch})

  return {...acc, major, minor, patch}
}, {sections: [], major: 0, minor: 0, patch: 0}).sections

export default sections

const matches = (path, section) => {
  let normalizedPath = path

  if (normalizedPath.startsWith('/')) {
    normalizedPath = normalizedPath.slice(1)
  }

  return normalizedPath === section.slug
}

export const getSection = (path, offset) => {
  const index = sections.findIndex(section => matches(path, section))

  if (index === -1) return null

  return sections[index + offset]
}

export const getNextSection = (path) => getSection(path, 1)

export const getPreviousSection = (path) => getSection(path, -1)

export const chapters = sections.reduce(
  (ch, section) => {
    const {depth} = section

    if (depth === 0) {
      ch.push([])
    }

    ch[ch.length - 1].push(section)

    return ch
  }, []
)
<commit_msg>Re-order sections<commit_after>let sections = [
  {depth: 0, title: 'Getting Started', slug: 'start'},
  {depth: 1, title: 'Babel', slug: 'babel'},
  {depth: 1, title: 'ES6', slug: 'es6'},
  {depth: 1, title: 'ES6 Continued', slug: 'es6_continued'},
  {depth: 1, title: 'ES7 and Beyond', slug: 'es7_and_beyond'},
  {depth: 1, title: 'JSX', slug: 'jsx'},

  {depth: 0, title: 'React Components', slug: 'components'},
  {depth: 1, title: 'Component API', slug: 'component_api'},
  {depth: 1, title: 'Lifecycle API', slug: 'lifecycle_api'},

  {depth: 0, title: 'Core Components', slug: 'core_components'},
  {depth: 1, title: 'View', slug: 'view'},
  {depth: 1, title: 'Flexbox', slug: 'flexbox'},
  {depth: 1, title: 'Text', slug: 'text'},
  {depth: 1, title: 'Image', slug: 'image'},
  {depth: 1, title: 'ScrollView', slug: 'scrollview'},
  {depth: 1, title: 'ListView', slug: 'listview'},

  {depth: 0, title: 'Data Management', slug: 'data'},
  {depth: 1, title: 'Component State', slug: 'data_component_state'},
  {depth: 1, title: 'Redux', slug: 'redux'},
  {depth: 2, title: 'React Redux', slug: 'react_redux'},
  // {depth: 2, title: 'Async Control Flow', slug: 'redux_async'},
  {depth: 1, title: 'Realm', slug: 'realm'},
  // {depth: 1, title: 'Firebase', slug: 'firebase_data'},
  //
  {depth: 0, title: 'Persistence', slug: 'persistence'},
  {depth: 1, title: 'AsyncStorage', slug: 'asyncstorage'},
  // {depth: 1, title: 'Redux Persist', slug: 'redux_persist'},

  // {depth: 0, title: 'Navigation', slug: 'navigation'},
  // {depth: 1, title: 'React Native Router Flux', slug: 'react_native_router_flux'},
  // {depth: 1, title: 'React Native Navigation', slug: 'react_native_navigation'},
  //
  {depth: 0, title: 'Animation', slug: 'animation'},
  {depth: 1, title: 'Animated', slug: 'animated'},
  {depth: 1, title: 'RN Animatable', slug: 'react_native_animatable'},
  {depth: 1, title: 'Gestures', slug: 'gestures'},

  {depth: 0, title: 'Exercises', slug: 'exercises'},

  {depth: 1, title: 'Todo List', slug: 'todo_list'},
  {depth: 2, title: 'App Layout', slug: 'todo_list_1'},
  {depth: 2, title: 'Input & Adding', slug: 'todo_list_2'},
  {depth: 2, title: 'List and Checkbox', slug: 'todo_list_3'},
  {depth: 2, title: 'Removal & Styling', slug: 'todo_list_4'},

  // {depth: 1, title: 'Reddit', slug: 'reddit'},

  {depth: 1, title: 'Uber', slug: 'uber'},
  {depth: 2, title: 'Search Header', slug: 'uber_1'},
  {depth: 2, title: 'Results List', slug: 'uber_2'},
  {depth: 2, title: 'Map & Geolocation', slug: 'uber_3'},
  {depth: 2, title: 'UI Polish', slug: 'uber_4'},
  //
  // {depth: 0, title: 'Boilerplates', slug: 'boilerplates'},
  // {depth: 1, title: 'Ignite', slug: 'ignite'},
  //
  // {depth: 0, title: 'Projects', slug: 'boilerplates'},
  // {depth: 1, title: 'Twitter Clone', slug: 'project_twitter'},
  // {depth: 2, title: 'Project Setup', slug: 'project_twitter_setup'},
  // {depth: 2, title: 'Item Component', slug: 'project_twitter_list_item'},
  // {depth: 2, title: 'List Component', slug: 'project_twitter_list'},
  // {depth: 2, title: 'Images', slug: 'project_twitter_images'},
  // {depth: 2, title: 'Video', slug: 'project_twitter_video'},
  // {depth: 2, title: 'Performance', slug: 'project_twitter_performance'},
  // {depth: 2, title: 'Bonus: Compose', slug: 'project_twitter_compose'},
  // {depth: 1, title: 'Uber Clone', slug: 'project_uber'},
  // {depth: 2, title: 'Project Setup', slug: 'project_uber'},
  // {depth: 2, title: 'Item Component', slug: 'project_uber'},
  // {depth: 2, title: 'List Component', slug: 'project_uber'},
  // {depth: 2, title: 'Images', slug: 'project_uber'},
  // {depth: 2, title: 'Video', slug: 'project_uber'},
  // {depth: 2, title: 'Performance', slug: 'project_uber'},
  // {depth: 2, title: 'Bonus: Compose', slug: 'project_uber'},
]

sections = sections.reduce((acc, section) => {
  let {major, minor, patch} = acc
  const {depth} = section

  if (depth === 0) {
    major++
    minor = 0
    patch = 0
  } else if (depth === 1) {
    minor++
    patch = 0
  } else {
    patch++
  }

  acc.sections.push({...section, major, minor, patch})

  return {...acc, major, minor, patch}
}, {sections: [], major: 0, minor: 0, patch: 0}).sections

export default sections

const matches = (path, section) => {
  let normalizedPath = path

  if (normalizedPath.startsWith('/')) {
    normalizedPath = normalizedPath.slice(1)
  }

  return normalizedPath === section.slug
}

export const getSection = (path, offset) => {
  const index = sections.findIndex(section => matches(path, section))

  if (index === -1) return null

  return sections[index + offset]
}

export const getNextSection = (path) => getSection(path, 1)

export const getPreviousSection = (path) => getSection(path, -1)

export const chapters = sections.reduce(
  (ch, section) => {
    const {depth} = section

    if (depth === 0) {
      ch.push([])
    }

    ch[ch.length - 1].push(section)

    return ch
  }, []
)
<|endoftext|>


<commit_before>require('codemirror/mode/javascript/javascript');
require('codemirror/mode/xml/xml');
require('codemirror/mode/markdown/markdown');

import React from 'react';
import {connect} from 'react-redux';
import Codemirror from 'react-codemirror';
import Resizable from 'react-resizable-box';

const hideRender = () => {

};

let options = {
  mode: 'text/html',
  lineNumbers: true,
  lineWrapping: true
};

const render = (state) => {
  let name = state.pager.newTextName;
  let currentPage = '-' + state.pager.currentPage;
  return (

{name}{currentPage}
+

      <Codemirror id="newC" value={state.pager.newText} options={options} readonly="readonly"/>

  );
};

const mapStateToProps = (state) => {
  return {
    pager: state.pager
  };
};

const NewText = connect(mapStateToProps)(render);

export default NewText;
<commit_msg>add readOnly option<commit_after>require('codemirror/mode/javascript/javascript');
require('codemirror/mode/xml/xml');
require('codemirror/mode/markdown/markdown');

import React from 'react';
import {connect} from 'react-redux';
import Codemirror from 'react-codemirror';
import Resizable from 'react-resizable-box';

const hideRender = () => {

};

let options = {
  mode: 'text/html',
  lineNumbers: true,
  lineWrapping: true,
  readOnly: true
};

const render = (state) => {
  let name = state.pager.newTextName;
  let currentPage = '-' + state.pager.currentPage;
  return (

{name}{currentPage}
+

      <Codemirror id="newC" value={state.pager.newText} options={options} />

  );
};

const mapStateToProps = (state) => {
  return {
    pager: state.pager
  };
};

const NewText = connect(mapStateToProps)(render);

export default NewText;
<|endoftext|>


<commit_before>/**
 * This module exports functions for checking types
 * and throwing exceptions.
 */

/*globals define, module */

(function (globals) {
    'use strict';

    // Default messages when an Error is thrown for a failed predicate.
    var defaultMessages = {
        quacksLike: 'Invalid type',
        isInstance: 'Invalid type',
        isEmptyObject: 'Invalid object',
        isObject: 'Invalid lbject',
        isLength: 'Invalid length',
        isArray: 'Invalid array',
        isDate: 'Invalid date',
        isFunction: 'Invalid function',
        isWebUrl: 'Invalid web Url',
        isUnemptyString: 'Invalid String',
        isString: 'Invalid String',
        isEvenNumber: 'Invalid Number',
        isOddNumber: 'Invalid Number',
        isPositiveNumber: 'Invalid Number',
        isNegativeNumber: 'Invalid Number',
        isNumber: 'Invalid Number'
    };

    // Predicate functions
    var predicates = {
        quacksLike: quacksLike,
        isInstance: isInstance,
        isEmptyObject: isEmptyObject,
        isObject: isObject,
        isLength: isLength,
        isArray: isArray,
        isDate: isDate,
        isFunction: isFunction,
        isWebUrl: isWebUrl,
        isUnemptyString: isUnemptyString,
        isString: isString,
        isEvenNumber: isEvenNumber,
        isOddNumber: isOddNumber,
        isPositiveNumber: isPositiveNumber,
        isNegativeNumber: isNegativeNumber,
        isNumber: isNumber
    };

    // Hash of exported functions
    var functions = {
        verifyQuack: verified(quacksLike, defaultMessages.quacksLike),
        quacksLike: quacksLike,
        verifyInstance: verified(isInstance, defaultMessages.isInstance),
        isInstance: isInstance,
        verifyEmptyObject: verified(isEmptyObject, defaultMessages.isEmptyObject),
        isEmptyObject: isEmptyObject,
        verifyObject: verified(isObject, defaultMessages.isObject),
        isObject: isObject,
        verifyLength: verified(isLength, defaultMessages.isLength),
        isLength: isLength,
        verifyArray: verified(isArray, defaultMessages.isArray),
        isArray: isArray,
        verifyDate: verified(isDate, defaultMessages.isDate),
        isDate: isDate,
        verifyFunction: verified(isFunction, defaultMessages.isFunction),
        isFunction: isFunction,
        verifyWebUrl: verified(isWebUrl, defaultMessages.isWebUrl),
        isWebUrl: isWebUrl,
        verifyUnemptyString: verified(isUnemptyString, defaultMessages.isUnemptyString),
        isUnemptyString:isUnemptyString,
        verifyString: verified(isString, defaultMessages.isString),
        isString: isString,
        verifyEvenNumber: verified(isEvenNumber, defaultMessages.isEvenNumber),
        isEvenNumber: isEvenNumber,
        verifyOddNumber: verified(isOddNumber, defaultMessages.isOddNumber),
        isOddNumber: isOddNumber,
        verifyPositiveNumber: verified(isPositiveNumber, defaultMessages.isPositiveNumber),
        isPositiveNumber: isPositiveNumber,
        verifyNegativeNumber: verified(isNegativeNumber, defaultMessages.isNegativeNumber),
        isNegativeNumber: isNegativeNumber,
        verifyNumber: verified(isNumber, defaultMessages.isNumber),
        isNumber: isNumber,
        map: map,
        every: every,
        any: any
    };

    // Add `check.verify.*` wrapped version of functions.
    functions.verify = verifyFunctions(predicates, defaultMessages);

    // Add `check.maybe.*` wrapped version of functions.
    functions.maybe  = maybeFunctions(functions);

    // Add `check.maybe.verify.*` wrapped version of functions.
    functions.maybe.verify = maybeFunctions(functions.verify);

    exportFunctions(functions);

    /**
     * Public function `verifyQuack`.
     *
     * Throws an exception if an object does not share
     * the properties of a second, archetypal object
     * (i.e. doesn't 'quack like a duck').
     *
     * @param thing {object}     The object to test.
     * @param duck {object}      The archetypal object,
     *                           or 'duck', that the test
     *                           is against.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyQuack (thing, duck, message) {
        verify(quacksLike, [ thing, duck ], message, 'Invalid type');
    }

    function verify (fn, args, message, defaultMessage) {
        if (fn.apply(null, args) === false) {
            throw new Error(message || defaultMessage);
        }
    }

    function maybe (predicate) {
        return function() {
            return arguments[0] === null || arguments[0] === undefined ?
                true :
                predicate.apply(null, arguments);
        };
    }

    function verified (fn, defaultMessage) {
        return function() {
            var message = arguments[arguments.length-1];
            message = isString(message) ? message : null;
            if (!fn.apply(null, arguments)) {
                throw new Error(message || defaultMessage);
            }
        };
    }

    /**
     * Public function `quacksLike`.
     *
     * Tests whether an object 'quacks like a duck'.
     * Returns `true` if the first argument has all of
     * the properties of the second, archetypal argument
     * (the 'duck'). Returns `false` otherwise. If either
     * argument is not an object, an exception is thrown.
     *
     * @param thing {object} The object to test.
     * @param duck {object}  The archetypal object, or
     *                       'duck', that the test is
     *                       against.
     */
    function quacksLike (thing, duck) {
        var property;

        verifyObject(thing);
        verifyObject(duck);

        for (property in duck) {
            if (duck.hasOwnProperty(property)) {
                if (thing.hasOwnProperty(property) === false) {
                    return false;
                }

                if (typeof thing[property] !== typeof duck[property]) {
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * Public function `verifyInstance`.
     *
     * Throws an exception if an object is not an instance
     * of a prototype.
     *
     * @param thing {object}       The object to test.
     * @param prototype {function} The prototype that the
     *                             test is against.
     * @param [message] {string}   An optional error message
     *                             to set on the thrown Error.
     */
    function verifyInstance (thing, prototype, message) {
        verify(isInstance, [ thing, prototype ], message, 'Invalid type');
    }

    /**
     * Public function `isInstance`.
     *
     * Returns `true` if an object is an instance of a prototype,
     * `false` otherwise.
     *
     * @param thing {object}       The object to test.
     * @param prototype {function} The prototype that the
     *                             test is against.
     */
    function isInstance (thing, prototype) {
        if (typeof thing === 'undefined' || thing === null) {
            return false;
        }

        if (isFunction(prototype) && thing instanceof prototype) {
            return true;
        }

        return false;
    }

    /**
     * Public function `verifyEmptyObject`.
     *
     * Throws an exception unless something is an empty, non-null,
     * non-array object.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyEmptyObject (thing, message) {
        verify(isEmptyObject, [ thing ], message, 'Invalid object');
    }

    /**
     * Public function `isEmptyObject`.
     *
     * Returns `true` if something is an empty, non-null, non-array object, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isEmptyObject (thing) {
        var property;

        if (isObject(thing)) {
            for (property in thing) {
                if (thing.hasOwnProperty(property)) {
                    return false;
                }
            }

            return true;
        }

        return false;
    }

    /**
     * Public function `verifyObject`.
     *
     * Throws an exception unless something is a non-null,
     * non-array, non-date object.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyObject (thing, message) {
        verify(isObject, [ thing ], message, 'Invalid object');
    }

    /**
     * Public function `isObject`.
     *
     * Returns `true` if something is a non-null, non-array,
     * non-date object, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isObject (thing) {
        return typeof thing === 'object' && thing !== null && isArray(thing) === false && isDate(thing) === false;
    }

    /**
     * Public function `verifyLength`.
     *
     * Throws an exception unless something is a non-null,
     * non-array object.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyLength (thing, length, message) {
        verify(isLength, [ thing, length ], message, 'Invalid length');
    }

    /**
     * Public function `isLength`.
     *
     * Returns `true` if something is has a length property
     * matching the specified value, `false` otherwise.
     *
     * @param thing  The thing to test.
     * @param length The required length to test against.
     */
    function isLength (thing, length) {
        return thing && thing.length === length;
    }

    /**
     * Public function `verifyArray`.
     *
     * Throws an exception unless something is an array.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyArray (thing, message) {
        verify(isArray, [ thing ], message, 'Invalid array');
    }

    /**
     * Public function `isArray`.
     *
     * Returns `true` something is an array, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isArray (thing) {
        if (Array.isArray) {
            return Array.isArray(thing);
        }

        return Object.prototype.toString.call(thing) === '[object Array]';
    }

    /**
     * Public function `verifyDate`.
     *
     * Throws an exception unless something is a date.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyDate (thing, message) {
        verify(isDate, [ thing ], message, 'Invalid date');
    }

    /**
     * Public function `isDate`.
     *
     * Returns `true` something is a date, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isDate (thing) {
        return Object.prototype.toString.call(thing) === '[object Date]';
    }

    /**
     * Public function `verifyFunction`.
     *
     * Throws an exception unless something is function.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyFunction (thing, message) {
        verify(isFunction, [ thing ], message, 'Invalid function');
    }

    /**
     * Public function `isFunction`.
     *
     * Returns `true` if something is function, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isFunction (thing) {
        return typeof thing === 'function';
    }

    /**
     * Public function `verifyWebUrl`.
     *
     * Throws an exception unless something is an HTTP or HTTPS URL.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyWebUrl (thing, message) {
        verify(isWebUrl, [thing], message, 'Invalid URL');
    }

    /**
     * Public function `isWebUrl`.
     *
     * Returns `true` if something is an HTTP or HTTPS URL,
     * `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isWebUrl (thing) {
        return isUnemptyString(thing) && /^https?:\/\/.+/.test(thing);
    }

    /**
     * Public function `verifyUnemptyString`.
     *
     * Throws an exception unless something is a non-empty string.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyUnemptyString (thing, message) {
        verify(isUnemptyString, [ thing ], message, 'Invalid string');
    }

    /**
     * Public function `isUnemptyString`.
     *
     * Returns `true` if something is a non-empty string, `false`
     * otherwise.
     *
     * @param thing          The thing to test.
     */
    function isUnemptyString (thing) {
        return isString(thing) && thing !== '';
    }

    /**
     * Public function `verifyString`.
     *
     * Throws an exception unless something is a string.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyString (thing, message) {
        verify(isString, [ thing ], message, 'Invalid string');
    }

    /**
     * Public function `isString`.
     *
     * Returns `true` if something is a string, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isString (thing) {
        return typeof thing === 'string';
    }

    /**
     * Public function `verifyOddNumber`.
     *
     * Throws an exception unless something is an odd number.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyOddNumber (thing, message) {
        verify(isOddNumber, [ thing ], message, 'Invalid number');
    }

    /**
     * Public function `isOddNumber`.
     *
     * Returns `true` if something is an odd number,
     * `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isOddNumber (thing) {
        return isNumber(thing) && (thing % 2 === 1 || thing % 2 === -1);
    }

    /**
     * Public function `verifyEvenNumber`.
     *
     * Throws an exception unless something is an even number.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyEvenNumber (thing, message) {
        verify(isEvenNumber, [ thing ], message, 'Invalid number');
    }

    /**
     * Public function `isEvenNumber`.
     *
     * Returns `true` if something is an even number,
     * `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isEvenNumber (thing) {
        return isNumber(thing) && thing % 2 === 0;
    }

    /**
     * Public function `verifyPositiveNumber`.
     *
     * Throws an exception unless something is a positive number.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyPositiveNumber (thing, message) {
        verify(isPositiveNumber, [ thing ], message, 'Invalid number');
    }

    /**
     * Public function `isPositiveNumber`.
     *
     * Returns `true` if something is a positive number,
     * `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isPositiveNumber (thing) {
        return isNumber(thing) && thing > 0;
    }

    /**
     * Public function `verifyNegativeNumber`.
     *
     * Throws an exception unless something is a positive number.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyNegativeNumber (thing, message) {
        verify(isNegativeNumber, [ thing ], message, 'Invalid number');
    }

    /**
     * Public function `isNegativeNumber`.
     *
     * Returns `true` if something is a positive number,
     * `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isNegativeNumber (thing) {
        return isNumber(thing) && thing < 0;
    }

    /**
     * Public function `verifyNumber`.
     *
     * Throws an exception unless something is a number, excluding NaN.
     *
     * @param thing              The thing to test.
     * @param [message] {string} An optional error message
     *                           to set on the thrown Error.
     */
    function verifyNumber (thing, message) {
        verify(isNumber, [ thing ], message, 'Invalid number');
    }

    /**
     * Public function `isNumber`.
     *
     * Returns `true` if something is a number other than NaN,
     * `false` otherwise.
     *
     * @param thing The thing to test.
     */
    function isNumber (thing) {
        return typeof thing === 'number' && isNaN(thing) === false;
    }

    /**
     * Public function `map`.
     *
     * Returns the results hash of mapping each predicate to the
     * corresponding thing's property. Similar to `quacksLike` but
     * with functions instead of values.
     *
     * @param things {object}     The things to test.
     * @param predicates {object} The map of functions to call against
     *                            the corresponding properties from `things`.
     */
    function map (things, predicates) {
        var property, result = {}, predicate;
        verifyObject(things);
        verifyObject(predicates);

        for (property in predicates) {
            if (predicates.hasOwnProperty(property)) {
                predicate = predicates[property];
                if (isFunction(predicate)) {
                    result[property] = things.hasOwnProperty(property) ?
                        predicate(things[property]) :
                        undefined;
                } else if (isObject(predicate)) {
                    result[property] = things.hasOwnProperty(property) ?
                        map(things[property], predicate) :
                        undefined;
                }
            }
        }

        return result;
    }

    /**
     * Public function `every`
     *
     * Returns the conjunction of all booleans in a hash.
     *
     * @param predicateResults {object} The hash of evaluated predicates.
     */
    function every (predicateResults) {
        var property, value;
        verifyObject(predicateResults);

        for (property in predicateResults) {
            if (predicateResults.hasOwnProperty(property)) {
                value = predicateResults[property];
                if (isObject(value) && !every(value)) {
                    return false;
                } else if (!value) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * Public function `any`
     *
     * Returns the disjunction of all booleans in a hash.
     *
     * @param predicateResults {object} The hash of evaluated predicates.
     */
    function any (predicateResults) {
        var property, value;
        verifyObject(predicateResults);

        for (property in predicateResults) {
            if (predicateResults.hasOwnProperty(property)) {
                value = predicateResults[property];
                if (isObject(value) && any(value)) {
                    return true;
                } else if (value === true) {
                    return true;
                }
            }
        }
        return false;
    }

    function maybeFunctions (predicates) {
        var property, fn, functions;
        functions = {};
        for (property in predicates) {
            if (predicates.hasOwnProperty(property)) {
                fn = predicates[property];
                functions[property] = maybe(fn);
            }
        }
        return functions;
    }

    function verifyFunctions (predicates, defaultMessages) {
        var property, verifiedPredicates, predicate, message;
        verifiedPredicates = {};
        for (property in predicates) {
            if (predicates.hasOwnProperty(property)) {
                predicate = predicates[property];
                message = defaultMessages[property];
                verifiedPredicates[property] = verified(predicate, message);
            }
        }
        return verifiedPredicates;
    }

    function exportFunctions (functions) {
        if (typeof define === 'function' && define.amd) {
            define(function () {
                return functions;
            });
        } else if (typeof module !== 'undefined' && module !== null) {
            module.exports = functions;
        } else {
            globals.check = functions;
        }
    }
}(this));
<commit_msg>removes explicit verify* declarations<commit_after>/**
 * This module exports functions for checking types
 * and throwing exceptions.
 */

/*globals define, module */

(function (globals) {
    'use strict';

    // Default messages when an Error is thrown for a failed predicate.
    var defaultMessages = {
        quacksLike: 'Invalid type',
        isInstance: 'Invalid type',
        isEmptyObject: 'Invalid object',
        isObject: 'Invalid lbject',
        isLength: 'Invalid length',
        isArray: 'Invalid array',
        isDate: 'Invalid date',
        isFunction: 'Invalid function',
        isWebUrl: 'Invalid web Url',
        isUnemptyString: 'Invalid String',
        isString: 'Invalid String',
        isEvenNumber: 'Invalid Number',
        isOddNumber: 'Invalid Number',
        isPositiveNumber: 'Invalid Number',
        isNegativeNumber: 'Invalid Number',
        isNumber: 'Invalid Number'
    };

    // Predicate functions
    var predicates = {
        quacksLike: quacksLike,
        isInstance: isInstance,
        isEmptyObject: isEmptyObject,
        isObject: isObject,
        isLength: isLength,
        isArray: isArray,
        isDate: isDate,
        isFunction: isFunction,
        isWebUrl: isWebUrl,
        isUnemptyString: isUnemptyString,
        isString: isString,
        isEvenNumber: isEvenNumber,
        isOddNumber: isOddNumber,
        isPositiveNumber: isPositiveNumber,
        isNegativeNumber: isNegativeNumber,
        isNumber: isNumber
    };

    // Hash of exported functions
    var functions = {
        verifyQuack: verify(quacksLike, defaultMessages.quacksLike),
        quacksLike: quacksLike,
        verifyInstance: verify(isInstance, defaultMessages.isInstance),
        isInstance: isInstance,
        verifyEmptyObject: verify(isEmptyObject, defaultMessages.isEmptyObject),
        isEmptyObject: isEmptyObject,
        verifyObject: verify(isObject, defaultMessages.isObject),
        isObject: isObject,
        verifyLength: verify(isLength, defaultMessages.isLength),
        isLength: isLength,
        verifyArray: verify(isArray, defaultMessages.isArray),
        isArray: isArray,
        verifyDate: verify(isDate, defaultMessages.isDate),
        isDate: isDate,
        verifyFunction: verify(isFunction, defaultMessages.isFunction),
        isFunction: isFunction,
        verifyWebUrl: verify(isWebUrl, defaultMessages.isWebUrl),
        isWebUrl: isWebUrl,
        verifyUnemptyString: verify(isUnemptyString, defaultMessages.isUnemptyString),
        isUnemptyString:isUnemptyString,
        verifyString: verify(isString, defaultMessages.isString),
        isString: isString,
        verifyEvenNumber: verify(isEvenNumber, defaultMessages.isEvenNumber),
        isEvenNumber: isEvenNumber,
        verifyOddNumber: verify(isOddNumber, defaultMessages.isOddNumber),
        isOddNumber: isOddNumber,
        verifyPositiveNumber: verify(isPositiveNumber, defaultMessages.isPositiveNumber),
        isPositiveNumber: isPositiveNumber,
        verifyNegativeNumber: verify(isNegativeNumber, defaultMessages.isNegativeNumber),
        isNegativeNumber: isNegativeNumber,
        verifyNumber: verify(isNumber, defaultMessages.isNumber),
        isNumber: isNumber,
        map: map,
        every: every,
        any: any
    };

    // Add `check.verify.*` wrapped version of functions.
    functions.verify = verifyFunctions(predicates, defaultMessages);

    // Add `check.maybe.*` wrapped version of functions.
    functions.maybe  = maybeFunctions(functions);

    // Add `check.maybe.verify.*` wrapped version of functions.
    functions.maybe.verify = maybeFunctions(functions.verify);

    exportFunctions(functions);

    function maybe (predicate) {
        return function() {
            return arguments[0] === null || arguments[0] === undefined ?
                true :
                predicate.apply(null, arguments);
        };
    }

    function verify (fn, defaultMessage) {
        return function() {
            var message = arguments[arguments.length-1];
            message = isString(message) ? message : null;
            if (!fn.apply(null, arguments)) {
                throw new Error(message || defaultMessage);
            }
        };
    }

    /**
     * Public function `quacksLike`.
     *
     * Tests whether an object 'quacks like a duck'.
     * Returns `true` if the first argument has all of
     * the properties of the second, archetypal argument
     * (the 'duck'). Returns `false` otherwise. If either
     * argument is not an object, an exception is thrown.
     *
     * @param thing {object} The object to test.
     * @param duck {object}  The archetypal object, or
     *                       'duck', that the test is
     *                       against.
     */
    function quacksLike (thing, duck) {
        var property;

        verify(isObject)(thing);
        verify(isObject)(duck);

        for (property in duck) {
            if (duck.hasOwnProperty(property)) {
                if (thing.hasOwnProperty(property) === false) {
                    return false;
                }

                if (typeof thing[property] !== typeof duck[property]) {
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * Public function `isInstance`.
     *
     * Returns `true` if an object is an instance of a prototype,
     * `false` otherwise.
     *
     * @param thing {object}       The object to test.
     * @param prototype {function} The prototype that the
     *                             test is against.
     */
    function isInstance (thing, prototype) {
        if (typeof thing === 'undefined' || thing === null) {
            return false;
        }

        if (isFunction(prototype) && thing instanceof prototype) {
            return true;
        }

        return false;
    }

    /**
     * Public function `isEmptyObject`.
     *
     * Returns `true` if something is an empty, non-null, non-array object, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isEmptyObject (thing) {
        var property;

        if (isObject(thing)) {
            for (property in thing) {
                if (thing.hasOwnProperty(property)) {
                    return false;
                }
            }

            return true;
        }

        return false;
    }

    /**
     * Public function `isObject`.
     *
     * Returns `true` if something is a non-null, non-array,
     * non-date object, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isObject (thing) {
        return typeof thing === 'object' && thing !== null && isArray(thing) === false && isDate(thing) === false;
    }

    /**
     * Public function `isLength`.
     *
     * Returns `true` if something is has a length property
     * matching the specified value, `false` otherwise.
     *
     * @param thing  The thing to test.
     * @param length The required length to test against.
     */
    function isLength (thing, length) {
        return thing && thing.length === length;
    }

    /**
     * Public function `isArray`.
     *
     * Returns `true` something is an array, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isArray (thing) {
        if (Array.isArray) {
            return Array.isArray(thing);
        }

        return Object.prototype.toString.call(thing) === '[object Array]';
    }

    /**
     * Public function `isDate`.
     *
     * Returns `true` something is a date, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isDate (thing) {
        return Object.prototype.toString.call(thing) === '[object Date]';
    }

    /**
     * Public function `isFunction`.
     *
     * Returns `true` if something is function, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isFunction (thing) {
        return typeof thing === 'function';
    }

    /**
     * Public function `isWebUrl`.
     *
     * Returns `true` if something is an HTTP or HTTPS URL,
     * `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isWebUrl (thing) {
        return isUnemptyString(thing) && /^https?:\/\/.+/.test(thing);
    }

    /**
     * Public function `isUnemptyString`.
     *
     * Returns `true` if something is a non-empty string, `false`
     * otherwise.
     *
     * @param thing          The thing to test.
     */
    function isUnemptyString (thing) {
        return isString(thing) && thing !== '';
    }

    /**
     * Public function `isString`.
     *
     * Returns `true` if something is a string, `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isString (thing) {
        return typeof thing === 'string';
    }

    /**
     * Public function `isOddNumber`.
     *
     * Returns `true` if something is an odd number,
     * `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isOddNumber (thing) {
        return isNumber(thing) && (thing % 2 === 1 || thing % 2 === -1);
    }

    /**
     * Public function `isEvenNumber`.
     *
     * Returns `true` if something is an even number,
     * `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isEvenNumber (thing) {
        return isNumber(thing) && thing % 2 === 0;
    }

    /**
     * Public function `isPositiveNumber`.
     *
     * Returns `true` if something is a positive number,
     * `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isPositiveNumber (thing) {
        return isNumber(thing) && thing > 0;
    }

    /**
     * Public function `isNegativeNumber`.
     *
     * Returns `true` if something is a positive number,
     * `false` otherwise.
     *
     * @param thing          The thing to test.
     */
    function isNegativeNumber (thing) {
        return isNumber(thing) && thing < 0;
    }

    /**
     * Public function `isNumber`.
     *
     * Returns `true` if something is a number other than NaN,
     * `false` otherwise.
     *
     * @param thing The thing to test.
     */
    function isNumber (thing) {
        return typeof thing === 'number' && isNaN(thing) === false;
    }

    /**
     * Public function `map`.
     *
     * Returns the results hash of mapping each predicate to the
     * corresponding thing's property. Similar to `quacksLike` but
     * with functions instead of values.
     *
     * @param things {object}     The things to test.
     * @param predicates {object} The map of functions to call against
     *                            the corresponding properties from `things`.
     */
    function map (things, predicates) {
        var property, result = {}, predicate;
        verify(isObject)(things);
        verify(isObject)(predicates);

        for (property in predicates) {
            if (predicates.hasOwnProperty(property)) {
                predicate = predicates[property];
                if (isFunction(predicate)) {
                    result[property] = things.hasOwnProperty(property) ?
                        predicate(things[property]) :
                        undefined;
                } else if (isObject(predicate)) {
                    result[property] = things.hasOwnProperty(property) ?
                        map(things[property], predicate) :
                        undefined;
                }
            }
        }

        return result;
    }

    /**
     * Public function `every`
     *
     * Returns the conjunction of all booleans in a hash.
     *
     * @param predicateResults {object} The hash of evaluated predicates.
     */
    function every (predicateResults) {
        var property, value;
        verify(isObject)(predicateResults);

        for (property in predicateResults) {
            if (predicateResults.hasOwnProperty(property)) {
                value = predicateResults[property];
                if (isObject(value) && !every(value)) {
                    return false;
                } else if (!value) {
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * Public function `any`
     *
     * Returns the disjunction of all booleans in a hash.
     *
     * @param predicateResults {object} The hash of evaluated predicates.
     */
    function any (predicateResults) {
        var property, value;
        verify(isObject)(predicateResults);

        for (property in predicateResults) {
            if (predicateResults.hasOwnProperty(property)) {
                value = predicateResults[property];
                if (isObject(value) && any(value)) {
                    return true;
                } else if (value === true) {
                    return true;
                }
            }
        }
        return false;
    }

    function maybeFunctions (predicates) {
        var property, fn, functions;
        functions = {};
        for (property in predicates) {
            if (predicates.hasOwnProperty(property)) {
                fn = predicates[property];
                functions[property] = maybe(fn);
            }
        }
        return functions;
    }

    function verifyFunctions (predicates, defaultMessages) {
        var property, verifiedPredicates, predicate, message;
        verifiedPredicates = {};
        for (property in predicates) {
            if (predicates.hasOwnProperty(property)) {
                predicate = predicates[property];
                message = defaultMessages[property];
                verifiedPredicates[property] = verify(predicate, message);
            }
        }
        return verifiedPredicates;
    }

    function exportFunctions (functions) {
        if (typeof define === 'function' && define.amd) {
            define(function () {
                return functions;
            });
        } else if (typeof module !== 'undefined' && module !== null) {
            module.exports = functions;
        } else {
            globals.check = functions;
        }
    }
}(this));
<|endoftext|>