<commit_before>

function saveMultiTag(){
	//console.log("saveMultiTag() try"); console.log(myMultiTags);
	hideSearchResults();
	if(userId != null && userId != ""){
		if(!notEmpty(myMultiTags)) myMultiTags = {};
		$.ajax({
	        type: "POST",
	        url: baseUrl+"/"+moduleId+"/person/updatemultitag",
	        data: {multitags : myMultiTags},
	       	dataType: "json",
	    	success: function(data){
	    		console.log("saveMultiTag() success");
		    },
			error: function(error){
				console.log("Une erreur est survenue pendant l'enregistrement des tags");
			}
		});
	}else{

	}
	showCountTag();
	rebuildSearchTagInput();
    saveCookieMultitags();
}

function saveCookieMultitags(){ //console.log("saveCookieMultitags", myMultiTags);
	$.cookie('multitags',   	JSON.stringify(myMultiTags),  	{ expires: 365, path: "/" });

}

function loadMultiTags(){
	$.each(myMultiTags, function(key, value){ //console.log("each myMultiTags");
		showTagInMultitag(key);
	});
	showCountTag();
	saveCookieMultitags();
}

function showCountTag(){
	var count = 0;
	//console.log("myMultiTags"); console.log(myMultiTags);
	$.each(myMultiTags, function(key, value){ //console.log("each myMultiTags");
		if(value.active==true) count++;
	}); //onsole.log("TAG COUNT : ", count);
	$(".tags-count").html(count);
	showTagsScopesMin(".list_tags_scopes");
	showEmptyMsg();
}
function tagExists(tagValue){
	return typeof myMultiTags[tagValue] != "undefined";
}
function selectAllTags(select){
	if(typeof select == "undefined"){ select = true;
		$.each(myMultiTags, function(key, value){
			 if(value.active) select = false;
		});
	}
	$.each(myMultiTags, function(key, value){
		 toogleTagMultitag(key, select);
	});
	saveMultiTag();
}
function showTagInMultitag(tagValue){ //console.log("showTagInMultitag()", tagValue);
	var html = "";
	if(tagExists(tagValue)){
		var faActive = myMultiTags[tagValue].active == true ? "check-circle" : "circle-o";
		var classDisable = myMultiTags[tagValue].active == false ? "disabled" : "";
		html =
		'' +
				'' +
					'' +
				'' +
				'#'+tagValue+'' +
				'' +
					'' +
			'' +
		'';
		$("#multi-tag-list").append(html);
		$(".tooltips").tooltip();
		$(".item-tag-checker").off().click(function(){ toogleTagMultitag( $(this).data("tag-value")) });
		$(".item-tag-deleter").off().click(function(){ deleteTagInMultitag( $(this).data("tag-value")); });
		//showMsgInfoMultiTag("Le tag a bien été ajouté", "success");
	}else{
		html = "";
		//showMsgInfoMultiTag("showTagInMultitag error : ce tag n'existe pas - " + tagValue, "danger");
	}

}

function addTagToMultitag(tagValue){
	if(tagValue == "") return;
	if(tagValue.indexOf("#") == 0) tagValue = tagValue.substr(1, tagValue.length);
	if(!tagExists(tagValue)){
		//console.log("adding", tagValue);
		myMultiTags[tagValue] = { active: true };
		//console.log("adding : myMultiTags :", myMultiTags);
		showTagInMultitag(tagValue);
		saveMultiTag();
		$("#input-add-multi-tag").val("");
		return true;
	}else{
		showMsgInfoMultiTag("Ce tag est déjà dans votre liste", "info");
		return false;
	}
}

function deleteTagInMultitag(tagValue){ //console.log("deleteTagInMultitag(tagValue)", tagValue);
	if(tagExists(tagValue)){
		delete myMultiTags[tagValue];
		$("[data-tag-value='"+tagValue+"']").remove();
		saveMultiTag();
		//showMsgInfoMultiTag("Le tag a bien été supprimé", "success");
	}
	//console.dir(myMultiTags);
}

function toogleTagMultitag(tagValue, selected){ //console.log("toogleTagMultitag(tagValue)", tagValue);
	if(tagExists(tagValue)){
		myMultiTags[tagValue].active = !myMultiTags[tagValue].active;

		if(typeof selected != "undefined")
			myMultiTags[tagValue].active = selected;

		saveMultiTag();

		if(myMultiTags[tagValue].active){
			$("[data-tag-value='"+tagValue+"'] .item-tag-checker i.fa").removeClass("fa-circle-o");
			$("[data-tag-value='"+tagValue+"'] .item-tag-checker i.fa").addClass("fa-check-circle");
			$("[data-tag-value='"+tagValue+"'].item-tag-input").removeClass("disabled");
		}else{
			$("[data-tag-value='"+tagValue+"'] .item-tag-checker i.fa").addClass("fa-circle-o");
			$("[data-tag-value='"+tagValue+"'] .item-tag-checker i.fa").removeClass("fa-check-circle");
			$("[data-tag-value='"+tagValue+"'].item-tag-input").addClass("disabled");
		}

		//rebuildSearchTagInput();

	}else{
		//showMsgInfoMultiTag("Ce tag n'existe pas", "danger");
	}
}

function getMultiTagList(){ return myMultiTags; }

var timerMsgMultitag;
function showMsgInfoMultiTag(msg, type){
	if(type == "success") msg = " " + msg;
	if(type == "danger") msg = " " + msg;
	if(type == "info") msg = " " + msg;

	var id = "#lbl-info-select-multi-tag";
	$(id).html(msg);
	if(type == "success") $(id).addClass("label-success"); else $(id).removeClass("label-success");
	if(type == "danger") $(id).addClass("label-danger"); else $(id).removeClass("label-danger");
	if(type == "info") $(id).addClass("label-info"); else $(id).removeClass("label-info");

	$(id).off().hide();
	$(id).show(200);

	if(typeof timerMsgMultitag != "undefined") clearTimeout(timerMsgMultitag);
	timerMsgMultitag = setTimeout(function(){ $(id).off().hide(500)}, 3000);
}

function rebuildSearchTagInput()
{
	searchTags = "";
	$.each(myMultiTags, function(key, value){
		if(value.active)
			searchTags += (searchTags == "") ? key :   ","+key;
	});
	//console.log("searchTags",searchTags);
	if( $("#searchTags") )
		$("#searchTags").val(searchTags);

	//if( typeof searchCallback == "function" )
	//	searchCallback();
}

function showTagsMin(htmlId){
	var html =  ""; //'' +
			        //'' +
			//    '</button> ';

	$.each(myMultiTags, function(key, value){
		var disabled = value.active == false ? "disabled" : "";
		html += "" +
					"#" + key +
				" ";
	});
	html += "
";

	$(htmlId).html(html);

	$(".item-tag-checker").off().click(function(){ toogleTagMultitag( $(this).data("tag-value")) });

	$(".toggle-tag-dropdown").click(function(){ //console.log("toogle");
		if(!$("#dropdown-content-multi-tag").hasClass('open'))
		setTimeout(function(){ $("#dropdown-content-multi-tag").addClass('open'); }, 300);
		$("#dropdown-content-multi-tag").addClass('open');
		//else
		//$("#dropdown-content-multi-tag").removeClass('open');
	});
}
<commit_msg>suggestions tags<commit_after>

function saveMultiTag(){
	//console.log("saveMultiTag() try"); console.log(myMultiTags);
	hideSearchResults();
	if(userId != null && userId != ""){
		if(!notEmpty(myMultiTags)) myMultiTags = {};
		$.ajax({
	        type: "POST",
	        url: baseUrl+"/"+moduleId+"/person/updatemultitag",
	        data: {multitags : myMultiTags},
	       	dataType: "json",
	    	success: function(data){
	    		console.log("saveMultiTag() success");
		    },
			error: function(error){
				console.log("Une erreur est survenue pendant l'enregistrement des tags");
			}
		});
	}else{

	}
	showCountTag();
	rebuildSearchTagInput();
    saveCookieMultitags();
}

function saveCookieMultitags(){ //console.log("saveCookieMultitags", myMultiTags);
	$.cookie('multitags',   	JSON.stringify(myMultiTags),  	{ expires: 365, path: "/" });

}

function loadMultiTags(){
	$.each(myMultiTags, function(key, value){ console.log("each myMultiTags", myMultiTags);
		showTagInMultitag(key);
	});
	showCountTag();
	saveCookieMultitags();
}

function showCountTag(){
	var count = 0;
	//console.log("myMultiTags"); console.log(myMultiTags);
	$.each(myMultiTags, function(key, value){ //console.log("each myMultiTags");
		if(value.active==true) count++;
	}); //onsole.log("TAG COUNT : ", count);
	$(".tags-count").html(count);
	showTagsScopesMin(".list_tags_scopes");
	showEmptyMsg();
}
function tagExists(tagValue){
	return typeof myMultiTags[tagValue] != "undefined";
}
function selectAllTags(select){
	if(typeof select == "undefined"){ select = true;
		$.each(myMultiTags, function(key, value){
			 if(value.active) select = false;
		});
	}
	$.each(myMultiTags, function(key, value){
		 toogleTagMultitag(key, select);
	});
	saveMultiTag();
}
function showTagInMultitag(tagValue){ //console.log("showTagInMultitag()", tagValue);
	var html = "";
	if(tagExists(tagValue)){
		var faActive = myMultiTags[tagValue].active == true ? "check-circle" : "circle-o";
		var classDisable = myMultiTags[tagValue].active == false ? "disabled" : "";
		html =
		'' +
				'' +
					'' +
				'' +
				'#'+tagValue+'' +
				'' +
					'' +
			'' +
		'';
		$("#multi-tag-list").append(html);
		$(".tooltips").tooltip();
		$(".item-tag-checker").off().click(function(){ toogleTagMultitag( $(this).data("tag-value")) });
		$(".item-tag-deleter").off().click(function(){ deleteTagInMultitag( $(this).data("tag-value")); });
		//showMsgInfoMultiTag("Le tag a bien été ajouté", "success");
	}else{
		html = "";
		//showMsgInfoMultiTag("showTagInMultitag error : ce tag n'existe pas - " + tagValue, "danger");
	}

}

function addTagToMultitag(tagValue){
	if(tagValue == "") return;
	if(tagValue.indexOf("#") == 0) tagValue = tagValue.substr(1, tagValue.length);
	if(!tagExists(tagValue)){
		//console.log("adding", tagValue);
		myMultiTags[tagValue] = { active: true };
		//console.log("adding : myMultiTags :", myMultiTags);
		showTagInMultitag(tagValue);
		saveMultiTag();
		$("#input-add-multi-tag").val("");
		$("[data-tag-value='"+tagValue+"'].item-tag-suggest").hide();
		return true;
	}else{
		showMsgInfoMultiTag("Ce tag est déjà dans votre liste", "info");
		return false;
	}
}

function deleteTagInMultitag(tagValue){ //console.log("deleteTagInMultitag(tagValue)", tagValue);
	if(tagExists(tagValue)){
		delete myMultiTags[tagValue];
		$("[data-tag-value='"+tagValue+"'].item-tag-input ").remove();
		$("[data-tag-value='"+tagValue+"'].item-tag-suggest").show();
		saveMultiTag();
		//showMsgInfoMultiTag("Le tag a bien été supprimé", "success");
	}
	//console.dir(myMultiTags);
}

function toogleTagMultitag(tagValue, selected){ //console.log("toogleTagMultitag(tagValue)", tagValue);
	if(tagExists(tagValue)){
		myMultiTags[tagValue].active = !myMultiTags[tagValue].active;

		if(typeof selected != "undefined")
			myMultiTags[tagValue].active = selected;

		saveMultiTag();

		if(myMultiTags[tagValue].active){
			$("[data-tag-value='"+tagValue+"'].item-tag-checker i.fa").removeClass("fa-circle-o");
			$("[data-tag-value='"+tagValue+"'].item-tag-checker i.fa").addClass("fa-check-circle");
			$("[data-tag-value='"+tagValue+"'].item-tag-input").removeClass("disabled");
		}else{
			$("[data-tag-value='"+tagValue+"'].item-tag-checker i.fa").addClass("fa-circle-o");
			$("[data-tag-value='"+tagValue+"'].item-tag-checker i.fa").removeClass("fa-check-circle");
			$("[data-tag-value='"+tagValue+"'].item-tag-input").addClass("disabled");
		}

		//rebuildSearchTagInput();

	}else{
		//showMsgInfoMultiTag("Ce tag n'existe pas", "danger");
	}
}

function getMultiTagList(){ return myMultiTags; }

var timerMsgMultitag;
function showMsgInfoMultiTag(msg, type){
	if(type == "success") msg = " " + msg;
	if(type == "danger") msg = " " + msg;
	if(type == "info") msg = " " + msg;

	var id = "#lbl-info-select-multi-tag";
	$(id).html(msg);
	if(type == "success") $(id).addClass("label-success"); else $(id).removeClass("label-success");
	if(type == "danger") $(id).addClass("label-danger"); else $(id).removeClass("label-danger");
	if(type == "info") $(id).addClass("label-info"); else $(id).removeClass("label-info");

	$(id).off().hide();
	$(id).show(200);

	if(typeof timerMsgMultitag != "undefined") clearTimeout(timerMsgMultitag);
	timerMsgMultitag = setTimeout(function(){ $(id).off().hide(500)}, 3000);
}

function rebuildSearchTagInput()
{
	searchTags = "";
	$.each(myMultiTags, function(key, value){
		if(value.active)
			searchTags += (searchTags == "") ? key :   ","+key;
	});
	//console.log("searchTags",searchTags);
	if( $("#searchTags") )
		$("#searchTags").val(searchTags);

	//if( typeof searchCallback == "function" )
	//	searchCallback();
}

function showTagsMin(htmlId){
	var html =  ""; //'' +
			        //'' +
			//    '</button> ';

	$.each(myMultiTags, function(key, value){
		var disabled = value.active == false ? "disabled" : "";
		html += "" +
					"#" + key +
				" ";
	});
	html += "
";

	$(htmlId).html(html);

	$(".item-tag-checker").off().click(function(){ toogleTagMultitag( $(this).data("tag-value")) });

	$(".toggle-tag-dropdown").click(function(){ //console.log("toogle");
		if(!$("#dropdown-content-multi-tag").hasClass('open'))
		setTimeout(function(){ $("#dropdown-content-multi-tag").addClass('open'); }, 300);
		$("#dropdown-content-multi-tag").addClass('open');
		//else
		//$("#dropdown-content-multi-tag").removeClass('open');
	});
}

function loadTagSuggestion(tagsSuggest){
	$.each(tagsSuggest, function(key, value){ console.log("each tagsSuggest");
		showTagSuggestion(key, value);
	});
}
function showTagSuggestion(tagValue, tagSpec){ console.log("showTagSuggestion()", tagValue);
	var html = "";
	if(!tagExists(tagValue)){
		var faActive = tagSpec.active == true ? "check-circle" : "circle-o";
		var classDisable = tagSpec.active == false ? "disabled" : "";
		html =
		'' +
				'' +
					'' +
				'' +
				'#'+tagValue+'' +
		'';
		$("#multi-tag-suggestion").append(html);
		$(".tooltips").tooltip();
		$(".item-tag-adder").off().click(function(){ addTagToMultitag( $(this).data("tag-value")) });
		//showMsgInfoMultiTag("Le tag a bien été ajouté", "success");
	}else{
		html = "";
		//showMsgInfoMultiTag("showTagInMultitag error : ce tag n'existe pas - " + tagValue, "danger");
	}

}<|endoftext|>


<commit_before>const path = require('path');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');
const fse = require('fs-extra');

const expectedFiles = {
    travis: ['.travis.yml'],
    jenkins: ['Jenkinsfile', 'src/main/docker/jenkins.yml', 'src/main/resources/idea.gdsl'],
    gitlab: ['.gitlab-ci.yml'],
    circle: ['.circleci/config.yml'],
    azure: ['azure-pipelines.yml'],
    github: ['.github/workflows/github-ci.yml'],
    dockerRegistry: ['src/main/docker/docker-registry.yml'],
};

describe('JHipster CI-CD Sub Generator', () => {
    //--------------------------------------------------
    // Jenkins tests
    //--------------------------------------------------
    describe('Jenkins tests', () => {
        describe('Jenkins: maven AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'jenkins',
                        insideDocker: false,
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.jenkins);
            });
            it("doesn't contain Docker, Sonar, Heroku", () => {
                assert.noFileContent('Jenkinsfile', /docker/);
                assert.noFileContent('Jenkinsfile', /sonar/);
                assert.noFileContent('Jenkinsfile', /heroku/);
            });
        });

        describe('Jenkins: Gradle AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/gradle-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'jenkins',
                        insideDocker: false,
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.jenkins);
            });
            it("doesn't contain Docker, Sonar, Heroku", () => {
                assert.noFileContent('Jenkinsfile', /docker/);
                assert.noFileContent('Jenkinsfile', /sonar/);
                assert.noFileContent('Jenkinsfile', /heroku/);
            });
        });
    });

    //--------------------------------------------------
    // GitLab CI tests
    //--------------------------------------------------
    describe('GitLab CI tests', () => {
        describe('GitLab: maven AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'gitlab',
                        insideDocker: false,
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.gitlab);
            });
            it("doesn't contain image: jhipster, Sonar, Heroku", () => {
                assert.noFileContent('.gitlab-ci.yml', /image: jhipster/);
                assert.noFileContent('.gitlab-ci.yml', /sonar/);
                assert.noFileContent('.gitlab-ci.yml', /heroku/);
            });
        });

        describe('GitLab: Gradle AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/gradle-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'gitlab',
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.gitlab);
            });
            it("doesn't contain jhipster/jhipster, Sonar, Heroku", () => {
                assert.noFileContent('.gitlab-ci.yml', /image: jhipster/);
                assert.noFileContent('.gitlab-ci.yml', /sonar/);
                assert.noFileContent('.gitlab-ci.yml', /heroku/);
            });
        });

        describe('GitLab: npm skip server', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/npm-skip-server'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'gitlab',
                        insideDocker: true,
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.gitlab);
            });
            it('contains image: jhipster', () => {
                assert.fileContent('.gitlab-ci.yml', /image: jhipster/);
            });
        });
    });

    //--------------------------------------------------
    // Travis CI tests
    //--------------------------------------------------
    describe('Travis CI tests', () => {
        describe('Travis CI: maven AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'travis',
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.travis);
            });
            it("doesn't contain Sonar, Heroku", () => {
                assert.noFileContent('.travis.yml', /sonar/);
                assert.noFileContent('.travis.yml', /heroku/);
            });
        });

        describe('Travis CI: Gradle AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/gradle-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'travis',
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.travis);
            });
            it("doesn't contain Sonar, Heroku", () => {
                assert.noFileContent('.travis.yml', /sonar/);
                assert.noFileContent('.travis.yml', /heroku/);
            });
        });
    });

    //--------------------------------------------------
    // Azure Pipelines tests
    //--------------------------------------------------
    describe('Azure Pipelines tests', () => {
        describe('Azure Pipelines: maven AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'azure',
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.azure);
            });
        });

        describe('Azure Pipelines: Gradle AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/gradle-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'azure',
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.azure);
            });
        });
    });

    //--------------------------------------------------
    // GitHub Actions tests
    //--------------------------------------------------
    describe('GitHub Actions tests', () => {
        describe('GitHub Actions: maven AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'github',
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.github);
            });
        });

        describe('GitHub Actions: Gradle AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/gradle-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'github',
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.github);
            });
        });
    });
});
<commit_msg>CI-CD: improve description tests<commit_after>const path = require('path');
const assert = require('yeoman-assert');
const helpers = require('yeoman-test');
const fse = require('fs-extra');

const expectedFiles = {
    travis: ['.travis.yml'],
    jenkins: ['Jenkinsfile', 'src/main/docker/jenkins.yml', 'src/main/resources/idea.gdsl'],
    gitlab: ['.gitlab-ci.yml'],
    circle: ['.circleci/config.yml'],
    azure: ['azure-pipelines.yml'],
    github: ['.github/workflows/github-ci.yml'],
    dockerRegistry: ['src/main/docker/docker-registry.yml'],
};

describe('JHipster CI-CD Sub Generator', () => {
    //--------------------------------------------------
    // Jenkins tests
    //--------------------------------------------------
    describe('Jenkins tests', () => {
        describe('Jenkins: Maven AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'jenkins',
                        insideDocker: false,
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.jenkins);
            });
            it("doesn't contain Docker, Sonar, Heroku", () => {
                assert.noFileContent('Jenkinsfile', /docker/);
                assert.noFileContent('Jenkinsfile', /sonar/);
                assert.noFileContent('Jenkinsfile', /heroku/);
            });
        });

        describe('Jenkins: Gradle AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/gradle-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'jenkins',
                        insideDocker: false,
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.jenkins);
            });
            it("doesn't contain Docker, Sonar, Heroku", () => {
                assert.noFileContent('Jenkinsfile', /docker/);
                assert.noFileContent('Jenkinsfile', /sonar/);
                assert.noFileContent('Jenkinsfile', /heroku/);
            });
        });
    });

    //--------------------------------------------------
    // GitLab CI tests
    //--------------------------------------------------
    describe('GitLab CI tests', () => {
        describe('GitLab CI: Maven AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'gitlab',
                        insideDocker: false,
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.gitlab);
            });
            it("doesn't contain image: jhipster, Sonar, Heroku", () => {
                assert.noFileContent('.gitlab-ci.yml', /image: jhipster/);
                assert.noFileContent('.gitlab-ci.yml', /sonar/);
                assert.noFileContent('.gitlab-ci.yml', /heroku/);
            });
        });

        describe('GitLab CI: Gradle AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/gradle-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'gitlab',
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.gitlab);
            });
            it("doesn't contain jhipster/jhipster, Sonar, Heroku", () => {
                assert.noFileContent('.gitlab-ci.yml', /image: jhipster/);
                assert.noFileContent('.gitlab-ci.yml', /sonar/);
                assert.noFileContent('.gitlab-ci.yml', /heroku/);
            });
        });

        describe('GitLab CI: npm skip server', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/npm-skip-server'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'gitlab',
                        insideDocker: true,
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.gitlab);
            });
            it('contains image: jhipster', () => {
                assert.fileContent('.gitlab-ci.yml', /image: jhipster/);
            });
        });
    });

    //--------------------------------------------------
    // Travis CI tests
    //--------------------------------------------------
    describe('Travis CI tests', () => {
        describe('Travis CI: Maven AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'travis',
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.travis);
            });
            it("doesn't contain Sonar, Heroku", () => {
                assert.noFileContent('.travis.yml', /sonar/);
                assert.noFileContent('.travis.yml', /heroku/);
            });
        });

        describe('Travis CI: Gradle AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/gradle-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'travis',
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.travis);
            });
            it("doesn't contain Sonar, Heroku", () => {
                assert.noFileContent('.travis.yml', /sonar/);
                assert.noFileContent('.travis.yml', /heroku/);
            });
        });
    });

    //--------------------------------------------------
    // Azure Pipelines tests
    //--------------------------------------------------
    describe('Azure Pipelines tests', () => {
        describe('Azure Pipelines: Maven AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'azure',
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.azure);
            });
        });

        describe('Azure Pipelines: Gradle AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/gradle-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'azure',
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.azure);
            });
        });
    });

    //--------------------------------------------------
    // GitHub Actions tests
    //--------------------------------------------------
    describe('GitHub Actions tests', () => {
        describe('GitHub Actions: Maven AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/maven-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'github',
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.github);
            });
        });

        describe('GitHub Actions: Gradle AngularX NPM', () => {
            before(done => {
                helpers
                    .run(require.resolve('../generators/ci-cd'))
                    .inTmpDir(dir => {
                        fse.copySync(path.join(__dirname, './templates/ci-cd/gradle-ngx-npm'), dir);
                    })
                    .withOptions({ skipChecks: true })
                    .withPrompts({
                        pipeline: 'github',
                        cicdIntegrations: [],
                    })
                    .on('end', done);
            });
            it('creates expected files', () => {
                assert.file(expectedFiles.github);
            });
        });
    });
});
<|endoftext|>


<commit_before>var $ = require('jquery');
var i18next = require('i18next');

export function bind(element) {
    $(element).each(function() {
        var
            $modal = null,
            $body = null,
            $btnRefresh = null,
            url = '/api/user/online';

        function reload() {
            if (!$modal) {
                $modal = $(require('./online.html'));

                $modal.find('.modal-title').text(i18next.t("who-online/title"));
                $modal.find('.btn-primary').text(i18next.t("who-online/refresh"));
                $modal.find('.btn-default').text(i18next.t("who-online/close"));

                $body = $modal.find('.modal-body');
                $btnRefresh = $modal.find('.btn-primary').on('click', function(e) {
                    e.preventDefault();
                    reload();
                });
            }
            $body.empty();
            $modal.modal();

            $btnRefresh.button('loading');
            $.get(url, {}, function(response) {
                $body.empty();
                $.map(response.items, function(user) {
                    var $e = $('  ')
                        .toggleClass('muted', !!user.deleted)
                        .toggleClass('long-away', !!user.long_away)
                        .toggleClass('green-man', !!user.green);

                    if (user.deleted) {
                        $e.append($('').text(i18next.t("deleted-user")));
                    } else {
                        $e.append($('').attr('href', user.url).text(user.name));
                    }

                    $body.append($e);
                });

                $btnRefresh.button('reset');
            });
        }

        $(this).on('click', function(e) {
            e.preventDefault();
            reload();
        });
    });
}
<commit_msg>append space<commit_after>var $ = require('jquery');
var i18next = require('i18next');

export function bind(element) {
    $(element).each(function() {
        var
            $modal = null,
            $body = null,
            $btnRefresh = null,
            url = '/api/user/online';

        function reload() {
            if (!$modal) {
                $modal = $(require('./online.html'));

                $modal.find('.modal-title').text(i18next.t("who-online/title"));
                $modal.find('.btn-primary').text(i18next.t("who-online/refresh"));
                $modal.find('.btn-default').text(i18next.t("who-online/close"));

                $body = $modal.find('.modal-body');
                $btnRefresh = $modal.find('.btn-primary').on('click', function(e) {
                    e.preventDefault();
                    reload();
                });
            }
            $body.empty();
            $modal.modal();

            $btnRefresh.button('loading');
            $.get(url, {}, function(response) {
                $body.empty();
                $.map(response.items, function(user) {
                    var $e = $(' ')
                        .toggleClass('muted', !!user.deleted)
                        .toggleClass('long-away', !!user.long_away)
                        .toggleClass('green-man', !!user.green);

                    if (user.deleted) {
                        $e.append($('').text(i18next.t("deleted-user")));
                    } else {
                        $e.append($('').attr('href', user.url).text(user.name));
                    }

                    $body.append([$e, ' ']);
                });

                $btnRefresh.button('reset');
            });
        }

        $(this).on('click', function(e) {
            e.preventDefault();
            reload();
        });
    });
}
<|endoftext|>


<commit_before>function SensePlatform() {

}

/**
 * Initializes the Sense Platform plugin.
 */
SensePlatform.prototype.init = function() {
	var success = function(result) {
		window.plugins.sense.isInitialized = true;
		console.log('Sense plugin initialized');
	};
	var failure = function(error) {
		window.plugins.sense.isInitialized = false;
		console.log('Failed to initialize Sense PhoneGap plugin: ' + error);
	};
	return cordova.exec(success, failure, 'SensePlatform', 'init', []);
};

/**
 * Adds a new data point to one of the Sense user's sensors. The data point will be put in Sense's
 * buffer on the until it is synchronized with CommonSense. The sync rate depends on the
 * application.
 *
 * @param name
 *            String with name of the sensor that the data belongs to. Typically this should be one
 *            of the standardized sensor names that are used throughout CommonSense.
 * @param displayName
 *            String with pretty display name for the sensor. (Optional)
 * @param description
 *            String with description of the sensor, e.g. the hardware model name. (Optional)
 * @param dataType
 *            String with data type of the sensor. Can be "bool", "float", "int", "json", "string".
 * @param value
 *            String with value for the data point. Take care to escape any slashes and quotes.
 * @param timestamp
 *            Number with timestamp of the data point, in milliseconds since epoch.
 * @param success
 *            The callback which will be called when the point was successfully given to Sense.
 * @param failure
 *            The callback which will be called when Sense login fails
 */
SensePlatform.prototype.addDataPoint = function(name, displayName, description, dataType, value,
		timestamp, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'add_data_point', [ name, displayName,
			description, dataType, value, timestamp ]);
};

/**
 * @param username
 * @param password
 * @param success
 *            The callback which will be called when Sense login is successful
 * @param failure
 *            The callback which will be called when Sense login fails
 */
SensePlatform.prototype.changeLogin = function(username, password, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'change_login', [ username, password ]);
};

/**
 * Forces a flush of buffered sensor data to CommonSense. The data is not guaranteed to be removed
 * from the phone, this is done by a separate process.
 */
SensePlatform.prototype.flushBuffer = function(success, failure) {
	return cordova.exec(success, failure, 'SensePlatform', 'flush_buffer', []);
};

/**
 * @param name
 *            String containing sensor name to lookup
 * @param onlyThisDevice
 *            Boolean to specify only to look for sensors that are connected to this specific phone
 * @param success
 *            The callback which will be called when sensor data was retrieved
 * @param failure
 *            The callback which will be called when execution fails
 *
 * @return JSONArray containing data
 */
SensePlatform.prototype.getRemoteData = function(name, onlyThisDevice, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'get_commonsense_data', [ name,
			onlyThisDevice ]);
};

/**
 * @param name
 *            String containing sensor name to lookup
 * @param success
 *            The callback which will be called when sensor data was retrieved
 * @param failure
 *            The callback which will be called when execution fails
 *
 * @return JSONArray containing data
 */
SensePlatform.prototype.getLocalData = function(name, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'get_data', [ name ]);
};

/**
 * @param name
 *            String containing sensor name to lookup
 * @param success
 *            The callback which will be called when sensor data was retrieved
 * @param failure
 *            The callback which will be called when execution fails
 *
 * @return JSONArray containing data
 * @deprecated use getLocalData instead
 */
SensePlatform.prototype.getData = function(name, success, failure) {
	return window.plugins.sense.getLocalData(name, success, failure);
};

/**
 * @param key
 *            String containing preference key to retrieve. A list of keys is provided with the
 *            SensePlatform class
 * @param success
 *            Callback which will be called when action was performed successfully
 * @param failure
 *            Callback which will be called when execution fails
 *
 * @return JSONArray containing data
 */
SensePlatform.prototype.getPref = function(key, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'get_pref', [ key ]);
};

/**
 * @param success
 *            The callback which will be called when Sense registration is successful
 * @param failure
 *            The callback which will be called when Sense registration fails
 */
SensePlatform.prototype.getStatus = function(success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'get_status', []);
};

/**
 * @param success
 *            The callback which will be called when Sense registration is successful
 * @param failure
 *            The callback which will be called when Sense registration fails
 */
SensePlatform.prototype.getSessionId = function(success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'get_session', []);
};

/**
 * @param username
 * @param password
 * @param success
 *            The callback which will be called when Sense login is successful
 * @param failure
 *            The callback which will be called when Sense login fails
 */
SensePlatform.prototype.logout = function(success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'logout', []);
};

/**
 * Gives feedback for a CommonSense state sensor.
 *
 * @param name
 *            String with state sensor name
 * @param start
 *            Number with start date of feedback period (in milliseconds since epoch)
 * @param end
 *            Number with end date of feedback period (in milliseconds since epoch)
 * @param label
 *            String with desired label for the feedback period
 * @param success
 *            Callback which will be called when action was performed successfully
 * @param failure
 *            Callback which will be called when execution fails
 */
SensePlatform.prototype.giveFeedback = function(name, start, end, label, success, failure) {
	return cordova.exec(success, failure, 'SensePlatform', 'give_feedback', [ name, start, end,
			label ]);
};

/**
 * @param username
 * @param password
 * @param firstName
 * @param surname
 * @param email
 * @param phone
 * @param success
 *            The callback which will be called when Sense registration is successful
 * @param failure
 *            The callback which will be called when Sense registration fails
 */
SensePlatform.prototype.register = function(username, password, firstName, surname, email, phone,
		success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'register', [ username, password,
			firstName, surname, email, phone ]);
};

/**
 * @param key
 *            String containing preference key to set. A list of valid keys is provided with the
 *            SensePlatform class.
 * @param value
 *            String containing preference value to set
 * @param success
 *            The callback which will be called when preference is successfully set
 * @param failure
 *            The callback which will be called when execution fails
 *
 * @return JSONArray containing data
 */
SensePlatform.prototype.setPref = function(key, value, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'set_pref', [ key, value ]);
};

/**
 * @param active
 *            boolean to indicate desired state
 * @param success
 *            The callback which will be called when Sense status is successfully changed
 * @param failure
 *            The callback which will be called when execution fails
 */
SensePlatform.prototype.toggleMain = function(active, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'toggle_main', [ active ]);
};

/**
 * @param active
 *            boolean to indicate desired state
 * @param success
 *            The callback which will be called when ambience sensor status is successfully changed
 * @param failure
 *            The callback which will be called when execution fails
 */
SensePlatform.prototype.toggleAmbience = function(active, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'toggle_ambience', [ active ]);
};

/**
 * @param active
 *            boolean to indicate desired state
 * @param success
 *            The callback which will be called when external sensor status is successfully changed
 * @param failure
 *            The callback which will be called when execution fails
 */
SensePlatform.prototype.toggleExternal = function(active, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'toggle_external', [ active ]);
};

/**
 * @param active
 *            boolean to indicate desired state
 * @param success
 *            The callback which will be called when motion sensor status is successfully changed
 * @param failure
 *            The callback which will be called when execution fails
 */
SensePlatform.prototype.togglePosition = function(active, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'toggle_position', [ active ]);
};

/**
 * @param active
 *            boolean to indicate desired state
 * @param success
 *            The callback which will be called when motion sensor status is successfully changed
 * @param failure
 *            The callback which will be called when execution fails
 */
SensePlatform.prototype.toggleMotion = function(active, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'toggle_motion', [ active ]);
};

/**
 * @param active
 *            boolean to indicate desired state
 * @param success
 *            The callback which will be called when neighboring devices sensor status is
 *            successfully changed
 * @param failure
 *            The callback which will be called when execution fails
 */
SensePlatform.prototype.toggleNeighDev = function(active, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'toggle_neighdev', [ active ]);
};

/**
 * @param active
 *            boolean to indicate desired state
 * @param success
 *            The callback which will be called when phone state sensor status is successfully
 *            changed
 * @param failure
 *            The callback which will be called when execution fails
 */
SensePlatform.prototype.togglePhoneState = function(active, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'toggle_phonestate', [ active ]);
};

/* status codes */
SensePlatform.STATUSCODE_AMBIENCE = 0x01;
SensePlatform.STATUSCODE_CONNECTED = 0x02;
SensePlatform.STATUSCODE_DEVICE_PROX = 0x04;
SensePlatform.STATUSCODE_EXTERNAL = 0x08;
SensePlatform.STATUSCODE_LOCATION = 0x10;
SensePlatform.STATUSCODE_MOTION = 0x20;
SensePlatform.STATUSCODE_PHONESTATE = 0x40;
SensePlatform.STATUSCODE_QUIZ = 0x80;
SensePlatform.STATUSCODE_RUNNING = 0x100;

/* sync rate settings */
SensePlatform.SYNC_ECO = "1";
SensePlatform.SYNC_NORMAL = "0";
SensePlatform.SYNC_OFTEN = "-1";
SensePlatform.SYNC_REALTIME = "-2";

/* sample rate settings */
SensePlatform.SAMPLE_RARELY = "1";
SensePlatform.SAMPLE_NORMAL = "0";
SensePlatform.SAMPLE_OFTEN = "-1";
SensePlatform.SAMPLE_REALTIME = "-2";

/* keys for main prefs */
SensePlatform.PREF_LOGIN_USERNAME = "login_mail";
SensePlatform.PREF_SAMPLE_RATE = "commonsense_rate";
SensePlatform.PREF_SYNC_RATE = "sync_rate";
SensePlatform.PREF_AUTOSTART = "autostart";

/* keys for phone state sensors */
SensePlatform.PREF_BATTERY = "phonestate_battery";
SensePlatform.PREF_SCREEN_ACTIVITY = "phonestate_screen_activity";
SensePlatform.PREF_PROXIMITY = "phonestate_proximity";
SensePlatform.PREF_IP_ADDRESS = "phonestate_ip";
SensePlatform.PREF_DATA_CONNECTION = "phonestate_data_connection";
SensePlatform.PREF_UNREAD_MSG = "phonestate_unread_msg";
SensePlatform.PREF_SERVICE_STATE = "phonestate_service_state";
SensePlatform.PREF_SIGNAL_STRENGTH = "phonestate_signal_strength";
SensePlatform.PREF_CALL_STATE = "phonestate_call_state";

/* keys for ambience sensor prefs */
SensePlatform.PREF_AUDIO_SPECTRUM = "ambience_audio_spectrum";
SensePlatform.PREF_CAMERA_LIGHT = "ambience_camera_light";
SensePlatform.PREF_LIGHT = "ambience_light";
SensePlatform.PREF_MIC = "ambience_mic";
SensePlatform.PREF_PRESSURE = "ambience_pressure";
SensePlatform.PREF_TEMPERATURE = "ambience_temperature";

/* keys for device proximity sensor prefs */
SensePlatform.PREF_BLUETOOTH = "proximity_bt";
SensePlatform.PREF_WIFI = "proximity_wifi";
SensePlatform.PREF_NFC = "proximity_nfc";

/* keys for location sensor prefs */
SensePlatform.PREF_GPS = "location_gps";
SensePlatform.PREF_NETWORK = "location_network";
SensePlatform.PREF_AUTO_GPS = "automatic_gps";

/* keys for motion sensor prefs */
SensePlatform.PREF_FALL_DETECT = "motion_fall_detector";
SensePlatform.PREF_FALL_DETECT_DEMO = "motion_fall_detector_demo";
SensePlatform.PREF_EPIMODE = "epimode";
SensePlatform.PREF_UNREG = "motion_unregister";
SensePlatform.PREF_MOTION_ENERGY = "motion_energy";
SensePlatform.PREF_SCREENOFF_FIX = "screenoff_fix";

/* keys for external sensor prefs */
SensePlatform.PREF_MYGLUCOHEALTH = "myglucohealth";
SensePlatform.PREF_TANITASCALE = "tanita_scale";
SensePlatform.PREF_ZEPHYR_BIOHARNESS = "zephyrBioHarness";
SensePlatform.PREF_ZEPHYR_HXM = "zephyrHxM";
SensePlatform.PREF_OBD2 = "obd2sensor";

/* keys for advanced prefs */
SensePlatform.PREF_DEV_MODE = "devmode";
SensePlatform.PREF_USE_COMMONSENSE = "use_commonsense";
SensePlatform.PREF_COMPRESS = "compression";

cordova.addConstructor(function() {
	try {
		cordova.addPlugin("sense", new SensePlatform());
	} catch (e) {
		// do it again to fix a bug in iOS:
		if (!window.plugins)
			window.plugins = {};
		if (!window.plugins.sense)
			window.plugins.sense = new SensePlatform();
	}
});
<commit_msg>fixed plugin registration in javascript<commit_after>function SensePlatform() {

}

/**
 * Initializes the Sense Platform plugin.
 */
SensePlatform.prototype.init = function() {
	var success = function(result) {
		window.plugins.sense.isInitialized = true;
		console.log('Sense plugin initialized');
	};
	var failure = function(error) {
		window.plugins.sense.isInitialized = false;
		console.log('Failed to initialize Sense PhoneGap plugin: ' + error);
	};
	return cordova.exec(success, failure, 'SensePlatform', 'init', []);
};

/**
 * Adds a new data point to one of the Sense user's sensors. The data point will be put in Sense's
 * buffer on the until it is synchronized with CommonSense. The sync rate depends on the
 * application.
 *
 * @param name
 *            String with name of the sensor that the data belongs to. Typically this should be one
 *            of the standardized sensor names that are used throughout CommonSense.
 * @param displayName
 *            String with pretty display name for the sensor. (Optional)
 * @param description
 *            String with description of the sensor, e.g. the hardware model name. (Optional)
 * @param dataType
 *            String with data type of the sensor. Can be "bool", "float", "int", "json", "string".
 * @param value
 *            String with value for the data point. Take care to escape any slashes and quotes.
 * @param timestamp
 *            Number with timestamp of the data point, in milliseconds since epoch.
 * @param success
 *            The callback which will be called when the point was successfully given to Sense.
 * @param failure
 *            The callback which will be called when Sense login fails
 */
SensePlatform.prototype.addDataPoint = function(name, displayName, description, dataType, value,
		timestamp, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'add_data_point', [ name, displayName,
			description, dataType, value, timestamp ]);
};

/**
 * @param username
 * @param password
 * @param success
 *            The callback which will be called when Sense login is successful
 * @param failure
 *            The callback which will be called when Sense login fails
 */
SensePlatform.prototype.changeLogin = function(username, password, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'change_login', [ username, password ]);
};

/**
 * Forces a flush of buffered sensor data to CommonSense. The data is not guaranteed to be removed
 * from the phone, this is done by a separate process.
 */
SensePlatform.prototype.flushBuffer = function(success, failure) {
	return cordova.exec(success, failure, 'SensePlatform', 'flush_buffer', []);
};

/**
 * @param name
 *            String containing sensor name to lookup
 * @param onlyThisDevice
 *            Boolean to specify only to look for sensors that are connected to this specific phone
 * @param success
 *            The callback which will be called when sensor data was retrieved
 * @param failure
 *            The callback which will be called when execution fails
 *
 * @return JSONArray containing data
 */
SensePlatform.prototype.getRemoteData = function(name, onlyThisDevice, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'get_commonsense_data', [ name,
			onlyThisDevice ]);
};

/**
 * @param name
 *            String containing sensor name to lookup
 * @param success
 *            The callback which will be called when sensor data was retrieved
 * @param failure
 *            The callback which will be called when execution fails
 *
 * @return JSONArray containing data
 */
SensePlatform.prototype.getLocalData = function(name, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'get_data', [ name ]);
};

/**
 * @param name
 *            String containing sensor name to lookup
 * @param success
 *            The callback which will be called when sensor data was retrieved
 * @param failure
 *            The callback which will be called when execution fails
 *
 * @return JSONArray containing data
 * @deprecated use getLocalData instead
 */
SensePlatform.prototype.getData = function(name, success, failure) {
	return window.plugins.sense.getLocalData(name, success, failure);
};

/**
 * @param key
 *            String containing preference key to retrieve. A list of keys is provided with the
 *            SensePlatform class
 * @param success
 *            Callback which will be called when action was performed successfully
 * @param failure
 *            Callback which will be called when execution fails
 *
 * @return JSONArray containing data
 */
SensePlatform.prototype.getPref = function(key, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'get_pref', [ key ]);
};

/**
 * @param success
 *            The callback which will be called when Sense registration is successful
 * @param failure
 *            The callback which will be called when Sense registration fails
 */
SensePlatform.prototype.getStatus = function(success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'get_status', []);
};

/**
 * @param success
 *            The callback which will be called when Sense registration is successful
 * @param failure
 *            The callback which will be called when Sense registration fails
 */
SensePlatform.prototype.getSessionId = function(success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'get_session', []);
};

/**
 * @param username
 * @param password
 * @param success
 *            The callback which will be called when Sense login is successful
 * @param failure
 *            The callback which will be called when Sense login fails
 */
SensePlatform.prototype.logout = function(success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'logout', []);
};

/**
 * Gives feedback for a CommonSense state sensor.
 *
 * @param name
 *            String with state sensor name
 * @param start
 *            Number with start date of feedback period (in milliseconds since epoch)
 * @param end
 *            Number with end date of feedback period (in milliseconds since epoch)
 * @param label
 *            String with desired label for the feedback period
 * @param success
 *            Callback which will be called when action was performed successfully
 * @param failure
 *            Callback which will be called when execution fails
 */
SensePlatform.prototype.giveFeedback = function(name, start, end, label, success, failure) {
	return cordova.exec(success, failure, 'SensePlatform', 'give_feedback', [ name, start, end,
			label ]);
};

/**
 * @param username
 * @param password
 * @param firstName
 * @param surname
 * @param email
 * @param phone
 * @param success
 *            The callback which will be called when Sense registration is successful
 * @param failure
 *            The callback which will be called when Sense registration fails
 */
SensePlatform.prototype.register = function(username, password, firstName, surname, email, phone,
		success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'register', [ username, password,
			firstName, surname, email, phone ]);
};

/**
 * @param key
 *            String containing preference key to set. A list of valid keys is provided with the
 *            SensePlatform class.
 * @param value
 *            String containing preference value to set
 * @param success
 *            The callback which will be called when preference is successfully set
 * @param failure
 *            The callback which will be called when execution fails
 *
 * @return JSONArray containing data
 */
SensePlatform.prototype.setPref = function(key, value, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'set_pref', [ key, value ]);
};

/**
 * @param active
 *            boolean to indicate desired state
 * @param success
 *            The callback which will be called when Sense status is successfully changed
 * @param failure
 *            The callback which will be called when execution fails
 */
SensePlatform.prototype.toggleMain = function(active, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'toggle_main', [ active ]);
};

/**
 * @param active
 *            boolean to indicate desired state
 * @param success
 *            The callback which will be called when ambience sensor status is successfully changed
 * @param failure
 *            The callback which will be called when execution fails
 */
SensePlatform.prototype.toggleAmbience = function(active, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'toggle_ambience', [ active ]);
};

/**
 * @param active
 *            boolean to indicate desired state
 * @param success
 *            The callback which will be called when external sensor status is successfully changed
 * @param failure
 *            The callback which will be called when execution fails
 */
SensePlatform.prototype.toggleExternal = function(active, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'toggle_external', [ active ]);
};

/**
 * @param active
 *            boolean to indicate desired state
 * @param success
 *            The callback which will be called when motion sensor status is successfully changed
 * @param failure
 *            The callback which will be called when execution fails
 */
SensePlatform.prototype.togglePosition = function(active, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'toggle_position', [ active ]);
};

/**
 * @param active
 *            boolean to indicate desired state
 * @param success
 *            The callback which will be called when motion sensor status is successfully changed
 * @param failure
 *            The callback which will be called when execution fails
 */
SensePlatform.prototype.toggleMotion = function(active, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'toggle_motion', [ active ]);
};

/**
 * @param active
 *            boolean to indicate desired state
 * @param success
 *            The callback which will be called when neighboring devices sensor status is
 *            successfully changed
 * @param failure
 *            The callback which will be called when execution fails
 */
SensePlatform.prototype.toggleNeighDev = function(active, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'toggle_neighdev', [ active ]);
};

/**
 * @param active
 *            boolean to indicate desired state
 * @param success
 *            The callback which will be called when phone state sensor status is successfully
 *            changed
 * @param failure
 *            The callback which will be called when execution fails
 */
SensePlatform.prototype.togglePhoneState = function(active, success, failure) {
	if (!window.plugins.sense.isInitialized) {
		window.plugins.sense.init();
	}
	return cordova.exec(success, failure, 'SensePlatform', 'toggle_phonestate', [ active ]);
};

/* status codes */
SensePlatform.STATUSCODE_AMBIENCE = 0x01;
SensePlatform.STATUSCODE_CONNECTED = 0x02;
SensePlatform.STATUSCODE_DEVICE_PROX = 0x04;
SensePlatform.STATUSCODE_EXTERNAL = 0x08;
SensePlatform.STATUSCODE_LOCATION = 0x10;
SensePlatform.STATUSCODE_MOTION = 0x20;
SensePlatform.STATUSCODE_PHONESTATE = 0x40;
SensePlatform.STATUSCODE_QUIZ = 0x80;
SensePlatform.STATUSCODE_RUNNING = 0x100;

/* sync rate settings */
SensePlatform.SYNC_ECO = "1";
SensePlatform.SYNC_NORMAL = "0";
SensePlatform.SYNC_OFTEN = "-1";
SensePlatform.SYNC_REALTIME = "-2";

/* sample rate settings */
SensePlatform.SAMPLE_RARELY = "1";
SensePlatform.SAMPLE_NORMAL = "0";
SensePlatform.SAMPLE_OFTEN = "-1";
SensePlatform.SAMPLE_REALTIME = "-2";

/* keys for main prefs */
SensePlatform.PREF_LOGIN_USERNAME = "login_mail";
SensePlatform.PREF_SAMPLE_RATE = "commonsense_rate";
SensePlatform.PREF_SYNC_RATE = "sync_rate";
SensePlatform.PREF_AUTOSTART = "autostart";

/* keys for phone state sensors */
SensePlatform.PREF_BATTERY = "phonestate_battery";
SensePlatform.PREF_SCREEN_ACTIVITY = "phonestate_screen_activity";
SensePlatform.PREF_PROXIMITY = "phonestate_proximity";
SensePlatform.PREF_IP_ADDRESS = "phonestate_ip";
SensePlatform.PREF_DATA_CONNECTION = "phonestate_data_connection";
SensePlatform.PREF_UNREAD_MSG = "phonestate_unread_msg";
SensePlatform.PREF_SERVICE_STATE = "phonestate_service_state";
SensePlatform.PREF_SIGNAL_STRENGTH = "phonestate_signal_strength";
SensePlatform.PREF_CALL_STATE = "phonestate_call_state";

/* keys for ambience sensor prefs */
SensePlatform.PREF_AUDIO_SPECTRUM = "ambience_audio_spectrum";
SensePlatform.PREF_CAMERA_LIGHT = "ambience_camera_light";
SensePlatform.PREF_LIGHT = "ambience_light";
SensePlatform.PREF_MIC = "ambience_mic";
SensePlatform.PREF_PRESSURE = "ambience_pressure";
SensePlatform.PREF_TEMPERATURE = "ambience_temperature";

/* keys for device proximity sensor prefs */
SensePlatform.PREF_BLUETOOTH = "proximity_bt";
SensePlatform.PREF_WIFI = "proximity_wifi";
SensePlatform.PREF_NFC = "proximity_nfc";

/* keys for location sensor prefs */
SensePlatform.PREF_GPS = "location_gps";
SensePlatform.PREF_NETWORK = "location_network";
SensePlatform.PREF_AUTO_GPS = "automatic_gps";

/* keys for motion sensor prefs */
SensePlatform.PREF_FALL_DETECT = "motion_fall_detector";
SensePlatform.PREF_FALL_DETECT_DEMO = "motion_fall_detector_demo";
SensePlatform.PREF_EPIMODE = "epimode";
SensePlatform.PREF_UNREG = "motion_unregister";
SensePlatform.PREF_MOTION_ENERGY = "motion_energy";
SensePlatform.PREF_SCREENOFF_FIX = "screenoff_fix";

/* keys for external sensor prefs */
SensePlatform.PREF_MYGLUCOHEALTH = "myglucohealth";
SensePlatform.PREF_TANITASCALE = "tanita_scale";
SensePlatform.PREF_ZEPHYR_BIOHARNESS = "zephyrBioHarness";
SensePlatform.PREF_ZEPHYR_HXM = "zephyrHxM";
SensePlatform.PREF_OBD2 = "obd2sensor";

/* keys for advanced prefs */
SensePlatform.PREF_DEV_MODE = "devmode";
SensePlatform.PREF_USE_COMMONSENSE = "use_commonsense";
SensePlatform.PREF_COMPRESS = "compression";

/* register the plugin */
if (!window.plugins)
	window.plugins = {};
if (!window.plugins.sense)
	window.plugins.sense = new SensePlatform();
<|endoftext|>


<commit_before>/* eslint-env mocha */

var chai = require("chai"),
    http = require("http"),
    Crawler = require("../");

chai.should();

var makeCrawler = function (url) {
    var crawler = new Crawler(url);
    crawler.interval = 5;
    return crawler;
};

describe("Fetch conditions", function() {
    it("should be able to add a fetch condition", function() {
        var crawler = makeCrawler("http://example.com"),
            conditionID = crawler.addFetchCondition(function() {});

        crawler._fetchConditions.length.should.equal(1);
        conditionID.should.be.a("number");
    });

    it("should be able to remove a fetch condition by ID", function() {
        var crawler = makeCrawler("http://example.com"),
            conditionID = crawler.addFetchCondition(function() {});

        crawler._fetchConditions.length.should.equal(1);
        crawler.removeFetchCondition(conditionID);
        crawler._fetchConditions.length.should.equal(0);
    });

    it("should be able to remove a fetch condition by reference", function() {
        var crawler = makeCrawler("http://example.com"),
            condition = function() {};

        crawler.addFetchCondition(condition);
        crawler._fetchConditions.length.should.equal(1);
        crawler.removeFetchCondition(condition);
        crawler._fetchConditions.length.should.equal(0);
    });

    it("should provide fetch conditions with the right data", function(done) {
        var crawler = makeCrawler("http://127.0.0.1:3000"),
            fetchConditionCalled = false;

        crawler.addFetchCondition(function(queueItem, referrerQueueItem) {
            if (fetchConditionCalled) {
                return false;
            }

            fetchConditionCalled = true;

            referrerQueueItem.should.be.an("object");
            referrerQueueItem.should.include({
                url: "http://127.0.0.1:3000/",
                status: "downloaded",
                fetched: true,
                depth: 1,
                protocol: "http",
                host: "127.0.0.1",
                port: "3000",
                path: "/"
            });

            referrerQueueItem.stateData.should.be.an("object");
            referrerQueueItem.stateData.should.have.property("requestLatency");
            referrerQueueItem.stateData.should.have.property("requestTime");
            referrerQueueItem.stateData.should.include({
                contentLength: 68,
                contentType: "text/html",
                code: 200
            });
            referrerQueueItem.stateData.should.have.property("headers").that.includes({
                "content-length": "68"
            });

            queueItem.should.be.an("object");
            queueItem.should.include({
                url: "http://127.0.0.1:3000/stage2",
                status: "created",
                fetched: false,
                depth: 2,
                protocol: "http",
                host: "127.0.0.1",
                port: "3000",
                path: "/stage2"
            });

            crawler.stop(true);
            done();
        });

        crawler.start();
    });

    it("should not fetch a resource when prevented by a fetch condition", function(done) {
        this.slow("1s");

        var crawler = makeCrawler("http://example.com");

        crawler.addFetchCondition(function() {
            return false;
        });

        crawler.on("complete", function() {
            crawler.queue.getLength(function(error, length) {
                length.should.equal(1);
                done();
            });
        });

        crawler.start();
    });
});

describe("Download conditions", function() {
    it("should be able to add a download condition", function() {
        var crawler = makeCrawler("http://example.com"),
            conditionID = crawler.addDownloadCondition(function() {});

        crawler._downloadConditions.length.should.equal(1);
        conditionID.should.be.a("number");
    });

    it("should be able to remove a download condition by ID", function() {
        var crawler = makeCrawler("http://example.com"),
            conditionID = crawler.addDownloadCondition(function() {});

        crawler._downloadConditions.length.should.equal(1);
        crawler.removeDownloadCondition(conditionID);
        crawler._downloadConditions.length.should.equal(0);
    });

    it("should be able to remove a download condition by reference", function() {
        var crawler = makeCrawler("http://example.com"),
            condition = function() {};

        crawler.addDownloadCondition(condition);
        crawler._downloadConditions.length.should.equal(1);
        crawler.removeDownloadCondition(condition);
        crawler._downloadConditions.length.should.equal(0);
    });

    it("should provide download conditions with the right data", function(done) {
        var crawler = makeCrawler("http://127.0.0.1:3000"),
            downloadConditionCalled = false;

        crawler.addDownloadCondition(function(queueItem, response) {
            if (downloadConditionCalled) {
                return false;
            }

            downloadConditionCalled = true;

            queueItem.should.be.an("object");
            queueItem.should.include({
                url: "http://127.0.0.1:3000/",
                status: "spooled",
                fetched: false,
                depth: 1,
                protocol: "http",
                host: "127.0.0.1",
                port: "3000",
                path: "/"
            });

            response.should.be.an("object");
            response.should.be.an.instanceof(http.IncomingMessage);

            crawler.stop(true);
            done();
        });

        crawler.start();
    });

    it("should not download a resource when prevented by a download condition", function(done) {
        this.slow("1s");

        var crawler = makeCrawler("http://example.com");
        crawler.maxDepth = 1;

        crawler.addDownloadCondition(function() {
            return false;
        });

        crawler.on("complete", function() {
            crawler.queue.getLength(function(error, length) {
                length.should.equal(1);

                crawler.queue.get(0, function(error, queueItem) {
                    queueItem.status.should.equal("downloadprevented");
                    done();
                });
            });
        });

        crawler.start();
    });

    it("should emit a downloadprevented event when a download condition returns false", function(done) {
        var crawler = makeCrawler("http://example.com");

        crawler.addDownloadCondition(function() {
            return false;
        });

        crawler.on("downloadprevented", function(queueItem, response) {
            queueItem.should.be.an("object");
            queueItem.status.should.equal("downloadprevented");

            response.should.be.an("object");
            response.should.be.an.instanceof(http.IncomingMessage);

            crawler.stop();
            done();
        });

        crawler.start();
    });
});
<commit_msg>Adjust slow time in fetch/download conditions tests<commit_after>/* eslint-env mocha */

var chai = require("chai"),
    http = require("http"),
    Crawler = require("../");

chai.should();

var makeCrawler = function (url) {
    var crawler = new Crawler(url);
    crawler.interval = 5;
    return crawler;
};

describe("Fetch conditions", function() {
    this.slow("150ms");

    it("should be able to add a fetch condition", function() {
        var crawler = makeCrawler("http://example.com"),
            conditionID = crawler.addFetchCondition(function() {});

        crawler._fetchConditions.length.should.equal(1);
        conditionID.should.be.a("number");
    });

    it("should be able to remove a fetch condition by ID", function() {
        var crawler = makeCrawler("http://example.com"),
            conditionID = crawler.addFetchCondition(function() {});

        crawler._fetchConditions.length.should.equal(1);
        crawler.removeFetchCondition(conditionID);
        crawler._fetchConditions.length.should.equal(0);
    });

    it("should be able to remove a fetch condition by reference", function() {
        var crawler = makeCrawler("http://example.com"),
            condition = function() {};

        crawler.addFetchCondition(condition);
        crawler._fetchConditions.length.should.equal(1);
        crawler.removeFetchCondition(condition);
        crawler._fetchConditions.length.should.equal(0);
    });

    it("should provide fetch conditions with the right data", function(done) {
        var crawler = makeCrawler("http://127.0.0.1:3000"),
            fetchConditionCalled = false;

        crawler.addFetchCondition(function(queueItem, referrerQueueItem) {
            if (fetchConditionCalled) {
                return false;
            }

            fetchConditionCalled = true;

            referrerQueueItem.should.be.an("object");
            referrerQueueItem.should.include({
                url: "http://127.0.0.1:3000/",
                status: "downloaded",
                fetched: true,
                depth: 1,
                protocol: "http",
                host: "127.0.0.1",
                port: "3000",
                path: "/"
            });

            referrerQueueItem.stateData.should.be.an("object");
            referrerQueueItem.stateData.should.have.property("requestLatency");
            referrerQueueItem.stateData.should.have.property("requestTime");
            referrerQueueItem.stateData.should.include({
                contentLength: 68,
                contentType: "text/html",
                code: 200
            });
            referrerQueueItem.stateData.should.have.property("headers").that.includes({
                "content-length": "68"
            });

            queueItem.should.be.an("object");
            queueItem.should.include({
                url: "http://127.0.0.1:3000/stage2",
                status: "created",
                fetched: false,
                depth: 2,
                protocol: "http",
                host: "127.0.0.1",
                port: "3000",
                path: "/stage2"
            });

            crawler.stop(true);
            done();
        });

        crawler.start();
    });

    it("should not fetch a resource when prevented by a fetch condition", function(done) {
        this.slow("1s");

        var crawler = makeCrawler("http://example.com");

        crawler.addFetchCondition(function() {
            return false;
        });

        crawler.on("complete", function() {
            crawler.queue.getLength(function(error, length) {
                length.should.equal(1);
                done();
            });
        });

        crawler.start();
    });
});

describe("Download conditions", function() {
    it("should be able to add a download condition", function() {
        var crawler = makeCrawler("http://example.com"),
            conditionID = crawler.addDownloadCondition(function() {});

        crawler._downloadConditions.length.should.equal(1);
        conditionID.should.be.a("number");
    });

    it("should be able to remove a download condition by ID", function() {
        var crawler = makeCrawler("http://example.com"),
            conditionID = crawler.addDownloadCondition(function() {});

        crawler._downloadConditions.length.should.equal(1);
        crawler.removeDownloadCondition(conditionID);
        crawler._downloadConditions.length.should.equal(0);
    });

    it("should be able to remove a download condition by reference", function() {
        var crawler = makeCrawler("http://example.com"),
            condition = function() {};

        crawler.addDownloadCondition(condition);
        crawler._downloadConditions.length.should.equal(1);
        crawler.removeDownloadCondition(condition);
        crawler._downloadConditions.length.should.equal(0);
    });

    it("should provide download conditions with the right data", function(done) {
        var crawler = makeCrawler("http://127.0.0.1:3000"),
            downloadConditionCalled = false;

        crawler.addDownloadCondition(function(queueItem, response) {
            if (downloadConditionCalled) {
                return false;
            }

            downloadConditionCalled = true;

            queueItem.should.be.an("object");
            queueItem.should.include({
                url: "http://127.0.0.1:3000/",
                status: "spooled",
                fetched: false,
                depth: 1,
                protocol: "http",
                host: "127.0.0.1",
                port: "3000",
                path: "/"
            });

            response.should.be.an("object");
            response.should.be.an.instanceof(http.IncomingMessage);

            crawler.stop(true);
            done();
        });

        crawler.start();
    });

    it("should not download a resource when prevented by a download condition", function(done) {
        this.slow("1s");

        var crawler = makeCrawler("http://example.com");
        crawler.maxDepth = 1;

        crawler.addDownloadCondition(function() {
            return false;
        });

        crawler.on("complete", function() {
            crawler.queue.getLength(function(error, length) {
                length.should.equal(1);

                crawler.queue.get(0, function(error, queueItem) {
                    queueItem.status.should.equal("downloadprevented");
                    done();
                });
            });
        });

        crawler.start();
    });

    it("should emit a downloadprevented event when a download condition returns false", function(done) {
        var crawler = makeCrawler("http://example.com");

        crawler.addDownloadCondition(function() {
            return false;
        });

        crawler.on("downloadprevented", function(queueItem, response) {
            queueItem.should.be.an("object");
            queueItem.status.should.equal("downloadprevented");

            response.should.be.an("object");
            response.should.be.an.instanceof(http.IncomingMessage);

            crawler.stop();
            done();
        });

        crawler.start();
    });
});
<|endoftext|>


<commit_before>import { Sockets } from './sockets';
import { keyboard } from './keyboard';
import { joystick } from './joystick';
import { Motors } from './motors';
import { Manipulator } from './manipulator';
import { telemetry } from './telemetry';
import { Stream } from './stream'
import { System } from './system';

const core = (actions) => {
    const sockets = new Sockets(actions);

    actions.motors = new Motors(sockets);

    actions.stream = new Stream();
    window.onbeforeunload = () => actions.stream.stop();

    actions.manipulator.m = new Manipulator(sockets);
    actions.system = new System(sockets);
    actions.joystick = joystick;

    console.log('[core][actions]:', actions);

    keyboard(actions.motors);

    // telemetry(actions, sockets);
}

export default core;
<commit_msg>format core/index<commit_after>import { Sockets } from './sockets';
import { keyboard } from './keyboard';
import { joystick } from './joystick';
import { Motors } from './motors';
import { Manipulator } from './manipulator';
import { telemetry } from './telemetry';
import { Stream } from './stream';
import { System } from './system';

const core = (actions) => {
    const sockets = new Sockets(actions);

    actions.motors = new Motors(sockets);

    actions.stream = new Stream();
    window.onbeforeunload = () => actions.stream.stop();

    actions.manipulator.m = new Manipulator(sockets);
    actions.system = new System(sockets);
    actions.joystick = joystick;

    console.log('[core][actions]:', actions);

    keyboard(actions.motors);

    telemetry(actions, sockets);
};

export default core;
<|endoftext|>


<commit_before>import Vue from 'vue'
import VueI18n from 'vue-i18n'

import en from './en'

Vue.use(VueI18n)

const i18n = new VueI18n({
  locale: 'en',
  messages: {
    en,
  },
})

export default i18n
<commit_msg>Detect the prefered lang automatically<commit_after>import Vue from 'vue'
import VueI18n from 'vue-i18n'

import en from './en'
import fr from './fr'

Vue.use(VueI18n)

export const SUPPORTED_LANGUAGES = ['en', 'fr']

const i18n = new VueI18n({
  locale: getPreferedLanguage(),
  fallbackLocale: 'en',
  messages: {
    en,
    fr,
  },
})

export function getPreferedLanguage () {
  const localStorageLanguage = window.localStorage.getItem('language')
  if (SUPPORTED_LANGUAGES.includes(localStorageLanguage)) {
    return localStorageLanguage
  }
  const browserLanguage = window.navigator.language
  if (SUPPORTED_LANGUAGES.includes(browserLanguage)) {
    return browserLanguage
  }
  return 'en'
}

export function savePreferedLanguage (language) {
  if (SUPPORTED_LANGUAGES.includes(language)) {
    window.localStorage.setItem('language', language)
    i18n.locale = language
    return language
  }
}

export default i18n
<|endoftext|>


<commit_before>'uses strict';

function el(type, attrs) {
    var e = document.createElement(type);

    if(attrs) {
        var keys = Object.keys(attrs);
        for (var i = 0; i < keys.length; i++) {
            var key = keys[i];

            if(key === 'content') {
                e.innerText = attrs[key];
            } else {
                e.setAttribute(key, attrs[key]);
            }
        }
    }
    return e;
}

function addEl(el) {
    document.body.appendChild(el);
}

function removeEl(el) {
    el.parentNode.removeChild(el);
}<commit_msg>Typo fix<commit_after>'use strict';

function el(type, attrs) {
    var e = document.createElement(type);

    if(attrs) {
        var keys = Object.keys(attrs);
        for (var i = 0; i < keys.length; i++) {
            var key = keys[i];

            if(key === 'content') {
                e.innerText = attrs[key];
            } else {
                e.setAttribute(key, attrs[key]);
            }
        }
    }
    return e;
}

function addEl(el) {
    document.body.appendChild(el);
}

function removeEl(el) {
    el.parentNode.removeChild(el);
}<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you 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.
 */

function onRequest(context){
    var viewModel = {};
    var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
    viewModel.hostName = devicemgtProps["httpsWebURL"];
    return viewModel;
}<commit_msg>Fixes to android sense download<commit_after>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you 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.
 */

function onRequest(context){
    var viewModel = {};
    var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
    viewModel.hostName = devicemgtProps["generalConfig"]["host"];
    return viewModel;
}<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
// Kind Control
//
// Displays and switches one tag kind on and off
////////////////////////////////////////////////////////////////////////////////
var controls = function (controls, $, data) {
	controls.kind = function (row, handler) {
		var self = Object.create(controls.control());

		self.data.row = row;
		self.data.handler = handler || function () {};

		//////////////////////////////
		// Overrides

		self.html = function () {
			var id = 'kind' + row.kind;
			return [
				'',
				'<input type="checkbox" id="', id, '"', !self.parent || !self.parent.hidden(row.kind) ? ' checked="checked"' : '', '/>',
				'', row.kind ? row.kind : "[default]", '',
				''
			].join('');
		};

		return self;
	};

	//////////////////////////////
	// Static event handlers

	// checkbox event handler
	// when checkbox or label is clicked
	function onChecked() {
		console.log('kind.onChecked()');

		var	$this = $(this),
				control = controls.lookup[$this.parent().attr('id')],
				row = control.data.row,
				handler = control.data.handler,
				checked = $this.attr('checked');
		handler(row.kind, checked);
	}

	// when tag background is clicked
	function onClick(event) {
		console.log('kind.onClick()');

		if (event.target === this) {
			var $this = $(this),
					control = controls.lookup[$this.attr('id')],
					row = control.data.row,
					handler = control.data.handler,
					$checkbox = $this.find(':checkbox'),
					checked = !$checkbox.attr('checked');
			$checkbox.attr('checked', checked);
			handler(row.kind, checked);
		}
	}

	$('.kind').live('click', onClick);
	$('.kind :checkbox').live('click', onChecked);

	return controls;
}(controls || {},
	jQuery,
	data);

<commit_msg>some debug code removed<commit_after>////////////////////////////////////////////////////////////////////////////////
// Kind Control
//
// Displays and switches one tag kind on and off
////////////////////////////////////////////////////////////////////////////////
var controls = function (controls, $, data) {
	controls.kind = function (row, handler) {
		var self = Object.create(controls.control());

		self.data.row = row;
		self.data.handler = handler || function () {};

		//////////////////////////////
		// Overrides

		self.html = function () {
			var id = 'kind' + row.kind;
			return [
				'',
				'<input type="checkbox" id="', id, '"', !self.parent || !self.parent.hidden(row.kind) ? ' checked="checked"' : '', '/>',
				'', row.kind ? row.kind : "[default]", '',
				''
			].join('');
		};

		return self;
	};

	//////////////////////////////
	// Static event handlers

	// checkbox event handler
	// when checkbox or label is clicked
	function onChecked() {
		var	$this = $(this),
				control = controls.lookup[$this.parent().attr('id')],
				row = control.data.row,
				handler = control.data.handler,
				checked = $this.attr('checked');
		handler(row.kind, checked);
	}

	// when tag background is clicked
	function onClick(event) {
		if (event.target === this) {
			var $this = $(this),
					control = controls.lookup[$this.attr('id')],
					row = control.data.row,
					handler = control.data.handler,
					$checkbox = $this.find(':checkbox'),
					checked = !$checkbox.attr('checked');
			$checkbox.attr('checked', checked);
			handler(row.kind, checked);
		}
	}

	$('.kind').live('click', onClick);
	$('.kind :checkbox').live('click', onChecked);

	return controls;
}(controls || {},
	jQuery,
	data);

<|endoftext|>