<commit_before>var exec = require( "child_process" ).exec,
	fs = require( "fs" ),
	mkdirp = require( "mkdirp" ),
	semver = require( "semver" ),
	template = require( "./template" ),
	wordpress = require( "./wordpress" ),
	pluginsDb = require( "./pluginsdb" ),
	config = require( "./config" );

function dirname( path ) {
	path = path.split( "/" );
	path.pop();
	return path.join( "/" );
}

function createError( message, code, data ) {
	var error = new Error( message );
	if ( code ) {
		error.code = code;
	}
	if ( data ) {
		error.data = data;
	}
	return error;
}

var reGithubSsh = /^git@github\.com:([^/]+)\/(.+)\.git$/,
	reGithubHttp = /^\w+?:\/\/\w+@github\.com\/([^/]+)\/([^/]+)\.git$/,
	reGithubGit = /^git:\/\/github\.com\/([^/]+)\/([^/]+)\.git$/,
	reGithubSite = /^https?:\/\/github\.com\/([^/]+)\/([^/]+)(\/.*)?$/;

function getRepoDetails( repo ) {
	var userName, repoName, partialPath,
		matches =
			reGithubSsh.exec( repo ) ||
			reGithubHttp.exec( repo ) ||
			reGithubGit.exec( repo ) ||
			reGithubSite.exec( repo );

	if ( matches ) {
		userName = matches[ 1 ];
		repoName = matches[ 2 ];
		partialPath = "/" + userName + "/" + repoName;
		return {
			userName: userName,
			repoName: repoName,
			url: "http://github.com" + partialPath,
			git: "git://github.com" + partialPath + ".git",
			downloadUrl: function( version ) {
				return "https://github.com" + partialPath + "/zipball/" + version
			},
			path: config.repoDir + partialPath
		};
	}

	return null;
}

function fetchPlugin( repoDetails, fn ) {
	// make sure the user's directory exists first
	mkdirp( dirname( repoDetails.path ), 0755, function( error ) {
		if ( error ) {
			return fn( error );
		}

		createOrUpdateRepo( repoDetails, function( error ) {
			if ( error ) {
				return fn( error );
			}

			fn( null );
		});
	});
}

function createOrUpdateRepo( repoDetails, fn ) {
	fs.stat( repoDetails.path, function( error ) {
		// repo already exists
		if ( !error ) {
			return updateRepo( repoDetails, fn );
		}

		// error other than repo not existing
		if ( error.code !== "ENOENT" ) {
			return fn( error );
		}

		createRepo( repoDetails, fn );
	});
}

function createRepo( repoDetails, fn ) {
	exec( "git clone " + repoDetails.git + " " + repoDetails.path, function( error, stdout, stderr ) {
		if ( error ) {
			return fn( error );
		}

		// TODO: handle stderr

		fn( null );
	});
}

function updateRepo( repoDetails, fn ) {
	exec( "git fetch -t && git reset --hard origin", { cwd: repoDetails.path }, function( error, stdout, stderr ) {
		if ( error ) {
			return fn( error );
		}

		// TODO: handle stderr

		fn( null );
	});
}

function getVersions( repoDetails, fn ) {
	exec( "git tag", { cwd: repoDetails.path }, function( error, stdout, stderr ) {
		if ( error ) {
			return fn( error );
		}

		var tags = stdout.split( "\n" );
		tags.pop();
		tags = tags.filter(function( version ) {
			// we allow a v prefix, but nothing else
			if ( version.charAt( 0 ) === "v" ) {
				version = version.substring( 1 );
			}

			// tag is not a clean version number
			if ( semver.clean( version ) !== version ) {
				return false;
			}

			return semver.valid( version );
		});
		fn( null, tags );
	});
}

function validateVersion( repoDetails, version, fn ) {
	getPackageJson( repoDetails, version, function( error, package ) {
		if ( error ) {
			return fn( error );
		}

		fn( null, {
			package: package,
			errors: validatePackageJson( package, version )
		});
	});
}

function getPackageJson( repoDetails, version, fn ) {
	exec( "git show " + version + ":package.json", { cwd: repoDetails.path }, function( error, stdout, stderr ) {
		// this will also result in an error being passed, so we check stderr first
		if ( stderr && stderr.substring( 0, 41 ) === "fatal: Path 'package.json' does not exist" ) {
			return fn( createError( "No package.json for " + version + ".", "NO_PACKAGE_JSON", {
				version: version
			}));
		}

		if ( error ) {
			return fn( error );
		}

		try {
			var package = JSON.parse( stdout );
		} catch( error ) {
			return fn( createError( "Could not parse package.json for " + version + ".", "INVALID_PACKAGE_JSON", {
				version: version
			}));
		}

		return fn( null, package );
	});
}

function validatePackageJson( package, version ) {
	var errors = [];

	if ( !package.name ) {
		errors.push( "Missing required field: name." );
	} else if ( package.name.charAt( 0 ) === "_" || package.name.charAt( 0 ) === "." ) {
		errors.push( "Name cannot start with an underscore or dot." );
	}

	if ( !package.version ) {
		errors.push( "Missing required field: version." );
	} else if ( package.version !== semver.clean( package.version ) ) {
		errors.push( "Package.json version (" + package.version + ") is invalid." );
	} else if ( package.version !== semver.clean( version ) ) {
		errors.push( "Package.json version (" + package.version + ") does not match tag (" + version + ")." );
	}

	if ( !package.title ) {
		errors.push( "Missing required field: title." );
	}

	if ( !package.author ) {
		errors.push( "Missing required field: author." );
	} else if ( !package.author.name ) {
		errors.push( "Missing required field: author.name." );
	}

	if ( !package.licenses ) {
		errors.push( "Missing required field: licenses." );
	} else if ( !package.licenses.length ) {
		errors.push( "There must be at least one license." );
	} else if ( package.licenses.filter(function( license ) { return !license.url; }).length ) {
		errors.push( "Missing required field: license.url." );
	}

	if ( !package.dependencies ) {
		errors.push( "Missing required field: dependencies." );
	} else if ( !package.dependencies.jquery ) {
		errors.push( "Missing required dependency: jquery." );
	}

	return errors;
}

function generatePage( package, fn ) {
	template.get( "page", function( error, template ) {
		if ( error ) {
			return fn( error );
		}

		try {
			var output = template( package );
		} catch( error ) {
			return fn( error );
		}

		fn( null, output );
	});
}

function processPlugin( repo, fn ) {
	var repoDetails = getRepoDetails( repo.url );

	if ( !repoDetails ) {
		return fn( createError( "Could not parse '" + repoUrl + "'.", "URL_PARSE" ) );
	}

	fetchPlugin( repoDetails, function( error ) {
		if ( error ) {
			return fn( error );
		}

		getVersions( repoDetails, _getVersions );
	});

	function _getVersions( error, versions ) {
		if ( error ) {
			return fn( error );
		}

		if ( !versions.length ) {
			return fn( null );
		}

		// TODO: track our actions so we can process metadata in done()
		var plugins = {},
			waiting = versions.length;

		function progress() {
			waiting--;
			if ( !waiting ) {
				done();
			}
		}

		function done() {
			// TODO: track invalid versions (user error, not system error)
			// TODO: update versionless post to have latest version
			// TODO: update metadata in WP
			// - don't list pre-release versions that are older than latest stable
			// - list pre-release versions greater than latest stable
			wordpress.end();
			fn();
		}

		versions.forEach(function( version ) {
			validateVersion( repoDetails, version, function( error, data ) {
				if ( error ) {
					// TODO: log failure for retry
					return progress();
				}

				if ( data.errors.length ) {
					// TODO: report errors to user
					return progress();
				}

				wordpress.getVersions( data.package.name, function( error, versions ) {
					if ( error ) {
						// TODO: log failure for retry
						return progress();
					}

					// this version has already been processed
					// TODO: when should we start passing around the clean version?
					if ( versions.indexOf( semver.clean( version ) ) !== -1 ) {
						return progress();
					}

					_addPluginVersion( version, data.package, function( error ) {
						if ( error ) {
							console.log( error );
							return progress();
						}

						var name = data.package.name;
						if ( !plugins[ name ] ) {
							plugins[ name ] = [];
						}
						plugins[ name ].push( semver.clean( version ) );
						progress();
					});
				});
			});
		});
	}

	function _addPluginVersion( version, package, fn ) {
		// find out who owns this plugin
		// if there is no owner, then set the user as the owner
		pluginsDb.getOrSetOwner( package.name, repoDetails.userName, function( error, owner ) {
			if ( error ) {
				// TODO: log failure for retry
				return fn( error );
			}

			// the plugin is owned by someone else
			if ( owner !== repoDetails.userName ) {
				// TODO: report error to user
				return fn( createError( "Plugin owned by someone else.", "NOT_OWNER", {
					owner: owner
				}));
			}

			pluginsDb.addVersion( repoDetails, package, function( error ) {
				if ( error ) {
					// TODO: log failure for retry
					return fn( error );
				}

				// add additional metadata and generate the plugin page
				var pluginData = Object.create( package );
				pluginData._downloadUrl = repoDetails.downloadUrl( version );
				pluginData.url = repoDetails.url;
				generatePage( pluginData, function( error, page ) {
					if ( error ) {
						// TODO: log failure for retry
						return fn( error );
					}

					wordpress.addVersionedPlugin( version, package, page, function( error ) {
						if ( error ) {
							// TODO: log failure for retry
							return fn( error );
						}
						console.log( "Added " + package.name + " " + package.version );
						fn();
					});
				});
			});
		});
	}
}

// TODO: track watchers and forks
processPlugin({
	url: "http://github.com/scottgonzalez/temp-jquery-foo",
	watchers: 25,
	forks: 3
}, function( error, data ) {
	// TODO: log error to file
	if ( error ) {
		console.log( error );
	}
});
<commit_msg>Don't re-process previous tags.<commit_after>var exec = require( "child_process" ).exec,
	fs = require( "fs" ),
	mkdirp = require( "mkdirp" ),
	semver = require( "semver" ),
	template = require( "./template" ),
	wordpress = require( "./wordpress" ),
	pluginsDb = require( "./pluginsdb" ),
	config = require( "./config" );

function dirname( path ) {
	path = path.split( "/" );
	path.pop();
	return path.join( "/" );
}

function createError( message, code, data ) {
	var error = new Error( message );
	if ( code ) {
		error.code = code;
	}
	if ( data ) {
		error.data = data;
	}
	return error;
}

var reGithubSsh = /^git@github\.com:([^/]+)\/(.+)\.git$/,
	reGithubHttp = /^\w+?:\/\/\w+@github\.com\/([^/]+)\/([^/]+)\.git$/,
	reGithubGit = /^git:\/\/github\.com\/([^/]+)\/([^/]+)\.git$/,
	reGithubSite = /^https?:\/\/github\.com\/([^/]+)\/([^/]+)(\/.*)?$/;

function getRepoDetails( repo ) {
	var userName, repoName, partialPath,
		matches =
			reGithubSsh.exec( repo ) ||
			reGithubHttp.exec( repo ) ||
			reGithubGit.exec( repo ) ||
			reGithubSite.exec( repo );

	if ( matches ) {
		userName = matches[ 1 ];
		repoName = matches[ 2 ];
		partialPath = "/" + userName + "/" + repoName;
		return {
			userName: userName,
			repoName: repoName,
			url: "http://github.com" + partialPath,
			git: "git://github.com" + partialPath + ".git",
			downloadUrl: function( version ) {
				return "https://github.com" + partialPath + "/zipball/" + version
			},
			path: config.repoDir + partialPath
		};
	}

	return null;
}

function fetchPlugin( repoDetails, fn ) {
	// make sure the user's directory exists first
	mkdirp( dirname( repoDetails.path ), 0755, function( error ) {
		if ( error ) {
			return fn( error );
		}

		createOrUpdateRepo( repoDetails, fn );
	});
}

function createOrUpdateRepo( repoDetails, fn ) {
	fs.stat( repoDetails.path, function( error ) {
		// repo already exists
		if ( !error ) {
			return updateRepo( repoDetails, fn );
		}

		// error other than repo not existing
		if ( error.code !== "ENOENT" ) {
			return fn( error );
		}

		createRepo( repoDetails, fn );
	});
}

function createRepo( repoDetails, fn ) {
	exec( "git clone " + repoDetails.git + " " + repoDetails.path, function( error, stdout, stderr ) {
		if ( error ) {
			return fn( error );
		}

		// TODO: handle stderr

		getVersions( repoDetails, fn );
	});
}

function updateRepo( repoDetails, fn ) {
	getVersions( repoDetails, function( error, prevVersions ) {
		if ( error ) {
			return fn( error );
		}

		exec( "git fetch -t", { cwd: repoDetails.path },
			function( error, stdout, stderr ) {
				if ( error ) {
					return fn( error );
				}

				// TODO: handle stderr

				getVersions( repoDetails, function( error, versions ) {
					if ( error ) {
						return fn( error );
					}

					fn( null, versions.filter(function( version ) {
						return prevVersions.indexOf( version ) === -1;
					}));
				});
			});
	});
}

function getVersions( repoDetails, fn ) {
	exec( "git tag", { cwd: repoDetails.path }, function( error, stdout, stderr ) {
		if ( error ) {
			return fn( error );
		}

		var tags = stdout.split( "\n" );
		tags.pop();
		tags = tags.filter(function( version ) {
			// we allow a v prefix, but nothing else
			if ( version.charAt( 0 ) === "v" ) {
				version = version.substring( 1 );
			}
			// TODO: disallow builds

			// tag is not a clean version number
			if ( semver.clean( version ) !== version ) {
				return false;
			}

			return semver.valid( version );
		});
		fn( null, tags );
	});
}

function validateVersion( repoDetails, version, fn ) {
	getPackageJson( repoDetails, version, function( error, package ) {
		if ( error ) {
			return fn( error );
		}

		fn( null, {
			package: package,
			errors: validatePackageJson( package, version )
		});
	});
}

function getPackageJson( repoDetails, version, fn ) {
	exec( "git show " + version + ":package.json", { cwd: repoDetails.path }, function( error, stdout, stderr ) {
		// this will also result in an error being passed, so we check stderr first
		if ( stderr && stderr.substring( 0, 41 ) === "fatal: Path 'package.json' does not exist" ) {
			return fn( createError( "No package.json for " + version + ".", "NO_PACKAGE_JSON", {
				version: version
			}));
		}

		if ( error ) {
			return fn( error );
		}

		try {
			var package = JSON.parse( stdout );
		} catch( error ) {
			return fn( createError( "Could not parse package.json for " + version + ".", "INVALID_PACKAGE_JSON", {
				version: version
			}));
		}

		return fn( null, package );
	});
}

function validatePackageJson( package, version ) {
	var errors = [];

	if ( !package.name ) {
		errors.push( "Missing required field: name." );
	} else if ( package.name.charAt( 0 ) === "_" || package.name.charAt( 0 ) === "." ) {
		errors.push( "Name cannot start with an underscore or dot." );
	}

	if ( !package.version ) {
		errors.push( "Missing required field: version." );
	} else if ( package.version !== semver.clean( package.version ) ) {
		errors.push( "Package.json version (" + package.version + ") is invalid." );
	} else if ( package.version !== semver.clean( version ) ) {
		errors.push( "Package.json version (" + package.version + ") does not match tag (" + version + ")." );
	}

	if ( !package.title ) {
		errors.push( "Missing required field: title." );
	}

	if ( !package.author ) {
		errors.push( "Missing required field: author." );
	} else if ( !package.author.name ) {
		errors.push( "Missing required field: author.name." );
	}

	if ( !package.licenses ) {
		errors.push( "Missing required field: licenses." );
	} else if ( !package.licenses.length ) {
		errors.push( "There must be at least one license." );
	} else if ( package.licenses.filter(function( license ) { return !license.url; }).length ) {
		errors.push( "Missing required field: license.url." );
	}

	if ( !package.dependencies ) {
		errors.push( "Missing required field: dependencies." );
	} else if ( !package.dependencies.jquery ) {
		errors.push( "Missing required dependency: jquery." );
	}

	return errors;
}

function generatePage( package, fn ) {
	template.get( "page", function( error, template ) {
		if ( error ) {
			return fn( error );
		}

		try {
			var output = template( package );
		} catch( error ) {
			return fn( error );
		}

		fn( null, output );
	});
}

function processPlugin( repo, fn ) {
	var repoDetails = getRepoDetails( repo.url );

	if ( !repoDetails ) {
		return fn( createError( "Could not parse '" + repoUrl + "'.", "URL_PARSE" ) );
	}

	fetchPlugin( repoDetails, function( error, versions ) {
		if ( error ) {
			return fn( error );
		}

		if ( !versions.length ) {
			return fn( null );
		}

		// TODO: track our actions so we can process metadata in done()
		var plugins = {},
			waiting = versions.length;

		function progress() {
			waiting--;
			if ( !waiting ) {
				done();
			}
		}

		function done() {
			// TODO: update versionless post to have latest version
			// TODO: update metadata in WP
			// - don't list pre-release versions that are older than latest stable
			// - list pre-release versions greater than latest stable
			wordpress.end();
			fn();
		}

		versions.forEach(function( version ) {
			validateVersion( repoDetails, version, function( error, data ) {
				if ( error ) {
					// TODO: log failure for retry
					return progress();
				}

				if ( data.errors.length ) {
					// TODO: report errors to user
					return progress();
				}

				wordpress.getVersions( data.package.name, function( error, versions ) {
					if ( error ) {
						// TODO: log failure for retry
						return progress();
					}

					// this version has already been processed
					// TODO: when should we start passing around the clean version?
					if ( versions.indexOf( semver.clean( version ) ) !== -1 ) {
						return progress();
					}

					_addPluginVersion( version, data.package, function( error ) {
						if ( error ) {
							console.log( error );
							return progress();
						}

						var name = data.package.name;
						if ( !plugins[ name ] ) {
							plugins[ name ] = [];
						}
						plugins[ name ].push( semver.clean( version ) );
						progress();
					});
				});
			});
		});
	});

	function _addPluginVersion( version, package, fn ) {
		// find out who owns this plugin
		// if there is no owner, then set the user as the owner
		pluginsDb.getOrSetOwner( package.name, repoDetails.userName, function( error, owner ) {
			if ( error ) {
				// TODO: log failure for retry
				return fn( error );
			}

			// the plugin is owned by someone else
			if ( owner !== repoDetails.userName ) {
				// TODO: report error to user
				return fn( createError( "Plugin owned by someone else.", "NOT_OWNER", {
					owner: owner
				}));
			}

			pluginsDb.addVersion( repoDetails, package, function( error ) {
				if ( error ) {
					// TODO: log failure for retry
					return fn( error );
				}

				// add additional metadata and generate the plugin page
				var pluginData = Object.create( package );
				pluginData._downloadUrl = repoDetails.downloadUrl( version );
				pluginData.url = repoDetails.url;
				generatePage( pluginData, function( error, page ) {
					if ( error ) {
						// TODO: log failure for retry
						return fn( error );
					}

					wordpress.addVersionedPlugin( version, package, page, function( error ) {
						if ( error ) {
							// TODO: log failure for retry
							return fn( error );
						}
						console.log( "Added " + package.name + " " + package.version );
						fn();
					});
				});
			});
		});
	}
}

// TODO: track watchers and forks
processPlugin({
	url: "http://github.com/scottgonzalez/temp-jquery-foo",
	watchers: 25,
	forks: 3
}, function( error, data ) {
	// TODO: log error to file
	if ( error ) {
		console.log( error );
	}
});
<|endoftext|>


<commit_before>// Get Querry string and parse it
var querry = parseQuery(window.location.search.slice(1));

// Tangram Map
var map = initMap( querry['style']? querry['style'] : "data/basic.yaml" );

// Editor
var editor = initEditor(document.getElementById("editor"), querry['style']? querry['style'] : "data/basic.yaml" );

//  UI
initUI(editor, map);

// Editor Widgets
loadWidgets("data/widgets.json");

// Once everything is loaded
setTimeout(function () {

    if (querry['foldLevel']) unfoldAll(editor); foldByLevel(editor,parseInt(querry['foldLevel']));
    if (querry['lines']) selectLines(editor,querry['lines']);

    updateWidgets(editor);

}, 1000);
<commit_msg>fixing bug + basic map<commit_after>// Get Querry string and parse it
var querry = parseQuery(window.location.search.slice(1));

// Tangram Map
var map = initMap( querry['style']? querry['style'] : "data/default.yaml" );

// Editor
var editor = initEditor(document.getElementById("editor"), querry['style']? querry['style'] : "data/default.yaml" );

//  UI
initUI(editor, map);

// Editor Widgets
loadWidgets("data/widgets.json");

// Once everything is loaded
setTimeout(function () {

    if (querry['foldLevel']) unfoldAll(editor); foldByLevel(editor,parseInt(querry['foldLevel']));
    if (querry['lines']) selectLines(editor,querry['lines']);

    updateWidgets(editor);

}, 1000);
<|endoftext|>


<commit_before>// require styles
import 'bootstrap/dist/css/bootstrap.min.css';

import $ from 'jquery';
import 'jquery-ui';
import es6Promise from 'es6-promise';

import i18next from 'i18next';
import _ from 'underscore';
import Backbone from 'backbone';
import Marionette from 'backbone.marionette';

import LayersCollection from 'eoxc/src/core/models/LayersCollection';
import MapModel from 'eoxc/src/core/models/MapModel';
import FiltersModel from 'eoxc/src/core/models/FiltersModel';
import HighlightModel from 'eoxc/src/core/models/HighlightModel';

import TimeSliderView from 'eoxc/src/core/views/TimeSliderView';
import LayerControlLayoutView from 'eoxc/src/core/views/layers/LayerControlLayoutView';

import SearchResultView from 'eoxc/src/search/views/SearchResultView';
import SearchModel from 'eoxc/src/search/models/SearchModel';
import { getParameters } from 'eoxc/src/search';

import DownloadView from 'eoxc/src/download/views/DownloadView';
import download from 'eoxc/src/download';

import OpenLayersMapView from 'eoxc/src/contrib/OpenLayers/OpenLayersMapView';

import RootLayoutView from './views/RootLayoutView';

import FiltersView from './views/FiltersView';
import SidePanelView from './views/SidePanelView';
import StopSelectionView from './views/StopSelectionView';
import WarningsView from './views/WarningsView';
import RecordsDetailsModalView from './views/RecordsDetailsModalView';

import WarningsCollection from './models/WarningsCollection';

import 'imports?jQuery=jquery!bootstrap/dist/js/bootstrap.min.js';

import getTutorialWidget from './tutorial';

es6Promise.polyfill();

const germanTranslation = require('./languages/de.json');
const englishTranslation = require('./languages/en.json');

function combineParameter(setting, param) {
  const options = setting.options || param.options;
  return {
    type: param.type,
    name: param.name,
    mandatory: setting.mandatory || param.mandatory,
    options,
    minExclusive: param.minExclusive,
    maxExclusive: param.maxExclusive,
    minInclusive: param.minInclusive,
    maxInclusive: param.maxInclusive,
    range: setting.range,
    min: setting.min,
    max: setting.max,
  };
}

window.Application = Marionette.Application.extend({
  initialize({ config, configPath, container, navbarTemplate }) {
    this.config = config;
    this.configPath = configPath;
    this.container = container;
    this.navbarTemplate = navbarTemplate;
  },

  onStart() {
    if (this.config) {
      this.onConfigLoaded(this.config);
    } else {
      $.getJSON(this.configPath, (config) => {
        this.onConfigLoaded(config);
      });
    }
  },

  onConfigLoaded(config) {
    this.config = config;
    i18next.init({
      lng: this.config.settings.language || 'en',
      fallbackLng: 'en',
      resources: {
        de: {
          translation: germanTranslation,
        },
        en: {
          translation: englishTranslation,
        },
      },
    }, () => {
      this.onI18NextInitialized(config);
    });
  },

  onI18NextInitialized(config) {
    // TODO: check parameters

    const baseLayersCollection = new LayersCollection(config.baseLayers, {
      exclusiveVisibility: true,
    });
    const layersCollection = new LayersCollection(config.layers);
    const overlayLayersCollection = new LayersCollection(config.overlayLayers);

    if (config.settings.parameters) {
      const parameterPromises = layersCollection
        .map(layerModel => getParameters(layerModel).then(parameters => [layerModel, parameters]));
      Promise.all(parameterPromises)
        .then((layersPlusParameters) => {
          const params = config.settings.parameters
            .map(param => [
              param, layersPlusParameters.filter(layerPlusParameters => (
                layerPlusParameters[1].find(p => p.type === param.type)
              )),
            ])

            // filter out the parameters that are nowhere available
            .filter(paramPlusApplicableLayers => paramPlusApplicableLayers[1].length)

            // combine the parameter settings info with the info from the search services
            .map((paramPlusApplicableLayers) => {
              let param = paramPlusApplicableLayers[0];
              for (let i = 0; i < paramPlusApplicableLayers[1].length; i += 1) {
                const [, layerParameters] = paramPlusApplicableLayers[1][i];
                param = combineParameter(
                  param, layerParameters.find(p => p.type === param.type)
                );
              }
              if (paramPlusApplicableLayers[1].length < layersCollection.length) {
                param.onlyAvailableAt = paramPlusApplicableLayers[1].map(layerPlusParameters => (
                  layerPlusParameters[0].get('displayName')
                ));
              }
              return param;
            });

          // const params = [].concat.apply([], extraParameters)
          //   .filter(param => param.type.startsWith('eo:'))
          //   .map((param) => {
          //     const paramSetting = config.settings.parameters[param.type];
          //     if (paramSetting) {
          //       return {
          //         type: param.type,
          //         name: param.name,
          //         mandatory: param.mandatory,
          //         options: param.options,
          //         minExclusive: param.minExclusive,
          //         maxExclusive: param.maxExclusive,
          //         minInclusive: param.minInclusive,
          //         maxInclusive: param.maxInclusive,
          //         ...paramSetting,
          //       };
          //     }
          //     return param;
          //   });

          this.onRun(
            config, baseLayersCollection, layersCollection, overlayLayersCollection, params
          );
        });
    } else {
      this.onRun(config, baseLayersCollection, layersCollection, overlayLayersCollection, []);
    }
  },

  onRun(config, baseLayersCollection, layersCollection, overlayLayersCollection, extraParameters) {
    const settings = config.settings;

    _.defaults(settings, {
      searchDebounceTime: 250,
      constrainTimeDomain: false,
      displayInterval: null,
      selectableInterval: null,
      maxTooltips: null,
      timeSliderControls: false,
      highlightFillColor: 'rgba(255, 255, 255, 0.2)',
      highlightStrokeColor: '#cccccc',
      highlightStrokeWidth: 1,
      filterFillColor: 'rgba(0, 0, 0, 0)',
      filterStrokeColor: 'rgba(0, 0, 0, 0)',
      filterOutsideColor: 'rgba(0, 0, 0, 0.2)',
      footprintFillColor: 'rgba(255, 255, 255, 0.2)',
      footprintStrokeColor: '#cccccc',
      selectedFootprintFillColor: 'rgba(255, 0, 0, 0.2)',
      selectedFootprintStrokeColor: '#ff0000',
      leftPanelOpen: false,
      rightPanelOpen: false,
    });

    // set up config
    const mapModel = new MapModel({
      center: settings.center,
      zoom: settings.zoom,
      time: [
        new Date(settings.selectedTimeDomain[0]),
        new Date(settings.selectedTimeDomain[1]),
      ],
    });
    const filtersModel = new FiltersModel({ });
    const highlightModel = new HighlightModel();

    const searchModels = layersCollection
      .filter(layerModel => layerModel.get('search.protocol'))
      .map(layerModel => new SearchModel({
        layerModel,
        filtersModel,
        mapModel,
        defaultPageSize: 50,
        maxCount: layerModel.get('search.searchLimit'),
        debounceTime: settings.searchDebounceTime,
      }));
    const searchCollection = new Backbone.Collection(searchModels);

    // set up layout
    const layout = new RootLayoutView({
      el: $(this.container),
      mapModel,
      searchCollection,
    });
    layout.render();

    const domain = {
      start: new Date(settings.timeDomain[0]),
      end: new Date(settings.timeDomain[1]),
    };
    const display = settings.displayTimeDomain ? {
      start: new Date(settings.displayTimeDomain[0]),
      end: new Date(settings.displayTimeDomain[1]),
    } : domain;

    layout.showChildView('timeSlider', new TimeSliderView({
      layersCollection,
      mapModel,
      filtersModel,
      highlightModel,
      filterFillColor: settings.filterFillColor,
      filterStrokeColor: settings.filterStrokeColor,
      filterOutsideColor: settings.filterOutsideColor,
      domain,
      display,
      constrainTimeDomain: settings.constrainTimeDomain,
      timeSliderControls: settings.timeSliderControls,
      displayInterval: settings.displayInterval,
      selectableInterval: settings.selectableInterval,
      maxTooltips: settings.maxTooltips,
    }));

    // set up panels

    const showRecordDetails = (records) => {
      layout.showChildView('modals', new RecordsDetailsModalView({
        baseLayersCollection,
        overlayLayersCollection,
        layersCollection,
        records,
      }));
    };

    layout.showChildView('content', new OpenLayersMapView({
      mapModel,
      filtersModel,
      baseLayersCollection,
      overlayLayersCollection,
      layersCollection,
      searchCollection,
      highlightModel,
      highlightFillColor: settings.highlightFillColor,
      highlightStrokeColor: settings.highlightStrokeColor,
      highlightStrokeWidth: settings.highlightStrokeWidth,
      filterFillColor: settings.filterFillColor,
      filterStrokeColor: settings.filterStrokeColor,
      filterOutsideColor: settings.filterOutsideColor,
      footprintFillColor: settings.footprintFillColor,
      footprintStrokeColor: settings.footprintStrokeColor,
      selectedFootprintFillColor: settings.selectedFootprintFillColor,
      selectedFootprintStrokeColor: settings.selectedFootprintStrokeColor,
      onFeatureClicked(records) {
        showRecordDetails(records);
      },
    }));

    layout.showChildView('leftPanel', new SidePanelView({
      position: 'left',
      icon: 'fa-cog',
      defaultOpen: settings.leftPanelOpen,
      views: [{
        name: 'Filters',
        view: new FiltersView({
          filtersModel,
          mapModel,
          highlightModel,
          layersCollection,
          extraParameters,
        }),
      }, {
        name: 'Layers',
        view: new LayerControlLayoutView({
          mapModel,
          filtersModel,
          baseLayersCollection,
          overlayLayersCollection,
          layersCollection,
        }),
      }],
    }));

    layout.showChildView('rightPanel', new SidePanelView({
      position: 'right',
      icon: 'fa-list',
      defaultOpen: settings.rightPanelOpen,
      views: [{
        name: 'Search Results',
        hasInfo: true,
        view: new SearchResultView({
          mapModel,
          filtersModel,
          highlightModel,
          collection: searchCollection,
        }),
      }, {
        name: 'Download',
        hasInfo: true,
        view: new DownloadView({
          filtersModel,
          highlightModel,
          collection: searchCollection,
        }),
      }],
    }));

    // hook up record info modal
    searchCollection.each((searchModel) => {
      searchModel.on('showInfo', (recordModels) => {
        showRecordDetails(
          recordModels.map(recordModel => [recordModel, searchModel])
        );
      });
    });

    layout.showChildView('bottomPanel', new StopSelectionView({ mapModel }));

    const warningsCollection = new WarningsCollection([]);
    layout.showChildView('topPanel', new WarningsView({ collection: warningsCollection }));

    // hook up the events that shall generate warnings
    filtersModel.on('change', () => {
      // show warning when time filter is set
      warningsCollection.setWarning(
        i18next.t('timefilter_warning'),
        filtersModel.get('time') || false
      );

      const otherFilters = Object.keys(filtersModel.attributes)
        .filter(key => key !== 'time' && key !== 'area');
      warningsCollection.setWarning(
        i18next.t('advancedfilter_warning'),
        otherFilters.length
      );
    });

    searchCollection.on('change', () => {
      const show = searchCollection
        .filter(searchModel => (
          !searchModel.get('isSearching') && !searchModel.get('hasError')
        ))
        .reduce((acc, searchModel) => (
          acc || searchModel.get('totalResults') > searchModel.get('hasLoaded')
        ), false);
      warningsCollection.setWarning(i18next.t('toomanyresults_warning'), show);
    });

    if (settings.extent) {
      mapModel.show({ bbox: settings.extent });
    }

    // create a dynamic style to set up the border/background color of record
    // items in the search results and download selection view.
    $(`
    `).appendTo('head');

    if (settings.hasOwnProperty('tutorial')) {
      if (settings.tutorial !== 'disabled') {
        const tutWidg = getTutorialWidget();

        if (settings.tutorial !== 'disabled') {
          $('.ol-attribution').append(
          `<button type="button" title="${i18next.t('Tutorial')}" id="tutorial" style="float:right;">

          </button>`);

          $('#tutorial').click(() => {
            // Iterate through anno elements to see if any is open and needs to
            // be closed
            let cv = tutWidg;
            while (cv._chainNext) {
              if (cv._annoElem) {
                cv.hide();
              }
              cv = cv._chainNext;
            }
            tutWidg.show();
          });
        }

        if (settings.tutorial === 'always') {
          tutWidg.show();
        }

        if (settings.tutorial === 'first') {
          if (typeof (Storage) !== 'undefined') {
            if (localStorage.getItem('firstVisit') === null) {
              // Open tutorial automatically if it is the first visit
              tutWidg.show();
              localStorage.setItem('firstVisit', false);
            }
          }
        }
      }
    }
    Backbone.history.start({ pushState: false });
  },
});
<commit_msg>Reverting order of highlighted and selected in order to visually show a selection in the search results but breaking highlighting when hovering on map for selected items.<commit_after>// require styles
import 'bootstrap/dist/css/bootstrap.min.css';

import $ from 'jquery';
import 'jquery-ui';
import es6Promise from 'es6-promise';

import i18next from 'i18next';
import _ from 'underscore';
import Backbone from 'backbone';
import Marionette from 'backbone.marionette';

import LayersCollection from 'eoxc/src/core/models/LayersCollection';
import MapModel from 'eoxc/src/core/models/MapModel';
import FiltersModel from 'eoxc/src/core/models/FiltersModel';
import HighlightModel from 'eoxc/src/core/models/HighlightModel';

import TimeSliderView from 'eoxc/src/core/views/TimeSliderView';
import LayerControlLayoutView from 'eoxc/src/core/views/layers/LayerControlLayoutView';

import SearchResultView from 'eoxc/src/search/views/SearchResultView';
import SearchModel from 'eoxc/src/search/models/SearchModel';
import { getParameters } from 'eoxc/src/search';

import DownloadView from 'eoxc/src/download/views/DownloadView';
import download from 'eoxc/src/download';

import OpenLayersMapView from 'eoxc/src/contrib/OpenLayers/OpenLayersMapView';

import RootLayoutView from './views/RootLayoutView';

import FiltersView from './views/FiltersView';
import SidePanelView from './views/SidePanelView';
import StopSelectionView from './views/StopSelectionView';
import WarningsView from './views/WarningsView';
import RecordsDetailsModalView from './views/RecordsDetailsModalView';

import WarningsCollection from './models/WarningsCollection';

import 'imports?jQuery=jquery!bootstrap/dist/js/bootstrap.min.js';

import getTutorialWidget from './tutorial';

es6Promise.polyfill();

const germanTranslation = require('./languages/de.json');
const englishTranslation = require('./languages/en.json');

function combineParameter(setting, param) {
  const options = setting.options || param.options;
  return {
    type: param.type,
    name: param.name,
    mandatory: setting.mandatory || param.mandatory,
    options,
    minExclusive: param.minExclusive,
    maxExclusive: param.maxExclusive,
    minInclusive: param.minInclusive,
    maxInclusive: param.maxInclusive,
    range: setting.range,
    min: setting.min,
    max: setting.max,
  };
}

window.Application = Marionette.Application.extend({
  initialize({ config, configPath, container, navbarTemplate }) {
    this.config = config;
    this.configPath = configPath;
    this.container = container;
    this.navbarTemplate = navbarTemplate;
  },

  onStart() {
    if (this.config) {
      this.onConfigLoaded(this.config);
    } else {
      $.getJSON(this.configPath, (config) => {
        this.onConfigLoaded(config);
      });
    }
  },

  onConfigLoaded(config) {
    this.config = config;
    i18next.init({
      lng: this.config.settings.language || 'en',
      fallbackLng: 'en',
      resources: {
        de: {
          translation: germanTranslation,
        },
        en: {
          translation: englishTranslation,
        },
      },
    }, () => {
      this.onI18NextInitialized(config);
    });
  },

  onI18NextInitialized(config) {
    // TODO: check parameters

    const baseLayersCollection = new LayersCollection(config.baseLayers, {
      exclusiveVisibility: true,
    });
    const layersCollection = new LayersCollection(config.layers);
    const overlayLayersCollection = new LayersCollection(config.overlayLayers);

    if (config.settings.parameters) {
      const parameterPromises = layersCollection
        .map(layerModel => getParameters(layerModel).then(parameters => [layerModel, parameters]));
      Promise.all(parameterPromises)
        .then((layersPlusParameters) => {
          const params = config.settings.parameters
            .map(param => [
              param, layersPlusParameters.filter(layerPlusParameters => (
                layerPlusParameters[1].find(p => p.type === param.type)
              )),
            ])

            // filter out the parameters that are nowhere available
            .filter(paramPlusApplicableLayers => paramPlusApplicableLayers[1].length)

            // combine the parameter settings info with the info from the search services
            .map((paramPlusApplicableLayers) => {
              let param = paramPlusApplicableLayers[0];
              for (let i = 0; i < paramPlusApplicableLayers[1].length; i += 1) {
                const [, layerParameters] = paramPlusApplicableLayers[1][i];
                param = combineParameter(
                  param, layerParameters.find(p => p.type === param.type)
                );
              }
              if (paramPlusApplicableLayers[1].length < layersCollection.length) {
                param.onlyAvailableAt = paramPlusApplicableLayers[1].map(layerPlusParameters => (
                  layerPlusParameters[0].get('displayName')
                ));
              }
              return param;
            });

          // const params = [].concat.apply([], extraParameters)
          //   .filter(param => param.type.startsWith('eo:'))
          //   .map((param) => {
          //     const paramSetting = config.settings.parameters[param.type];
          //     if (paramSetting) {
          //       return {
          //         type: param.type,
          //         name: param.name,
          //         mandatory: param.mandatory,
          //         options: param.options,
          //         minExclusive: param.minExclusive,
          //         maxExclusive: param.maxExclusive,
          //         minInclusive: param.minInclusive,
          //         maxInclusive: param.maxInclusive,
          //         ...paramSetting,
          //       };
          //     }
          //     return param;
          //   });

          this.onRun(
            config, baseLayersCollection, layersCollection, overlayLayersCollection, params
          );
        });
    } else {
      this.onRun(config, baseLayersCollection, layersCollection, overlayLayersCollection, []);
    }
  },

  onRun(config, baseLayersCollection, layersCollection, overlayLayersCollection, extraParameters) {
    const settings = config.settings;

    _.defaults(settings, {
      searchDebounceTime: 250,
      constrainTimeDomain: false,
      displayInterval: null,
      selectableInterval: null,
      maxTooltips: null,
      timeSliderControls: false,
      highlightFillColor: 'rgba(255, 255, 255, 0.2)',
      highlightStrokeColor: '#cccccc',
      highlightStrokeWidth: 1,
      filterFillColor: 'rgba(0, 0, 0, 0)',
      filterStrokeColor: 'rgba(0, 0, 0, 0)',
      filterOutsideColor: 'rgba(0, 0, 0, 0.2)',
      footprintFillColor: 'rgba(255, 255, 255, 0.2)',
      footprintStrokeColor: '#cccccc',
      selectedFootprintFillColor: 'rgba(255, 0, 0, 0.2)',
      selectedFootprintStrokeColor: '#ff0000',
      leftPanelOpen: false,
      rightPanelOpen: false,
    });

    // set up config
    const mapModel = new MapModel({
      center: settings.center,
      zoom: settings.zoom,
      time: [
        new Date(settings.selectedTimeDomain[0]),
        new Date(settings.selectedTimeDomain[1]),
      ],
    });
    const filtersModel = new FiltersModel({ });
    const highlightModel = new HighlightModel();

    const searchModels = layersCollection
      .filter(layerModel => layerModel.get('search.protocol'))
      .map(layerModel => new SearchModel({
        layerModel,
        filtersModel,
        mapModel,
        defaultPageSize: 50,
        maxCount: layerModel.get('search.searchLimit'),
        debounceTime: settings.searchDebounceTime,
      }));
    const searchCollection = new Backbone.Collection(searchModels);

    // set up layout
    const layout = new RootLayoutView({
      el: $(this.container),
      mapModel,
      searchCollection,
    });
    layout.render();

    const domain = {
      start: new Date(settings.timeDomain[0]),
      end: new Date(settings.timeDomain[1]),
    };
    const display = settings.displayTimeDomain ? {
      start: new Date(settings.displayTimeDomain[0]),
      end: new Date(settings.displayTimeDomain[1]),
    } : domain;

    layout.showChildView('timeSlider', new TimeSliderView({
      layersCollection,
      mapModel,
      filtersModel,
      highlightModel,
      filterFillColor: settings.filterFillColor,
      filterStrokeColor: settings.filterStrokeColor,
      filterOutsideColor: settings.filterOutsideColor,
      domain,
      display,
      constrainTimeDomain: settings.constrainTimeDomain,
      timeSliderControls: settings.timeSliderControls,
      displayInterval: settings.displayInterval,
      selectableInterval: settings.selectableInterval,
      maxTooltips: settings.maxTooltips,
    }));

    // set up panels

    const showRecordDetails = (records) => {
      layout.showChildView('modals', new RecordsDetailsModalView({
        baseLayersCollection,
        overlayLayersCollection,
        layersCollection,
        records,
      }));
    };

    layout.showChildView('content', new OpenLayersMapView({
      mapModel,
      filtersModel,
      baseLayersCollection,
      overlayLayersCollection,
      layersCollection,
      searchCollection,
      highlightModel,
      highlightFillColor: settings.highlightFillColor,
      highlightStrokeColor: settings.highlightStrokeColor,
      highlightStrokeWidth: settings.highlightStrokeWidth,
      filterFillColor: settings.filterFillColor,
      filterStrokeColor: settings.filterStrokeColor,
      filterOutsideColor: settings.filterOutsideColor,
      footprintFillColor: settings.footprintFillColor,
      footprintStrokeColor: settings.footprintStrokeColor,
      selectedFootprintFillColor: settings.selectedFootprintFillColor,
      selectedFootprintStrokeColor: settings.selectedFootprintStrokeColor,
      onFeatureClicked(records) {
        showRecordDetails(records);
      },
    }));

    layout.showChildView('leftPanel', new SidePanelView({
      position: 'left',
      icon: 'fa-cog',
      defaultOpen: settings.leftPanelOpen,
      views: [{
        name: 'Filters',
        view: new FiltersView({
          filtersModel,
          mapModel,
          highlightModel,
          layersCollection,
          extraParameters,
        }),
      }, {
        name: 'Layers',
        view: new LayerControlLayoutView({
          mapModel,
          filtersModel,
          baseLayersCollection,
          overlayLayersCollection,
          layersCollection,
        }),
      }],
    }));

    layout.showChildView('rightPanel', new SidePanelView({
      position: 'right',
      icon: 'fa-list',
      defaultOpen: settings.rightPanelOpen,
      views: [{
        name: 'Search Results',
        hasInfo: true,
        view: new SearchResultView({
          mapModel,
          filtersModel,
          highlightModel,
          collection: searchCollection,
        }),
      }, {
        name: 'Download',
        hasInfo: true,
        view: new DownloadView({
          filtersModel,
          highlightModel,
          collection: searchCollection,
        }),
      }],
    }));

    // hook up record info modal
    searchCollection.each((searchModel) => {
      searchModel.on('showInfo', (recordModels) => {
        showRecordDetails(
          recordModels.map(recordModel => [recordModel, searchModel])
        );
      });
    });

    layout.showChildView('bottomPanel', new StopSelectionView({ mapModel }));

    const warningsCollection = new WarningsCollection([]);
    layout.showChildView('topPanel', new WarningsView({ collection: warningsCollection }));

    // hook up the events that shall generate warnings
    filtersModel.on('change', () => {
      // show warning when time filter is set
      warningsCollection.setWarning(
        i18next.t('timefilter_warning'),
        filtersModel.get('time') || false
      );

      const otherFilters = Object.keys(filtersModel.attributes)
        .filter(key => key !== 'time' && key !== 'area');
      warningsCollection.setWarning(
        i18next.t('advancedfilter_warning'),
        otherFilters.length
      );
    });

    searchCollection.on('change', () => {
      const show = searchCollection
        .filter(searchModel => (
          !searchModel.get('isSearching') && !searchModel.get('hasError')
        ))
        .reduce((acc, searchModel) => (
          acc || searchModel.get('totalResults') > searchModel.get('hasLoaded')
        ), false);
      warningsCollection.setWarning(i18next.t('toomanyresults_warning'), show);
    });

    if (settings.extent) {
      mapModel.show({ bbox: settings.extent });
    }

    // create a dynamic style to set up the border/background color of record
    // items in the search results and download selection view.
    $(`
    `).appendTo('head');

    if (settings.hasOwnProperty('tutorial')) {
      if (settings.tutorial !== 'disabled') {
        const tutWidg = getTutorialWidget();

        if (settings.tutorial !== 'disabled') {
          $('.ol-attribution').append(
          `<button type="button" title="${i18next.t('Tutorial')}" id="tutorial" style="float:right;">

          </button>`);

          $('#tutorial').click(() => {
            // Iterate through anno elements to see if any is open and needs to
            // be closed
            let cv = tutWidg;
            while (cv._chainNext) {
              if (cv._annoElem) {
                cv.hide();
              }
              cv = cv._chainNext;
            }
            tutWidg.show();
          });
        }

        if (settings.tutorial === 'always') {
          tutWidg.show();
        }

        if (settings.tutorial === 'first') {
          if (typeof (Storage) !== 'undefined') {
            if (localStorage.getItem('firstVisit') === null) {
              // Open tutorial automatically if it is the first visit
              tutWidg.show();
              localStorage.setItem('firstVisit', false);
            }
          }
        }
      }
    }
    Backbone.history.start({ pushState: false });
  },
});
<|endoftext|>


<commit_before>require('babel/register');

try {
  var fs = require('fs');
  var pathToken = process.env.SLACK_POKER_BOT_TOKEN;
  var token = pathToken || fs.readFileSync('token.txt', 'utf8').trim();
} catch (error) {
  console.log("Your API token should be placed in a 'token.txt' file, which is missing.");
  return;
}

var Bot = require('./bot');
var bot = new Bot(token);
bot.login();
<commit_msg>listen on environment port so Heroku won't kill it<commit_after>require('babel/register');
var http = require('http');

try {
  var fs = require('fs');
  var pathToken = process.env.SLACK_POKER_BOT_TOKEN;
  var token = pathToken || fs.readFileSync('token.txt', 'utf8').trim();
} catch (error) {
  console.log("Your API token should be placed in a 'token.txt' file, which is missing.");
  return;
}

var Bot = require('./bot');
var bot = new Bot(token);
bot.login();

// Heroku requires the process to bind to this port within 60 seconds or it is killed
http.createServer(function(req, res) {
  res.end('SLACK_POKER_BOT');
}).listen(process.env.PORT || 5000)
<|endoftext|>


<commit_before>/**
 * import your css files here
 *
 * for SPA just use jspm bundle to bundle the css into the js file, or use separateCSS to bundle it into a .css file
 * for MPA it's better to use link tags in the header for most css files to prevent FOUC.
 * unstyled content can be prevented that way bit there will still be visual buildup because the javascript.
 * the only way to prevent it is to hide elements until they are ready to be displayed.
 *
 * for now this page is setup for use with MPA and only pulls in the prism style at runtime.
 */
//import "bootstrap";
import "bootstrap/css/bootstrap.css!";
import "github:PrismJS/prism@gh-pages/themes/prism.css!";

//these are here to make sure they are included in the bundling process
import "gooy-angular";
import "gooy-angular-code";

export function configure(gooy) {

  //setup resources
  gooy
    .withComponent("gooy-angular-code")
  ;

  gooy.start().then(a => a.setRoot('app'));
}
<commit_msg>update<commit_after>/**
 * import your css files here
 *
 * for SPA just use jspm bundle to bundle the css into the js file, or use separateCSS to bundle it into a .css file
 * for MPA it's better to use link tags in the header for most css files to prevent FOUC.
 * unstyled content can be prevented that way bit there will still be visual buildup because the javascript.
 * the only way to prevent it is to hide elements until they are ready to be displayed.
 *
 * for now this page is setup for use with MPA and only pulls in the prism style at runtime.
 */
//import "bootstrap";
import "bootstrap/css/bootstrap.css!";
import "github:PrismJS/prism@gh-pages/themes/prism.css!";

//these are here to make sure they are included in the bundling process (temporary solution)
import "gooy-angular";
import "gooy-angular-code";

export function configure(gooy) {

  //setup resources
  gooy
    .withComponent("gooy-angular-code")
  ;

  gooy.start().then(a => a.setRoot('app'));
}
<|endoftext|>


<commit_before>/*
This file is part of the GhostDriver by Ivan De Marino <http://ivandemarino.me>.

Copyright (c) 2012-2014, Ivan De Marino <http://ivandemarino.me>
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

var server = require("webserver").create(), //< webserver
    router,                                 //< router request handler
    _log;                                   //< logger for "main.js"

// "ghostdriver" global namespace
ghostdriver = {
    system  : require("system"),
    hub     : require("./hub_register.js"),
    logger  : require("./logger.js"),
    config  : null,                         //< this will be set below
    version : "1.3.0-dev"
};

// create logger
_log = ghostdriver.logger.create("GhostDriver");

// Initialize the configuration
require("./config.js").init(ghostdriver.system.args);
ghostdriver.config = require("./config.js").get();

// Enable "strict mode" for the 'parseURI' library
require("./third_party/parseuri.js").options.strictMode = true;

// Load all the core dependencies
// NOTE: We need to provide PhantomJS with the "require" module ASAP. This is a pretty s**t way to load dependencies
phantom.injectJs("session.js");
phantom.injectJs("inputs.js");
phantom.injectJs("request_handlers/request_handler.js");
phantom.injectJs("request_handlers/status_request_handler.js");
phantom.injectJs("request_handlers/shutdown_request_handler.js");
phantom.injectJs("request_handlers/session_manager_request_handler.js");
phantom.injectJs("request_handlers/session_request_handler.js");
phantom.injectJs("request_handlers/webelement_request_handler.js");
phantom.injectJs("request_handlers/router_request_handler.js");
phantom.injectJs("webelementlocator.js");

try {
    // HTTP Request Router
    router = new ghostdriver.RouterReqHand();

    // Start the server
    if (server.listen(ghostdriver.config.ip+":"+ghostdriver.config.port, { "keepAlive" : true }, router.handle)) {
        _log.info("Main", "running on port " + server.port);

        // If a Selenium Grid HUB was provided, register to it!
        if (ghostdriver.config.hub !== null) {
            _log.info("Main", "registering to Selenium HUB"+
                " '" + ghostdriver.config.hub + "' version: " + ghostdriver.config.version +
                " using '" + ghostdriver.config.ip + ":" + ghostdriver.config.port + "' with " +
                (ghostdriver.config.remoteHost ? "remoteHost:" + ghostdriver.config.remoteHost + " " : "") +
                ghostdriver.config.proxy + " as remote proxy.");
            ghostdriver.hub.register(ghostdriver.config.ip,
                ghostdriver.config.port,
                ghostdriver.config.hub,
                ghostdriver.config.proxy,
                ghostdriver.config.version,
                ghostdriver.config.remoteHost);
        }
    } else {
        throw new Error("Could not start Ghost Driver");
        phantom.exit(1);
    }
} catch (e) {
    _log.error("main.fail", JSON.stringify(e));
    phantom.exit(1);
}
<commit_msg>display ghostdriver version on startup<commit_after>/*
This file is part of the GhostDriver by Ivan De Marino <http://ivandemarino.me>.

Copyright (c) 2012-2014, Ivan De Marino <http://ivandemarino.me>
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

var server = require("webserver").create(), //< webserver
    router,                                 //< router request handler
    _log;                                   //< logger for "main.js"

// "ghostdriver" global namespace
ghostdriver = {
    system  : require("system"),
    hub     : require("./hub_register.js"),
    logger  : require("./logger.js"),
    config  : null,                         //< this will be set below
    version : "1.3.0-dev"
};

// create logger
_log = ghostdriver.logger.create("GhostDriver");

// Initialize the configuration
require("./config.js").init(ghostdriver.system.args);
ghostdriver.config = require("./config.js").get();

// Enable "strict mode" for the 'parseURI' library
require("./third_party/parseuri.js").options.strictMode = true;

// Load all the core dependencies
// NOTE: We need to provide PhantomJS with the "require" module ASAP. This is a pretty s**t way to load dependencies
phantom.injectJs("session.js");
phantom.injectJs("inputs.js");
phantom.injectJs("request_handlers/request_handler.js");
phantom.injectJs("request_handlers/status_request_handler.js");
phantom.injectJs("request_handlers/shutdown_request_handler.js");
phantom.injectJs("request_handlers/session_manager_request_handler.js");
phantom.injectJs("request_handlers/session_request_handler.js");
phantom.injectJs("request_handlers/webelement_request_handler.js");
phantom.injectJs("request_handlers/router_request_handler.js");
phantom.injectJs("webelementlocator.js");

try {
    _log.info("Main", "Ghost Driver Version " + ghostdriver.version);
    // HTTP Request Router
    router = new ghostdriver.RouterReqHand();

    // Start the server
    if (server.listen(ghostdriver.config.ip+":"+ghostdriver.config.port, { "keepAlive" : true }, router.handle)) {
        _log.info("Main", "running on port " + server.port);

        // If a Selenium Grid HUB was provided, register to it!
        if (ghostdriver.config.hub !== null) {
            _log.info("Main", "registering to Selenium HUB"+
                " '" + ghostdriver.config.hub + "' version: " + ghostdriver.config.version +
                " using '" + ghostdriver.config.ip + ":" + ghostdriver.config.port + "' with " +
                (ghostdriver.config.remoteHost ? "remoteHost:" + ghostdriver.config.remoteHost + " " : "") +
                ghostdriver.config.proxy + " as remote proxy.");
            ghostdriver.hub.register(ghostdriver.config.ip,
                ghostdriver.config.port,
                ghostdriver.config.hub,
                ghostdriver.config.proxy,
                ghostdriver.config.version,
                ghostdriver.config.remoteHost);
        }
    } else {
        throw new Error("Could not start Ghost Driver");
        phantom.exit(1);
    }
} catch (e) {
    _log.error("main.fail", JSON.stringify(e));
    phantom.exit(1);
}
<|endoftext|>


<commit_before>
var FC = $.fullCalendar = {
	version: "<%= meta.version %>",
	internalApiVersion: 4
};
var fcViews = FC.views = {};

$.fn.fullCalendar = function(options) {
	var args = Array.prototype.slice.call(arguments, 1); // for a possible method call
	var res = this; // what this function will return (this jQuery object by default)

	this.each(function(i, _element) { // loop each DOM element involved
		var element = $(_element);
		var calendar = element.data('fullCalendar'); // get the existing calendar object (if any)
		var singleRes; // the returned value of this single method call

		// a method call
		if (typeof options === 'string') {
			if (calendar && $.isFunction(calendar[options])) {
				singleRes = calendar[options].apply(calendar, args);
				if (!i) {
					res = singleRes; // record the first method call result
				}
				if (options === 'destroy') { // for the destroy method, must remove Calendar object data
					element.removeData('fullCalendar');
				}
			}
		}
		// a new calendar initialization
		else if (!calendar) { // don't initialize twice
			calendar = new Calendar(element, options);
			element.data('fullCalendar', calendar);
			calendar.render();
		}
	});

	return res;
};

var complexOptions = [ // names of options that are objects whose properties should be combined
	'header',
	'buttonText',
	'buttonIcons',
	'themeButtonIcons'
];

// Merges an array of option objects into a single object
function mergeOptions(optionObjs) {
	return mergeProps(optionObjs, complexOptions);
}

// Given options specified for the calendar's constructor, massages any legacy options into a non-legacy form.
// Converts View-Option-Hashes into the View-Specific-Options format.
function massageOverrides(input) {
	var overrides = { views: input.views || {} }; // the output. ensure a `views` hash
	var subObj;

	// iterate through all option override properties (except `views`)
	$.each(input, function(name, val) {
		if (name != 'views') {

			// could the value be a legacy View-Option-Hash?
			if (
				$.isPlainObject(val) &&
				!/(time|duration|interval)$/i.test(name) && // exclude duration options. might be given as objects
				$.inArray(name, complexOptions) == -1 // complex options aren't allowed to be View-Option-Hashes
			) {
				subObj = null;

				// iterate through the properties of this possible View-Option-Hash value
				$.each(val, function(subName, subVal) {

					// is the property targeting a view?
					if (/^(month|week|day|default|basic(Week|Day)?|agenda(Week|Day)?)$/.test(subName)) {
						if (!overrides.views[subName]) { // ensure the view-target entry exists
							overrides.views[subName] = {};
						}
						overrides.views[subName][name] = subVal; // record the value in the `views` object
					}
					else { // a non-View-Option-Hash property
						if (!subObj) {
							subObj = {};
						}
						subObj[subName] = subVal; // accumulate these unrelated values for later
					}
				});

				if (subObj) { // non-View-Option-Hash properties? transfer them as-is
					overrides[name] = subObj;
				}
			}
			else {
				overrides[name] = val; // transfer normal options as-is
			}
		}
	});

	return overrides;
}
<commit_msg>bump internal api version<commit_after>
var FC = $.fullCalendar = {
	version: "<%= meta.version %>",
	internalApiVersion: 5
};
var fcViews = FC.views = {};

$.fn.fullCalendar = function(options) {
	var args = Array.prototype.slice.call(arguments, 1); // for a possible method call
	var res = this; // what this function will return (this jQuery object by default)

	this.each(function(i, _element) { // loop each DOM element involved
		var element = $(_element);
		var calendar = element.data('fullCalendar'); // get the existing calendar object (if any)
		var singleRes; // the returned value of this single method call

		// a method call
		if (typeof options === 'string') {
			if (calendar && $.isFunction(calendar[options])) {
				singleRes = calendar[options].apply(calendar, args);
				if (!i) {
					res = singleRes; // record the first method call result
				}
				if (options === 'destroy') { // for the destroy method, must remove Calendar object data
					element.removeData('fullCalendar');
				}
			}
		}
		// a new calendar initialization
		else if (!calendar) { // don't initialize twice
			calendar = new Calendar(element, options);
			element.data('fullCalendar', calendar);
			calendar.render();
		}
	});

	return res;
};

var complexOptions = [ // names of options that are objects whose properties should be combined
	'header',
	'buttonText',
	'buttonIcons',
	'themeButtonIcons'
];

// Merges an array of option objects into a single object
function mergeOptions(optionObjs) {
	return mergeProps(optionObjs, complexOptions);
}

// Given options specified for the calendar's constructor, massages any legacy options into a non-legacy form.
// Converts View-Option-Hashes into the View-Specific-Options format.
function massageOverrides(input) {
	var overrides = { views: input.views || {} }; // the output. ensure a `views` hash
	var subObj;

	// iterate through all option override properties (except `views`)
	$.each(input, function(name, val) {
		if (name != 'views') {

			// could the value be a legacy View-Option-Hash?
			if (
				$.isPlainObject(val) &&
				!/(time|duration|interval)$/i.test(name) && // exclude duration options. might be given as objects
				$.inArray(name, complexOptions) == -1 // complex options aren't allowed to be View-Option-Hashes
			) {
				subObj = null;

				// iterate through the properties of this possible View-Option-Hash value
				$.each(val, function(subName, subVal) {

					// is the property targeting a view?
					if (/^(month|week|day|default|basic(Week|Day)?|agenda(Week|Day)?)$/.test(subName)) {
						if (!overrides.views[subName]) { // ensure the view-target entry exists
							overrides.views[subName] = {};
						}
						overrides.views[subName][name] = subVal; // record the value in the `views` object
					}
					else { // a non-View-Option-Hash property
						if (!subObj) {
							subObj = {};
						}
						subObj[subName] = subVal; // accumulate these unrelated values for later
					}
				});

				if (subObj) { // non-View-Option-Hash properties? transfer them as-is
					overrides[name] = subObj;
				}
			}
			else {
				overrides[name] = val; // transfer normal options as-is
			}
		}
	});

	return overrides;
}
<|endoftext|>


<commit_before>
module.exports = function(config, mongoose) {
	var Organization = mongoose.model('Organization');

	return {
		get: function(req, res, next) {
			res.data.organization = res.app.locals.organization;
			next();
		},

		update: function(req, res, next) {
			Organization.findOne({}, function(err, organization) {
				delete req.body._id;
				delete req.body.__v;

				_.extend(organization, req.body);

				return organization.save(function(err) {
					if(err) return next(err);

					if (organization) res.app.locals.organization = organization;

					return res.status(200).json(organization);
				});
			});
		}
	};
};
<commit_msg>Fix update (remove missing keys).<commit_after>
module.exports = function(config, mongoose) {
	var Organization = mongoose.model('Organization');

	return {
		get: function(req, res, next) {
			res.data.organization = res.app.locals.organization;
			next();
		},

		update: function(req, res, next) {
			Organization.findOne({}, function(err, organization) {
				_.difference(_.keys(organization.toObject()), _.keys(req.body)).forEach(function(key) {
					organization[key] = undefined;
				});

				_.extend(organization, _.omit(req.body, '_id', '__v'));

				return organization.save(function(err) {
					if(err) return next(err);

					if (organization) res.app.locals.organization = organization;

					return res.status(200).json(organization);
				});
			});
		}
	};
};
<|endoftext|>


<commit_before>#!/usr/bin/env node
// ---------------------------------------------------------------------------------------------------------------------
// This script is intended to execute all unit tests.
// ---------------------------------------------------------------------------------------------------------------------
/* eslint-env node, es6 */

require('shelljs/global');

// set directories and files for test and coverage report
var path = require('path'),

    chalk = require('chalk'),

    IS_WINDOWS = (/^win/).test(process.platform),
    COV_REPORT_PATH = '.coverage',
    REPORT_PATH = path.join('.tmp', 'report.xml'),
    SPEC_SOURCES = path.join('test', 'unit');

module.exports = function (exit) {
    var specPattern = (process.argv[2] || '.*'),
        mochaReporter = 'spec',
        istanbulReport = '';

    // for CI, we use simple xunit reporter (not on Travis since it does not parse results)
    // if (process.env.CI) {
    //     mochaReporter = 'xunit';
    //     istanbulReport = '--report cobertura';
    // }

    // banner line
    console.log(chalk.yellow.bold('Running unit tests using mocha on node...'));

    mkdir('-p', '.tmp');
    test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH) && mkdir('-p', COV_REPORT_PATH);

    // windows istanbul and mocha commands need some special attention.
    if (IS_WINDOWS) {
        // sample command in case you're confused
        // node_modules\.bin\istanbul.cmd cover  --dir .coverage --color --print both
        //      node_modules\mocha\bin\_mocha -- --reporter spec --reporter-options output=
        //      .tmp\report.xml test\unit --recursive --prof --colors --grep=.*
        exec(`node_modules\\.bin\\istanbul.cmd cover ${istanbulReport} --dir ${COV_REPORT_PATH} --colors ` +
            // eslint-disable-next-line max-len
            `--print both node_modules\\mocha\\bin\\_mocha -- ${SPEC_SOURCES} --reporter ${mochaReporter} --timeout 10000 ` +
            `--reporter-options output=${REPORT_PATH} --recursive --prof --colors --grep=${specPattern}`, exit);
    }
    else {
        exec(`./node_modules/.bin/istanbul cover ${istanbulReport} --dir ${COV_REPORT_PATH} --colors ` +
            // eslint-disable-next-line max-len
            `--print both node_modules/mocha/bin/_mocha -- ${SPEC_SOURCES} --reporter ${mochaReporter} --timeout 10000 ` +
            `--reporter-options output=${REPORT_PATH} --recursive --prof --colors --grep=${specPattern}`, exit);
    }
};

// ensure we run this script exports if this is a direct stdin.tty run
!module.parent && module.exports(exit);
<commit_msg>Add chai `expect` to unit test<commit_after>#!/usr/bin/env node
/* eslint-env node, es6 */
// ---------------------------------------------------------------------------------------------------------------------
// This script is intended to execute all unit tests.
// ---------------------------------------------------------------------------------------------------------------------

require('shelljs/global');
require('colors');

// set directories and files for test and coverage report
var path = require('path'),
    expect = require('chai').expect,

    NYC = require('nyc'),
    recursive = require('recursive-readdir'),

    COV_REPORT_PATH = '.coverage',
    SPEC_SOURCE_DIR = path.join(__dirname, '..', 'test', 'unit');

module.exports = function (exit) {
    // banner line
    console.info('Running unit tests using mocha...'.yellow.bold);

    test('-d', COV_REPORT_PATH) && rm('-rf', COV_REPORT_PATH);
    mkdir('-p', COV_REPORT_PATH);

    var Mocha = require('mocha'),
        nyc = new NYC({
            reporter: ['text', 'lcov'],
            reportDir: COV_REPORT_PATH,
            tempDirectory: COV_REPORT_PATH
        });

    nyc.wrap();
    // add all spec files to mocha
    recursive(SPEC_SOURCE_DIR, function (err, files) {
        if (err) {
            console.error(err);

            return exit(1);
        }

        var mocha = new Mocha({ timeout: 1000 * 60 });

        files.filter(function (file) { // extract all test files
            return (file.substr(-8) === '.test.js');
        }).forEach(mocha.addFile.bind(mocha));

        // start the mocha run
        global.expect = expect; // for easy reference

        mocha.run(function (runError) {
            // clear references and overrides
            delete global.expect;

            runError && console.error(runError.stack || runError);

            nyc.reset();
            nyc.writeCoverageFile();
            nyc.report();
            exit(runError ? 1 : 0);
        });
    });
};

// ensure we run this script exports if this is a direct stdin.tty run
!module.parent && module.exports(exit);
<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.7.1
module.exports = {
  "login title": "Cozy - Sign in",
  "login headline": "Welcome",
  "login connection invitation": "Please type your password to sign in:",
  "login password placeholder": "Your password",
  "login button": "Sign in",
  "login forget password button": "Did you forget your password?",
  "login success message": "Sign in succeeded, let's go to the Cozy Home...",
  "login reset success message": "An email has been sent to your mailbox, follow its instructions to get a new password.",
  "reset title": "Cozy - Reset password",
  "reset headline": "Tell me your new password",
  "reset instructions": "After a password reset, you must reconfigure your confidential data like your mailbox or your bank account.",
  "reset password placeholder": "Your new password",
  "reset button": "Change my password",
  "reset success message": "Password surcessfully reset.",
  "register title": "Cozy - Sign up",
  "register headline": "Welcome to your Cozy!",
  "register informations": "It's the first time you connect.",
  "register instructions": "Before going further, I need:",
  "register reinsurance modification": "Those information can be modified at any time from the configuration page.",
  "register reinsurance share": "Your Cozy will NEVER share your data without your consent.",
  "register button moreinfo": "Enter additional information",
  "register button separator": "or",
  "register button": "Send informations",
  "register success message": "Good, let's go to your Cozy homepage.",
  "register email placeholder": "You email address",
  "register email info": "Your Cozy will use this email address if you lose your password or to send you various information like alerts or daily reports.",
  "register email valid": "The email address is valid.",
  "register email invalid": "Enter a valid email address, e.g. john.doe@example.com.",
  "register password placeholder": "Pick a new password",
  "register password info": "Pick a unique password, made of numbers and letters, uppercased and lowercased: it's the shield that keeps your data private!",
  "register password valid": "Password long enough.",
  "register password invalid": "The password should be at least 5 characters long.",
  "register check password placeholder": "Enter your password again",
  "register check password info": "Confirm your password.",
  "register check password valid": "Password successfully confirmed.",
  "register check password invalid": "Passwords don't match.",
  "register public name placeholder": "Your public name on your Cozy",
  "register public name info": "Your public name will be used by your Cozy and its apps to communicate with you.",
  "register timezone info": "The timezone is used by Cozy and its apps to be always on time!",
  "error title": "Oops, an error has occurred",
  "error headline": "It seems that something went wrong.",
  "error reinsurance": "Don't worry, that's probably not so bad!",
  "error temporary issue": "It should be a temporary issue, please try again in 5 minutes.",
  "error try restart": "If nothing has changed despite that, try to restart your Cozy.",
  "error contact cozy team": "If the problem persists, feel free to contact the Cozy team:",
  "error contact forum": 'Ask for help on our forum',
  "error contact email": "Send an email at contact@cozycloud.cc",
  "error contact irc": "Report the issue on IRC, #cozycloud on irc.freenode.net",
  "error wait a bit": "Wait for 5 minutes",
  "error restart app": 'Restart the application ("Manage your apps" menu)',
  "error reinstall app": "Reinstall the application",
  "error not found info": "You are trying to access an application that is not installed or that is being installed.",
  "error try to fix": "You can try the following to fix it:",
  "error contact developer": "If nothing has worked, you can contact the application's developer or the Cozy team:",
  "error public info": "Please wait for 5 minutes then contact the Cozy owner if nothing has changed!",
  "error server": "Server error occurred.",
  "error bad credentials": "Incorrect password.",
  "error keys not initialized": "Keys aren't initialized.",
  "error login failed": "Login failed.",
  "reset password email from": "Your Cozy instance <no-reply@%{domain}>",
  "reset password email subject": "[Cozy] Reset password procedure",
  "reset password email text": "It seems that you forgot your Cozy's password. No worry about that, just\ngo to the following url and you will be able to set a new one:\n\nhttps://%{domain}/password/reset/%{key}\n\nDon't forget to reset all your encrypted data afterwards!"
};
<commit_msg>build<commit_after>// Generated by CoffeeScript 1.7.1
module.exports = {
  "login title": "Cozy - Sign in",
  "login headline": "Welcome",
  "login connection invitation": "Please type your password to sign in:",
  "login password placeholder": "Your password",
  "login button": "Sign in",
  "login forget password button": "Did you forget your password?",
  "login success message": "Sign in succeeded, let's go to the Cozy Home...",
  "login reset success message": "An email has been sent to your mailbox, follow its instructions to get a new password.",
  "reset title": "Cozy - Reset password",
  "reset headline": "Tell me your new password",
  "reset instructions": "After a password reset, you must reconfigure your confidential data like your mailbox or your bank account.",
  "reset password placeholder": "Your new password",
  "reset button": "Change my password",
  "reset success message": "Password successfully reset.",
  "register title": "Cozy - Sign up",
  "register headline": "Welcome to your Cozy!",
  "register informations": "It's the first time you connect.",
  "register instructions": "Before going further, I need:",
  "register reinsurance modification": "Those information can be modified at any time from the configuration page.",
  "register reinsurance share": "Your Cozy will NEVER share your data without your consent.",
  "register button moreinfo": "Enter additional information",
  "register button separator": "or",
  "register button": "Send informations",
  "register success message": "Good, let's go to your Cozy homepage.",
  "register email placeholder": "You email address",
  "register email info": "Your Cozy will use this email address if you lose your password or to send you various information like alerts or daily reports.",
  "register email valid": "The email address is valid.",
  "register email invalid": "Enter a valid email address, e.g. john.doe@example.com.",
  "register password placeholder": "Pick a new password",
  "register password info": "Pick a unique password, made of numbers and letters, uppercased and lowercased: it's the shield that keeps your data private!",
  "register password valid": "Password long enough.",
  "register password invalid": "The password should be at least 5 characters long.",
  "register check password placeholder": "Enter your password again",
  "register check password info": "Confirm your password.",
  "register check password valid": "Password successfully confirmed.",
  "register check password invalid": "Passwords don't match.",
  "register public name placeholder": "Your public name on your Cozy",
  "register public name info": "Your public name will be used by your Cozy and its apps to communicate with you.",
  "register timezone info": "The timezone is used by Cozy and its apps to be always on time!",
  "error title": "Oops, an error has occurred",
  "error headline": "It seems that something went wrong.",
  "error reinsurance": "Don't worry, that's probably not so bad!",
  "error temporary issue": "It should be a temporary issue, please try again in 5 minutes.",
  "error try restart": "If nothing has changed despite that, try to restart your Cozy.",
  "error contact cozy team": "If the problem persists, feel free to contact the Cozy team:",
  "error contact forum": 'Ask for help on our forum',
  "error contact email": "Send an email at contact@cozycloud.cc",
  "error contact irc": "Report the issue on IRC, #cozycloud on irc.freenode.net",
  "error wait a bit": "Wait for 5 minutes",
  "error restart app": 'Restart the application ("Manage your apps" menu)',
  "error reinstall app": "Reinstall the application",
  "error not found info": "You are trying to access an application that is not installed or that is being installed.",
  "error try to fix": "You can try the following to fix it:",
  "error contact developer": "If nothing has worked, you can contact the application's developer or the Cozy team:",
  "error public info": "Please wait for 5 minutes then contact the Cozy owner if nothing has changed!",
  "error server": "Server error occurred.",
  "error bad credentials": "Incorrect password.",
  "error keys not initialized": "Keys aren't initialized.",
  "error login failed": "Login failed.",
  "reset password email from": "Your Cozy instance <no-reply@%{domain}>",
  "reset password email subject": "[Cozy] Reset password procedure",
  "reset password email text": "It seems that you forgot your Cozy's password. No worry about that, just\ngo to the following url and you will be able to set a new one:\n\nhttps://%{domain}/password/reset/%{key}\n\nDon't forget to reset all your encrypted data afterwards!"
};
<|endoftext|>


<commit_before>'use strict';

const { Dialect } = require('../dialect');
const MysqlSchemaInspector = require('./schema-inspector');

class MysqlDialect extends Dialect {
  constructor(db) {
    super(db);

    this.schemaInspector = new MysqlSchemaInspector(db);
  }

  configure() {
    this.db.config.connection.connection.supportBigNumbers = true;
    this.db.config.connection.connection.bigNumberStrings = true;
    this.db.config.connection.connection.typeCast = (field, next) => {
      if (field.type === 'DECIMAL' || field.type === 'NEWDECIMAL') {
        var value = field.string();
        return value === null ? null : Number(value);
      }

      if (field.type === 'TINY' && field.length === 1) {
        let value = field.string();
        return value ? value === '1' : null;
      }

      if (field.type === 'DATE') {
        return field.string();
      }

      return next();
    };
  }

  async initialize() {
    try {
      await this.db.connection.raw(`set session sql_require_primary_key = 0;`);
    } catch (err) {
      console.error({ err });
    }
  }

  async startSchemaUpdate() {
    await this.db.connection.raw(`set foreign_key_checks = 0;`);
  }

  async endSchemaUpdate() {
    await this.db.connection.raw(`set foreign_key_checks = 1;`);
  }

  supportsUnsigned() {
    return true;
  }

  usesForeignKeys() {
    return true;
  }

  transformErrors(error) {
    super.transformErrors(error);
  }
}

module.exports = MysqlDialect;
<commit_msg>fix: empty catch block for primary key rule<commit_after>'use strict';

const { Dialect } = require('../dialect');
const MysqlSchemaInspector = require('./schema-inspector');

class MysqlDialect extends Dialect {
  constructor(db) {
    super(db);

    this.schemaInspector = new MysqlSchemaInspector(db);
  }

  configure() {
    this.db.config.connection.connection.supportBigNumbers = true;
    this.db.config.connection.connection.bigNumberStrings = true;
    this.db.config.connection.connection.typeCast = (field, next) => {
      if (field.type === 'DECIMAL' || field.type === 'NEWDECIMAL') {
        var value = field.string();
        return value === null ? null : Number(value);
      }

      if (field.type === 'TINY' && field.length === 1) {
        let value = field.string();
        return value ? value === '1' : null;
      }

      if (field.type === 'DATE') {
        return field.string();
      }

      return next();
    };
  }

  async initialize() {
    try {
      await this.db.connection.raw(`set session sql_require_primary_key = 0;`);
    } catch (err) {
      // Ignore error due to lack of session permissions
    }
  }

  async startSchemaUpdate() {
    await this.db.connection.raw(`set foreign_key_checks = 0;`);
  }

  async endSchemaUpdate() {
    await this.db.connection.raw(`set foreign_key_checks = 1;`);
  }

  supportsUnsigned() {
    return true;
  }

  usesForeignKeys() {
    return true;
  }

  transformErrors(error) {
    super.transformErrors(error);
  }
}

module.exports = MysqlDialect;
<|endoftext|>