<commit_before>// Copyright 2017-2022, University of Colorado Boulder

/**
 * Runs the lint rules on the specified files.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Michael Kauzmann (PhET Interactive Simulations)
 */

// modules
const _ = require( 'lodash' ); // eslint-disable-line require-statement-match
const { ESLint } = require( 'eslint' ); // eslint-disable-line
const fs = require( 'fs' );
const grunt = require( 'grunt' );
const crypto = require( 'crypto' );
const chipAway = require( './chipAway' );
// constants
const EXCLUDE_PATTERNS = [ // patterns that have no code that should be linted

  '../babel',
  '../decaf',
  '../phet-android-app',
  '../phet-info',
  '../phet-io-client-guides',
  '../phet-io-website',
  '../phet-io-wrapper-arithmetic',
  '../phet-io-wrapper-hookes-law-energy',
  '../phet-ios-app',
  '../qa',
  '../smithers',
  '../tasks'
];

/**
 * Lints the specified repositories.
 * @public
 *
 * @returns {Promise} - results from linting files, see ESLint.lintFiles
 */
const lint = async ( patterns, options ) => {

  options = _.assignIn( {
    cache: true,
    format: false, // append an extra set of rules for formatting code.
    fix: false, // whether fixes should be written to disk
    warn: true, // whether errors should reported with grunt.warn
    typeInfo: false, // (for typescript) whether to include eslint rules that require project info, much slower
    chipAway: false // returns responsible dev info for easier chipping.
  }, options );

  // filter out all unlintable pattern. An unlintable repo is one that has no `js` in it, so it will fail when trying to
  // lint it.  Also, if the user doesn't have some repos checked out, those should be skipped
  patterns = patterns.filter( pattern => !EXCLUDE_PATTERNS.includes( pattern ) &&
                                         fs.existsSync( pattern ) );

  const hash = crypto.createHash( 'md5' )
    .update( patterns.join( ',' ) )
    .digest( 'hex' );

  const eslintConfig = {

    // optional auto-fix
    fix: options.fix,

    // Caching only checks changed files or when the list of rules is changed.  Changing the implementation of a
    // custom rule does not invalidate the cache.  Caches are declared in .eslintcache files in the directory where
    // grunt was run from.
    cache: options.cache,

    // Where to store the target-specific cache file
    cacheLocation: `../chipper/eslint/cache/${hash}.eslintcache`,

    ignorePath: '../chipper/eslint/.eslintignore',

    resolvePluginsRelativeTo: '../chipper/',

    // Our custom rules live here
    rulePaths: [ '../chipper/eslint/rules' ],

    extensions: [ '.js', '.jsx', '.ts', '.tsx' ]
  };

  const config = {};
  const configExtends = [];
  if ( options.format ) {
    configExtends.push( '../chipper/eslint/format_eslintrc.js' );
  }
  if ( options.typeInfo ) {
    if ( patterns.length !== 1 ) {
      grunt.fail.warn( 'typeInfo can only work for one repository at a time' );
    }

    // include the rules that use type information
    configExtends.push( '../chipper/eslint/type_info_eslintrc.js' );

    // signify where the project configuration lives for this repo - if we apply this to all files
    // ESLint complains that .js files are not in project configurations
    config.overrides = [ {
      files: [
        '**/*.ts'
      ],
      parserOptions: {
        project: [ `${patterns[ 0 ]}/tsconfig.json` ]
      }
    } ];
  }

  config.extends = configExtends;
  eslintConfig.baseConfig = config;

  const eslint = new ESLint( eslintConfig );

  grunt.verbose.writeln( `linting: ${patterns.join( ', ' )}` );

  // 2. Lint files. This doesn't modify target files.
  const results = await eslint.lintFiles( patterns );

  // 3. Modify the files with the fixed code.
  if ( options.fix ) {
    await ESLint.outputFixes( results );
  }

  // 4. Parse the results.
  const totalWarnings = _.sum( results.map( result => result.warningCount ) );
  const totalErrors = _.sum( results.map( result => result.errorCount ) );

  // 5. Output results on errors.
  if ( totalWarnings + totalErrors > 0 ) {
    const formatter = await eslint.loadFormatter( 'stylish' );
    const resultText = formatter.format( results );
    console.log( resultText );

    // The chip-away option provides a quick and easy method to assign devs to their respective repositories.
    // Check ./chipAway.js for more information.
    if ( options.chipAway ) {
      const message = chipAway( results );
      console.log( 'Results from chipAway: \n' + message );
    }

    options.warn && grunt.fail.warn( `${totalErrors} errors and ${totalWarnings} warnings` );
  }

  return results;
};

// Mark the version so that the pre-commit hook will only try to use the promise-based API, this means
// it won't run lint precommit hook on SHAs before the promise-based API
lint.chipperAPIVersion = 'promises1';

module.exports = lint;<commit_msg>typeInfo option points to tsconfig.eslint.json in overrides, see https://github.com/phetsims/chipper/issues/1238<commit_after>// Copyright 2017-2022, University of Colorado Boulder

/**
 * Runs the lint rules on the specified files.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Michael Kauzmann (PhET Interactive Simulations)
 */

// modules
const _ = require( 'lodash' ); // eslint-disable-line require-statement-match
const { ESLint } = require( 'eslint' ); // eslint-disable-line
const fs = require( 'fs' );
const grunt = require( 'grunt' );
const crypto = require( 'crypto' );
const chipAway = require( './chipAway' );
// constants
const EXCLUDE_PATTERNS = [ // patterns that have no code that should be linted

  '../babel',
  '../decaf',
  '../phet-android-app',
  '../phet-info',
  '../phet-io-client-guides',
  '../phet-io-website',
  '../phet-io-wrapper-arithmetic',
  '../phet-io-wrapper-hookes-law-energy',
  '../phet-ios-app',
  '../qa',
  '../smithers',
  '../tasks'
];

/**
 * Lints the specified repositories.
 * @public
 *
 * @returns {Promise} - results from linting files, see ESLint.lintFiles
 */
const lint = async ( patterns, options ) => {

  options = _.assignIn( {
    cache: true,
    format: false, // append an extra set of rules for formatting code.
    fix: false, // whether fixes should be written to disk
    warn: true, // whether errors should reported with grunt.warn
    typeInfo: false, // (for typescript) whether to include eslint rules that require project info, much slower
    chipAway: false // returns responsible dev info for easier chipping.
  }, options );

  // filter out all unlintable pattern. An unlintable repo is one that has no `js` in it, so it will fail when trying to
  // lint it.  Also, if the user doesn't have some repos checked out, those should be skipped
  patterns = patterns.filter( pattern => !EXCLUDE_PATTERNS.includes( pattern ) &&
                                         fs.existsSync( pattern ) );

  const hash = crypto.createHash( 'md5' )
    .update( patterns.join( ',' ) )
    .digest( 'hex' );

  const eslintConfig = {

    // optional auto-fix
    fix: options.fix,

    // Caching only checks changed files or when the list of rules is changed.  Changing the implementation of a
    // custom rule does not invalidate the cache.  Caches are declared in .eslintcache files in the directory where
    // grunt was run from.
    cache: options.cache,

    // Where to store the target-specific cache file
    cacheLocation: `../chipper/eslint/cache/${hash}.eslintcache`,

    ignorePath: '../chipper/eslint/.eslintignore',

    resolvePluginsRelativeTo: '../chipper/',

    // Our custom rules live here
    rulePaths: [ '../chipper/eslint/rules' ],

    extensions: [ '.js', '.jsx', '.ts', '.tsx' ]
  };

  const config = {};
  const configExtends = [];
  if ( options.format ) {
    configExtends.push( '../chipper/eslint/format_eslintrc.js' );
  }
  if ( options.typeInfo ) {
    if ( patterns.length !== 1 ) {
      grunt.fail.warn( 'typeInfo can only work for one repository at a time' );
    }

    // include the rules that use type information
    configExtends.push( '../chipper/eslint/type_info_eslintrc.js' );

    // signify where the project configuration lives for this repo - if we apply this to all files
    // ESLint complains that .js files are not in project configurations
    config.overrides = [ {
      files: [
        '**/*.ts'
      ],
      parserOptions: {
        project: [ '../chipper/eslint/tsconfig.eslint.json' ]
      }
    } ];
  }

  config.extends = configExtends;
  eslintConfig.baseConfig = config;

  const eslint = new ESLint( eslintConfig );

  grunt.verbose.writeln( `linting: ${patterns.join( ', ' )}` );

  // 2. Lint files. This doesn't modify target files.
  const results = await eslint.lintFiles( patterns );

  // 3. Modify the files with the fixed code.
  if ( options.fix ) {
    await ESLint.outputFixes( results );
  }

  // 4. Parse the results.
  const totalWarnings = _.sum( results.map( result => result.warningCount ) );
  const totalErrors = _.sum( results.map( result => result.errorCount ) );

  // 5. Output results on errors.
  if ( totalWarnings + totalErrors > 0 ) {
    const formatter = await eslint.loadFormatter( 'stylish' );
    const resultText = formatter.format( results );
    console.log( resultText );

    // The chip-away option provides a quick and easy method to assign devs to their respective repositories.
    // Check ./chipAway.js for more information.
    if ( options.chipAway ) {
      const message = chipAway( results );
      console.log( 'Results from chipAway: \n' + message );
    }

    options.warn && grunt.fail.warn( `${totalErrors} errors and ${totalWarnings} warnings` );
  }

  return results;
};

// Mark the version so that the pre-commit hook will only try to use the promise-based API, this means
// it won't run lint precommit hook on SHAs before the promise-based API
lint.chipperAPIVersion = 'promises1';

module.exports = lint;<|endoftext|>


<commit_before>var map;
var infowindow;
var service;
var userPosition;
var idCounter = 0;
var idCounterTwo = 0;
var listArray = new Array();
var listTwoArray = new Array();
var searchBox;
var isGetLocationChecked = false;

/*
* Funktion som initiera Google Maps kartan och tar redan
*/

function initMap() {
	map = new google.maps.Map(document.getElementById('map'), {
	  center: {lat: 55.5916628, lng: 12.9875187},
	  zoom: 12,
      scrollwheel: false
	});

	service = new google.maps.places.PlacesService(map);
	infowindow = new google.maps.InfoWindow();
	autoCompleteFunction();
}

function autoCompleteFunction(){
// Create the search box and link it to the UI element.
  var input = document.getElementById('pac-input');
  searchBox = new google.maps.places.Autocomplete(input);

  // Bias the SearchBox results towards current map's viewport.
  map.addListener('bounds_changed', function() {
    searchBox.setBounds(map.getBounds());
  });

  //var markers = [];
}

/*
* Funktion som triggras när man klickar på Get Location knappen
* funktionen tar reda på användarens position
*/
$("#getLocationBtn").click(function() {

	var location_timeout = setTimeout("geolocFail()", 10000);
	document.getElementById('getLocationBtn').innerHTML= "Loading...  ";

	if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position){
			clearTimeout(location_timeout);
			userPosition = {lat:position.coords.latitude, lng: position.coords.longitude};
			console.log(userPosition);
			makeSearch(userPosition);
            document.getElementById('getLocationBtn').innerHTML= "Got it ✓";
			if (position){
				var button = document.querySelector("#searchBtn")
				button.className = "btn btn-dark btn-lg activated";
				isGetLocationChecked = true;
			}
			document.getElementById('resultFromAPI').innerHTML= " ";
			document.getElementById('resultTwoFromAPI').innerHTML= " ";
		},function(error) {
            document.getElementById('getLocationBtn').innerHTML= "Access denied   ✖";
            clearTimeout(location_timeout);
		});
	} else {
        document.getElementById('getLocationBtn').innerHTML= "Geolocation not supported";
        alert("Geolocation is not supported by this browser.");
    }
});

$("#searchBtn").click(function(){

	if($('#pac-input').val().length != 0){
        document.getElementById('resultFromAPI').innerHTML= " ";
        document.getElementById('resultTwoFromAPI').innerHTML= " ";
		var place = searchBox.getPlace();
		var latitude = place.geometry.location.lat();
		var longitude = place.geometry.location.lng();
		var location = {lat: latitude, lng: longitude};
		makeSearch(location);
		show();
		$('html, body').animate({
            scrollTop: $("#portfolio").offset().top
    	}, 2000);
			document.getElementById('pac-input').value= "";
	}else if(isGetLocationChecked == true){
		show();
		$('html, body').animate({
            scrollTop: $("#portfolio").offset().top
		}, 2000);
	}else{
		alert("Something went wrong, please write in your adress or get your location!");
	}
});

function showSearch(){
    var pacCard = document.querySelector("#pac-card");
    pacCard.className = "pac-card visShow";
}

/*
* Funktion som gör sökningen av närliggande resturanger från användarens position
*/
function makeSearch(userPosition){
	var userPos = userPosition;
	console.log(userPosition);
	var request = {
		location: userPos,
	  	radius: 1000,
	  	type: ['restaurant'],
		opennow: true
	}
	service.nearbySearch(request, callback);

}

/*
* Funktion som tar emot närliggande resturanger ifrån APIn
*/
function callback(results, status) {
	console.log(status);
	console.log(results);
    $("resultsFromAPI").text(" ");
	if (status === google.maps.places.PlacesServiceStatus.OK) {
		for (var i = 0; i < results.length; i++) {
			if (i <= 9) {
				$("#resultFromAPI").append('' + results[i].name + '');
				var restaurantSection = document.querySelector("#portfolio");
				restaurantSection.className = "show";
				listArray.push(results[i]);
				idCounter++;
            } else {
                $("#resultTwoFromAPI").append('' + results[i].name + '');
                listTwoArray.push(results[i]);
                idCounterTwo++;
            }
        }
		createUserMarker();
	}
}

/*
* Funktion som skapar markern för användarens position i kartan
*/
function createUserMarker(){
	var userMarker = new google.maps.Marker({
		position: userPosition,
		map: map,
		title: 'Din position',
		icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png'
	});

	google.maps.event.addListener(userMarker, 'click', function() {
		infowindow.setContent("Your position");
		infowindow.open(map, this);
	});
}

/*
* Funktion som triggas när man klickar på ett resturangnamn i listan
* funktionen tar reda på vilken resturang man har klickat
*/
$('#resultFromAPI').on('click', '.selectedRestaurang', function(){
	console.log(this.id);
	console.log(listArray[this.id]);
	var currentId = listArray[this.id];
	createMarker(currentId);
	$('html, body').animate({
        scrollTop: $("#contact").offset().top
    }, 2000);
});
$('#resultTwoFromAPI').on('click', '.selectedRestaurang', function(){
	console.log(this.id);
	console.log(listTwoArray[this.id]);
	var currentId = listTwoArray[this.id];
	createMarker(currentId);
	$('html, body').animate({
        scrollTop: $("#contact").offset().top
    }, 2000);
});

/*
* Funktion som sätter ut en marker för en vald resturang
* Visar även detljer för varje resturang i liten ruta när
* man klickar på en ikon
*/

function createMarker(place) {
	var los = place.geometry.location;
	var infowindow = new google.maps.InfoWindow({ map: map });
    infowindow.close();
	var marker = new google.maps.Marker({
	  map: map,
	  position: place.geometry.location
	});

	marker.addListener('click', function(){
		var request = {
			reference: place.reference
		};
		service.getDetails(request, function(details, status) {
			console.log(details)
			infowindow.setContent([
			details.name,
			details.formatted_address,
			'' + details.website + '',
			details.opening_hours.weekday_text[0],
			details.opening_hours.weekday_text[1],
			details.opening_hours.weekday_text[2],
			details.opening_hours.weekday_text[3],
			details.opening_hours.weekday_text[4],
			details.opening_hours.weekday_text[5],
			details.opening_hours.weekday_text[6],
			'Betyg: ' + details.rating,
			details.formatted_phone_number].join("
"));
		  infowindow.open(map, marker);

		});
	})

	map.setZoom(15);
	map.panTo(marker.position);
}

// ----- DÖLJER ALLT UTOM FÖRSTASIDAN I FÖRSTA LÄGET & VISAR ALLT NÄR MAN TRYCKER PÅ SÖK -----

function show(){
    var menuSection = document.querySelector(".menu");
		var portfolio = document.querySelector("#portfolio");
    var mapSection = document.querySelector("#contact");
    var footerSection = document.querySelector("#footer");
		var map = document.querySelector("#map")

    menuSection.className = "visShow";
		portfolio.className = "show"
    mapSection.className = "show";
    footerSection.className = "show";
		map.className ="show"

		$(document).ready(function() {
    $(window).resize(function() {
        google.maps.event.trigger(map, 'resize');
    });
    google.maps.event.trigger(map, 'resize');
});

}
<commit_msg>Made if statement<commit_after>var map;
var infowindow;
var service;
var userPosition;
var idCounter = 0;
var idCounterTwo = 0;
var listArray = new Array();
var listTwoArray = new Array();
var searchBox;
var isGetLocationChecked = false;
var userMarker;

/*
* Funktion som initiera Google Maps kartan och tar redan
*/

function initMap() {
	map = new google.maps.Map(document.getElementById('map'), {
	  center: {lat: 55.5916628, lng: 12.9875187},
	  zoom: 12,
      scrollwheel: false
	});

	service = new google.maps.places.PlacesService(map);
	infowindow = new google.maps.InfoWindow();
	autoCompleteFunction();
}

function autoCompleteFunction(){
// Create the search box and link it to the UI element.
  var input = document.getElementById('pac-input');
  searchBox = new google.maps.places.Autocomplete(input);

  // Bias the SearchBox results towards current map's viewport.
  map.addListener('bounds_changed', function() {
    searchBox.setBounds(map.getBounds());
  });

  //var markers = [];
}

/*
* Funktion som triggras när man klickar på Get Location knappen
* funktionen tar reda på användarens position
*/
$("#getLocationBtn").click(function() {

	var location_timeout = setTimeout("geolocFail()", 10000);
	document.getElementById('getLocationBtn').innerHTML= "Loading...  ";

	if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(position){
			clearTimeout(location_timeout);
			userPosition = {lat:position.coords.latitude, lng: position.coords.longitude};
			console.log(userPosition);
			makeSearch(userPosition);
            document.getElementById("getLocationBtn").innerHTML= "Got it ✓";
			if (position){
				var button = document.querySelector("#searchBtn");
				button.className = "btn btn-dark btn-lg activated";
				isGetLocationChecked = true;
			}
			document.getElementById('resultFromAPI').innerHTML= " ";
			document.getElementById('resultTwoFromAPI').innerHTML= " ";
		},function(error) {
            document.getElementById('getLocationBtn').innerHTML= "Access denied   ✖";
            clearTimeout(location_timeout);
		});
	} else {
        document.getElementById('getLocationBtn').innerHTML= "Geolocation not supported";
        alert("Geolocation is not supported by this browser.");
    }
});

$("#searchBtn").click(function(){

	if($('#pac-input').val().length != 0){
        document.getElementById('resultFromAPI').innerHTML= " ";
        document.getElementById('resultTwoFromAPI').innerHTML= " ";
		var place = searchBox.getPlace();
		var latitude = place.geometry.location.lat();
		var longitude = place.geometry.location.lng();
		var location = {lat: latitude, lng: longitude};
		makeSearch(location);
		show();
		$('html, body').animate({
            scrollTop: $("#portfolio").offset().top
    	}, 2000);
			document.getElementById('pac-input').value= "";
	}else if(isGetLocationChecked == true){
		show();
		$('html, body').animate({
            scrollTop: $("#portfolio").offset().top
		}, 2000);
	}else{
		alert("Something went wrong, please write in your adress or get your location!");
	}
});

function showSearch(){
    var pacCard = document.querySelector("#pac-card");
    pacCard.className = "pac-card visShow";
}

/*
* Funktion som gör sökningen av närliggande resturanger från användarens position
*/
function makeSearch(userPosition){
	var userPos = userPosition;
	console.log(userPosition);
	var request = {
		location: userPos,
	  	radius: 1000,
	  	type: ['restaurant'],
		opennow: true
	};
	service.nearbySearch(request, callback);

}

/*
* Funktion som tar emot närliggande resturanger ifrån APIn
*/
function callback(results, status) {
	console.log(status);
	console.log(results);
    $("resultsFromAPI").text(" ");
	if (status === google.maps.places.PlacesServiceStatus.OK) {
		for (var i = 0; i < results.length; i++) {
			if (i <= 9) {
				$("#resultFromAPI").append('' + results[i].name + '');
				var restaurantSection = document.querySelector("#portfolio");
				restaurantSection.className = "show";
				listArray.push(results[i]);
				idCounter++;
            } else {
                $("#resultTwoFromAPI").append('' + results[i].name + '');
                listTwoArray.push(results[i]);
                idCounterTwo++;
            }
        }
		createUserMarker();
	}
}

/*
* Funktion som skapar markern för användarens position i kartan
*/
function createUserMarker(){
	if (userMarker){
		alert("USERMARKER FINNS")
	}
	userMarker = new google.maps.Marker({
		position: userPosition,
		map: map,
		title: 'Din position',
		icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png'
	});

	google.maps.event.addListener(userMarker, 'click', function() {
		infowindow.setContent("Your position");
		infowindow.open(map, this);
	});
}

/*
* Funktion som triggas när man klickar på ett resturangnamn i listan
* funktionen tar reda på vilken resturang man har klickat
*/
$('#resultFromAPI').on('click', '.selectedRestaurang', function(){
	console.log(this.id);
	console.log(listArray[this.id]);
	var currentId = listArray[this.id];
	createMarker(currentId);
	$('html, body').animate({
        scrollTop: $("#contact").offset().top
    }, 2000);
});
$('#resultTwoFromAPI').on('click', '.selectedRestaurang', function(){
	console.log(this.id);
	console.log(listTwoArray[this.id]);
	var currentId = listTwoArray[this.id];
	createMarker(currentId);
	$('html, body').animate({
        scrollTop: $("#contact").offset().top
    }, 2000);
});

/*
* Funktion som sätter ut en marker för en vald resturang
* Visar även detljer för varje resturang i liten ruta när
* man klickar på en ikon
*/

function createMarker(place) {
	var los = place.geometry.location;
	var infowindow = new google.maps.InfoWindow({ map: map });
    infowindow.close();
	var marker = new google.maps.Marker({
	  map: map,
	  position: place.geometry.location
	});

	marker.addListener('click', function(){
		var request = {
			reference: place.reference
		};
		service.getDetails(request, function(details, status) {
			console.log(details)
			infowindow.setContent([
			details.name,
			details.formatted_address,
			'' + details.website + '',
			details.opening_hours.weekday_text[0],
			details.opening_hours.weekday_text[1],
			details.opening_hours.weekday_text[2],
			details.opening_hours.weekday_text[3],
			details.opening_hours.weekday_text[4],
			details.opening_hours.weekday_text[5],
			details.opening_hours.weekday_text[6],
			'Betyg: ' + details.rating,
			details.formatted_phone_number].join("
"));
		  infowindow.open(map, marker);

		});
	})

	map.setZoom(15);
	map.panTo(marker.position);
}

// ----- DÖLJER ALLT UTOM FÖRSTASIDAN I FÖRSTA LÄGET & VISAR ALLT NÄR MAN TRYCKER PÅ SÖK -----

function show(){
    var menuSection = document.querySelector(".menu");
		var portfolio = document.querySelector("#portfolio");
    var mapSection = document.querySelector("#contact");
    var footerSection = document.querySelector("#footer");
		var map = document.querySelector("#map")

    menuSection.className = "visShow";
		portfolio.className = "show"
    mapSection.className = "show";
    footerSection.className = "show";
		map.className ="show"

		$(document).ready(function() {
    $(window).resize(function() {
        google.maps.event.trigger(map, 'resize');
    });
    google.maps.event.trigger(map, 'resize');
});

}
<|endoftext|>


<commit_before>var stildosyasi=document.createElement("link");
stildosyasi.setAttribute("rel", "stylesheet");
stildosyasi.setAttribute("type", "text/css");
stildosyasi.setAttribute("href", "http://e-mete.com/css/bildirim.css");
document.getElementsByTagName("head")[0].appendChild(stildosyasi);
function bildirim(mesaj,tur){
	var iDiv = document.createElement('div');
	var turler = ["kdtoast hata","kdtoast basari","kdtoast","kdtoast"];
	iDiv.className = turler[tur];
	document.getElementsByTagName('body')[0].appendChild(iDiv);
	iDiv.innerHTML=mesaj;
	if(tur >= 2){
	setTimeout(function(){ iDiv.parentNode.removeChild(iDiv); }, 4000);
	}
	else{
		if(tur == 4){
		setTimeout(function(){ iDiv.parentNode.removeChild(iDiv); }, 16000);
		}
	var te = iDiv.getElementsByTagName("A");
	te[te.length - 1].onclick=function(){
	iDiv.parentNode.removeChild(iDiv);
	}
	}
	}
function bildirimkapat(elem){
	if(elem.href.length >= 5){
		window.open(elem.href,'');
	}
	event.preventDefault();
	var maq = document.querySelectorAll(".kdtoast");
	[].forEach.call(maq, function(bild) {
		bild.parentNode.removeChild(bild);
});
}
<commit_msg>Update kdbildirim.js<commit_after>var stildosyasi=document.createElement("link");
stildosyasi.setAttribute("rel", "stylesheet");
stildosyasi.setAttribute("type", "text/css");
stildosyasi.setAttribute("href", "http://e-mete.com/css/bildirim.css");
document.getElementsByTagName("head")[0].appendChild(stildosyasi);
function bildirim(mesaj,tur){
	var iDiv = document.createElement('div');
	var turler = ["kdtoast hata","kdtoast basari","kdtoast","kdtoast","kdtoast"];
	iDiv.className = turler[tur];
	document.getElementsByTagName('body')[0].appendChild(iDiv);
	iDiv.innerHTML=mesaj;
	if(tur <= 2){
	setTimeout(function(){ iDiv.parentNode.removeChild(iDiv); }, 4000);
	}
	else{
		if(tur == 4){
		setTimeout(function(){ iDiv.parentNode.removeChild(iDiv); }, 16000);
		}
	var te = iDiv.getElementsByTagName("A");
	te[te.length - 1].onclick=function(){
	iDiv.parentNode.removeChild(iDiv);
	}
	}
	}
function bildirimkapat(elem){
	if(elem.href.length >= 5){
		window.open(elem.href,'');
	}
	event.preventDefault();
	var maq = document.querySelectorAll(".kdtoast");
	[].forEach.call(maq, function(bild) {
		bild.parentNode.removeChild(bild);
});
}
<|endoftext|>


<commit_before>"use strict";

// Stages
var nextStage = false;
var minionTime = false;
var bossTime = true;
var round = 0;
var playerEnd = false;

var test = true;
var spawn = true;

var playerReset = [false, false];
var resetInital = true;

var soundPlayed = false;

var update = function (game, audio) {
    // Calls the update function for all objects
	[game.world.platforms,
        game.world.bullets
	].forEach (
		function(gameElementArray) {
			gameElementArray.forEach(function(gameElement) {
				gameElement.update();
			});
		}
	);

    // Calls update for player function
    for (var i = 0; i < game.world.controllers.length; i++) {
        game.world.controllers[i].update();
        if (game.world.controllers[i].buttonSelect) {
            playerReset[i] = true;
        } else {
            playerReset[i] = false;
        }
    }

    if (playerReset[0] && playerReset[1]) {
        soundPlayed = false;
        console.log("reseting . . .");
        game.world.players.forEach(function(player) {
            player.active = false;
        });
        game.world.addPlayer(new Player(game.world, Bullet, game.audio, game.controllerOne, {
            x : game.world.width / 20,
            y : game.world.height / 2,
            type : "playerOne",
            direction : "right",
            healthX : 50,
            percent : game.paramsOne.percent,
            result : game.paramsOne.result,
            walking : "walking1",
            shield : "shield1",
            sprite : "connor"
        }));
        game.world.addPlayer(new Player(game.world, Bullet, game.audio, game.controllerTwo, {
            x : game.world.width * 17 / 20,
            y : game.world.height / 2,
            type : "playerTwo",
            direction : "left",
            healthX : 350,
            percent : game.paramsTwo.percent,
            result : game.paramsTwo.result,
            walking : "walking2",
            shield : "shield2",
            sprite : "evilConnor"
        }));

        game.world.died = false;
        console.log("reset");
        for (var i = 0; i < playerReset.length; i++) {
            playerReset[i] = false;
        };
        game.audio["reset1"].setVolume(80);
        game.audio["reset1"].play();
        /*
        if (game.audio["reset1"].isEnded() && game.audio["reset2"].isEnded()) {
            if (resetInital) {
                game.audio["reset1"].play();
                resetTime = false;
            } else {
                game.audio["reset2"].play();
                resetTime = true;
            }
        }
        */
    }

    game.world.players.forEach( function(player) {
        player.update();
        if (player.reachEnd === true) {
            playerEnd = true;
        }
    });

    // Filters inactive objects
    game.world.players = game.world.players.filter(function(player) {
        return player.active;
    });

	game.world.platforms = game.world.platforms.filter(function(platform) {
		return platform.active;
	});

    game.world.bullets = game.world.bullets.filter(function(bullet) {
        return bullet.active;
    });

    // Start of the level layout
    if (playerEnd === true) {
        game.world.end = true;
    } else if (game.world.players.length < 2) {
        game.world.died = true;
        if (!soundPlayed) {
            //buzz.all().setVolume(10);
            game.audio["gameover"].setVolume(100);
            game.audio["gameover"].play();
            //buzz.all().setVolume(20);
            soundPlayed = true;
        }
    } else if (spawn) {
        // The floor
        game.world.platforms.push (new Platform(game.world, {
            x: 0,
            y: game.world.height - 30,
            width: game.world.width,
            height: 200
        }));

        // Platforms
        /*
        game.world.platforms.push(new Platform(game.world, {
			x: 175,
			y: 250,
		}));
		game.world.platforms.push(new Platform(game.world, {
			x: 375,
			y: 250,
		}));
		game.world.platforms.push(new Platform(game.world, {
			x: 130,
			y: 196,
		}));
		game.world.platforms.push(new Platform(game.world, {
			x: 420,
			y: 196,
		}));
        game.world.platforms.push(new Platform(game.world, {
            x: 130,
            y: 140
        }));
        game.world.platforms.push(new Platform(game.world, {
            x: 420,
            y: 140
        }));
        game.world.platforms.push(new Platform(game.world, {
            x: 175,
            y: 83
        }));
        game.world.platforms.push(new Platform(game.world, {
            x: 375,
            y: 83
        }));
        game.world.platforms.push(new Platform(game.world, {
            x: 275,
            y: 83
        }));
        */

        spawn = false;
	}

};
<commit_msg>fixed restart button<commit_after>"use strict";

// Stages
var nextStage = false;
var minionTime = false;
var bossTime = true;
var round = 0;
var playerEnd = false;

var test = true;
var spawn = true;

var playerReset = [false, false];
var resetInital = true;

var soundPlayed = false;

var update = function (game, audio) {
    // Calls the update function for all objects
	[game.world.platforms,
        game.world.bullets
	].forEach (
		function(gameElementArray) {
			gameElementArray.forEach(function(gameElement) {
				gameElement.update();
			});
		}
	);

    // Calls update for player function
    for (var i = 0; i < game.world.controllers.length; i++) {
        game.world.controllers[i].update();
        if (game.world.controllers[i].buttonSelect) {
            playerReset[i] = true;
        } else {
            playerReset[i] = false;
        }
    }

    if (playerReset[0] && playerReset[1]) {
        soundPlayed = false;
        console.log("reseting . . .");
        game.world.players.forEach(function(player) {
            player.active = false;
        });
        game.world.addPlayer(new Player(game.world, Bullet, game.audio, game.controllerOne, {
            x : game.world.width / 20,
            y : game.world.height / 2,
            type : "playerOne",
            direction : "right",
            healthX : 50,
            percent : game.paramsOne.percent,
            result : game.paramsOne.result,
            walking : "walking1",
            shield : "shield1",
            punch : "punch1",
            hitStart : 1,
            hitEnd : 4,
            fireball : "fireball1",
            sprite : "connor"
        }));
        game.world.addPlayer(new Player(game.world, Bullet, game.audio, game.controllerTwo, {
            x : game.world.width * 17 / 20,
            y : game.world.height / 2,
            type : "playerTwo",
            direction : "left",
            healthX : 350,
            percent : game.paramsTwo.percent,
            result : game.paramsTwo.result,
            walking : "walking2",
            shield : "shield2",
            punch : "punch2",
            hitStart : 4,
            hitEnd : 7,
            fireball : "fireball2",
            sprite : "evilConnor"
        }));

        game.world.died = false;
        console.log("reset");
        for (var i = 0; i < playerReset.length; i++) {
            playerReset[i] = false;
        };
        game.audio["reset1"].setVolume(80);
        game.audio["reset1"].play();
        /*
        if (game.audio["reset1"].isEnded() && game.audio["reset2"].isEnded()) {
            if (resetInital) {
                game.audio["reset1"].play();
                resetTime = false;
            } else {
                game.audio["reset2"].play();
                resetTime = true;
            }
        }
        */
    }

    game.world.players.forEach( function(player) {
        player.update();
        if (player.reachEnd === true) {
            playerEnd = true;
        }
    });

    // Filters inactive objects
    game.world.players = game.world.players.filter(function(player) {
        return player.active;
    });

	game.world.platforms = game.world.platforms.filter(function(platform) {
		return platform.active;
	});

    game.world.bullets = game.world.bullets.filter(function(bullet) {
        return bullet.active;
    });

    // Start of the level layout
    if (playerEnd === true) {
        game.world.end = true;
    } else if (game.world.players.length < 2) {
        game.world.died = true;
        if (!soundPlayed) {
            //buzz.all().setVolume(10);
            game.audio["gameover"].setVolume(100);
            game.audio["gameover"].play();
            //buzz.all().setVolume(20);
            soundPlayed = true;
        }
    } else if (spawn) {
        // The floor
        game.world.platforms.push (new Platform(game.world, {
            x: 0,
            y: game.world.height - 30,
            width: game.world.width,
            height: 200
        }));

        // Platforms
        /*
        game.world.platforms.push(new Platform(game.world, {
			x: 175,
			y: 250,
		}));
		game.world.platforms.push(new Platform(game.world, {
			x: 375,
			y: 250,
		}));
		game.world.platforms.push(new Platform(game.world, {
			x: 130,
			y: 196,
		}));
		game.world.platforms.push(new Platform(game.world, {
			x: 420,
			y: 196,
		}));
        game.world.platforms.push(new Platform(game.world, {
            x: 130,
            y: 140
        }));
        game.world.platforms.push(new Platform(game.world, {
            x: 420,
            y: 140
        }));
        game.world.platforms.push(new Platform(game.world, {
            x: 175,
            y: 83
        }));
        game.world.platforms.push(new Platform(game.world, {
            x: 375,
            y: 83
        }));
        game.world.platforms.push(new Platform(game.world, {
            x: 275,
            y: 83
        }));
        */

        spawn = false;
	}

};
<|endoftext|>


<commit_before>var fs = require('fs');
var Conf = require('../conf.js');

createLogLine = function(event,languages,session){
    var message =  {
        time: new Date().toString(),
        action: event,
        chatId : session.chatId,
        firstName : session.firstName
    };
    if(event == "get" && languages.length > 0){
        message.show = session.choosenSeries.show.name;
        message.season =  session.choosenSeason;
        message.episode =  session.choosenEpisode;
        message.lang = languages;
    }else{
        message.show =  session.choosenSeriesAlert.show.name;
        message.lang = [];
        session.chosenLanguagesAlert.forEach(function(element) {
            message.lang.push(element);
        });
    }
    return JSON.stringify(message);
}

exports.logEvent = function(event, languages, session){
    fs.exists(Conf.logFile, function (exists) {
        if (exists) {
            fs.appendFile(Conf.logFile, this.createLogLine(event,languages,session), function (err) {
                if (err) return console.log(err);
            });
        }
    });
}<commit_msg>commented logger because bugged<commit_after>var fs = require('fs');
var Conf = require('../conf.js');

createLogLine = function(event,languages,session){
    var message =  {
        time: new Date().toString(),
        action: event,
        chatId : session.chatId,
        firstName : session.firstName
    };
    if(event == "get" && languages.length > 0){
        message.show = session.choosenSeries.show.name;
        message.season =  session.choosenSeason;
        message.episode =  session.choosenEpisode;
        message.lang = languages;
    }else{
        // message.show =  session.choosenSeriesAlert.show.name;
        // message.lang = [];
        // session.chosenLanguagesAlert.forEach(function(element) {
        //     message.lang.push(element);
        // });
    }
    return JSON.stringify(message);
}

exports.logEvent = function(event, languages, session){
    fs.exists(Conf.logFile, function (exists) {
        if (exists) {
            fs.appendFile(Conf.logFile, this.createLogLine(event,languages,session), function (err) {
                if (err) return console.log(err);
            });
        }
    });
}<|endoftext|>


<commit_before>var orientation = 0;

var setOrientation = function(i) {
	orientation = i;

	var clickedOrientation = $("#orientation" + i);
	var otherOrientation = $("#orientation" + (3-i));

	clickedOrientation.css("opacity", "1.0");
	otherOrientation.css("opacity", "0.75");

	clickedOrientation.off("mouseenter mouseleave");
	otherOrientation.mouseenter(function() {
		$(this).css("opacity", "0.90");
	});
	otherOrientation.mouseleave(function() {
		$(this).css("opacity", "0.75");
	});
}

var errorHTML = function(msg) {
	return '
ERROR: ' + msg + '
';
}

var transitionBody = function(html, time) {
		var body = $("#body");

		body.fadeOut(time);
		setTimeout(function() {
			body.html(html);
			body.fadeIn(time);
		}, time);

}

var scoutMatch = function() {

	var html = "";

	if (orientation < 1) {
		html = errorHTML("Must Select An Orientation");
		html += '
';
		html += '
Scout Match
';
		html += '
';
		$("#scoutMatch").html(html);
	} else {
		html = '
';
		html += '

';
		html += '
';
		html += '
Orientation ' + orientation + ' Selected
';
		html += '
';
		html += '

';
		html += '
';

		transitionBody(html, 500);
	}

}<commit_msg>push from sublime text<commit_after>var main = {
	orientation: 0
}

var setOrientation = function(i) {
	main.orientation = i;

	alert("orientation: " + main.orientation + "\ni: " + i);

	var clickedOrientation = $("#orientation" + i);
	var otherOrientation = $("#orientation" + (3-i));

	clickedOrientation.css("opacity", "1.0");
	otherOrientation.css("opacity", "0.75");

	clickedOrientation.off("mouseenter mouseleave");
	otherOrientation.mouseenter(function() {
		$(this).css("opacity", "0.90");
	});
	otherOrientation.mouseleave(function() {
		$(this).css("opacity", "0.75");
	});
}

var errorHTML = function(msg) {
	return '
ERROR: ' + msg + '
';
}

var transitionBody = function(html, time) {
		var body = $("#body");

		body.fadeOut(time);
		setTimeout(function() {
			body.html(html);
			body.fadeIn(time);
		}, time);

}

var scoutMatch = function() {

	var html = "";

	if (main.orientation < 1) {
		html = errorHTML("Must Select An Orientation");
		html += '
';
		html += '
Scout Match
';
		html += '
';
		$("#scoutMatch").html(html);
	} else {
		html = '
';
		html += '

';
		html += '
';
		html += '
Orientation ' + main.orientation + ' Selected
';
		html += '
';
		html += '

';
		html += '
';

		transitionBody(html, 500);
	}

}
<|endoftext|>


<commit_before>// Copyright 2002-2013, University of Colorado

/**
 * HBox arranges the child nodes horizontally, and they can be centered, left or right justified.
 * Horizontal spacing can be set as a constant or a function which depends on the adjacent nodes.
 * TODO: add an option (not enabled by default) to update layout when children or children bounds change
 *
 * @author Sam Reid
 */

define( function( require ) {
  'use strict';

  var scenery = require( 'SCENERY/scenery' );
  var Node = require( 'SCENERY/nodes/Node' );
  var objectCreate = require( 'SCENERY/util/Util' ).objectCreate; // i.e. Object.create

  /**
   *
   * @param options Same as Node.constructor.options with the following additions:
   *
   * spacing: can be a number or a function.  If a number, then it will be the vertical spacing between each object.
   *              If a function, then the function will have the signature function(top,bottom){} which returns the spacing between adjacent pairs of items.
   * align:   How to line up the items horizontally.  One of 'center', 'left' or 'right'.  Defaults to 'center'.
   *
   * @constructor
   */
  scenery.HBox = function HBox( options ) {
    // ensure we have a parameter object
    this.options = options = _.extend( {
      // defaults
      spacing: function() { return 0; },
      align: 'center'
    }, options );

    if ( typeof options.spacing === 'number' ) {
      var spacingConstant = options.spacing;
      options.spacing = function() { return spacingConstant; };
    }

    Node.call( this, options );
    this.updateLayout();
  };
  var HBox = scenery.HBox;

  HBox.prototype = objectCreate( Node.prototype );

  HBox.prototype.updateLayout = function() {
    var minY = _.min( _.map( this.children, function( child ) {return child.top;} ) );
    var maxY = _.max( _.map( this.children, function( child ) {return child.top + child.height;} ) );
    var centerY = (maxY + minY) / 2;

    //Start at x=0 in the coordinate frame of this node.  Not possible to set this through the spacing option, instead just set it with the {y:number} option.
    var x = 0;
    for ( var i = 0; i < this.children.length; i++ ) {
      var child = this.children[i];
      child.left = x;

      //Set the position horizontally
      if ( this.options.align === 'top' ) {
        child.top = minY;
      }
      else if ( this.options.align === 'bottom' ) {
        child.bottom = maxY;
      }
      else {//default to center
        child.centerY = centerY;
      }

      //Move to the next vertical position.
      x += child.width + this.options.spacing( child, this.children[i + 1] );
    }
  };
  HBox.prototype.constructor = HBox;

  return HBox;
} );
<commit_msg>In HBox, call mutate at the end of the constructor to fix layout problems specified with options<commit_after>// Copyright 2002-2013, University of Colorado Boulder

/**
 * HBox arranges the child nodes horizontally, and they can be centered, left or right justified.
 * Horizontal spacing can be set as a constant or a function which depends on the adjacent nodes.
 * TODO: add an option (not enabled by default) to update layout when children or children bounds change
 *
 * @author Sam Reid
 */

define( function( require ) {
  'use strict';

  var scenery = require( 'SCENERY/scenery' );
  var Node = require( 'SCENERY/nodes/Node' );
  var objectCreate = require( 'SCENERY/util/Util' ).objectCreate; // i.e. Object.create

  /**
   *
   * @param options Same as Node.constructor.options with the following additions:
   *
   * spacing: can be a number or a function.  If a number, then it will be the vertical spacing between each object.
   *              If a function, then the function will have the signature function(top,bottom){} which returns the spacing between adjacent pairs of items.
   * align:   How to line up the items horizontally.  One of 'center', 'left' or 'right'.  Defaults to 'center'.
   *
   * @constructor
   */
  scenery.HBox = function HBox( options ) {
    // ensure we have a parameter object
    this.options = options = _.extend( {
      // defaults
      spacing: function() { return 0; },
      align: 'center'
    }, options );

    if ( typeof options.spacing === 'number' ) {
      var spacingConstant = options.spacing;
      options.spacing = function() { return spacingConstant; };
    }

    Node.call( this, options );
    this.updateLayout();

    //TODO: perhaps not all options must be passed to Node.call AND this.mutate.  On 7/17/2013, layout problems occurred when using only mutate() or only Node.call(this,options)
    if ( options ) {
      this.mutate( options );
    }
  };
  var HBox = scenery.HBox;

  HBox.prototype = objectCreate( Node.prototype );

  HBox.prototype.updateLayout = function() {
    var minY = _.min( _.map( this.children, function( child ) {return child.top;} ) );
    var maxY = _.max( _.map( this.children, function( child ) {return child.top + child.height;} ) );
    var centerY = (maxY + minY) / 2;

    //Start at x=0 in the coordinate frame of this node.  Not possible to set this through the spacing option, instead just set it with the {y:number} option.
    var x = 0;
    for ( var i = 0; i < this.children.length; i++ ) {
      var child = this.children[i];
      child.left = x;

      //Set the position horizontally
      if ( this.options.align === 'top' ) {
        child.top = minY;
      }
      else if ( this.options.align === 'bottom' ) {
        child.bottom = maxY;
      }
      else {//default to center
        child.centerY = centerY;
      }

      //Move to the next vertical position.
      x += child.width + this.options.spacing( child, this.children[i + 1] );
    }
  };
  HBox.prototype.constructor = HBox;

  return HBox;
} );
<|endoftext|>


<commit_before>/**
 * ownCloud - ocsms
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Loic Blot <loic.blot@unix-experience.fr>
 * @copyright Loic Blot 2014-2015
 */

// Some global vars to improve performances
var g_selectedConversation = null;
var g_curPhoneNumber = null;
var g_curContactName = '';
var g_lastMsgDate = 0;
var g_unreadCountCurrentConv = 0;
var g_unreadCountAllConv = 0;
var g_unreadCountNotifStep = 12;
var g_lastUnreadCountAllConv = 0;
var g_originalTitle = document.title;

var g_ulContactList = $('.contact-list');
var app = angular.module('OcSms', []);

function inArray(val, arr) {
	return ($.inArray(val, arr) != -1);
}

function arrayUnique(arr) {
	var unq = arr.filter(function(item, i, arr) {
		return i == arr.indexOf(item);
	})
	return unq;
}

app.controller('OcSmsController', ['$scope',
	function ($scope) {
		$scope.buttons = [
			{text: "Send"}
		];
		$scope.contacts = [];
		$scope.sendCountry = function () {
			$.post(OC.generateUrl('/apps/ocsms/set/country'),{'country': $('select[name=intl_phone]').val()});
		};
		$scope.loadConversation = function (contact) {
			OC.Util.History.pushState('phonenumber=' + contact.nav);

			// phoneNumber must exist
			if (contact.nav !== null) {
				fetchConversation(contact.nav);
				changeSelectedConversation($("a[mailbox-navigation='" + contact.nav + "']"));
			}
		};
		$scope.removeConversation = function() {
			$.post(OC.generateUrl('/apps/ocsms/delete/conversation'), {"contact": g_curContactName}, function(data) {
			});
		}

		$scope.addContact = function (ct) {
			$scope.$apply(function () {
				$scope.contacts.push(ct);
			});
		};
	}
]);

$.urlParam = function(name){
	var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (results == null) {
		return null;
	}
	else {
		return results[1] || 0;
	}
};

var refreshConversation = function() {
	// if no conversation selected, then don't fetch page
	if (g_curPhoneNumber == null) {
		if ($('#app-content-header').is(':visible')) {
			$('#app-content-header').hide();
		}
		return;
	}
	$.getJSON(OC.generateUrl('/apps/ocsms/get/conversation'),
		{
			'phoneNumber': g_curPhoneNumber,
			"lastDate": g_lastMsgDate
		},
		function(jsondata, status) {
			var fmt = formatConversation(jsondata);
			conversationBuf = fmt[1];
			if (conversationBuf != '') {
				$('.msg-endtag').before(conversationBuf);
				$('#app-content').scrollTop(1E10);
				// This will blink the tab because there is new messages
				if (document.hasFocus() == false) {
					g_unreadCountCurrentConv += fmt[0];
					document.title = g_originalTitle + " (" + g_unreadCountCurrentConv + ")";
					desktopNotify(g_unreadCountCurrentConv + " unread message(s) in conversation with " + g_curContactName);
				}
			}

			setMessageCountInfo(jsondata);
			if ($('#ocsms-conversation-removal').is(':hidden')) {
				$('#ocsms-conversation-removal').show();
			}

			if ($('#app-content-header').is(':hidden')) {
				$('#app-content-header').show();
			}
		}
	);
};

var checkNewMessages = function() {
	g_unreadCountAllConv = 0;
	$.getJSON(OC.generateUrl('/apps/ocsms/get/new_messages'),
		{ 'lastDate': g_lastMsgDate },
		function(jsondata, status) {
			var peerListBuf = '';
			var bufferedContacts = [];

			$.each(jsondata['phonelist'], function(id, val) {
				var fn, peerLabel, idxVal;
				idxVal = id.replace(/\//g,' ');
				idxVal2 = idxVal.replace('/ /g','');
				if (typeof jsondata['contacts'][id] == 'undefined') {
					fn = '';
					peerLabel = idxVal;
				}
				else {
					fn = jsondata['contacts'][id];
					peerLabel = fn;
				}

				if (!inArray(peerLabel, bufferedContacts)) {
					$("li[peer-label='" + peerLabel + "']").remove();
					peerListBuf = '

' + peerLabel + ' (' + val + ')
';

					g_ulContactList.prepend(peerListBuf);
					bufferedContacts.push(peerLabel);

					// Re-set conversation because we reload the element
					if (idxVal == g_curPhoneNumber) {
						changeSelectedConversation($("a[mailbox-navigation='" + idxVal + "']"));
					}

					g_unreadCountAllConv += parseInt(val);

					// Now bind the events when we click on the phone number
					$("a[mailbox-navigation='" + idxVal + "']").on('click', function (event) {
						var phoneNumber = $(this).attr('mailbox-navigation');
						OC.Util.History.pushState('phonenumber=' + phoneNumber);

						// phoneNumber must exist
						if (phoneNumber != null) {
							fetchConversation(phoneNumber);
							g_unreadCountAllConv += val;
							changeSelectedConversation($(this));
						}
						event.preventDefault();
					});
				}
			});

			/*
			* Decrement notification step counter, but stop it a zero
			* Stop at zero permit to notify instanly the user when
			* there is new messages in all conversations
			*/

			if (g_unreadCountNotifStep > 0) {
				g_unreadCountNotifStep--;
			}

			if (g_unreadCountAllConv > 0) {
				/*
				* We notify user every two minutes for all messages
				* or if unreadCount changes
				*/
				if (g_unreadCountNotifStep == 0 || g_lastUnreadCountAllConv != g_unreadCountAllConv) {
					desktopNotify(g_unreadCountAllConv + " unread message(s) for all conversations");
					g_unreadCountNotifStep = 12;
					g_lastUnreadCountAllConv = g_unreadCountAllConv;
				}
			}
		}
	);
};

function setMessageCountInfo(jsondata) {
	if (typeof jsondata['msgCount'] != 'undefined') {
		if (jsondata['msgCount'] == 1) {
			$('#ocsms-phone-msg-nb').html(jsondata['msgCount'] + ' message');
		}
		else {
			$('#ocsms-phone-msg-nb').html(jsondata['msgCount'] + ' messages');
		}
	}
	else {
		$('#ocsms-phone-msg-nb').html('');
	}
}

function fetchConversation(phoneNumber) {
	$.getJSON(OC.generateUrl('/apps/ocsms/get/conversation'),
		{
			'phoneNumber': phoneNumber
		},
		function(jsondata, status) {
			var phoneNumberLabel = phoneNumber;

			if (typeof jsondata['phoneNumbers'] != 'undefined') {
				phoneNumberList = arrayUnique(jsondata['phoneNumbers']);
				phoneNumberLabel = phoneNumberList.toString();
			}

			var conversationBuf = formatConversation(jsondata)[1];
			conversationBuf += '

';
			if (typeof jsondata['contactName'] == 'undefined' || jsondata['contactName'] == '') {
				$('#ocsms-phone-label').html(phoneNumberLabel);
				g_curContactName = phoneNumberLabel;
				$('#ocsms-phone-opt-number').html('');
			}
			else {
				$('#ocsms-phone-label').html(jsondata['contactName']);
				g_curContactName = jsondata['contactName'];
				$('#ocsms-phone-opt-number').html(phoneNumberLabel);
			}

			setMessageCountInfo(jsondata);

			if ($('#app-content-header').is(':hidden')) {
				$('#app-content-header').show();
			}

			if ($('#ocsms-conversation-removal').is(':hidden')) {
				$('#ocsms-conversation-removal').show();
			}

			$('#app-content-wrapper').html(conversationBuf);
			$('#app-content').scrollTop(1E10);

			g_curPhoneNumber = phoneNumber;
		}
	);
}

// Return (int) msgCount, (str) htmlConversation
function formatConversation(jsondata) {
	// Improve jQuery performance
	var buf = "";
	// Improve JS performance
	var msgClass = '';

	var msgCount = 0;
	var formatedDate = '';
	var formatedHour = '00';
	var formatedMin = '00';
	var months = ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'Jun.', 'Jul.', 'Aug.', 'Sep.',
		'Oct.', 'Nov.', 'Dec.'];

	$.each(jsondata["conversation"], function(id, vals) {
		if (vals["type"] == 1) {
			msgClass = "msg-recv";
		}
		else if (vals["type"] == 2) {
			msgClass = "msg-sent";
		}
		else {
			msgClass = '';
		}

		// Store the greater msg date for refresher
		// Note: we divide by 100 because number compare too large integers
		if ((id/100) > (g_lastMsgDate/100)) {
			g_lastMsgDate = id;
		}

		// Multiplicate ID to permit date to use it properly
		msgDate = new Date(id*1);

		formatedHour = msgDate.getHours();
		if (formatedHour < 10) {
			formatedHour = '0' + formatedHour;
		}

		formatedMin = msgDate.getMinutes();
		if (formatedMin < 10) {
			formatedMin = '0' + formatedMin;
		}
		formatedDate = msgDate.getDate() + " " + months[msgDate.getMonth()] + " " +
			formatedHour + ":" + formatedMin;

		buf += '

' +
			vals["msg"] + '

' +
			formatedDate + '

';
		msgCount++;

	});

	return [msgCount,buf];
}

function changeSelectedConversation(item) {
	if (item === 'undefined' || item == null) {
		return;
	}

	if (g_selectedConversation != null) {
		g_selectedConversation.parent().removeClass('selected');
	}
	g_selectedConversation = item;
	g_selectedConversation.parent().addClass('selected');
	g_selectedConversation.css("font-weight", "normal");
	g_selectedConversation.html(g_selectedConversation.attr("mailbox-label"));
}

function fetchInitialPeerList(jsondata) {
	// Use a buffer for better jQuery performance
	var peerListBuf = "";
	var bufferedContacts = [];
	var aScope = angular.element('[ng-controller="OcSmsController"]').scope();

	$.each(jsondata['phonelist'], function(id, val) {
		var fn, peerLabel, idxVal;
		idxVal = id.replace(/\//g,' ');
		idxVal2 = idxVal.replace('/ /g','');
		if (typeof jsondata['contacts'][id] == 'undefined') {
			fn = '';
			peerLabel = idxVal;
		}
		else {
			fn = jsondata['contacts'][id];
			peerLabel = fn;
		}
		if (!inArray(peerLabel, bufferedContacts)) {
			aScope.addContact({'label': peerLabel, 'nav': idxVal2, 'avatar': jsondata['photos'][peerLabel]});
			bufferedContacts.push(peerLabel);
		}
	});

	g_lastMsgDate = jsondata["lastRead"];
}

function initDesktopNotifies() {
	if (!("Notification" in window)) {
		return;
	}

	Notification.requestPermission(function (permission) {
		if(!('permission' in Notification)) {
			Notification.permission = permission;
		}
	});
}

function desktopNotify(msg) {
	if (!("Notification" in window)) {
		return;
	}
	else if (Notification.permission === "granted") {
		new Notification("ownCloud SMS - " + msg);
	}
	else if (Notification.permission !== 'denied') {
		Notification.requestPermission(function (permission) {
			if(!('permission' in Notification)) {
				Notification.permission = permission;
			}
			if (permission === "granted") {
				new Notification("ownCloud SMS - " + msg);
			}
		});
	}
}

function fetchInitialSettings() {
	$.getJSON(OC.generateUrl('/apps/ocsms/get/country'), function(jsondata, status) {
		if (jsondata['status'] == true) {
			$('#sel_intl_phone').val(jsondata["country"]);
		}
		else {
		}
	});
}
(function ($, OC) {
	$(document).ready(function () {
		// Register real title
		g_originalTitle = document.title;

		// Now bind the events when we click on the phone number
		$.getJSON(OC.generateUrl('/apps/ocsms/get/peerlist'), function(jsondata, status) {
			fetchInitialPeerList(jsondata);

			var pnParam = $.urlParam('phonenumber');
			if (pnParam != null) {
				var urlPhoneNumber = decodeURIComponent(pnParam);
				if (urlPhoneNumber != null) {
					fetchConversation(urlPhoneNumber);
					changeSelectedConversation($("a[mailbox-navigation='" + urlPhoneNumber + "']"));
				}
			}
			// Don't show message headers if no conversation selected
			else {
				if ($('#app-content-header').is(':visible')) {
					$('#app-content-header').hide();
				}
			}

		});
		fetchInitialSettings();
		initDesktopNotifies();
		setInterval(refreshConversation, 10000);
		setInterval(checkNewMessages, 10000);
	});

	// reset count and title
	window.onfocus = function () {
		g_unreadCountCurrentConv = 0;
		document.title = g_originalTitle;
	};
})(jQuery, OC);
<commit_msg>Remove interface elements on POST call<commit_after>/**
 * ownCloud - ocsms
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Loic Blot <loic.blot@unix-experience.fr>
 * @copyright Loic Blot 2014-2015
 */

// Some global vars to improve performances
var g_selectedConversation = null;
var g_curPhoneNumber = null;
var g_curContactName = '';
var g_lastMsgDate = 0;
var g_unreadCountCurrentConv = 0;
var g_unreadCountAllConv = 0;
var g_unreadCountNotifStep = 12;
var g_lastUnreadCountAllConv = 0;
var g_originalTitle = document.title;

var g_ulContactList = $('.contact-list');
var app = angular.module('OcSms', []);

function inArray(val, arr) {
	return ($.inArray(val, arr) != -1);
}

function arrayUnique(arr) {
	var unq = arr.filter(function(item, i, arr) {
		return i == arr.indexOf(item);
	})
	return unq;
}

app.controller('OcSmsController', ['$scope',
	function ($scope) {
		$scope.buttons = [
			{text: "Send"}
		];
		$scope.contacts = [];
		$scope.sendCountry = function () {
			$.post(OC.generateUrl('/apps/ocsms/set/country'),{'country': $('select[name=intl_phone]').val()});
		};
		$scope.loadConversation = function (contact) {
			OC.Util.History.pushState('phonenumber=' + contact.nav);

			// phoneNumber must exist
			if (contact.nav !== null) {
				fetchConversation(contact.nav);
				changeSelectedConversation($("a[mailbox-navigation='" + contact.nav + "']"));
			}
		};
		$scope.removeConversation = function() {
			$.post(OC.generateUrl('/apps/ocsms/delete/conversation'), {"contact": g_curContactName}, function(data) {
				// Reinit main window
				$('#ocsms-phone-label').html('');
				$('#ocsms-phone-opt-number').html('');
				$('#ocsms-phone-msg-nb').html('');
				$('#app-content-wrapper').html('
Please choose a conversation on the left menu
');
				$('#ocsms-conversation-removal').hide();
				$('#app-content-header').hide();
				$("li[peer-label='" + g_curContactName + "']").remove();
			});
		}

		$scope.addContact = function (ct) {
			$scope.$apply(function () {
				$scope.contacts.push(ct);
			});
		};
	}
]);

$.urlParam = function(name){
	var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (results == null) {
		return null;
	}
	else {
		return results[1] || 0;
	}
};

var refreshConversation = function() {
	// if no conversation selected, then don't fetch page
	if (g_curPhoneNumber == null) {
		if ($('#app-content-header').is(':visible')) {
			$('#app-content-header').hide();
		}
		return;
	}
	$.getJSON(OC.generateUrl('/apps/ocsms/get/conversation'),
		{
			'phoneNumber': g_curPhoneNumber,
			"lastDate": g_lastMsgDate
		},
		function(jsondata, status) {
			var fmt = formatConversation(jsondata);
			conversationBuf = fmt[1];
			if (conversationBuf != '') {
				$('.msg-endtag').before(conversationBuf);
				$('#app-content').scrollTop(1E10);
				// This will blink the tab because there is new messages
				if (document.hasFocus() == false) {
					g_unreadCountCurrentConv += fmt[0];
					document.title = g_originalTitle + " (" + g_unreadCountCurrentConv + ")";
					desktopNotify(g_unreadCountCurrentConv + " unread message(s) in conversation with " + g_curContactName);
				}
			}

			setMessageCountInfo(jsondata);
			if ($('#ocsms-conversation-removal').is(':hidden')) {
				$('#ocsms-conversation-removal').show();
			}

			if ($('#app-content-header').is(':hidden')) {
				$('#app-content-header').show();
			}
		}
	);
};

var checkNewMessages = function() {
	g_unreadCountAllConv = 0;
	$.getJSON(OC.generateUrl('/apps/ocsms/get/new_messages'),
		{ 'lastDate': g_lastMsgDate },
		function(jsondata, status) {
			var peerListBuf = '';
			var bufferedContacts = [];

			$.each(jsondata['phonelist'], function(id, val) {
				var fn, peerLabel, idxVal;
				idxVal = id.replace(/\//g,' ');
				idxVal2 = idxVal.replace('/ /g','');
				if (typeof jsondata['contacts'][id] == 'undefined') {
					fn = '';
					peerLabel = idxVal;
				}
				else {
					fn = jsondata['contacts'][id];
					peerLabel = fn;
				}

				if (!inArray(peerLabel, bufferedContacts)) {
					$("li[peer-label='" + peerLabel + "']").remove();
					peerListBuf = '

' + peerLabel + ' (' + val + ')
';

					g_ulContactList.prepend(peerListBuf);
					bufferedContacts.push(peerLabel);

					// Re-set conversation because we reload the element
					if (idxVal == g_curPhoneNumber) {
						changeSelectedConversation($("a[mailbox-navigation='" + idxVal + "']"));
					}

					g_unreadCountAllConv += parseInt(val);

					// Now bind the events when we click on the phone number
					$("a[mailbox-navigation='" + idxVal + "']").on('click', function (event) {
						var phoneNumber = $(this).attr('mailbox-navigation');
						OC.Util.History.pushState('phonenumber=' + phoneNumber);

						// phoneNumber must exist
						if (phoneNumber != null) {
							fetchConversation(phoneNumber);
							g_unreadCountAllConv += val;
							changeSelectedConversation($(this));
						}
						event.preventDefault();
					});
				}
			});

			/*
			* Decrement notification step counter, but stop it a zero
			* Stop at zero permit to notify instanly the user when
			* there is new messages in all conversations
			*/

			if (g_unreadCountNotifStep > 0) {
				g_unreadCountNotifStep--;
			}

			if (g_unreadCountAllConv > 0) {
				/*
				* We notify user every two minutes for all messages
				* or if unreadCount changes
				*/
				if (g_unreadCountNotifStep == 0 || g_lastUnreadCountAllConv != g_unreadCountAllConv) {
					desktopNotify(g_unreadCountAllConv + " unread message(s) for all conversations");
					g_unreadCountNotifStep = 12;
					g_lastUnreadCountAllConv = g_unreadCountAllConv;
				}
			}
		}
	);
};

function setMessageCountInfo(jsondata) {
	if (typeof jsondata['msgCount'] != 'undefined') {
		if (jsondata['msgCount'] == 1) {
			$('#ocsms-phone-msg-nb').html(jsondata['msgCount'] + ' message');
		}
		else {
			$('#ocsms-phone-msg-nb').html(jsondata['msgCount'] + ' messages');
		}
	}
	else {
		$('#ocsms-phone-msg-nb').html('');
	}
}

function fetchConversation(phoneNumber) {
	$.getJSON(OC.generateUrl('/apps/ocsms/get/conversation'),
		{
			'phoneNumber': phoneNumber
		},
		function(jsondata, status) {
			var phoneNumberLabel = phoneNumber;

			if (typeof jsondata['phoneNumbers'] != 'undefined') {
				phoneNumberList = arrayUnique(jsondata['phoneNumbers']);
				phoneNumberLabel = phoneNumberList.toString();
			}

			var conversationBuf = formatConversation(jsondata)[1];
			conversationBuf += '

';
			if (typeof jsondata['contactName'] == 'undefined' || jsondata['contactName'] == '') {
				$('#ocsms-phone-label').html(phoneNumberLabel);
				g_curContactName = phoneNumberLabel;
				$('#ocsms-phone-opt-number').html('');
			}
			else {
				$('#ocsms-phone-label').html(jsondata['contactName']);
				g_curContactName = jsondata['contactName'];
				$('#ocsms-phone-opt-number').html(phoneNumberLabel);
			}

			setMessageCountInfo(jsondata);

			if ($('#app-content-header').is(':hidden')) {
				$('#app-content-header').show();
			}

			if ($('#ocsms-conversation-removal').is(':hidden')) {
				$('#ocsms-conversation-removal').show();
			}

			$('#app-content-wrapper').html(conversationBuf);
			$('#app-content').scrollTop(1E10);

			g_curPhoneNumber = phoneNumber;
		}
	);
}

// Return (int) msgCount, (str) htmlConversation
function formatConversation(jsondata) {
	// Improve jQuery performance
	var buf = "";
	// Improve JS performance
	var msgClass = '';

	var msgCount = 0;
	var formatedDate = '';
	var formatedHour = '00';
	var formatedMin = '00';
	var months = ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'Jun.', 'Jul.', 'Aug.', 'Sep.',
		'Oct.', 'Nov.', 'Dec.'];

	$.each(jsondata["conversation"], function(id, vals) {
		if (vals["type"] == 1) {
			msgClass = "msg-recv";
		}
		else if (vals["type"] == 2) {
			msgClass = "msg-sent";
		}
		else {
			msgClass = '';
		}

		// Store the greater msg date for refresher
		// Note: we divide by 100 because number compare too large integers
		if ((id/100) > (g_lastMsgDate/100)) {
			g_lastMsgDate = id;
		}

		// Multiplicate ID to permit date to use it properly
		msgDate = new Date(id*1);

		formatedHour = msgDate.getHours();
		if (formatedHour < 10) {
			formatedHour = '0' + formatedHour;
		}

		formatedMin = msgDate.getMinutes();
		if (formatedMin < 10) {
			formatedMin = '0' + formatedMin;
		}
		formatedDate = msgDate.getDate() + " " + months[msgDate.getMonth()] + " " +
			formatedHour + ":" + formatedMin;

		buf += '

' +
			vals["msg"] + '

' +
			formatedDate + '

';
		msgCount++;

	});

	return [msgCount,buf];
}

function changeSelectedConversation(item) {
	if (item === 'undefined' || item == null) {
		return;
	}

	if (g_selectedConversation != null) {
		g_selectedConversation.parent().removeClass('selected');
	}
	g_selectedConversation = item;
	g_selectedConversation.parent().addClass('selected');
	g_selectedConversation.css("font-weight", "normal");
	g_selectedConversation.html(g_selectedConversation.attr("mailbox-label"));
}

function fetchInitialPeerList(jsondata) {
	// Use a buffer for better jQuery performance
	var peerListBuf = "";
	var bufferedContacts = [];
	var aScope = angular.element('[ng-controller="OcSmsController"]').scope();

	$.each(jsondata['phonelist'], function(id, val) {
		var fn, peerLabel, idxVal;
		idxVal = id.replace(/\//g,' ');
		idxVal2 = idxVal.replace('/ /g','');
		if (typeof jsondata['contacts'][id] == 'undefined') {
			fn = '';
			peerLabel = idxVal;
		}
		else {
			fn = jsondata['contacts'][id];
			peerLabel = fn;
		}
		if (!inArray(peerLabel, bufferedContacts)) {
			aScope.addContact({'label': peerLabel, 'nav': idxVal2, 'avatar': jsondata['photos'][peerLabel]});
			bufferedContacts.push(peerLabel);
		}
	});

	g_lastMsgDate = jsondata["lastRead"];
}

function initDesktopNotifies() {
	if (!("Notification" in window)) {
		return;
	}

	Notification.requestPermission(function (permission) {
		if(!('permission' in Notification)) {
			Notification.permission = permission;
		}
	});
}

function desktopNotify(msg) {
	if (!("Notification" in window)) {
		return;
	}
	else if (Notification.permission === "granted") {
		new Notification("ownCloud SMS - " + msg);
	}
	else if (Notification.permission !== 'denied') {
		Notification.requestPermission(function (permission) {
			if(!('permission' in Notification)) {
				Notification.permission = permission;
			}
			if (permission === "granted") {
				new Notification("ownCloud SMS - " + msg);
			}
		});
	}
}

function fetchInitialSettings() {
	$.getJSON(OC.generateUrl('/apps/ocsms/get/country'), function(jsondata, status) {
		if (jsondata['status'] == true) {
			$('#sel_intl_phone').val(jsondata["country"]);
		}
		else {
		}
	});
}
(function ($, OC) {
	$(document).ready(function () {
		// Register real title
		g_originalTitle = document.title;

		// Now bind the events when we click on the phone number
		$.getJSON(OC.generateUrl('/apps/ocsms/get/peerlist'), function(jsondata, status) {
			fetchInitialPeerList(jsondata);

			var pnParam = $.urlParam('phonenumber');
			if (pnParam != null) {
				var urlPhoneNumber = decodeURIComponent(pnParam);
				if (urlPhoneNumber != null) {
					fetchConversation(urlPhoneNumber);
					changeSelectedConversation($("a[mailbox-navigation='" + urlPhoneNumber + "']"));
				}
			}
			// Don't show message headers if no conversation selected
			else {
				if ($('#app-content-header').is(':visible')) {
					$('#app-content-header').hide();
				}
			}

		});
		fetchInitialSettings();
		initDesktopNotifies();
		setInterval(refreshConversation, 10000);
		setInterval(checkNewMessages, 10000);
	});

	// reset count and title
	window.onfocus = function () {
		g_unreadCountCurrentConv = 0;
		document.title = g_originalTitle;
	};
})(jQuery, OC);
<|endoftext|>


<commit_before>'use strict';

function draw_boxen(args){
    canvas_draw_path({
      'style': 'stroke',
      'vertices': [
        {
          'type': 'rect',
           'radius': args['radius'],
           'startAngle': args['startAngle'],
           'x': args['x'],
           'y': args['y'],
         },
      ],
    });
}

function draw_logic(){
    // If mouse down, draw current unsaved box.
    if(core_mouse['down']){
        draw_boxen({
          'radius': core_mouse['x'] - core_mouse['down-x'],
          'startAngle': core_mouse['y'] - core_mouse['down-y'],
          'x': core_mouse['down-x'],
          'y': core_mouse['down-y'],
        });
    }

    // Draw saved boxen.
    for(var box in boxen){
        draw_boxen({
          'radius': boxen[box]['width'],
          'startAngle': boxen[box]['height'],
          'x': boxen[box]['x'],
          'y': boxen[box]['y'],
        });
    }

    canvas_buffer.fillText(
      'Click + Drag! ESC = Clear! '
        + boxen.length + '!',
      5,
      25
    );
}

function repo_escape(){
    boxen = [];
}

function repo_init(){
    core_events_bind({
      'mousebinds': {
        'mouseup': {
          'todo': function(){
              boxen.push({
                'height': core_mouse['y'] - core_mouse['down-y'],
                'width': core_mouse['x'] - core_mouse['down-x'],
                'x': core_mouse['down-x'],
                'y': core_mouse['down-y'],
              });
          },
        },
      },
    });
    canvas_init();
}

function resize_logic(){
    canvas_buffer.fillStyle = '#fff';
    canvas_buffer.strokeStyle = '#fff';
}

var boxen = [];
<commit_msg>added core_repo_init() usage<commit_after>'use strict';

function draw_boxen(args){
    canvas_draw_path({
      'style': 'stroke',
      'vertices': [
        {
          'type': 'rect',
           'radius': args['radius'],
           'startAngle': args['startAngle'],
           'x': args['x'],
           'y': args['y'],
         },
      ],
    });
}

function draw_logic(){
    // If mouse down, draw current unsaved box.
    if(core_mouse['down']){
        draw_boxen({
          'radius': core_mouse['x'] - core_mouse['down-x'],
          'startAngle': core_mouse['y'] - core_mouse['down-y'],
          'x': core_mouse['down-x'],
          'y': core_mouse['down-y'],
        });
    }

    // Draw saved boxen.
    for(var box in boxen){
        draw_boxen({
          'radius': boxen[box]['width'],
          'startAngle': boxen[box]['height'],
          'x': boxen[box]['x'],
          'y': boxen[box]['y'],
        });
    }

    canvas_buffer.fillText(
      'Click + Drag! ESC = Clear! '
        + boxen.length + '!',
      5,
      25
    );
}

function repo_escape(){
    boxen = [];
}

function repo_init(){
    core_repo_init({
      'title': 'RTS-Boxing.htm',
    });
    core_events_bind({
      'mousebinds': {
        'mouseup': {
          'todo': function(){
              boxen.push({
                'height': core_mouse['y'] - core_mouse['down-y'],
                'width': core_mouse['x'] - core_mouse['down-x'],
                'x': core_mouse['down-x'],
                'y': core_mouse['down-y'],
              });
          },
        },
      },
    });
    canvas_init();
}

function resize_logic(){
    canvas_buffer.fillStyle = '#fff';
    canvas_buffer.strokeStyle = '#fff';
}

var boxen = [];
<|endoftext|>


<commit_before>var bouncy = require('bouncy');
var r = require('rethinkdb');
var fs = require('fs');
var path = require('path');
var iso8601 = require('iso8601');

var server = bouncy(function (req, res, bounce) {
  var parts = req.url.split('/');
  var username = parts[1]
  var scriptname = parts[2]
  var key = parts[3]

  console.log(req.method+" "+req.url)
 if(username == 'npm' && key == null) {
    console.log('fetching npm '+scriptname)
    res.statusCode = 200;
    res.end(fs.readFileSync('npm/'+path.basename(scriptname)));
  } else {
    var fullname = username+'/'+scriptname
    console.log((new Date())+' fetching '+fullname)
    r.connect({host:'localhost', port:28015, db:'cointhink'},
      function(err, conn) {
        r.table('scripts').get(fullname).run(conn, function(err, doc){
          if(doc) {
            if(doc.key == key) {
              res.statusCode = 200;
              // Authorized
              if(req.method == 'GET') {
                res.end(doc.body);
              }
              if(req.method == 'POST') {
                req.on("data",function(data){
                  var body = data.toString('utf8')
                  sig_doc = JSON.parse(body)
                  sig_doc.name = username+'/'+scriptname
                  sig_doc.time = new Date() //iso8601.fromDate(new Date())
                  console.log('posting '+JSON.stringify(sig_doc))
                  r.table('signals').insert(sig_doc).run(conn, function(err, doc){
                    if(err){
                      res.end({error: err});
                    } else {
                      res.end(JSON.stringify(doc));
                    }
                  })
                })
              }
            } else {
              res.statusCode = 403;
              res.end(JSON.stringify({error: "bad key"}));

            }
          } else {
            res.statusCode = 403;
            res.end(JSON.stringify({error: "not found"}));
          }
        })
      }
    )
  }
});
console.log("listening on 3002")
server.listen(3002);

<commit_msg>iso take 2<commit_after>var bouncy = require('bouncy');
var r = require('rethinkdb');
var fs = require('fs');
var path = require('path');
var iso8601 = require('iso8601');

var server = bouncy(function (req, res, bounce) {
  var parts = req.url.split('/');
  var username = parts[1]
  var scriptname = parts[2]
  var key = parts[3]

  console.log(req.method+" "+req.url)
 if(username == 'npm' && key == null) {
    console.log('fetching npm '+scriptname)
    res.statusCode = 200;
    res.end(fs.readFileSync('npm/'+path.basename(scriptname)));
  } else {
    var fullname = username+'/'+scriptname
    console.log((new Date())+' fetching '+fullname)
    r.connect({host:'localhost', port:28015, db:'cointhink'},
      function(err, conn) {
        r.table('scripts').get(fullname).run(conn, function(err, doc){
          if(doc) {
            if(doc.key == key) {
              res.statusCode = 200;
              // Authorized
              if(req.method == 'GET') {
                res.end(doc.body);
              }
              if(req.method == 'POST') {
                req.on("data",function(data){
                  var body = data.toString('utf8')
                  sig_doc = JSON.parse(body)
                  sig_doc.name = username+'/'+scriptname
                  sig_doc.time = iso8601.fromDate(new Date())
                  console.log('posting '+JSON.stringify(sig_doc))
                  r.table('signals').insert(sig_doc).run(conn, function(err, doc){
                    if(err){
                      res.end({error: err});
                    } else {
                      res.end(JSON.stringify(doc));
                    }
                  })
                })
              }
            } else {
              res.statusCode = 403;
              res.end(JSON.stringify({error: "bad key"}));

            }
          } else {
            res.statusCode = 403;
            res.end(JSON.stringify({error: "not found"}));
          }
        })
      }
    )
  }
});
console.log("listening on 3002")
server.listen(3002);

<|endoftext|>


<commit_before>/**
 * jspsych-survey-html-form
 * a jspsych plugin for free html forms
 *
 * Jan Simson
 *
 * documentation: docs.jspsych.org
 *
 */

jsPsych.plugins['survey-html-form'] = (function() {

  var plugin = {};

  plugin.info = {
    name: 'survey-html-form',
    description: '',
    parameters: {
      html: {
        type: jsPsych.plugins.parameterType.HTML_STRING,
        pretty_name: 'HTML',
        default: null,
        description: 'HTML formatted string containing all the input elements to display. Every element has to have its own distinctive name attribute. The <form> tag must not be included and is generated by the plugin.'
      },
      preamble: {
        type: jsPsych.plugins.parameterType.STRING,
        pretty_name: 'Preamble',
        default: null,
        description: 'HTML formatted string to display at the top of the page above all the questions.'
      },
      button_label: {
        type: jsPsych.plugins.parameterType.STRING,
        pretty_name: 'Button label',
        default:  'Continue',
        description: 'The text that appears on the button to finish the trial.'
      },
      autofocus: {
	type: jsPsych.plugins.parameterType.STRING,
	pretty_name: 'Element ID to focus',
	default: '',
	description: 'The HTML element ID of a form field to autofocus on.'
      },
      dataAsArray: {
        type: jsPsych.plugins.parameterType.BOOLEAN,
        pretty_name: 'Data As Array',
        default:  false,
        description: 'Retrieve the data as an array e.g. [{name: "INPUT_NAME", value: "INPUT_VALUE"}, ...] instead of an object e.g. {INPUT_NAME: INPUT_VALUE, ...}.'
      },
      autocomplete: {
        type: jsPsych.plugins.parameterType.BOOL,
        pretty_name: 'Allow autocomplete',
        default: false,
        description: "Setting this to true will enable browser auto-complete or auto-fill for the form."
      }
    }
  }

  plugin.trial = function(display_element, trial) {

    var html = '';
    // show preamble text
    if(trial.preamble !== null){
      html += '
'+trial.preamble+'
';
    }
    // start form
    if ( trial.autocomplete ) {
      html += '<form id="jspsych-survey-html-form">'
    } else {
      html += '<form id="jspsych-survey-html-form" autocomplete="off">'
    }

    // add form HTML / input elements
    html += trial.html;

    // add submit button
    html += '<input type="submit" id="jspsych-survey-html-form-next" class="jspsych-btn jspsych-survey-html-form" value="'+trial.button_label+'"></input>';

    html += '</form>';
    display_element.innerHTML = html;

    if ( trial.autofocus !== '' ) {
      var focus_elements = display_element.querySelectorAll('#'+trial.autofocus);
      if ( focus_elements.length === 0 ) {
	      console.warn('No element found with id: '+trial.autofocus);
      } else if ( focus_elements.length > 1 ) {
	      console.warn('The id "'+trial.autofocus+'" is not unique so autofocus will not work.')
      } else {
	      focus_elements[0].focus()
      }
    }

    display_element.querySelector('#jspsych-survey-html-form').addEventListener('submit', function(event) {
      // don't submit form
      event.preventDefault();

      // measure response time
      var endTime = performance.now();
      var response_time = endTime - startTime;

      var question_data = serializeArray(this);

      if (!trial.dataAsArray) {
        question_data = objectifyForm(question_data);
      }

      // save data
      var trialdata = {
        "rt": response_time,
        "responses": JSON.stringify(question_data)
      };

      display_element.innerHTML = '';

      // next trial
      jsPsych.finishTrial(trialdata);
    });

    var startTime = performance.now();
  };

  /*!
   * Serialize all form data into an array
   * (c) 2018 Chris Ferdinandi, MIT License, https://gomakethings.com
   * @param  {Node}   form The form to serialize
   * @return {String}      The serialized form data
   */
  var serializeArray = function (form) {
    // Setup our serialized data
    var serialized = [];

    // Loop through each field in the form
    for (var i = 0; i < form.elements.length; i++) {
      var field = form.elements[i];

      // Don't serialize fields without a name, submits, buttons, file and reset inputs, and disabled fields
      if (!field.name || field.disabled || field.type === 'file' || field.type === 'reset' || field.type === 'submit' || field.type === 'button') continue;

      // If a multi-select, get all selections
      if (field.type === 'select-multiple') {
        for (var n = 0; n < field.options.length; n++) {
          if (!field.options[n].selected) continue;
          serialized.push({
            name: field.name,
            value: field.options[n].value
          });
        }
      }

      // Convert field data to a query string
      else if ((field.type !== 'checkbox' && field.type !== 'radio') || field.checked) {
        serialized.push({
          name: field.name,
          value: field.value
        });
      }
    }

    return serialized;
  };

  // from https://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery
  function objectifyForm(formArray) {//serialize data function
    var returnArray = {};
    for (var i = 0; i < formArray.length; i++){
      returnArray[formArray[i]['name']] = formArray[i]['value'];
    }
    return returnArray;
  }

  return plugin;
})();
<commit_msg>edit formatting<commit_after>/**
 * jspsych-survey-html-form
 * a jspsych plugin for free html forms
 *
 * Jan Simson
 *
 * documentation: docs.jspsych.org
 *
 */

jsPsych.plugins['survey-html-form'] = (function() {

  var plugin = {};

  plugin.info = {
    name: 'survey-html-form',
    description: '',
    parameters: {
      html: {
        type: jsPsych.plugins.parameterType.HTML_STRING,
        pretty_name: 'HTML',
        default: null,
        description: 'HTML formatted string containing all the input elements to display. Every element has to have its own distinctive name attribute. The <form> tag must not be included and is generated by the plugin.'
      },
      preamble: {
        type: jsPsych.plugins.parameterType.STRING,
        pretty_name: 'Preamble',
        default: null,
        description: 'HTML formatted string to display at the top of the page above all the questions.'
      },
      button_label: {
        type: jsPsych.plugins.parameterType.STRING,
        pretty_name: 'Button label',
        default:  'Continue',
        description: 'The text that appears on the button to finish the trial.'
      },
      autofocus: {
        type: jsPsych.plugins.parameterType.STRING,
        pretty_name: 'Element ID to focus',
        default: '',
        description: 'The HTML element ID of a form field to autofocus on.'
      },
      dataAsArray: {
        type: jsPsych.plugins.parameterType.BOOLEAN,
        pretty_name: 'Data As Array',
        default:  false,
        description: 'Retrieve the data as an array e.g. [{name: "INPUT_NAME", value: "INPUT_VALUE"}, ...] instead of an object e.g. {INPUT_NAME: INPUT_VALUE, ...}.'
      },
      autocomplete: {
        type: jsPsych.plugins.parameterType.BOOL,
        pretty_name: 'Allow autocomplete',
        default: false,
        description: "Setting this to true will enable browser auto-complete or auto-fill for the form."
      }
    }
  }

  plugin.trial = function(display_element, trial) {

    var html = '';
    // show preamble text
    if(trial.preamble !== null){
      html += '
'+trial.preamble+'
';
    }
    // start form
    if ( trial.autocomplete ) {
      html += '<form id="jspsych-survey-html-form">'
    } else {
      html += '<form id="jspsych-survey-html-form" autocomplete="off">'
    }

    // add form HTML / input elements
    html += trial.html;

    // add submit button
    html += '<input type="submit" id="jspsych-survey-html-form-next" class="jspsych-btn jspsych-survey-html-form" value="'+trial.button_label+'"></input>';

    html += '</form>';
    display_element.innerHTML = html;

    if ( trial.autofocus !== '' ) {
      var focus_elements = display_element.querySelectorAll('#'+trial.autofocus);
      if ( focus_elements.length === 0 ) {
	      console.warn('No element found with id: '+trial.autofocus);
      } else if ( focus_elements.length > 1 ) {
	      console.warn('The id "'+trial.autofocus+'" is not unique so autofocus will not work.');
      } else {
	      focus_elements[0].focus();
      }
    }

    display_element.querySelector('#jspsych-survey-html-form').addEventListener('submit', function(event) {
      // don't submit form
      event.preventDefault();

      // measure response time
      var endTime = performance.now();
      var response_time = endTime - startTime;

      var question_data = serializeArray(this);

      if (!trial.dataAsArray) {
        question_data = objectifyForm(question_data);
      }

      // save data
      var trialdata = {
        "rt": response_time,
        "responses": JSON.stringify(question_data)
      };

      display_element.innerHTML = '';

      // next trial
      jsPsych.finishTrial(trialdata);
    });

    var startTime = performance.now();
  };

  /*!
   * Serialize all form data into an array
   * (c) 2018 Chris Ferdinandi, MIT License, https://gomakethings.com
   * @param  {Node}   form The form to serialize
   * @return {String}      The serialized form data
   */
  var serializeArray = function (form) {
    // Setup our serialized data
    var serialized = [];

    // Loop through each field in the form
    for (var i = 0; i < form.elements.length; i++) {
      var field = form.elements[i];

      // Don't serialize fields without a name, submits, buttons, file and reset inputs, and disabled fields
      if (!field.name || field.disabled || field.type === 'file' || field.type === 'reset' || field.type === 'submit' || field.type === 'button') continue;

      // If a multi-select, get all selections
      if (field.type === 'select-multiple') {
        for (var n = 0; n < field.options.length; n++) {
          if (!field.options[n].selected) continue;
          serialized.push({
            name: field.name,
            value: field.options[n].value
          });
        }
      }

      // Convert field data to a query string
      else if ((field.type !== 'checkbox' && field.type !== 'radio') || field.checked) {
        serialized.push({
          name: field.name,
          value: field.value
        });
      }
    }

    return serialized;
  };

  // from https://stackoverflow.com/questions/1184624/convert-form-data-to-javascript-object-with-jquery
  function objectifyForm(formArray) {//serialize data function
    var returnArray = {};
    for (var i = 0; i < formArray.length; i++){
      returnArray[formArray[i]['name']] = formArray[i]['value'];
    }
    return returnArray;
  }

  return plugin;
})();
<|endoftext|>


<commit_before>// Delete user group

'use strict';

module.exports = function (N, apiPath) {
  var UserGroup = N.models.users.UserGroup
    , User      = N.models.users.User;

  N.validate(apiPath, {
    _id: {
      type: 'string'
    , required: true
    }
  });

  N.wire.on(apiPath, function (env, callback) {
    UserGroup.findById(env.params._id).exec(function(err, group) {
      if (err) {
        callback(err);
        return;
      }

      if (!group) {
        callback(N.io.NOT_FOUND);
        return;
      }

      if (group.is_protected) {
        callback({
          code: N.io.CLIENT_ERROR
        , message: env.helpers.t('admin.users.usergroups.destroy.error_protected')
        });
        return;
      }

      // Count children.
      UserGroup.count({ parent: group._id }).exec(function(err, childrenCount) {
        if (err) {
          callback(err);
          return;
        }

        if (0 !== childrenCount) {
          callback({
            code: N.io.CLIENT_ERROR
          , message: env.helpers.t('admin.users.usergroups.destroy.error_has_children')
          });
          return;
        }

        // Count users associated with the group.
        User.count({ usergroups: group._id }).exec(function(err, usersCount) {
          if (err) {
            callback(err);
            return;
          }

          if (0 !== usersCount) {
            callback({
              code: N.io.CLIENT_ERROR
            , message: env.helpers.t('admin.users.usergroups.destroy.error_not_empty')
            });
            return;
          }

          group.remove(callback);
        });
      });
    });
  });
};
<commit_msg>Fix 'groups has descendants' check on usergroup.destroy method.<commit_after>// Delete user group

'use strict';

module.exports = function (N, apiPath) {
  var UserGroup = N.models.users.UserGroup
    , User      = N.models.users.User;

  N.validate(apiPath, {
    _id: {
      type: 'string'
    , required: true
    }
  });

  N.wire.on(apiPath, function (env, callback) {
    UserGroup.findById(env.params._id).exec(function(err, group) {
      if (err) {
        callback(err);
        return;
      }

      if (!group) {
        callback(N.io.NOT_FOUND);
        return;
      }

      if (group.is_protected) {
        callback({
          code: N.io.CLIENT_ERROR
        , message: env.helpers.t('admin.users.usergroups.destroy.error_protected')
        });
        return;
      }

      // Count children.
      UserGroup.count({ parent_group: group._id }).exec(function(err, childrenCount) {
        if (err) {
          callback(err);
          return;
        }

        if (0 !== childrenCount) {
          callback({
            code: N.io.CLIENT_ERROR
          , message: env.helpers.t('admin.users.usergroups.destroy.error_has_children')
          });
          return;
        }

        // Count users associated with the group.
        User.count({ usergroups: group._id }).exec(function(err, usersCount) {
          if (err) {
            callback(err);
            return;
          }

          if (0 !== usersCount) {
            callback({
              code: N.io.CLIENT_ERROR
            , message: env.helpers.t('admin.users.usergroups.destroy.error_not_empty')
            });
            return;
          }

          group.remove(callback);
        });
      });
    });
  });
};
<|endoftext|>


<commit_before>var Roadmap = require('./roadmapModel.js');

module.exports = {

  createRoadmap : function (req, res, next) {
    var newRoadmap = req.body;
    Roadmap(newRoadmap).save()
      .then(function(dbResults){
        res.status(201).json(dbResults);
      })
      .catch(function(err){
        next(err);
      });
  },
  getRoadmaps : function (req, res, next) {
    Roadmap.find({})
      .then(function(dbResults){
        res.status(200).json(dbResults);
      })
      .catch(function(err){
        next(err);
      });
  },
  getRoadmapByID : function (req, res, next) {

  },
  updateRoadmap : function (req, res, next) {

  },
  deleteRoadmap : function (req, res, next) {

  }

};<commit_msg>Refactor .catch's to use util.handleError<commit_after>var Roadmap = require('./roadmapModel.js'),
    handleError = require('../../util.js').handleError;

module.exports = {

  createRoadmap : function (req, res, next) {
    var newRoadmap = req.body;
    Roadmap(newRoadmap).save()
      .then(function(dbResults){
        res.status(201).json(dbResults);
      })
      .catch(handleError(next));
  },
  getRoadmaps : function (req, res, next) {
    Roadmap.find({})
      .then(function(dbResults){
        res.status(200).json(dbResults);
      })
      .catch(handleError(next));
  },
  getRoadmapByID : function (req, res, next) {
    var _id = req.params.roadmapID;
    Roadmap.findById(_id)
      .then(function(dbResults){
        res.json(dbResults);
      })
      .catch(handleError(next));
  },
  updateRoadmap : function (req, res, next) {

  },
  deleteRoadmap : function (req, res, next) {

  }

};<|endoftext|>


<commit_before><commit_msg>source test lang/kindOf<commit_after><|endoftext|>