<commit_before>var onPullRequestCommitPage = document.URL.indexOf("/pull/") != -1;
var onComparePage = document.URL.indexOf("/compare/") != -1;

var commits = document.getElementsByClassName('commit-links');
var pullCommits = document.getElementsByClassName('commit');

var foreach = Array.prototype.forEach;
foreach.call(commits, function(commit) {
	addCheckbox(commit, commit.children[0].attributes['data-clipboard-text'].value, true);
});
foreach.call(pullCommits, function(node) {
	var messageNode = node.children[2];
	var codeNode = messageNode.children[1];
	var commitRef = '';
	if (onComparePage) {
		var metaNode = node.children[3];
		var tokens = metaNode.children[0].children[0].attributes['href'].value.split("/");
		commitRef = tokens[tokens.length - 1];
	} else {
		commitRef = node.attributes['data-channel'].value.split(":")[2];
	}
	addCheckbox(messageNode, commitRef, false);
});

function addCheckbox(commitLinkNode, ref, floatLeft) {
    var container = document.createElement('span');
    container.className = 'commit-selector';
    container.style.marginTop = '5px';
    if (floatLeft) {
	container.style.float = 'left';
    } else {
	container.style.float = 'right';
    }

    var input = document.createElement('input');
    input.type = 'checkbox';
    input.name = 'box-' + ref;
    input.value = ref;
    input.onclick = compareDiffs;

    container.appendChild(input);
    commitLinkNode.insertBefore(container, commitLinkNode.lastChild);
}

function compareDiffs(event) {
    if (event.currentTarget.checked) {
	var filter = Array.prototype.filter;
	var selectedDiffs = filter.call(document.getElementsByClassName('commit-selector'),
					function(node) {
					    return node.children[0].checked
					});
	if (selectedDiffs.length == 2) {
	    var firstCommit = selectedDiffs[0].children[0].value;
	    var secondCommit = selectedDiffs[1].children[0].value;
	    if (onPullRequestCommitPage || onComparePage) {
		// commits in a Pull Request's Commits tab have time travelling DOWN
		window.location = compareUrl(document.URL, secondCommit, firstCommit);
	    } else {
		// commits in a Pull Request's Commits tab have time travelling UP
		window.location = compareUrl(document.URL, firstCommit, secondCommit);
	    }
	}
    }
}

function compareUrl(baseUrl, firstCommit, secondCommit) {
    var base = baseUrl.substring("https://".length, baseUrl.length);
    var tokens = base.split("/");
    var url = "https://" + tokens[0] + "/" + tokens[1] + "/" + tokens[2] + "/compare/" + secondCommit + "..." + firstCommit;
    return url;
}
<commit_msg>Undo the horror of mixing tabs and spaces.<commit_after>var onPullRequestCommitPage = document.URL.indexOf("/pull/") != -1;
var onComparePage = document.URL.indexOf("/compare/") != -1;

var commits = document.getElementsByClassName('commit-links');
var pullCommits = document.getElementsByClassName('commit');

var foreach = Array.prototype.forEach;
foreach.call(commits, function(commit) {
    addCheckbox(commit, commit.children[0].attributes['data-clipboard-text'].value, true);
});
foreach.call(pullCommits, function(node) {
    var messageNode = node.children[2];
    var codeNode = messageNode.children[1];
    var commitRef = '';
    if (onComparePage) {
        var metaNode = node.children[3];
        var tokens = metaNode.children[0].children[0].attributes['href'].value.split("/");
        commitRef = tokens[tokens.length - 1];
    } else {
        commitRef = node.attributes['data-channel'].value.split(":")[2];
    }
    addCheckbox(messageNode, commitRef, false);
});

function addCheckbox(commitLinkNode, ref, floatLeft) {
    var container = document.createElement('span');
    container.className = 'commit-selector';
    container.style.marginTop = '5px';
    if (floatLeft) {
        container.style.float = 'left';
    } else {
        container.style.float = 'right';
    }

    var input = document.createElement('input');
    input.type = 'checkbox';
    input.name = 'box-' + ref;
    input.value = ref;
    input.onclick = compareDiffs;

    container.appendChild(input);
    commitLinkNode.insertBefore(container, commitLinkNode.lastChild);
}

function compareDiffs(event) {
    if (event.currentTarget.checked) {
        var filter = Array.prototype.filter;
        var selectedDiffs = filter.call(document.getElementsByClassName('commit-selector'),
                                        function(node) {
                                            return node.children[0].checked
                                        });
        if (selectedDiffs.length == 2) {
            var firstCommit = selectedDiffs[0].children[0].value;
            var secondCommit = selectedDiffs[1].children[0].value;
            if (onPullRequestCommitPage || onComparePage) {
                // commits in a Pull Request's Commits tab have time travelling DOWN
                window.location = compareUrl(document.URL, secondCommit, firstCommit);
            } else {
                // commits in a Pull Request's Commits tab have time travelling UP
                window.location = compareUrl(document.URL, firstCommit, secondCommit);
            }
        }
    }
}

function compareUrl(baseUrl, firstCommit, secondCommit) {
    var base = baseUrl.substring("https://".length, baseUrl.length);
    var tokens = base.split("/");
    var url = "https://" + tokens[0] + "/" + tokens[1] + "/" + tokens[2] + "/compare/" + secondCommit + "..." + firstCommit;
    return url;
}
<|endoftext|>


<commit_before>/**
 * Copyright 2013-2020 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const chalk = require('chalk');
const _ = require('lodash');
const needleClientBase = require('./needle-client');
const constants = require('../../generator-constants');
const jhipsterUtils = require('../../utils');

const CLIENT_MAIN_SRC_DIR = constants.CLIENT_MAIN_SRC_DIR;

module.exports = class extends needleClientBase {
    addGlobalSCSSStyle(style, comment) {
        const filePath = `${CLIENT_MAIN_SRC_DIR}content/scss/global.scss`;
        this.addStyle(style, comment, filePath, 'jhipster-needle-scss-add-main');
    }

    addVendorSCSSStyle(style, comment) {
        const filePath = `${CLIENT_MAIN_SRC_DIR}content/scss/vendor.scss`;
        super.addStyle(style, comment, filePath, 'jhipster-needle-scss-add-vendor');
    }

    addModule(appName, angularName, folderName, fileName, enableTranslation, clientFramework) {
        const modulePath = `${CLIENT_MAIN_SRC_DIR}app/app.module.ts`;
        const importNeedle = 'jhipster-needle-angular-add-module-import';
        const moduleNeedle = 'jhipster-needle-angular-add-module';

        this._genericAddModule(
            appName,
            angularName,
            folderName,
            fileName,
            enableTranslation,
            clientFramework,
            modulePath,
            importNeedle,
            moduleNeedle
        );
    }

    addToAdminModule(appName, adminAngularName, adminFolderName, adminFileName, enableTranslation, clientFramework) {
        const adminModulePath = `${CLIENT_MAIN_SRC_DIR}app/admin/admin-routing.module.ts`;
        const importNeedle = 'jhipster-needle-add-admin-module-import';
        const moduleNeedle = 'jhipster-needle-add-admin-module';

        this._genericAddModule(
            appName,
            adminAngularName,
            adminFolderName,
            adminFileName,
            enableTranslation,
            clientFramework,
            adminModulePath,
            importNeedle,
            moduleNeedle
        );
    }

    _genericAddModule(
        appName,
        angularName,
        folderName,
        fileName,
        enableTranslation,
        clientFramework,
        modulePath,
        importNeedle,
        moduleNeedle
    ) {
        const errorMessage = `${chalk.yellow('Reference to ') +
            angularName +
            folderName +
            fileName +
            enableTranslation +
            clientFramework} ${chalk.yellow(`not added to ${modulePath}.\n`)}`;

        const importRewriteFileModel = this._generateRewriteFileModelWithImportStatement(
            appName,
            angularName,
            folderName,
            fileName,
            modulePath,
            importNeedle
        );
        this.addBlockContentToFile(importRewriteFileModel, errorMessage);

        const moduleRewriteFileModel = this._generateRewriteFileModelAddModule(appName, angularName, modulePath, moduleNeedle);
        this.addBlockContentToFile(moduleRewriteFileModel, errorMessage);
    }

    _generateRewriteFileModelWithImportStatement(appName, angularName, folderName, fileName, modulePath, needle) {
        const importStatement = this._generateImportStatement(appName, angularName, folderName, fileName);

        return this.generateFileModel(modulePath, needle, this.generator.stripMargin(importStatement));
    }

    _generateImportStatement(appName, angularName, folderName, fileName) {
        let importStatement = `|import { ${appName}${angularName}Module } from './${folderName}/${fileName}.module';`;
        if (importStatement.length > constants.LINE_LENGTH) {
            // prettier-ignore
            importStatement = `|import {
                        |    ${appName}${angularName}Module
                        |} from './${folderName}/${fileName}.module';`;
        }

        return importStatement;
    }

    _generateRewriteFileModelAddModule(appName, angularName, modulePath, needle) {
        return this.generateFileModel(modulePath, needle, this.generator.stripMargin(`|${appName}${angularName}Module,`));
    }

    addIcon(iconName) {
        const iconsPath = `${CLIENT_MAIN_SRC_DIR}app/core/icons/font-awesome-icons.ts`;
        const iconImport = `fa${this.generator.upperFirstCamelCase(iconName)}`;
        if (!jhipsterUtils.checkRegexInFile(iconsPath, new RegExp(`\\b${iconImport}\\b`), this.generator)) {
            try {
                jhipsterUtils.replaceContent(
                    {
                        file: iconsPath,
                        pattern: /\n {2}\/\/ jhipster-needle-add-icon-import/g,
                        content: `,\n  ${iconImport}\n  // jhipster-needle-add-icon-import`
                    },
                    this.generator
                );
            } catch (e) {
                this.generator.log(
                    chalk.yellow('\nUnable to find ') +
                        iconsPath +
                        chalk.yellow(' or other error. Icon imports not updated with icon ') +
                        iconImport +
                        chalk.yellow('.\n')
                );
                this.generator.debug('Error:', e);
            }
        }
    }

    addEntityToMenu(routerName, enableTranslation, entityTranslationKeyMenu) {
        const errorMessage = `${chalk.yellow('Reference to ') + routerName} ${chalk.yellow('not added to menu.\n')}`;
        const entityMenuPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
        const entityEntry =
            // prettier-ignore
            this.generator.stripMargin(`|

                             |
                             |                            <fa-icon icon="asterisk" fixedWidth="true"></fa-icon>
                             |                            <span${enableTranslation ? ` jhiTranslate="global.menu.entities.${entityTranslationKeyMenu}"` : ''}>${_.startCase(routerName)}
                             |
                             |
`);
        const rewriteFileModel = this.generateFileModel(entityMenuPath, 'jhipster-needle-add-entity-to-menu', entityEntry);

        this.addBlockContentToFile(rewriteFileModel, errorMessage);
    }

    addElementToMenu(routerName, iconName, enableTranslation, translationKeyMenu = routerName) {
        const errorMessage = `${chalk.yellow('Reference to ') + routerName} ${chalk.yellow('not added to menu.\n')}`;
        const entityMenuPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
        // prettier-ignore
        const entityEntry = `

                                    <fa-icon icon="${iconName}" fixedWidth="true"></fa-icon>
                                    <span${enableTranslation ? ` jhiTranslate="global.menu.${translationKeyMenu}"` : ''}>${_.startCase(routerName)}

`;
        const rewriteFileModel = this.generateFileModel(entityMenuPath, 'jhipster-needle-add-element-to-menu', entityEntry);

        this.addBlockContentToFile(rewriteFileModel, errorMessage);
        this.addIcon(iconName);
    }

    addElementToAdminMenu(routerName, iconName, enableTranslation, translationKeyMenu = routerName) {
        const errorMessage = `${chalk.yellow('Reference to ') + routerName} ${chalk.yellow('not added to admin menu.\n')}`;
        const navbarAdminPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
        // prettier-ignore
        const entityEntry = `

                            <fa-icon icon="${iconName}" fixedWidth="true"></fa-icon>
                            <span${enableTranslation ? ` jhiTranslate="global.menu.admin.${translationKeyMenu}"` : ''}>${_.startCase(routerName)}

`;
        const rewriteFileModel = this.generateFileModel(navbarAdminPath, 'jhipster-needle-add-element-to-admin-menu', entityEntry);

        this.addBlockContentToFile(rewriteFileModel, errorMessage);
        this.addIcon(iconName);
    }

    addEntityToModule(entityInstance, entityClass, entityAngularName, entityFolderName, entityFileName, entityUrl, microServiceName) {
        const entityModulePath = `${CLIENT_MAIN_SRC_DIR}app/entities/entity.module.ts`;
        const errorMessage = `${chalk.yellow('Reference to ') +
            entityInstance +
            entityClass +
            entityFolderName +
            entityFileName} ${chalk.yellow(`not added to ${entityModulePath}.\n`)}`;

        try {
            const isSpecificEntityAlreadyGenerated = jhipsterUtils.checkStringInFile(
                entityModulePath,
                `path: '${entityUrl}'`,
                this.generator
            );

            if (!isSpecificEntityAlreadyGenerated) {
                const appName = this.generator.getAngularXAppName();
                const isAnyEntityAlreadyGenerated = jhipsterUtils.checkStringInFile(entityModulePath, 'loadChildren', this.generator);

                const modulePath = `./${entityFolderName}/${entityFileName}.module`;
                const moduleName = microServiceName
                    ? `${this.generator.upperFirstCamelCase(microServiceName)}${entityAngularName}Module`
                    : `${appName}${entityAngularName}Module`;

                const splicable = isAnyEntityAlreadyGenerated
                    ? `|,{
                            |                path: '${entityUrl}',
                            |                loadChildren: () => import('${modulePath}').then(m => m.${moduleName})
                            |            }`
                    : `|{
                                |                path: '${entityUrl}',
                                |                loadChildren: () => import('${modulePath}').then(m => m.${moduleName})
                                |            }`;
                const rewriteFileModel = this.generateFileModel(
                    entityModulePath,
                    'jhipster-needle-add-entity-route',
                    this.generator.stripMargin(splicable)
                );

                this.addBlockContentToFile(rewriteFileModel, errorMessage);
            }
        } catch (e) {
            this.generator.debug('Error:', e);
        }
    }
};
<commit_msg>🐛: allow addIcon() to function correctly<commit_after>/**
 * Copyright 2013-2020 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see https://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const chalk = require('chalk');
const _ = require('lodash');
const needleClientBase = require('./needle-client');
const constants = require('../../generator-constants');
const jhipsterUtils = require('../../utils');

const CLIENT_MAIN_SRC_DIR = constants.CLIENT_MAIN_SRC_DIR;

module.exports = class extends needleClientBase {
    addGlobalSCSSStyle(style, comment) {
        const filePath = `${CLIENT_MAIN_SRC_DIR}content/scss/global.scss`;
        this.addStyle(style, comment, filePath, 'jhipster-needle-scss-add-main');
    }

    addVendorSCSSStyle(style, comment) {
        const filePath = `${CLIENT_MAIN_SRC_DIR}content/scss/vendor.scss`;
        super.addStyle(style, comment, filePath, 'jhipster-needle-scss-add-vendor');
    }

    addModule(appName, angularName, folderName, fileName, enableTranslation, clientFramework) {
        const modulePath = `${CLIENT_MAIN_SRC_DIR}app/app.module.ts`;
        const importNeedle = 'jhipster-needle-angular-add-module-import';
        const moduleNeedle = 'jhipster-needle-angular-add-module';

        this._genericAddModule(
            appName,
            angularName,
            folderName,
            fileName,
            enableTranslation,
            clientFramework,
            modulePath,
            importNeedle,
            moduleNeedle
        );
    }

    addToAdminModule(appName, adminAngularName, adminFolderName, adminFileName, enableTranslation, clientFramework) {
        const adminModulePath = `${CLIENT_MAIN_SRC_DIR}app/admin/admin-routing.module.ts`;
        const importNeedle = 'jhipster-needle-add-admin-module-import';
        const moduleNeedle = 'jhipster-needle-add-admin-module';

        this._genericAddModule(
            appName,
            adminAngularName,
            adminFolderName,
            adminFileName,
            enableTranslation,
            clientFramework,
            adminModulePath,
            importNeedle,
            moduleNeedle
        );
    }

    _genericAddModule(
        appName,
        angularName,
        folderName,
        fileName,
        enableTranslation,
        clientFramework,
        modulePath,
        importNeedle,
        moduleNeedle
    ) {
        const errorMessage = `${chalk.yellow('Reference to ') +
            angularName +
            folderName +
            fileName +
            enableTranslation +
            clientFramework} ${chalk.yellow(`not added to ${modulePath}.\n`)}`;

        const importRewriteFileModel = this._generateRewriteFileModelWithImportStatement(
            appName,
            angularName,
            folderName,
            fileName,
            modulePath,
            importNeedle
        );
        this.addBlockContentToFile(importRewriteFileModel, errorMessage);

        const moduleRewriteFileModel = this._generateRewriteFileModelAddModule(appName, angularName, modulePath, moduleNeedle);
        this.addBlockContentToFile(moduleRewriteFileModel, errorMessage);
    }

    _generateRewriteFileModelWithImportStatement(appName, angularName, folderName, fileName, modulePath, needle) {
        const importStatement = this._generateImportStatement(appName, angularName, folderName, fileName);

        return this.generateFileModel(modulePath, needle, this.generator.stripMargin(importStatement));
    }

    _generateImportStatement(appName, angularName, folderName, fileName) {
        let importStatement = `|import { ${appName}${angularName}Module } from './${folderName}/${fileName}.module';`;
        if (importStatement.length > constants.LINE_LENGTH) {
            // prettier-ignore
            importStatement = `|import {
                        |    ${appName}${angularName}Module
                        |} from './${folderName}/${fileName}.module';`;
        }

        return importStatement;
    }

    _generateRewriteFileModelAddModule(appName, angularName, modulePath, needle) {
        return this.generateFileModel(modulePath, needle, this.generator.stripMargin(`|${appName}${angularName}Module,`));
    }

    addIcon(iconName) {
        const iconsPath = `${CLIENT_MAIN_SRC_DIR}app/core/icons/font-awesome-icons.ts`;
        const iconImport = `fa${this.generator.upperFirstCamelCase(iconName)}`;
        if (!jhipsterUtils.checkRegexInFile(iconsPath, new RegExp(`\\b${iconImport}\\b`), this.generator)) {
            try {
                jhipsterUtils.replaceContent(
                    {
                        file: iconsPath,
                        pattern: /(\r?\n)(\s*)\/\/ jhipster-needle-add-icon-import/g,
                        content: `,\n  ${iconImport}\n  // jhipster-needle-add-icon-import`
                    },
                    this.generator
                );
            } catch (e) {
                this.generator.log(
                    chalk.yellow('\nUnable to find ') +
                        iconsPath +
                        chalk.yellow(' or other error. Icon imports not updated with icon ') +
                        iconImport +
                        chalk.yellow('.\n')
                );
                this.generator.debug('Error:', e);
            }
        }
    }

    addEntityToMenu(routerName, enableTranslation, entityTranslationKeyMenu) {
        const errorMessage = `${chalk.yellow('Reference to ') + routerName} ${chalk.yellow('not added to menu.\n')}`;
        const entityMenuPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
        const entityEntry =
            // prettier-ignore
            this.generator.stripMargin(`|

                             |
                             |                            <fa-icon icon="asterisk" fixedWidth="true"></fa-icon>
                             |                            <span${enableTranslation ? ` jhiTranslate="global.menu.entities.${entityTranslationKeyMenu}"` : ''}>${_.startCase(routerName)}
                             |
                             |
`);
        const rewriteFileModel = this.generateFileModel(entityMenuPath, 'jhipster-needle-add-entity-to-menu', entityEntry);

        this.addBlockContentToFile(rewriteFileModel, errorMessage);
    }

    addElementToMenu(routerName, iconName, enableTranslation, translationKeyMenu = routerName) {
        const errorMessage = `${chalk.yellow('Reference to ') + routerName} ${chalk.yellow('not added to menu.\n')}`;
        const entityMenuPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
        // prettier-ignore
        const entityEntry = `

                                    <fa-icon icon="${iconName}" fixedWidth="true"></fa-icon>
                                    <span${enableTranslation ? ` jhiTranslate="global.menu.${translationKeyMenu}"` : ''}>${_.startCase(routerName)}

`;
        const rewriteFileModel = this.generateFileModel(entityMenuPath, 'jhipster-needle-add-element-to-menu', entityEntry);

        this.addBlockContentToFile(rewriteFileModel, errorMessage);
        this.addIcon(iconName);
    }

    addElementToAdminMenu(routerName, iconName, enableTranslation, translationKeyMenu = routerName) {
        const errorMessage = `${chalk.yellow('Reference to ') + routerName} ${chalk.yellow('not added to admin menu.\n')}`;
        const navbarAdminPath = `${CLIENT_MAIN_SRC_DIR}app/layouts/navbar/navbar.component.html`;
        // prettier-ignore
        const entityEntry = `

                            <fa-icon icon="${iconName}" fixedWidth="true"></fa-icon>
                            <span${enableTranslation ? ` jhiTranslate="global.menu.admin.${translationKeyMenu}"` : ''}>${_.startCase(routerName)}

`;
        const rewriteFileModel = this.generateFileModel(navbarAdminPath, 'jhipster-needle-add-element-to-admin-menu', entityEntry);

        this.addBlockContentToFile(rewriteFileModel, errorMessage);
        this.addIcon(iconName);
    }

    addEntityToModule(entityInstance, entityClass, entityAngularName, entityFolderName, entityFileName, entityUrl, microServiceName) {
        const entityModulePath = `${CLIENT_MAIN_SRC_DIR}app/entities/entity.module.ts`;
        const errorMessage = `${chalk.yellow('Reference to ') +
            entityInstance +
            entityClass +
            entityFolderName +
            entityFileName} ${chalk.yellow(`not added to ${entityModulePath}.\n`)}`;

        try {
            const isSpecificEntityAlreadyGenerated = jhipsterUtils.checkStringInFile(
                entityModulePath,
                `path: '${entityUrl}'`,
                this.generator
            );

            if (!isSpecificEntityAlreadyGenerated) {
                const appName = this.generator.getAngularXAppName();
                const isAnyEntityAlreadyGenerated = jhipsterUtils.checkStringInFile(entityModulePath, 'loadChildren', this.generator);

                const modulePath = `./${entityFolderName}/${entityFileName}.module`;
                const moduleName = microServiceName
                    ? `${this.generator.upperFirstCamelCase(microServiceName)}${entityAngularName}Module`
                    : `${appName}${entityAngularName}Module`;

                const splicable = isAnyEntityAlreadyGenerated
                    ? `|,{
                            |                path: '${entityUrl}',
                            |                loadChildren: () => import('${modulePath}').then(m => m.${moduleName})
                            |            }`
                    : `|{
                                |                path: '${entityUrl}',
                                |                loadChildren: () => import('${modulePath}').then(m => m.${moduleName})
                                |            }`;
                const rewriteFileModel = this.generateFileModel(
                    entityModulePath,
                    'jhipster-needle-add-entity-route',
                    this.generator.stripMargin(splicable)
                );

                this.addBlockContentToFile(rewriteFileModel, errorMessage);
            }
        } catch (e) {
            this.generator.debug('Error:', e);
        }
    }
};
<|endoftext|>


<commit_before>$(function() {

    window.toggleTheme = function (theme){
        toggleThemeFilterClass($('.fullSchedule-talk-theme-' + theme));
	}

    window.toggleTheme2 = function (theme){
		// Le filtre sélectionné
		let currentFilter = $('.fullSchedule-filter-themes .fullSchedule-talk-theme-' + theme)
		console.log('Filtre courant:',currentFilter)

		// Les éléments à filtrer
		let currentElems = $('.fullSchedule-talk-theme-' + theme)
		console.log('Elms:',currentElems)

		if(currentFilter && currentFilter.attr('data-filter-theme')){
			// Si element courant est désactivé alors le réactiver
			console.log(theme + " doit être visible");
			toggleThemeFilterClass(currentFilter[0]);
			currentElems.each(function(index, element) {
				toggleThemeFilterClass(element);
			}, this);
		}
		else{
			console.log(theme + " doit être caché");

			let otherFilters = $('.fullSchedule-filter-themes .fullSchedule-filter-item').not('.fullSchedule-talk-theme-' + theme)
			let otherElems = $('.fullSchedule-talk .fullSchedule-filter-item').not('.fullSchedule-talk-theme-' + theme)
			if(otherFilters.length > 0){
				otherFilters.each(function(index, element) {
					toggleThemeFilterClass(element);
				}, this);
				otherElems.each(function(index, element) {
					toggleThemeFilterClass(element);
				}, this);
			}
			else{
				toggleThemeFilterClass($('.fullSchedule-talk-theme-' + theme));
			}
			console.log('Elms:',currentElems)
		}

		// Sinon {
			// Si aucun élément désactivé on désactive tous les autres
			// Sinon on désactive l'élément courant
		//}

    }

    window.toggleLevel = function (level){
        toggleLevelFilterClass($('.fullSchedule-talk-level-' + level));
    }

    var toggleThemeFilterClass = function (elem){
		toggleFilterClass(elem, 'data-filter-theme', 'hidden');
	}

	var toggleLevelFilterClass = function (elem){
		toggleFilterClass(elem, 'data-filter-level', 'hidden');
	}

    var toggleFilterClass = function(elem, attrName, className){
        if(elem && (!elem.attr(attrName))){
            elem.attr(attrName,className);
		}
        else{
            elem.removeAttr(attrName,className);
            elem.removeAttribute(attrName);
        }
    }

	var toggleFilterClass2 = function(elem, attrName, className){
		if(elem && (!elem.getAttribute(attrName))){
			elem.setAttribute(attrName,className);
		}
		else{
			elem.removeAttribute(attrName);
		}
	}
});<commit_msg>Work in Progress on filter on schedule<commit_after>$(function() {

    window.toggleTheme = function (theme){
        toggleThemeFilterClass($('.fullSchedule-talk-theme-' + theme));
	}

    window.toggleTheme2 = function (theme){
		// Le filtre sélectionné
		let currentFilter = $('.fullSchedule-filter-themes .fullSchedule-talk-theme-' + theme)
		console.log('Filtre courant:',currentFilter)

		// Les éléments à filtrer
		let currentElems = $('.fullSchedule-talk-theme-' + theme)
		console.log('Elms:',currentElems)

		if(currentFilter && currentFilter.attr('data-filter-theme')){
			// Si element courant est désactivé alors le réactiver
			console.log(theme + " doit être visible");
			currentElems.each(function(index, element) {
				toggleThemeFilterClass(element);
			}, this);
		}
		else{
			console.log(theme + " doit être caché");

			let otherHiddenFilters = $('.fullSchedule-filter-themes .fullSchedule-filter-item[data-filter-theme]').not('.fullSchedule-talk-theme-' + theme)
			let otherFilters = $('.fullSchedule-filter-themes .fullSchedule-filter-item').not('.fullSchedule-talk-theme-' + theme)
			// Si d'autres éléments sont déjà cachés alors on cache l'élément sélectionné
			if(otherHiddenFilters.length > 0 && otherHiddenFilters.length !== otherFilters.length){
				currentElems.each(function(index, element) {
					toggleThemeFilterClass(element);
				}, this);
				return;
			}

			// Si aucun éléments n'est cachés alors on cache tous les autres

			let otherElems = $('.fullSchedule-talk .fullSchedule-filter-item').not('.fullSchedule-talk-theme-' + theme)
			if(otherFilters.length > 0){
				otherFilters.each(function(index, element) {
					toggleThemeFilterClass(element);
				}, this);
				otherElems.each(function(index, element) {
					toggleThemeFilterClass(element);
				}, this);
			}
			else{
				toggleThemeFilterClass($('.fullSchedule-talk-theme-' + theme));
			}
			console.log('Elms:',currentElems)
		}

		// Sinon {
			// Si aucun élément désactivé on désactive tous les autres
			// Sinon on désactive l'élément courant
		//}

    }

    window.toggleLevel = function (level){
        toggleLevelFilterClass($('.fullSchedule-talk-level-' + level));
    }

    var toggleThemeFilterClass = function (elem){
		toggleFilterClass(elem, 'data-filter-theme', 'hidden');
	}

	var toggleLevelFilterClass = function (elem){
		toggleFilterClass(elem, 'data-filter-level', 'hidden');
	}

    var toggleFilterClass = function(elem, attrName, className){
        if(elem && (!elem.attr(attrName))){
            elem.attr(attrName,className);
		}
        else{
            elem.removeAttr(attrName,className);
            elem.removeAttribute(attrName);
        }
    }

	var toggleFilterClass2 = function(elem, attrName, className){
		if(elem && (!elem.getAttribute(attrName))){
			elem.setAttribute(attrName,className);
		}
		else{
			elem.removeAttribute(attrName);
		}
	}
});<|endoftext|>


<commit_before>import $ from 'jquery';
import _ from 'underscore';

import ItemCollection from '@girder/core/collections/ItemCollection';
import LoadingAnimation from '@girder/core/views/widgets/LoadingAnimation';
import View from '@girder/core/views/View';
import { formatSize } from '@girder/core/misc';

import ItemListTemplate from '@girder/core/templates/widgets/itemList.pug';

/**
 * This widget shows a list of items under a given folder.
 */
var ItemListWidget = View.extend({
    events: {
        'click a.g-item-list-link': function (event) {
            event.preventDefault();
            var cid = $(event.currentTarget).attr('g-item-cid');
            this.trigger('g:itemClicked', this.collection.get(cid), event);
        },
        'click a.g-show-more-items': function () {
            this.collection.fetchNextPage();
        },
        'change .g-list-checkbox': function (event) {
            const target = $(event.currentTarget);
            const cid = target.attr('g-item-cid');
            if (target.prop('checked')) {
                this.checked.push(cid);
            } else {
                const idx = this.checked.indexOf(cid);
                if (idx !== -1) {
                    this.checked.splice(idx, 1);
                }
            }
            this.trigger('g:checkboxesChanged');
        }
    },

    initialize: function (settings) {
        this.checked = [];
        this._checkboxes = settings.checkboxes;
        this._downloadLinks = (
            _.has(settings, 'downloadLinks') ? settings.downloadLinks : true);
        this._viewLinks = (
            _.has(settings, 'viewLinks') ? settings.viewLinks : true);
        this._showSizes = (
            _.has(settings, 'showSizes') ? settings.showSizes : true);
        this.accessLevel = settings.accessLevel;
        this.public = settings.public;
        this._selectedItem = settings.selectedItem;

        new LoadingAnimation({
            el: this.$el,
            parentView: this
        }).render();

        this.collection = new ItemCollection();
        this.collection.append = true; // Append, don't replace pages
        this.collection.filterFunc = settings.itemFilter;

        this.collection.on('g:changed', function () {
            if (this.accessLevel !== undefined) {
                this.collection.each((model) => {
                    model.set('_accessLevel', this.accessLevel);
                });
            }
            this.render();
            this.trigger('g:changed');
        }, this).fetch({ folderId: settings.folderId });
    },

    render: function () {
        this.checked = [];
        this.$el.html(ItemListTemplate({
            items: this.collection.toArray(),
            isParentPublic: this.public,
            hasMore: this.collection.hasNextPage(),
            formatSize: formatSize,
            checkboxes: this._checkboxes,
            downloadLinks: this._downloadLinks,
            viewLinks: this._viewLinks,
            showSizes: this._showSizes,
            selectedItemId: (this._selectedItem || {}).id
        }));

        return this;
    },

    /**
     * Insert an item into the collection and re-render it.
     */
    insertItem: function (item) {
        if (this.accessLevel !== undefined) {
            item.set('_accessLevel', this.accessLevel);
        }
        this.collection.add(item);
        this.trigger('g:changed');
        this.render();
    },

    /**
     * Set all item checkboxes to a certain checked state. The event
     * g:checkboxesChanged is triggered once after checking/unchecking everything.
     * @param {bool} checked The checked state.
     */
    checkAll: function (checked) {
        this.$('.g-list-checkbox').prop('checked', checked);

        this.checked = [];
        if (checked) {
            this.collection.each(function (model) {
                this.checked.push(model.cid);
            }, this);
        }

        this.trigger('g:checkboxesChanged');
    },

    /**
     * Select (highlight) an item in the list.
     * @param item An ItemModel instance representing the item to select.
     */
    selectItem: function (item) {
        this.$('li.g-item-list-entry').removeClass('g-selected');
        this.$('a.g-item-list-link[g-item-cid=' + item.cid + ']')
            .parents('li.g-item-list-entry').addClass('g-selected');
    },

    /**
     * Return the currently selected item, or null if there is no selected item.
     */
    getSelectedItem: function () {
        var el = this.$('li.g-item-list-entry.g-selected');
        if (!el.length) {
            return null;
        }
        var cid = $('.g-item-list-link', $(el[0])).attr('g-item-cid');
        return this.collection.get(cid);
    },

    recomputeChecked: function () {
        this.checked = _.map(this.$('.g-list-checkbox:checked'), function (checkbox) {
            return $(checkbox).attr('g-item-cid');
        }, this);
    }
});

export default ItemListWidget;
<commit_msg>Adding in a first test of the scrolling system<commit_after>import $ from 'jquery';
import _ from 'underscore';

import ItemCollection from '@girder/core/collections/ItemCollection';
import LoadingAnimation from '@girder/core/views/widgets/LoadingAnimation';
import View from '@girder/core/views/View';
import { formatSize } from '@girder/core/misc';

import ItemListTemplate from '@girder/core/templates/widgets/itemList.pug';

/**
 * This widget shows a list of items under a given folder.
 */
var ItemListWidget = View.extend({
    events: {
        'click a.g-item-list-link': function (event) {
            event.preventDefault();
            var cid = $(event.currentTarget).attr('g-item-cid');
            this.trigger('g:itemClicked', this.collection.get(cid), event);
        },
        'click a.g-show-more-items': function () {
            this.collection.fetchNextPage();
        },
        'change .g-list-checkbox': function (event) {
            const target = $(event.currentTarget);
            const cid = target.attr('g-item-cid');
            if (target.prop('checked')) {
                this.checked.push(cid);
            } else {
                const idx = this.checked.indexOf(cid);
                if (idx !== -1) {
                    this.checked.splice(idx, 1);
                }
            }
            this.trigger('g:checkboxesChanged');
        }
    },

    initialize: function (settings) {
        this.checked = [];
        this._checkboxes = settings.checkboxes;
        this._downloadLinks = (
            _.has(settings, 'downloadLinks') ? settings.downloadLinks : true);
        this._viewLinks = (
            _.has(settings, 'viewLinks') ? settings.viewLinks : true);
        this._showSizes = (
            _.has(settings, 'showSizes') ? settings.showSizes : true);
        this.accessLevel = settings.accessLevel;
        this.public = settings.public;
        this._selectedItem = settings.selectedItem;

        new LoadingAnimation({
            el: this.$el,
            parentView: this
        }).render();

        this.collection = new ItemCollection();
        this.collection.append = true; // Append, don't replace pages
        this.collection.filterFunc = settings.itemFilter;

        this.collection.on('g:changed', function () {
            if (this.accessLevel !== undefined) {
                this.collection.each((model) => {
                    model.set('_accessLevel', this.accessLevel);
                });
            }
            this.render();
            this.trigger('g:changed');
        }, this).fetch({ folderId: settings.folderId });
    },

    render: function () {
        this.checked = [];
        this.$el.html(ItemListTemplate({
            items: this.collection.toArray(),
            isParentPublic: this.public,
            hasMore: this.collection.hasNextPage(),
            formatSize: formatSize,
            checkboxes: this._checkboxes,
            downloadLinks: this._downloadLinks,
            viewLinks: this._viewLinks,
            showSizes: this._showSizes,
            selectedItemId: (this._selectedItem || {}).id
        }));

        if (this._selectedItem) {
            this.observerPosition();
        }
        return this;
    },

    /**
     * Insert an item into the collection and re-render it.
     */
    insertItem: function (item) {
        if (this.accessLevel !== undefined) {
            item.set('_accessLevel', this.accessLevel);
        }
        this.collection.add(item);
        this.trigger('g:changed');
        this.render();
    },

    /**
     * Set all item checkboxes to a certain checked state. The event
     * g:checkboxesChanged is triggered once after checking/unchecking everything.
     * @param {bool} checked The checked state.
     */
    checkAll: function (checked) {
        this.$('.g-list-checkbox').prop('checked', checked);

        this.checked = [];
        if (checked) {
            this.collection.each(function (model) {
                this.checked.push(model.cid);
            }, this);
        }

        this.trigger('g:checkboxesChanged');
    },

    /**
     * Select (highlight) an item in the list.
     * @param item An ItemModel instance representing the item to select.
     */
    selectItem: function (item) {
        this.$('li.g-item-list-entry').removeClass('g-selected');
        this.$('a.g-item-list-link[g-item-cid=' + item.cid + ']')
            .parents('li.g-item-list-entry').addClass('g-selected');
    },

    /**
     * Return the currently selected item, or null if there is no selected item.
     */
    getSelectedItem: function () {
        var el = this.$('li.g-item-list-entry.g-selected');
        if (!el.length) {
            return null;
        }
        var cid = $('.g-item-list-link', $(el[0])).attr('g-item-cid');
        return this.collection.get(cid);
    },

    recomputeChecked: function () {
        this.checked = _.map(this.$('.g-list-checkbox:checked'), function (checkbox) {
            return $(checkbox).attr('g-item-cid');
        }, this);
    },

    /**
     * This will look at the position of the selected item and update it as images load and
     * the DOM reflows
     */
    observerPosition: function () {
        if (window.MutationObserver) {
            let selector = $('li.g-item-list-entry.g-selected');
            let target = $('.g-hierarchy-widget-container');
            let observer = new MutationObserver(function (mutations) {
                // for every mutation
                mutations.forEach(function (mutation) {
                    // for every added element
                    mutation.addedNodes.forEach(function (node) {
                        // console.log(node);
                        // Check if we appended a node type that isn't
                        // an element that we can search for images inside,
                        // like a text node.

                        if (_.isFunction(node.getElementsByTagName)) {
                            let imgs = node.getElementsByTagName('img');
                            console.log(imgs);
                            for (let i = 0; i < imgs.length; i++) {
                                let img = imgs[i];
                                // if it hasn't loaded yet
                                if (!img.complete) {
                                    let onLoadImage = function (event) {
                                        if (selector.length !== 1) {
                                            return;
                                        }
                                        target.scrollTop(selector.offset().top - target.height());
                                    };
                                    // when the image is done loading, call the function above
                                    img.addEventListener('load', onLoadImage);
                                }
                            }

                            // return;
                        }

                        /*

                        let imgs = node.getElementsByTagName('img');
                        console.log(imgs);
                        // for every new image
                        imgs.forEach(function (img) {
                            // if it hasn't loaded yet
                            if (!img.complete) {
                                let onLoadImage = function (event) {
                                    target.scrollTop($(selector).offset().top - target.height());
                                };
                                // when the image is done loading, call the function above
                                img.addEventListener('load', onLoadImage);
                            }
                        });
                        */
                    });
                });
            });

            // bind mutation observer to a specific element (probably a div somewhere)
            observer.observe(target[0], { childList: true, subtree: true });
        }
    }
});

export default ItemListWidget;
<|endoftext|>


<commit_before>(function (form) {

    form.modules.apache = {
        options: [
            'system',
            'apache'
        ],
        onUpdate: function () {

        }
    };

})(window.form);
<commit_msg>Update script.js<commit_after>(function (form) {

    form.modules.apache = {
        options: [
            'system',
            'apache'
        ],
        onUpdate: function () {
            form.setCommand(form.apache_version.value, 'apache', form.apache_version.value);
        }
    };

})(window.form);
<|endoftext|>


<commit_before>/*jslint browser: true*/
/*global L */
/*global GEOHEX */
var geohexcode = null;
var startZoomlevel = 12;
var localStoragePrefix = 'EW_'; // earthWatchers
var user = localStorage.getItem(localStoragePrefix + 'user') || 'anonymous' ;
var satelliteImages = null;
var map = null;
var polygon = null;
var default_geohex_level = 7;
var defaultSatelliteType = 'Landsat';
var uservote = null;

function getSatelliteImageByDate(date) {
    for (var i = 0; i < satelliteImages.features.length; i++) {
        if (satelliteImages.features[i].properties.Published === date) {
            return satelliteImages.features[i];
        }
    }
    return null;
}

function findEarthWatchersLayer() {
    var result = null;
    map.eachLayer(function (layer) {
        if (layer.options.type !== null) {
            if (layer.options.type === 'earthWatchers') {
                result = layer;
            }
        }
    });
    return result;
}

function saveCleanedObservation(observationString) {
    // logging user actions
    //
    // create new line in localStorage like
    // { ...,
    //      'EW_1427635304381': '{"user":"barack","lat":1.0347919593425408,"lon":111.97073616826705,"level":7,"observation":"no","geohex":"PO5020737"}',
    //      ...}
    localStorage.setItem(
            localStoragePrefix + (new Date()).getTime(), observationString);
}

function timeSliderChanged(ctrl) {
    var day = satelliteImages.features[ctrl.value].properties.Published;
    var label = document.getElementById('rangeValLabel');
    label.innerHTML = day;
    // update label positioning
    label.className = 'value' + ctrl.value;

    var earthWatchersLayer = findEarthWatchersLayer();

    var s = getSatelliteImageByDate(day);
    var url = s.properties.UrlTileCache + '/{z}/{x}/{y}.png';
    var maxlevel = s.properties.MaxLevel;
    var newLayer = L.tileLayer(url, {
        tms: true,
        maxZoom: maxlevel,
        type: 'earthWatchers'
    });
    map.addLayer(newLayer);

    if (earthWatchersLayer !== null) {
        map.removeLayer(earthWatchersLayer);
    }
}

function getGeohexPolygon(geohexcode, style) {
    var zone = GEOHEX.getZoneByCode(geohexcode);
    return L.polygon(zone.getHexCoords(), style);
}

function next() {
    var url = location.href.replace(location.hash,'');
    location.href=url;
}

function styleButton(button,checked){
    if(checked){
        button.style.border='5px solid black'
    }
    else{
        button.style.border='0px solid black'
    }
}

function toggleSatelliteType(sel) {
    var labels = {
            Landsat: 'Landsat 8',
            Sentinel: 'Sentinel 1'
        },
        newtype = sel.value === 'Landsat' ? 'Sentinel' : 'Landsat';

    // change map layer
    satelliteTypeSelectionChanged({value: newtype});

    // update satellite type value
    sel.parentNode.classList.remove(sel.value.toLowerCase());
    sel.setAttribute('value', newtype);
    sel.parentNode.classList.add(sel.value.toLowerCase());

    // update satellite type label
    document.getElementById('satTypeLabel').innerText = labels[newtype];
}

function satelliteTypeSelectionChanged(sel) {
    var currentImageType = sel.value;
    var polygon = getGeohexPolygon(geohexcode);
    var bbox = polygon.getBounds().toBBoxString();
    getSatelliteImageData(bbox, currentImageType, function(resp){
        satelliteImages = resp;
        var sel = document.getElementById('timeSlider');
        satelliteImages.features.sort(compare);
        sel.onchange();
    });
}

function sendObservation(observation){
    if(observation!=uservote){
        colorizePolygon(observation);
        postObservation(observation,user,geohexcode,function(resp){
            getHexagon(geohexcode, user, function(resp){
                processHexagonResponse(resp);
            });

        });
    };
}

function updateUsername(newName) {
    // update global var and localstorage value
    user = newName;
    localStorage.setItem(localStoragePrefix + 'user', newName);
}

function changeName(event) {
    var form = event.target,
        newName = form.children[0].value;

    // stop from saving empty name
    if (!newName) return false;

    updateUsername(newName);

    // clean and hide form
    form.parentElement.classList.add('hide');
    form.children[0].value = '';

    updateUserinfo();
    uservote=null;
    getHexagon(geohexcode, user, function(resp){
        processHexagonResponse(resp);
    });

    return false;
}

function showUserForm() {
    var userform = document.getElementById('userform');

    userform.classList.remove('hide');
}

function initUserpanel() {
    updateUserinfo();
    var userform = document.getElementById('userform');
    userform.children[0].onsubmit = changeName;
}

function updateUserinfo() {
    var userinfo = document.getElementById('userinfo');

    userinfo.innerHTML =
        ' Hi, ' + user + '! ' +
        'Change?';
}

function processHexagonResponse(resp){
    document.getElementById('btnYes').innerText = 'Yes (' + resp.yes + ')';
    document.getElementById('btnNo').innerText = 'No (' + resp.no + ')';
    document.getElementById('btnMaybe').innerText = 'Maybe (' + resp.maybe + ')';

    uservote = resp.uservote;
    styleButton (document.getElementById('btnYes'),uservote === 'yes');
    styleButton (document.getElementById('btnNo'),uservote === 'no');
    styleButton (document.getElementById('btnMaybe'),uservote === 'maybe');
}

(function (window, document, L) {
    'use strict';
    L.Icon.Default.imagePath = 'images/';

    Path.map("#/hexagon/:hex").to(function(){
        // sample: #/hexagon/PO2670248
        geohexcode = this.params['hex'];
    });
    Path.listen();

    initUserpanel();

    var lon_min = 111.0;
    var lon_max = 112.0;
    var lat_min = 1;
    var lat_max = 2;

    loadJSON('data/projects.geojson', function(response) {
        var projects = JSON.parse(response);
        L.geoJson(projects,{fill:false}).addTo(map);
        // todo: calculate hexagon based on project areas
    });

    if(geohexcode===null){
        var lon_rnd = random(lon_min, lon_max);
        var lat_rnd = random(lat_min, lat_max);
        geohexcode = GEOHEX.getZoneByLocation(lat_rnd, lon_rnd, default_geohex_level).code;
        location.hash = '#/hexagon/' + geohexcode;
    }

    // fire onchange event of first combobox
    satelliteTypeSelectionChanged({value: defaultSatelliteType});

    map = L.map('map', {
        zoomControl: false,
        attributionControl: false
    });

    var myStyle = {
        'color': '#000000',
        'weight': 5,
        'opacity': 0.65,
        fillOpacity: 0
    };

    getHexagon(geohexcode, user, function (resp){
        processHexagonResponse(resp);
    });

    polygon = getGeohexPolygon(geohexcode, myStyle);
    var centerHex = polygon.getBounds().getCenter();
    map.setView(centerHex, startZoomlevel, {
        animation: true
    });

    map.addControl(new L.Control.ZoomMin({
        position: 'topright', startLevel: startZoomlevel, startCenter: centerHex
    }));

    L.control.scale({imperial: false, position: 'topleft'}).addTo(map);

    var ggl2 = new L.Google('satellite');
    map.addLayer(ggl2);
    map.addLayer(polygon);
}(window, document, L));
<commit_msg>start with select hexagon within project area<commit_after>/*jslint browser: true*/
/*global L */
/*global GEOHEX */
var geohexcode = null;
var startZoomlevel = 12;
var localStoragePrefix = 'EW_'; // earthWatchers
var user = localStorage.getItem(localStoragePrefix + 'user') || 'anonymous' ;
var satelliteImages = null;
var map = null;
var polygon = null;
var default_geohex_level = 7;
var defaultSatelliteType = 'Landsat';
var uservote = null;
var defaultProject = 'Borneo';

function getSatelliteImageByDate(date) {
    for (var i = 0; i < satelliteImages.features.length; i++) {
        if (satelliteImages.features[i].properties.Published === date) {
            return satelliteImages.features[i];
        }
    }
    return null;
}

function findEarthWatchersLayer() {
    var result = null;
    map.eachLayer(function (layer) {
        if (layer.options.type !== null) {
            if (layer.options.type === 'earthWatchers') {
                result = layer;
            }
        }
    });
    return result;
}

function saveCleanedObservation(observationString) {
    // logging user actions
    //
    // create new line in localStorage like
    // { ...,
    //      'EW_1427635304381': '{"user":"barack","lat":1.0347919593425408,"lon":111.97073616826705,"level":7,"observation":"no","geohex":"PO5020737"}',
    //      ...}
    localStorage.setItem(
            localStoragePrefix + (new Date()).getTime(), observationString);
}

function timeSliderChanged(ctrl) {
    var day = satelliteImages.features[ctrl.value].properties.Published;
    var label = document.getElementById('rangeValLabel');
    label.innerHTML = day;
    // update label positioning
    label.className = 'value' + ctrl.value;

    var earthWatchersLayer = findEarthWatchersLayer();

    var s = getSatelliteImageByDate(day);
    var url = s.properties.UrlTileCache + '/{z}/{x}/{y}.png';
    var maxlevel = s.properties.MaxLevel;
    var newLayer = L.tileLayer(url, {
        tms: true,
        maxZoom: maxlevel,
        type: 'earthWatchers'
    });
    map.addLayer(newLayer);

    if (earthWatchersLayer !== null) {
        map.removeLayer(earthWatchersLayer);
    }
}

function getGeohexPolygon(geohexcode, style) {
    var zone = GEOHEX.getZoneByCode(geohexcode);
    return L.polygon(zone.getHexCoords(), style);
}

function next() {
    var url = location.href.replace(location.hash,'');
    location.href=url;
}

function styleButton(button,checked){
    if(checked){
        button.style.border='5px solid black'
    }
    else{
        button.style.border='0px solid black'
    }
}

function toggleSatelliteType(sel) {
    var labels = {
            Landsat: 'Landsat 8',
            Sentinel: 'Sentinel 1'
        },
        newtype = sel.value === 'Landsat' ? 'Sentinel' : 'Landsat';

    // change map layer
    satelliteTypeSelectionChanged({value: newtype});

    // update satellite type value
    sel.parentNode.classList.remove(sel.value.toLowerCase());
    sel.setAttribute('value', newtype);
    sel.parentNode.classList.add(sel.value.toLowerCase());

    // update satellite type label
    document.getElementById('satTypeLabel').innerText = labels[newtype];
}

function satelliteTypeSelectionChanged(sel) {
    var currentImageType = sel.value;
    var polygon = getGeohexPolygon(geohexcode);
    var bbox = polygon.getBounds().toBBoxString();
    getSatelliteImageData(bbox, currentImageType, function(resp){
        satelliteImages = resp;
        var sel = document.getElementById('timeSlider');
        satelliteImages.features.sort(compare);
        sel.onchange();
    });
}

function sendObservation(observation){
    if(observation!=uservote){
        colorizePolygon(observation);
        postObservation(observation,user,geohexcode,function(resp){
            getHexagon(geohexcode, user, function(resp){
                processHexagonResponse(resp);
            });

        });
    };
}

function updateUsername(newName) {
    // update global var and localstorage value
    user = newName;
    localStorage.setItem(localStoragePrefix + 'user', newName);
}

function changeName(event) {
    var form = event.target,
        newName = form.children[0].value;

    // stop from saving empty name
    if (!newName) return false;

    updateUsername(newName);

    // clean and hide form
    form.parentElement.classList.add('hide');
    form.children[0].value = '';

    updateUserinfo();
    uservote=null;
    getHexagon(geohexcode, user, function(resp){
        processHexagonResponse(resp);
    });

    return false;
}

function showUserForm() {
    var userform = document.getElementById('userform');

    userform.classList.remove('hide');
}

function initUserpanel() {
    updateUserinfo();
    var userform = document.getElementById('userform');
    userform.children[0].onsubmit = changeName;
}

function updateUserinfo() {
    var userinfo = document.getElementById('userinfo');

    userinfo.innerHTML =
        ' Hi, ' + user + '! ' +
        'Change?';
}

function processHexagonResponse(resp){
    document.getElementById('btnYes').innerText = 'Yes (' + resp.yes + ')';
    document.getElementById('btnNo').innerText = 'No (' + resp.no + ')';
    document.getElementById('btnMaybe').innerText = 'Maybe (' + resp.maybe + ')';

    uservote = resp.uservote;
    styleButton (document.getElementById('btnYes'),uservote === 'yes');
    styleButton (document.getElementById('btnNo'),uservote === 'no');
    styleButton (document.getElementById('btnMaybe'),uservote === 'maybe');
}

(function (window, document, L) {
    'use strict';
    L.Icon.Default.imagePath = 'images/';

    Path.map("#/hexagon/:hex").to(function(){
        // sample: #/hexagon/PO2670248
        geohexcode = this.params['hex'];
    });
    Path.listen();

    initUserpanel();

    loadJSON('data/projects.geojson', function(response) {
        var projects = JSON.parse(response);

        for(var p=0;p<projects.features.length;p++){
            var project = projects.features[p];
            if(project.properties.Name === defaultProject){
                var env = turf.envelope(project);
                var bbox = env.geometry.coordinates[0];
                // get random point in env
                // todo: add check if hexagon is within the project (not only within envelope)
                var lon_rnd = random(bbox[0][0], bbox[1][0]);
                var lat_rnd = random(bbox[0][1], bbox[2][1]);
                if(geohexcode===null){
                    geohexcode = GEOHEX.getZoneByLocation(lat_rnd, lon_rnd, default_geohex_level).code;
                    location.hash = '#/hexagon/' + geohexcode;
                }
            }
        }

        // fire onchange event of first combobox
        satelliteTypeSelectionChanged({value: defaultSatelliteType});

        map = L.map('map', {
            zoomControl: false,
            attributionControl: false
        });

        var myStyle = {
            'color': '#000000',
            'weight': 5,
            'opacity': 0.65,
            fillOpacity: 0
        };

        getHexagon(geohexcode, user, function (resp){
            processHexagonResponse(resp);
        });

        polygon = getGeohexPolygon(geohexcode, myStyle);
        var centerHex = polygon.getBounds().getCenter();
        map.setView(centerHex, startZoomlevel, {
            animation: true
        });

        map.addControl(new L.Control.ZoomMin({
            position: 'topright', startLevel: startZoomlevel, startCenter: centerHex
        }));

        L.control.scale({imperial: false, position: 'topleft'}).addTo(map);

        var ggl2 = new L.Google('satellite');
        map.addLayer(ggl2);
        map.addLayer(polygon);

        L.geoJson(projects,{fill:false}).addTo(map);
        // todo: calculate hexagon based on project areas
    });

}(window, document, L));
<|endoftext|>


<commit_before>var c;
var ctx;
var enemynum;
var enemycounter;
var score;

var FPS;
var player;
var enemies = [];

function Initialise()
{
  score = 0;
  if(c == null)
  {
    c=document.getElementById("canvas");
    ctx=c.getContext("2d");
    enemynum = 0;
    enemycounter=100;
    FPS = 60;
    canvas.addEventListener('mousemove', MouseMove, false);
    setInterval(function() {
    update();
    draw();
    }, 1000/FPS);
  }
    player = {
    color: "#00A",
    x: 220,
    y: 270,
    width: 32,
    height: 32,
    draw: function() {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
};
}

function draw(){
ctx.clearRect(0, 0, 400, 400);
player.draw();
for(var i = 0; i<enemynum; i++)
  {
    enemies[i].y+=2;
    enemies[i].draw();
    collisions(i);  // Check collisions with current enemy.
  }
}

function collisions(i){

  var e = enemies[i];
  var p = player

  // Top Left

  if(p.x<e.hole && (p.y<(e.y+e.height)&&p.y>e.y))
  {
     document.getElementById("testout").innerHTML=String("TL Collide");
     Finalise();
  }

  // Top Right

  if((p.x+p.width)>(e.hole+p.width+e.extragap) && ((p.y)<(e.y+e.height)&&p.y>e.y))
  {
     document.getElementById("testout").innerHTML=String("TR Collide");
     Finalise();
  }

  // Bottom Left

  if(p.x<e.hole && ((p.y+p.height)<(e.y+e.height)&&(p.y+p.height)>e.y))
  {
     document.getElementById("testout").innerHTML=String("BL Collide");
     Finalise();
  }

  // Bottom Right

  if((p.x+p.width)>(e.hole+p.width+e.extragap) && ((p.y+p.height)<(e.y+e.height)&&(p.y+p.height)>e.y))
  {
     document.getElementById("testout").innerHTML=String("BR Collide");
     Finalise();
  }
}

function update(){

  score++;
  // Add only 4 enemies to the screen
  if(enemynum<4)
  {
    enemycounter++;
    if(enemycounter > 50)
    // Spacing of enemies
    {
      enemycounter = 0;
      enemynum++;
    }
  }

  for(var i = 0; i<enemynum; i++)
  {
    enemies.push({
    color: "#0F0",
    x: 0,
    y: -20,
    width: 400,
    height: 20,
    extragap: 20,
    hole: Math.floor(Math.random()*380),
    draw: function() {
      if(this.y>400)
      {
        this.hole = Math.floor(Math.random()*this.width-20);
        this.y=-this.height;
      }
      ctx.fillStyle = this.color;
      ctx.fillRect(this.x, this.y, this.hole, this.height);
      ctx.fillRect(this.hole+player.width+this.extragap, this.y, this.width, this.height);
      }
    });
  }
}

function MouseMove(e){

player.x = e.clientX-canvas.offsetLeft-player.height/2;
document.getElementById("testout").innerHTML=String(score);
player.y = e.clientY-canvas.offsetTop-player.height/2+$(document).scrollTop();

}

function Finalise(){

  alert("You lost, but scored " + score);
  Initialise();
}
<commit_msg>Update games.js<commit_after>var c;
var ctx;
var enemynum;
var enemycounter;
var score;

var FPS;
var player;
var enemies = [];

function Initialise()
{
  score = 0;
  if(c == null)
  {
    c=document.getElementById("canvas");
    ctx=c.getContext("2d");
    enemynum = 0;
    enemycounter=100;
    FPS = 60;
    canvas.addEventListener('mousemove', MouseMove, false);
    setInterval(function() {
    update();
    draw();
    }, 1000/FPS);
  }
    player = {
    color: "#00A",
    x: 220,
    y: 270,
    width: 32,
    height: 32,
    draw: function() {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
};
}

function draw(){
ctx.clearRect(0, 0, 400, 400);
player.draw();
for(var i = 0; i<enemynum; i++)
  {
    enemies[i].y+=2;
    enemies[i].draw();
    collisions(i);  // Check collisions with current enemy.
  }
}

function collisions(i){

  var e = enemies[i];
  var p = player

  // Top Left

  if(p.x<e.hole && (p.y<(e.y+e.height)&&p.y>e.y))
  {
     //document.getElementById("testout").innerHTML=String("TL Collide");
     Finalise();
  }

  // Top Right

  if((p.x+p.width)>(e.hole+p.width+e.extragap) && ((p.y)<(e.y+e.height)&&p.y>e.y))
  {
     //document.getElementById("testout").innerHTML=String("TR Collide");
     Finalise();
  }

  // Bottom Left

  if(p.x<e.hole && ((p.y+p.height)<(e.y+e.height)&&(p.y+p.height)>e.y))
  {
     //document.getElementById("testout").innerHTML=String("BL Collide");
     Finalise();
  }

  // Bottom Right

  if((p.x+p.width)>(e.hole+p.width+e.extragap) && ((p.y+p.height)<(e.y+e.height)&&(p.y+p.height)>e.y))
  {
     //document.getElementById("testout").innerHTML=String("BR Collide");
     Finalise();
  }
}

function update(){

  score++;
  // Add only 4 enemies to the screen
  if(enemynum<4)
  {
    enemycounter++;
    if(enemycounter > 50)
    // Spacing of enemies
    {
      enemycounter = 0;
      enemynum++;
    }
  }

  for(var i = 0; i<enemynum; i++)
  {
    enemies.push({
    color: "#0F0",
    x: 0,
    y: -20,
    width: 400,
    height: 20,
    extragap: 20,
    hole: Math.floor(Math.random()*380),
    draw: function() {
      if(this.y>400)
      {
        this.hole = Math.floor(Math.random()*this.width-20);
        this.y=-this.height;
      }
      ctx.fillStyle = this.color;
      ctx.fillRect(this.x, this.y, this.hole, this.height);
      ctx.fillRect(this.hole+player.width+this.extragap, this.y, this.width, this.height);
      }
    });
  }
}

function MouseMove(e){

player.x = e.clientX-canvas.offsetLeft-player.height/2;
document.getElementById("testout").innerHTML=String(score);
player.y = e.clientY-canvas.offsetTop-player.height/2+$(document).scrollTop();

}

function Finalise(){

  alert("You lost, but scored " + score);
  Initialise();
}
<|endoftext|>


<commit_before>import {reject} from 'redux-simple-promise';
import {createAction} from 'redux-actions';

export const LOGIN = 'LOGIN';

const initialState = {};

export default function login (state = initialState, action) {
  switch (action.type) {
  case LOGIN: {
    console.log(action.payload);

    return state;
  }
  case reject(LOGIN): {
    console.log('rejected');

    return state;
  }
  default:
    return state;
  }
}

export const localLogin = createAction(LOGIN, ({email, password}) => ({
  client: 'auth',
  request: {
    url: '/local',
    method: 'POST',
    data: {
      email,
      password
    }
  }
}));
<commit_msg>refactor(client): removed unnecessary method name<commit_after>import {reject} from 'redux-simple-promise';
import {createAction} from 'redux-actions';

export const LOGIN = 'LOGIN';

const initialState = {};

export default function (state = initialState, action) {
  switch (action.type) {
  case LOGIN: {
    console.log(action.payload);

    return state;
  }
  case reject(LOGIN): {
    console.log('rejected');

    return state;
  }
  default:
    return state;
  }
}

export const localLogin = createAction(LOGIN, ({email, password}) => ({
  client: 'auth',
  request: {
    url: '/local',
    method: 'POST',
    data: {
      email,
      password
    }
  }
}));
<|endoftext|>


<commit_before><commit_msg>Remove unneeded code that hid the geolocation prompt because firefox already automatically hides it<commit_after><|endoftext|>


<commit_before>(function(angular, smi2) {
	'use strict';

	angular.module(smi2.app.name).service('API', API);
	API.$inject = ['$http', '$q', 'localStorageService'];

	/**
	 * @ngdoc service
	 * @name smi2.service:API
	 * @description Менеджер API. Нужен для обмена данными с backend.
	 */
	function API($http, $q, localStorageService) {

		var CURRENT_BASE_KEY = 'currentBaseConfig';
		var database = null;
		var connection = {};

		// Первичная загрузка данных из LS
		var data = localStorageService.get(CURRENT_BASE_KEY);
		if (data && data.host) {
			connection = data;
		}

		/**
		 * @ngdoc method
		 * @methodOf smi2.service:API
		 * @name setConnection
		 * @description Сохранение данных подключения в БД
		 * @param {mixed} db Данные подключения
		 */
		this.setConnection = function(db) {
			localStorageService.set(CURRENT_BASE_KEY, db);
			connection = db;
		};

		/**
		 * @ngdoc method
		 * @methodOf smi2.service:API
		 * @name clear
		 * @description Сброс авторизации
		 */
		this.clear = function() {
			database = null;
			connection = {};
			localStorageService.set(CURRENT_BASE_KEY, {});
		};

		/**
		 * @ngdoc method
		 * @methodOf smi2.service:API
		 * @name query
		 * @description Выполнение запроса к БД
		 * @param {string} sql Текст запроса
		 * @return {promise} Promise
		 */
		this.query = function(sql, format, withDatabase,extend_settings) {
			var defer = $q.defer();

			format = (format || ' format JSON');
			if (format=='null')  format='';

			var url = 'http://' + connection.host +
				'/?query=' + encodeURIComponent(sql + ' ' + format ) +
				'&user=' + connection.login +
				'&password=' + connection.password +
				'&add_http_cors_header=1';
			if (withDatabase) {
				url += '&database=' + database;
			}
			if (extend_settings)
			{
				url += '&'+extend_settings;

			}

			var req = {
				method: 'GET',
				url: url,
				headers: {
					'Content-Type': undefined
				}
			};

			if (format) {
				$http(req).then(function (response) {
					defer.resolve(response.data);
				}, function (response) {
					console.log("RPTT");
					console.log(response.data);
					defer.reject(response.data);
				});

			}
			else {
				$http.post(url).then(function (response) {
					defer.resolve(response.data);
				}, function (response) {
					defer.reject(response);
				});
			}
			return defer.promise;
		};

		/**
		 * @ngdoc method
		 * @methodOf smi2.service:API
		 * @name getConnectionInfo
		 * @description Получение данных подключения
		 * @return {mixed} Объект с данными подключения
		 */
		this.getConnectionInfo = function() {
			return connection;
		};

		/**
		 * @ngdoc method
		 * @methodOf smi2.service:API
		 * @name setDatabase
		 * @description Установка дефолтной БД
		 * @param {mixed} db Данные БД
		 */
		this.setDatabase = function(db) {
			database = db;
		};

		/**
		 * @ngdoc method
		 * @methodOf smi2.service:API
		 * @name dataToHtml
		 * @description Преобразование JSON данных запроса в таблицу
		 * @param {mixed} data Объект, который содержит ответ БД
		 * @return {string} Строка HTML
		 */
		this.dataToHtml = function(data) {
			console.log(data);
			var html = '

';
			var keys = [];
			data.meta.forEach(function(cell) {
				html += '' + cell.name + '
' + cell.type + '
	';
				keys.push(cell.name);
			});
			data.data.forEach(function(row) {
				html += '
';
				keys.forEach(function(key) {
					html += '' + row[key] + '	';
				});
				html += '
';
			});
			html += '
';
			return html;
		};
	}
})(angular, smi2);
<commit_msg>error in limits<commit_after>(function(angular, smi2) {
	'use strict';

	angular.module(smi2.app.name).service('API', API);
	API.$inject = ['$http', '$q', 'localStorageService'];

	/**
	 * @ngdoc service
	 * @name smi2.service:API
	 * @description Менеджер API. Нужен для обмена данными с backend.
	 */
	function API($http, $q, localStorageService) {

		var CURRENT_BASE_KEY = 'currentBaseConfig';
		var database = null;
		var connection = {};

		// Первичная загрузка данных из LS
		var data = localStorageService.get(CURRENT_BASE_KEY);
		if (data && data.host) {
			connection = data;
		}

		/**
		 * @ngdoc method
		 * @methodOf smi2.service:API
		 * @name setConnection
		 * @description Сохранение данных подключения в БД
		 * @param {mixed} db Данные подключения
		 */
		this.setConnection = function(db) {
			localStorageService.set(CURRENT_BASE_KEY, db);
			connection = db;
		};

		/**
		 * @ngdoc method
		 * @methodOf smi2.service:API
		 * @name clear
		 * @description Сброс авторизации
		 */
		this.clear = function() {
			database = null;
			connection = {};
			localStorageService.set(CURRENT_BASE_KEY, {});
		};

		/**
		 * @ngdoc method
		 * @methodOf smi2.service:API
		 * @name query
		 * @description Выполнение запроса к БД
		 * @param {string} sql Текст запроса
		 * @return {promise} Promise
		 */
		this.query = function(sql, format, withDatabase,extend_settings) {
			var defer = $q.defer();

			format = (format || ' format JSON');
			if (format=='null')  format='';

			var url = 'http://' + connection.host +
				'/?query=' + encodeURIComponent(sql + ' ' + format ) +
				'&user=' + connection.login +
				'&password=' + connection.password +
				'&add_http_cors_header=1';
			if (withDatabase) {
				url += '&database=' + database;
			}
			if (extend_settings)
			{
				url += '&'+extend_settings;

			}
			function appendTransform(defaults, transform) {

				// We can't guarantee that the default transformation is an array
				defaults = angular.isArray(defaults) ? defaults : [defaults];

				// Append the new transformation to the defaults
				return defaults.concat(transform);
			}

			var req = {
				method: 'GET',
				url: url,
				headers: {
					'Content-Type': undefined
				},
				transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
					return (value);
				})
			};

			if (format) {
				$http(req).then(function (response) {
					defer.resolve(response.data);
				}, function (response) {
					console.log("RPTT");
					console.log(response.data);
					defer.reject(response.data);
				});

			}
			else {
				$http.post(url).then(function (response) {
					defer.resolve(response.data);
				}, function (response) {
					defer.reject(response);
				});
			}
			return defer.promise;
		};

		/**
		 * @ngdoc method
		 * @methodOf smi2.service:API
		 * @name getConnectionInfo
		 * @description Получение данных подключения
		 * @return {mixed} Объект с данными подключения
		 */
		this.getConnectionInfo = function() {
			return connection;
		};

		/**
		 * @ngdoc method
		 * @methodOf smi2.service:API
		 * @name setDatabase
		 * @description Установка дефолтной БД
		 * @param {mixed} db Данные БД
		 */
		this.setDatabase = function(db) {
			database = db;
		};

		/**
		 * @ngdoc method
		 * @methodOf smi2.service:API
		 * @name dataToHtml
		 * @description Преобразование JSON данных запроса в таблицу
		 * @param {mixed} data Объект, который содержит ответ БД
		 * @return {string} Строка HTML
		 */
		this.dataToHtml = function(data) {
			console.log(data);
			var html = '

';
			var keys = [];
			data.meta.forEach(function(cell) {
				html += '' + cell.name + '
' + cell.type + '
	';
				keys.push(cell.name);
			});
			data.data.forEach(function(row) {
				html += '
';
				keys.forEach(function(key) {
					html += '' + row[key] + '	';
				});
				html += '
';
			});
			html += '
';
			return html;
		};
	}
})(angular, smi2);
<|endoftext|>


<commit_before>// yeah, nasty, but it allows me to switch from a RTF to plain text if we're running a iOS
var noop = function () {},
    rootClassName = document.body.className;

if (jsbin.mobile || jsbin.tablet || rootClassName.indexOf('ie6') !== -1 || rootClassName.indexOf('ie7') !== -1) {
  $('body').addClass('mobile');
  jsbin.lameEditor = true;
  Editor = function (el, options) {
    this.textarea = el;
    this.win = { document : this.textarea };
    this.ready = true;
    this.wrapping = document.createElement('div');

    var textareaParent = this.textarea.parentNode;
    this.wrapping.appendChild(this.textarea);
    textareaParent.appendChild(this.wrapping);

    this.textarea.style.opacity = 1;
    // this.textarea.style.width = '100%';

    $(this.textarea).blur(throttle(function () {
      $(document).trigger('codeChange', { panelId: el.id });
    }, 200));

    $(this.textarea).keyup(throttle(function () {
      $(document).trigger('codeChange', { panelId: el.id });
    }, 200));

    options.initCallback && $(options.initCallback);
  };

  Editor.prototype = {
    getWrapperElement: function () {
      return this.wrapping;
    },
    getScrollerElement: function () {
      return this.textarea;
    },
    setOption: function (type, handler) {
      if (type == 'onChange') {
        $(this.textarea).change(handler);
      }
    },
    setCode: function (code) {
      this.textarea.value = code;
    },
    getCode: function () {
      return this.textarea.value;
    },
    getValue: function () {
      return this.textarea.value;
    },
    setValue: function (code)  {
      this.textarea.value = code;
    },
    focus: noop,
    getCursor: function () {
      return { line: 0, ch: 0 };
    },
    setCursor: noop,
    currentLine: function () {
      return 0;
    },
    cursorPosition: function () {
      return { character: 0 };
    },
    nthLine: noop,
    refresh: noop,
    selectLines: noop,
    on: noop
  };

  var _oldCM = CodeMirror;

  CodeMirror = noop;

  for (var key in _oldCM) {
    CodeMirror[key] = noop;
  }

  CodeMirror.fromTextArea = function (el, options) {
      return new Editor(el, options);
  };

  CodeMirror.keyMap = { basic: {} };

}<commit_msg>Changed event on which the output is updated.<commit_after>// yeah, nasty, but it allows me to switch from a RTF to plain text if we're running a iOS
var noop = function () {},
    rootClassName = document.body.className;

if (jsbin.mobile || jsbin.tablet || rootClassName.indexOf('ie6') !== -1 || rootClassName.indexOf('ie7') !== -1) {
  $('body').addClass('mobile');
  jsbin.lameEditor = true;
  Editor = function (el, options) {
    this.textarea = el;
    this.win = { document : this.textarea };
    this.ready = true;
    this.wrapping = document.createElement('div');

    var textareaParent = this.textarea.parentNode;
    this.wrapping.appendChild(this.textarea);
    textareaParent.appendChild(this.wrapping);

    this.textarea.style.opacity = 1;
    // this.textarea.style.width = '100%';

    $(this.textarea)[jsbin.mobile || jsbin.tablet ? 'blur' : 'keyup'](throttle(function () {
      $(document).trigger('codeChange', { panelId: el.id });
    }, 200));

    options.initCallback && $(options.initCallback);
  };

  Editor.prototype = {
    getWrapperElement: function () {
      return this.wrapping;
    },
    getScrollerElement: function () {
      return this.textarea;
    },
    setOption: function (type, handler) {
      if (type == 'onChange') {
        $(this.textarea).change(handler);
      }
    },
    setCode: function (code) {
      this.textarea.value = code;
    },
    getCode: function () {
      return this.textarea.value;
    },
    getValue: function () {
      return this.textarea.value;
    },
    setValue: function (code)  {
      this.textarea.value = code;
    },
    focus: noop,
    getCursor: function () {
      return { line: 0, ch: 0 };
    },
    setCursor: noop,
    currentLine: function () {
      return 0;
    },
    cursorPosition: function () {
      return { character: 0 };
    },
    nthLine: noop,
    refresh: noop,
    selectLines: noop,
    on: noop
  };

  var _oldCM = CodeMirror;

  CodeMirror = noop;

  for (var key in _oldCM) {
    CodeMirror[key] = noop;
  }

  CodeMirror.fromTextArea = function (el, options) {
      return new Editor(el, options);
  };

  CodeMirror.keyMap = { basic: {} };

}<|endoftext|>


<commit_before>var c;
var ctx;
var enemynum;
var enemycounter;

var FPS;
var player;
var enemies = [];

function Initialise()
{
  if(c == null)
  {
    c=document.getElementById("canvas");
    ctx=c.getContext("2d");
    enemynum = 0;
    enemycounter=100;
    FPS = 60;
    canvas.addEventListener('mousemove', MouseMove, false);
    setInterval(function() {
    update();
    draw();
    }, 1000/FPS);
  }
    player = {
    color: "#00A",
    x: 220,
    y: 270,
    width: 32,
    height: 32,
    draw: function() {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
};
}

function draw(){
ctx.clearRect(0, 0, 400, 400);
player.draw();
for(var i = 0; i<enemynum; i++)
  {
    enemies[i].y++;
    enemies[i].draw();
  }
}

function update(){
  // Add only 4 enemies to the screen
  if(enemynum<4)
  {
    enemycounter++;
    if(enemycounter > 100)
    // Spacing of enemies
    {
      enemycounter = 0;
      enemynum++;
    }
  }

  for(var i = 0; i<enemynum; i++)
  {
    enemies.push({
    color: "#0F0",
    x: 0,
    y: -20,
    width: 400,
    height: 20,
    hole: Math.floor(Math.random()*380),
    draw: function() {
      if(this.y>400)
      {
        this.hole = Math.floor(Math.random()*this.width-20);
        this.y=-this.height;
      }
      ctx.fillStyle = this.color;
      ctx.fillRect(this.x, this.y, this.hole, this.height);
      ctx.fillRect(this.hole+player.width+20, this.y, this.width, this.height);
      }
    });
  }
}

function MouseMove(e){

player.x = e.clientX-canvas.offsetLeft-player.height/2;
//document.getElementById("testout").innerHTML=String(enemies[1].hole)+",";
player.y = e.clientY-canvas.offsetTop-player.height/2+$(document).scrollTop();
//document.getElementById("testout").innerHTML+=String(enemies[1].hole);

}
<commit_msg>Rudimentory Collisions<commit_after>var c;
var ctx;
var enemynum;
var enemycounter;

var FPS;
var player;
var enemies = [];

function Initialise()
{
  if(c == null)
  {
    c=document.getElementById("canvas");
    ctx=c.getContext("2d");
    enemynum = 0;
    enemycounter=100;
    FPS = 60;
    canvas.addEventListener('mousemove', MouseMove, false);
    setInterval(function() {
    update();
    draw();
    }, 1000/FPS);
  }
    player = {
    color: "#00A",
    x: 220,
    y: 270,
    width: 32,
    height: 32,
    draw: function() {
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }
};
}

function draw(){
ctx.clearRect(0, 0, 400, 400);
player.draw();
for(var i = 0; i<enemynum; i++)
  {
    enemies[i].y+=2;
    enemies[i].draw();
    collisions(i);  // Check collisions with current enemy.
  }
}

function collisions(i){

  var e = enemies[i];
  var p = player

  // Top Left

  if(p.x<e.hole && (p.y<(e.y+e.height)&&p.y>e.y))
  {
     document.getElementById("testout").innerHTML=String("TL Collide");
  }

  // Top Right

  if((p.x+p.width)>(e.hole+p.width+e.extragap) && ((p.y)<(e.y+e.height)&&p.y>e.y))
  {
     document.getElementById("testout").innerHTML=String("TR Collide");
  }

  // Bottom Left

  if(p.x<e.hole && ((p.y+p.height)<(e.y+e.height)&&(p.y+p.height)>e.y))
  {
     document.getElementById("testout").innerHTML=String("BL Collide");
  }

  // Bottom Right

  if((p.x+p.width)>(e.hole+p.width+e.extragap) && ((p.y+p.height)<(e.y+e.height)&&(p.y+p.height)>e.y))
  {
     document.getElementById("testout").innerHTML=String("BR Collide");
  }
}

function update(){
  // Add only 4 enemies to the screen
  if(enemynum<4)
  {
    enemycounter++;
    if(enemycounter > 50)
    // Spacing of enemies
    {
      enemycounter = 0;
      enemynum++;
    }
  }

  for(var i = 0; i<enemynum; i++)
  {
    enemies.push({
    color: "#0F0",
    x: 0,
    y: -20,
    width: 400,
    height: 20,
    extragap: 20,
    hole: Math.floor(Math.random()*380),
    draw: function() {
      if(this.y>400)
      {
        this.hole = Math.floor(Math.random()*this.width-20);
        this.y=-this.height;
      }
      ctx.fillStyle = this.color;
      ctx.fillRect(this.x, this.y, this.hole, this.height);
      ctx.fillRect(this.hole+player.width+this.extragap, this.y, this.width, this.height);
      }
    });
  }
}

function MouseMove(e){

player.x = e.clientX-canvas.offsetLeft-player.height/2;
document.getElementById("testout").innerHTML=String("");
player.y = e.clientY-canvas.offsetTop-player.height/2+$(document).scrollTop();

}
<|endoftext|>