<commit_before>// Copyright 2016, University of Colorado Boulder

/**
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var assertInstanceOf = require( 'PHET_IO/assertions/assertInstanceOf' );
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
  var TBoolean = require( 'PHET_IO/types/TBoolean' );
  var TNode = require( 'PHET_IO/types/scenery/nodes/TNode' );
  var TTandemDragHandler = require( 'PHET_IO/types/tandem/scenery/input/TTandemDragHandler' );
  var TVoid = require( 'PHET_IO/types/TVoid' );

  var THSliderTrack = phetioInherit( TNode, 'THSliderTrack', function( sliderTrack, phetioID ) {
    TNode.call( this, sliderTrack, phetioID );
    assertInstanceOf( sliderTrack, phet.sun.HSliderTrack );
  }, {}, {
    api: {
      trackInputListener: TTandemDragHandler
    },
    documentation: 'The track for a knob of a traditional slider'
  } );

  var THSlider = phetioInherit( TNode, 'THSlider', function( slider, phetioID ) {
    TNode.call( this, slider, phetioID );
    assertInstanceOf( slider, phet.sun.HSlider );
  }, {
    setMajorTicksVisible: {
      returnType: TVoid,
      parameterTypes: [ TBoolean ],
      implementation: function( visible ) {
        this.instance.setMajorTicksVisible( visible );
      },
      documentation: 'Set whether the major tick marks should be shown'
    },
    setMinorTicksVisible: {
      returnType: TVoid,
      parameterTypes: [ TBoolean ],
      implementation: function( visible ) {
        this.instance.setMinorTicksVisible( visible );
      },
      documentation: 'Set whether the minor tick marks should be shown'
    }
  }, {
    api: {
      sliderTrack: THSliderTrack,
      thumbInputListener: TTandemDragHandler
    },
    documentation: 'A traditional slider component, with a knob and possibly tick marks'
  } );

  phetioNamespace.register( 'THSlider', THSlider );

  return THSlider;
} );<commit_msg>Split THSliderTrack out from THSlider (#489)<commit_after>// Copyright 2016, University of Colorado Boulder

/**
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var assertInstanceOf = require( 'PHET_IO/assertions/assertInstanceOf' );
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
  var TBoolean = require( 'PHET_IO/types/TBoolean' );
  var THSliderTrack = require( 'PHET_IO/types/tandem/sun/THSliderTrack' );
  var TNode = require( 'PHET_IO/types/scenery/nodes/TNode' );
  var TTandemDragHandler = require( 'PHET_IO/types/tandem/scenery/input/TTandemDragHandler' );
  var TVoid = require( 'PHET_IO/types/TVoid' );

  var THSlider = phetioInherit( TNode, 'THSlider', function( slider, phetioID ) {
    TNode.call( this, slider, phetioID );
    assertInstanceOf( slider, phet.sun.HSlider );
  }, {
    setMajorTicksVisible: {
      returnType: TVoid,
      parameterTypes: [ TBoolean ],
      implementation: function( visible ) {
        this.instance.setMajorTicksVisible( visible );
      },
      documentation: 'Set whether the major tick marks should be shown'
    },
    setMinorTicksVisible: {
      returnType: TVoid,
      parameterTypes: [ TBoolean ],
      implementation: function( visible ) {
        this.instance.setMinorTicksVisible( visible );
      },
      documentation: 'Set whether the minor tick marks should be shown'
    }
  }, {
    api: {
      sliderTrack: THSliderTrack,
      thumbInputListener: TTandemDragHandler
    },
    documentation: 'A traditional slider component, with a knob and possibly tick marks'
  } );

  phetioNamespace.register( 'THSlider', THSlider );

  return THSlider;
} );<|endoftext|>


<commit_before>const fs = require('fs');
const cp = require('child_process');
const _ = require('lodash');
const find = require('find');
const _path = require('path');

function targetFilesForPathAndPackage(directory, path, pack) {
    const packTargetDirs = pack['source-directories'];
    const targetFiles = _.uniq(_.flatten(packTargetDirs.map(x => {
        const exists = fs.existsSync(path + '/' + x);
        if (!exists) {
            return []
        }

        return find.fileSync(/\.elm$/, path + '/' + x)
            .filter(x => {
                return x.replace(path, '')
                    .indexOf('elm-stuff') === -1 && (x.length > 0)
            });
    }))).map(function(s) {
        const sParts = s.split(_path.sep);
        const dirParts = directory.split(_path.sep);

        while (sParts.length > 0 && dirParts.length > 0) {
            if (sParts[0] == dirParts[0]) {
                sParts.shift();
                dirParts.shift();
            } else {
                break;
            }
        }

        const result = dirParts.map(_ => "../").join() + sParts.join('/');
        return result;
    });
    return targetFiles;
}

function dependencyFiles(directory, dep, version) {
    const depPath = directory + "/elm-stuff/packages/" + dep + "/" + version;
    const depPackageFile = require(depPath + '/elm-package.json');
    const unfilteredTargetFiles = targetFilesForPathAndPackage(directory, depPath, depPackageFile);

    const exposedModules = depPackageFile['exposed-modules'].map(x => '/' + x.replace('.', '/') + '.elm');
    return unfilteredTargetFiles.filter(function(x) {
        return exposedModules.filter(e => x.endsWith(e))[0];
    });
}

function gather(directory) {
    const packageFile = require(directory + '/elm-package.json');
    const exactDeps = require(directory + '/elm-stuff/exact-dependencies.json');
    const targetDirs = packageFile['source-directories'];
    const dependencies = Object.keys(packageFile['dependencies']);

    var interfaceFiles = dependencies
        .filter(x => exactDeps[x])
        .map(x => [x, exactDeps[x]]);

    dependencies.filter(x => !exactDeps[x]).forEach(x => {
        console.log('Missing dependency `' + x + '`. Maybe run elm-package to update the dependencies.');
    });

    const input = {
        interfaceFiles: interfaceFiles,
        sourceFiles: targetFilesForPathAndPackage(directory, directory, packageFile)
    };
    return input;
}

module.exports = {
    gather: gather,
    getDependencyFiles: dependencyFiles
}
<commit_msg>Issue #22: Ignore files located in node_modules<commit_after>const fs = require('fs');
const cp = require('child_process');
const _ = require('lodash');
const find = require('find');
const _path = require('path');

function targetFilesForPathAndPackage(directory, path, pack) {
    const packTargetDirs = pack['source-directories'];
    const targetFiles = _.uniq(_.flatten(packTargetDirs.map(x => {
        const exists = fs.existsSync(path + '/' + x);
        if (!exists) {
            return []
        }

        return find.fileSync(/\.elm$/, path + '/' + x)
            .filter(x => {
                const relativePath = x.replace(path, '')
                return relativePath.indexOf('elm-stuff') === -1
                      && relativePath.indexOf('node_modules') === -1
                      && (x.length > 0)
            });
    }))).map(function(s) {
        const sParts = s.split(_path.sep);
        const dirParts = directory.split(_path.sep);

        while (sParts.length > 0 && dirParts.length > 0) {
            if (sParts[0] == dirParts[0]) {
                sParts.shift();
                dirParts.shift();
            } else {
                break;
            }
        }

        const result = dirParts.map(_ => "../").join() + sParts.join('/');
        return result;
    });
    return targetFiles;
}

function dependencyFiles(directory, dep, version) {
    const depPath = directory + "/elm-stuff/packages/" + dep + "/" + version;
    const depPackageFile = require(depPath + '/elm-package.json');
    const unfilteredTargetFiles = targetFilesForPathAndPackage(directory, depPath, depPackageFile);

    const exposedModules = depPackageFile['exposed-modules'].map(x => '/' + x.replace('.', '/') + '.elm');
    return unfilteredTargetFiles.filter(function(x) {
        return exposedModules.filter(e => x.endsWith(e))[0];
    });
}

function gather(directory) {
    const packageFile = require(directory + '/elm-package.json');
    const exactDeps = require(directory + '/elm-stuff/exact-dependencies.json');
    const targetDirs = packageFile['source-directories'];
    const dependencies = Object.keys(packageFile['dependencies']);

    var interfaceFiles = dependencies
        .filter(x => exactDeps[x])
        .map(x => [x, exactDeps[x]]);

    dependencies.filter(x => !exactDeps[x]).forEach(x => {
        console.log('Missing dependency `' + x + '`. Maybe run elm-package to update the dependencies.');
    });

    const input = {
        interfaceFiles: interfaceFiles,
        sourceFiles: targetFilesForPathAndPackage(directory, directory, packageFile)
    };
    return input;
}

module.exports = {
    gather: gather,
    getDependencyFiles: dependencyFiles
}
<|endoftext|>


<commit_before>import api from 'plugins/http/api';

/**
 * Simple interface for interacting with user roles and permissions
 *
 * permissions is an array with the following structure
 *
[
		{
			"name": "Create Subsites",
			"slug": "subsite.create",
			"roles": [
				"site.owner"
			]
		},
		...
 */
const state = {
	roles: [],
	currentRole: '',
	globalRole: '',
};

const getters = {
	getCurrentRole(state, getters) {
		return state.currentSiteRole;
	},

	getRoles(state, getters) {
		return state.roles;
	},

	/**
	 * can the user perform the requested action
	 * if the user is a global admin then let them do anything
	 *
	 * @param {object} state - the vuex state
	 * @param {string} the permission to check i.e. subsite.edit, subsite.create
	 * @returns {bool} true or false
	 */
	canUser: (state, getters) => (permissionSlug) => {

		let permitted = false;

		// if the user has the global role of admin then then they can do anything
		if (state.globalRole === 'admin') {
			return true;
		}
		const matchedRole = state.roles.find(function(value) {
			if (value.slug == this.permissionSlug) {
				return true;
			}
		}, {permissionSlug});

		if (matchedRole) {
			permitted = matchedRole.roles.includes(state.currentRole);
		}

		return permitted;
	}
};

const actions = {

	/**
	 * gets list of roles from the api can calls mutation to store this in the state
	 * called from TopBar.vue->mounted
	 *
	 * @param {object} state - the vuex state
	 */
	loadPermissions({commit, state}) {
		api
			.get('permissions?include=roles')
			.then((response) => {
				let permissions = response.data.data;
				commit('setPermissions', permissions);
			})
	},

	/**
	 * gets list of a user's roles from the api can calls mutation to store this in the state
	 * called from Editor.vue->created
	 *
	 * @param {object} state - the vuex state
	 * @param {object}	payload
	 * @param {int}		payload.site_id  - the id of the current site
	 * @param {string}	payload.username -  the name of the user
	 */
	loadSiteRole({commit, state}, payload) {
		api
			.get(`sites/${payload.site_id}?include=users`)
			.then(({data}) => {
				const userList = data.data.users;
				if (userList) {
					const currentUser = userList.find((element) => element.name === payload.username);
					commit('setCurrentRole', currentUser.role);
				}
				else {
					commit('setCurrentRole', {});
				}
			});
	},

	/**
	 * gets list of the logged in user's gloabl role
	 * called from TopBar.vue->mounted
	 *
	 * @param {string} username - the name of the user
	 */
	loadGlobalRole({commit, state}, username) {
		// note - username for admin is Admin, make assumption that all username should be lowercase
		api
			.get(`users/${username.toLowerCase()}`)
			.then(({data}) => {
				commit('setGlobalRole', data.data.global_role);
			})
			.catch(()=> {
				commit('setGlobalRole', '');
			})
	}

}

const mutations = {

	/**
	 * Used to initially set the permissions the editor understands
	 *
	 * @param {object} vuex state
	 * @param {object} permissions - the set of permissions as received from the API
	 */
	setPermissions(state, permissions) {
		state.roles = permissions;
	},

	/**
	 * sets the current role for the site
	 *
	 * @param {object} state - the vuex state
	 * @param {string} currentRole
	 */
	setCurrentRole(state, currentRole) {
		state.currentRole = currentRole;
	},

	/**
	 * sets the user's global role
	 *
	 * @param {object} state - the vuex state
	 * @param {string} gloablRole
	 */
	setGlobalRole(state, gloablRole) {
		state.globalRole = gloablRole;
	}
};

export default {
	state,
	getters,
	mutations,
	actions
};<commit_msg>Correcting confusion between username and name<commit_after>import api from 'plugins/http/api';

/**
 * Simple interface for interacting with user roles and permissions
 *
 * permissions is an array with the following structure
 *
[
		{
			"name": "Create Subsites",
			"slug": "subsite.create",
			"roles": [
				"site.owner"
			]
		},
		...
 */
const state = {
	roles: [],
	currentRole: '',
	globalRole: '',
};

const getters = {
	getCurrentRole(state, getters) {
		return state.currentSiteRole;
	},

	getRoles(state, getters) {
		return state.roles;
	},

	/**
	 * can the user perform the requested action
	 * if the user is a global admin then let them do anything
	 *
	 * @param {object} state - the vuex state
	 * @param {string} the permission to check i.e. subsite.edit, subsite.create
	 * @returns {bool} true or false
	 */
	canUser: (state, getters) => (permissionSlug) => {

		let permitted = false;

		// if the user has the global role of admin then then they can do anything
		if (state.globalRole === 'admin') {
			return true;
		}
		const matchedRole = state.roles.find(function(value) {
			if (value.slug == this.permissionSlug) {
				return true;
			}
		}, {permissionSlug});

		if (matchedRole) {
			permitted = matchedRole.roles.includes(state.currentRole);
		}

		return permitted;
	}
};

const actions = {

	/**
	 * gets list of roles from the api can calls mutation to store this in the state
	 * called from TopBar.vue->mounted
	 *
	 * @param {object} state - the vuex state
	 */
	loadPermissions({commit, state}) {
		api
			.get('permissions?include=roles')
			.then((response) => {
				let permissions = response.data.data;
				commit('setPermissions', permissions);
			})
	},

	/**
	 * gets list of a user's roles from the api can calls mutation to store this in the state
	 * called from Editor.vue->created
	 *
	 * @param {object} state - the vuex state
	 * @param {object}	payload
	 * @param {int}		payload.site_id  - the id of the current site
	 * @param {string}	payload.username -  the name of the user
	 */
	loadSiteRole({commit, state}, payload) {
		api
			.get(`sites/${payload.site_id}?include=users`)
			.then(({data}) => {
				const userList = data.data.users;
				if (userList) {
					const currentUser = userList.find((element) => element.username === payload.username);
					commit('setCurrentRole', currentUser.role);
				}
				else {
					commit('setCurrentRole', {});
				}
			});
	},

	/**
	 * gets list of the logged in user's gloabl role
	 * called from TopBar.vue->mounted
	 *
	 * @param {string} username - the name of the user
	 */
	loadGlobalRole({commit, state}, username) {
		// note - username for admin is Admin, make assumption that all username should be lowercase
		api
			.get(`users/${username.toLowerCase()}`)
			.then(({data}) => {
				commit('setGlobalRole', data.data.global_role);
			})
			.catch(()=> {
				commit('setGlobalRole', '');
			})
	}

}

const mutations = {

	/**
	 * Used to initially set the permissions the editor understands
	 *
	 * @param {object} vuex state
	 * @param {object} permissions - the set of permissions as received from the API
	 */
	setPermissions(state, permissions) {
		state.roles = permissions;
	},

	/**
	 * sets the current role for the site
	 *
	 * @param {object} state - the vuex state
	 * @param {string} currentRole
	 */
	setCurrentRole(state, currentRole) {
		state.currentRole = currentRole;
	},

	/**
	 * sets the user's global role
	 *
	 * @param {object} state - the vuex state
	 * @param {string} gloablRole
	 */
	setGlobalRole(state, gloablRole) {
		state.globalRole = gloablRole;
	}
};

export default {
	state,
	getters,
	mutations,
	actions
};<|endoftext|>


<commit_before>app.directive('bubbleChart', ['$window', function($window) {
	return {
		restrict: 'A',
		controller: 'chartController',
		link: function($scope, element, attrs) {
            var active = false;

            var w = angular.element($window);
            $scope.getWindowDimensions = function () {
                return {
                    'h': w.height(),
                    'w': w.width()
                };
            };

            angular.element($window).on('resize', function(){
                $scope.$apply();

                if(active)
                    renderChart();
            });

            $scope.$watch("artistData", function(n,o) {
                if(n==o) return;
                renderChart();
            });

            function renderChart() {
                active = true;

                element.empty();

                var width = $window.innerWidth,
                    height = $window.innerHeight - 98,
                    format = d3.format(",d"),
                    color = d3.scale.category10();

                var bubble = d3.layout.pack()
                    .sort(null)
                    .size([width, height])
                    .padding(18);

                var svg = d3.select(".d3").append("svg")
                    .attr("width", width)
                    .attr("height", height)
                    .attr("class", "bubble");

                var root = $scope.artistData;
                var node = svg.selectAll(".node")
                    .data(bubble.nodes(classes(root))
                    .filter(function(d) { return !d.children; }))
                    .enter().append("g")
                    .attr("class", "node")
                    .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
                    .style("cursor","pointer");

                d3.selectAll(".node").append("title")
                    .text(function(d) { return d.className + ": " + format(d.value); });

                node.append("circle")
                    .attr("r", function(d) { return d.r; })
                    .style("fill", "#202020")
                    .on("mouseover", function() {
                        d3.select(this)
                            .style("fill","red");
                    })
                    .on("mouseout", function() {
                        d3.select(this)
                            .style("fill", "#202020");
                    });

                d3.select(".node").append("text")
                    .attr("dy", ".3em")
                    .style("text-anchor", "middle")
                    .text(function(d) { return d.className; });

                // Returns a flattened hierarchy containing all leaf nodes under the root.
                function classes(root) {
                  var classes = [];

                  function recurse(name, node) {
                    if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
                    else classes.push({packageName: name, className: node.name, value: node.size});
                  }

                  recurse(null, root);
                  return {children: classes};
                }

                d3.select(self.frameElement).style("height", height + "px");
            }
		}
	}
}]);<commit_msg>modified SVG interactions<commit_after>app.directive('bubbleChart', ['$window', function($window) {
	return {
		restrict: 'A',
		controller: 'chartController',
		link: function($scope, element, attrs) {
            var active = false;

            var w = angular.element($window);
            $scope.getWindowDimensions = function () {
                return {
                    'h': w.height(),
                    'w': w.width()
                };
            };

            angular.element($window).on('resize', function(){
                $scope.$apply();

                if(active)
                    renderChart();
            });

            $scope.$watch("artistData", function(n,o) {
                if(n==o) return;
                renderChart();
            });

            $scope.clear = function() {
                $scope.searchTerm = '';
                element.empty();
            }

            function renderChart() {
                active = true;

                element.empty();

                var width = $window.innerWidth,
                    height = $window.innerHeight - 98,
                    format = d3.format(",d"),
                    color = d3.scale.category10();

                var bubble = d3.layout.pack()
                    .sort(null)
                    .size([width, height])
                    .padding(18);

                var root = $scope.artistData;

                var svg = d3.select(".d3").append("svg")
                    .attr("width", width)
                    .attr("height", height)
                    .attr("class", "bubble");

//                var defs = d3.select("svg")
//                    .append("svg:defs")
//                    .attr("id","mdef")
//                    .selectAll("pattern")
//                    .data(bubble.nodes(classes(root))
//                    .filter(function(d) { return !d.children; }))
//                    .enter().append("pattern")
//                    .attr("id", function(d) { return "image"+d.value; })
//                    .attr('patternUnits', 'userSpaceOnUse')
//                    .attr("x", 0)
//                    .attr("y", 0)
//                    .attr("width", function(d) { return Math.round(d.x/10); })
//                    .attr("height", function(d) { return Math.round(d.x/10); })
//                    .append("svg:image")
//                    .attr("x", 0)
//                    .attr("y", 0)
//                    .attr("width", function(d) { return Math.round(d.x/10); })
//                    .attr("height", function(d) { return Math.round(d.x/10); })
//                    .attr("xlink:href", function(d) { return d.image; });

                var node = svg.selectAll(".node")
                    .data(bubble.nodes(classes(root))
                    .filter(function(d) { return !d.children; }))
                    .enter().append("g")
                    .attr("class", "node")
                    .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
                    .style("cursor", "pointer");

                switch($scope.searchType) {
                    case 'artist':
                        d3.selectAll(".node")
                            .append("title")
                            .text(function(d) { return format(d.value) + " listeners"; });
                        break;
                    case 'similar':
                        d3.selectAll(".node")
                            .append("title")
                            .text(function(d) { return d.value*100 + "% similarity"; });
                        break;
                }

                node.append("circle")
                    .attr("r", function(d) { return d.r; })
                    .style("fill", "#202020")
                    .on("mouseenter", function() {
                        d3.select(this)
                            .style("fill", "red");

                        if(d3.select(this)[0][0].nextSibling) {
                            node.select("text").remove();
                            d3.select(this.parentNode)
                                .append("text")
                                .attr("dy", ".3em")
                                .style("text-anchor", "middle")
                                .style("pointer-events", "none")
                                .text(function(d) { return d.className });
                        }
                    })
                    .on("mouseleave", function() {
                        d3.select(this)
                            .style("fill", "#202020");

                        if(d3.select(this)[0][0].nextSibling) {
                            node.select("text").remove();
                            node.append("text")
                                .attr("dy", ".3em")
                                .style("text-anchor", "middle")
                                .style("pointer-events", "none")
                                .text(function(d) { return d.className.substring(0, d.r / 3); });
                        }
                    })
                    .on("mousedown", function() {
                        $scope.searchTerm = d3.select(this)[0][0].nextSibling.innerHTML
                        $scope.searchAgain();
                    });

//                d3.select(".node").append("text")
//                    .attr("dy", ".3em")
//                    .style("text-anchor", "middle")
//                    .text(function(d) { return d.className; });

                node.append("text")
                    .attr("dy", ".3em")
                    .style("text-anchor", "middle")
                    .style("pointer-events", "none")
                    .text(function(d) { return d.className.substring(0, d.r / 3); });

                // Returns a flattened hierarchy containing all leaf nodes under the root.
                function classes(root) {
                    var classes = [];

                    function recurse(name, node) {
                        if (node.children) {
                            node.children.forEach(function(child) {
                                recurse(node.name, child);
                            });
                        } else {
                            classes.push({packageName: name, className: node.name, value: node.size, image: (node.image) ? node.image : ''});
                        }
                    }

                    recurse(null, root);
                    return {children: classes};
                }

                d3.select(self.frameElement).style("height", height + "px");
            }
		}
	}
}]);<|endoftext|>


<commit_before>console.log('Loaded!');

//change the text of main-text div
var element = document.getElementById('main-text');
element.innerHTML = 'New Value';

var img = document.getElementById('madi');

var marginLeft = '0';
function moveRight(){
    marginLeft = marginLeft + 10;
    img.style.marginLeft = marginLeft + 'px';
}
img.onclick=function(){
    var interval = setInterval(moveRight,1000);
    //img.style.marginLeft = '100px';
};<commit_msg>[imad-console] Updates ui/main.js<commit_after>console.log('Loaded!');

//change the text of main-text div
var element = document.getElementById('main-text');
element.innerHTML = 'New Value';

var img = document.getElementById('madi');

var marginLeft = 0;
function moveRight(){
    marginLeft = marginLeft + 10;
    img.style.marginLeft = marginLeft + 'px';
}
img.onclick=function(){
    var interval = setInterval(moveRight,100);
    //img.style.marginLeft = '100px';
};<|endoftext|>


<commit_before>var request = require("request");
var fs = require("fs");
var toMarkdown = require('to-markdown');
var htmlparser = require("htmlparser2");

var articleModule = require('../model/article.js');
var blogModule = require('../model/blog.js');

var async = require('async');

// For Translation:

categoryTranslation =
{
  "[Aktuelle Kategorie]":"[Actual Category]",
  "In eigener Sache":"About us",
  "Wochenaufruf":"Weekly exerciseEN:",
  "Mapping":"Mapping",
  "Community":"Community",
  "Importe":"Imports",
  "OpenStreetMap Foundation":"OpenStreetMap Foundation",
  "Veranstaltungen":"Events",
  "Humanitarian OSM":"Humanitarian OSM",
  "Karten":"Maps",
  "switch2OSM":"#switch2OSM",
  "Open-Data":"Open Data",
  "Lizenzen":"Licences",
  "Programme":"Software",
  "Programmierung":"Programming",
  "Kennst Du schon …":"Did you know …",
  "Weitere Themen mit Geo-Bezug":'Other “geo” things',
  "Wochenvorschau" :"Weekly Preview",
  "ODbL":"ODbL",
  "Humanitarian OpenStreetMap":"Humanitarian OpenStreetMap",
  "Humanitarian OpenStreetMap Team":"Humanitarian OpenStreetMap Team",
  "Weltweit":"Global",
  "Sonstiges":"Other",
  "Talk, Forum, Wiki & Blog":"Talk, Forum, Wiki & Blog",
  "Talk, Forum, Wiki":"Talk, Forum, Wiki",
  "Blog & Twitter":"Blog & Twitter",
  "Import":"Import",
  "Tagging":"Tagging",
  "Open Data & ODbL":"Open Data & ODbL",
  "Konferenzen & Treffen":"Conferences",
  "und sonst":"Other",
  "Karten & Programme":"Maps & Programs",
  "#switch2osm":"#switch2osm",
  "Weltweit & sonstiges":"Global & Other"

}

// This is the simple HTML Parser for the WN

var currentCategory = new Category();
var currentElement = "";

var status = null;
var result = [];
var categoryList = [];

var parser = new htmlparser.Parser({
    onopentag: function(name, attribs){
        // ignore everything in comment mode
        if (status == "finished") return;

        if(name == "h2" ){
            status = "category";

        }
        if (name == "li") {
          status = "list";
        }
        if (name == "a" && status == "list") {
            currentElement += "";

        }
        if (name == "div") {
          if (attribs.id == "entry-author-info") {
            status = "finished";
            result.push(currentCategory);
          }
        }
    },
    ontext: function(text){
        if (status == "finished") return;

        if (status == "category" && text != currentCategory.title) {
          text = text.replace("&","&")
          result.push(currentCategory);
          currentCategory =new Category();
          currentCategory.title = text;
          categoryList.push(text);
        }
        if (status == "list") {
          currentElement += text;
        }

    },
    onclosetag: function(tagname){
        if (status == "finished") return;
        if(tagname === "h2"){
           status = "";
        }
        if(tagname === "li"){
           status = "";
           currentCategory.element.push(currentElement);
           currentElement = "";
        }
        if (tagname == "a" && status == "list") {
            currentElement += "";

        }

    }
}, {decodeEntities: false});

 function Category() {
    this.title = null;
    this.element = [];
  }

 function importBlog(nr,callback) {
   var number = "000"+nr;

   var blogName = "WN"+number.substring(number.length-3,99);
   console.log("Import WN "+blogName);

   blogModule.findOne({name:blogName},function (err,b) {
    if (b) {
      console.log(blogName+" allready exists");
      return callback();
    }

    var body = null;
    var url = null;
    async.parallel([
      function tryOneName(cb) {
        var u = "http://blog.openstreetmap.de/blog/wochennotiz-nr-"+nr;
        request(u, function (error, response, b) {
          if (!error) {
            body = b;
            url = u;
          }
          cb();
        })
      },
      function tryOneName(cb) {
        var u = "http://blog.openstreetmap.de/blog/osm-wochennotiz-nr-"+nr;
        request(u, function (error, response, b) {
          if (!error) {
            body = b;
            url = u;
          }
          cb();
        })
      }

      ],
      function loadedWN(err){
        website = body;
        if (body) {
          status = null;
          result = [];
          categoryList = [];
          parser.write(body);
          console.log("Loaded Url:",url);
          //console.log("Articles: ",result);
          var blog = blogModule.create();

          //fs.writeFileSync(blogName,body,"utf8");

          var cat =[];
          for (var i=0;i<categoryList.length;i++) {
            var c = {DE:categoryList[i]};
            if (c.DE in categoryTranslation) {
              c.EN = categoryTranslation[c.DE];
            }
            else
            {
              c.EN = c.DE+"Not Translated";
              console.log(c.EN);
            }
            cat.push(c);
          }

          blog.setAndSave("IMPORT",{name:blogName,status:"published",categories:cat},function(err,erg){
            console.log("Blog Saved Error("+err+")");
            async.each(result,function iterator(item,cb) {
              var category = item.title;
              //console.dir("ITEM"+item);
              if (category == null) return cb();
              //console.dir("Import Category: "+category);
              //console.dir(item.element.length+" Elements in Category");
              async.each(item.element,function eachArticle(articleProto,cba) {
                //console.log(articleProto);
                var markdown = toMarkdown(articleProto);
                var article = articleModule.create();
                article.setAndSave("IMPORT",{blog:blogName,category:category,markdown:markdown},function(err){
                  //console.log("Article Saved");
                  cba(err);
                });

              }, function done() {cb();}
              )

            }, function(done) {
              console.log("Blog "+blogName+ " imported");
              callback();
            }
            )
          })
        }
      })

    });
  }

async.timesLimit(268,1,function (n,next){
  importBlog(n,next);

})
<commit_msg>Quickfix for import.<commit_after>var request = require("request");
var fs = require("fs");
var toMarkdown = require('to-markdown');
var htmlparser = require("htmlparser2");

var articleModule = require('../model/article.js');
var blogModule = require('../model/blog.js');
var config=require('../config.js')

var async = require('async');

// For Translation:

categoryTranslation =
{
  "[Aktuelle Kategorie]":"[Actual Category]",
  "In eigener Sache":"About us",
  "Wochenaufruf":"Weekly exerciseEN:",
  "Mapping":"Mapping",
  "Community":"Community",
  "Importe":"Imports",
  "OpenStreetMap Foundation":"OpenStreetMap Foundation",
  "Veranstaltungen":"Events",
  "Humanitarian OSM":"Humanitarian OSM",
  "Karten":"Maps",
  "switch2OSM":"#switch2OSM",
  "Open-Data":"Open Data",
  "Lizenzen":"Licences",
  "Programme":"Software",
  "Programmierung":"Programming",
  "Kennst Du schon …":"Did you know …",
  "Weitere Themen mit Geo-Bezug":'Other “geo” things',
  "Wochenvorschau" :"Weekly Preview",
  "ODbL":"ODbL",
  "Humanitarian OpenStreetMap":"Humanitarian OpenStreetMap",
  "Humanitarian OpenStreetMap Team":"Humanitarian OpenStreetMap Team",
  "Weltweit":"Global",
  "Sonstiges":"Other",
  "Talk, Forum, Wiki & Blog":"Talk, Forum, Wiki & Blog",
  "Talk, Forum, Wiki":"Talk, Forum, Wiki",
  "Blog & Twitter":"Blog & Twitter",
  "Import":"Import",
  "Tagging":"Tagging",
  "Open Data & ODbL":"Open Data & ODbL",
  "Konferenzen & Treffen":"Conferences",
  "und sonst":"Other",
  "Karten & Programme":"Maps & Programs",
  "#switch2osm":"#switch2osm",
  "Weltweit & sonstiges":"Global & Other"

}

// This is the simple HTML Parser for the WN

var currentCategory = new Category();
var currentElement = "";

var status = null;
var result = [];
var categoryList = [];

var parser = new htmlparser.Parser({
    onopentag: function(name, attribs){
        // ignore everything in comment mode
        if (status == "finished") return;

        if(name == "h2" ){
            status = "category";

        }
        if (name == "li") {
          status = "list";
        }
        if (name == "a" && status == "list") {
            currentElement += "";

        }
        if (name == "div") {
          if (attribs.id == "entry-author-info") {
            status = "finished";
            result.push(currentCategory);
          }
        }
    },
    ontext: function(text){
        if (status == "finished") return;

        if (status == "category" && text != currentCategory.title) {
          text = text.replace("&","&")
          result.push(currentCategory);
          currentCategory =new Category();
          currentCategory.title = text;
          categoryList.push(text);
        }
        if (status == "list") {
          currentElement += text;
        }

    },
    onclosetag: function(tagname){
        if (status == "finished") return;
        if(tagname === "h2"){
           status = "";
        }
        if(tagname === "li"){
           status = "";
           currentCategory.element.push(currentElement);
           currentElement = "";
        }
        if (tagname == "a" && status == "list") {
            currentElement += "";

        }

    }
}, {decodeEntities: false});

 function Category() {
    this.title = null;
    this.element = [];
  }

 function importBlog(nr,callback) {
   var number = "000"+nr;

   var blogName = "WN"+number.substring(number.length-3,99);
   console.log("Import WN "+blogName);

   blogModule.findOne({name:blogName},function (err,b) {
    if (b) {
      console.log(blogName+" allready exists");
      return callback();
    }

    var body = null;
    var url = null;
    async.parallel([
      function tryOneName(cb) {
        var u = "http://blog.openstreetmap.de/blog/wochennotiz-nr-"+nr;
        request(u, function (error, response, b) {
          if (!error) {
            body = b;
            url = u;
          }
          cb();
        })
      },
      function tryOneName(cb) {
        var u = "http://blog.openstreetmap.de/blog/osm-wochennotiz-nr-"+nr;
        request(u, function (error, response, b) {
          if (!error) {
            body = b;
            url = u;
          }
          cb();
        })
      }

      ],
      function loadedWN(err){
        website = body;
        if (body) {
          status = null;
          result = [];
          categoryList = [];
          parser.write(body);
          console.log("Loaded Url:",url);
          //console.log("Articles: ",result);
          var blog = blogModule.create();

          //fs.writeFileSync(blogName,body,"utf8");

          var cat =[];
          for (var i=0;i<categoryList.length;i++) {
            var c = {DE:categoryList[i]};
            if (c.DE in categoryTranslation) {
              c.EN = categoryTranslation[c.DE];
            }
            else
            {
              c.EN = c.DE+"Not Translated";
              console.log(c.EN);
            }
            cat.push(c);
          }

          blog.setAndSave("IMPORT",{name:blogName,status:"published",categories:cat},function(err,erg){
            console.log("Blog Saved Error("+err+")");
            async.each(result,function iterator(item,cb) {
              var category = item.title;
              //console.dir("ITEM"+item);
              if (category == null) return cb();
              //console.dir("Import Category: "+category);
              //console.dir(item.element.length+" Elements in Category");
              async.each(item.element,function eachArticle(articleProto,cba) {
                //console.log(articleProto);
                var markdown = toMarkdown(articleProto);
                var article = articleModule.create();
                article.setAndSave("IMPORT",{blog:blogName,category:category,markdown:markdown},function(err){
                  //console.log("Article Saved");
                  cba(err);
                });

              }, function done() {cb();}
              )

            }, function(done) {
              console.log("Blog "+blogName+ " imported");
              callback();
            }
            )
          })
        }
      })

    });
  }

config.initialise();

importBlog(268,function(){console.log("Ready.")});
importBlog(269,function(){console.log("Ready.")});
importBlog(270,function(){console.log("Ready.")});
importBlog(271,function(){console.log("Ready.")});
/*
async.timesLimit(1,1,function (n,next){
  console.log("Start Import for "+n);
  importBlog(n,next);

})*/
<|endoftext|>


<commit_before>var RealAccOpeningUI = (function(){
    "use strict";

    function setValues(dobdd, dobmm, dobyy, state, question){
        generateBirthDate(dobdd, dobmm, dobyy);
        generateState(state);

        var secretQuestions = [
            "Mother's maiden name",
            "Name of your pet",
            "Name of first love",
            "Memorable town/city",
            "Memorable date",
            "Favourite dish",
            "Brand of first car",
            "Favourite artist"
        ];

        for (i = 0; i < secretQuestions.length; i++) {
            appendTextValueChild(question, secretQuestions[i], secretQuestions[i]);
        }

    }

    function showError(){
        $('#real-form').remove();
        var error = document.getElementsByClassName('notice-msg')[0];
        error.innerHTML = Content.localize().textUnavailableReal;
        error.parentNode.parentNode.parentNode.setAttribute('style', 'display:block');
    }

    function hideAllErrors(allErrors) {
        for (i = 0; i < allErrors.length; i++) {
            Validate.hideErrorMessage(allErrors[i]);
        }
    }

    function checkValidity(){
        var errorCounter = 0;

        var letters = Content.localize().textLetters,
            numbers = Content.localize().textNumbers,
            space   = Content.localize().textSpace,
            hyphen  = Content.localize().textHyphen,
            period  = Content.localize().textPeriod,
            apost   = Content.localize().textApost;

        var title     = document.getElementById('title'),
            fname     = document.getElementById('fname'),
            lname     = document.getElementById('lname'),
            dobdd     = document.getElementById('dobdd'),
            dobmm     = document.getElementById('dobmm'),
            dobyy     = document.getElementById('dobyy'),
            residence = document.getElementById('residence-disabled'),
            address1  = document.getElementById('address1'),
            address2  = document.getElementById('address2'),
            town      = document.getElementById('address-town'),
            state     = document.getElementById('address-state'),
            postcode  = document.getElementById('address-postcode'),
            tel       = document.getElementById('tel'),
            question  = document.getElementById('secret-question'),
            answer    = document.getElementById('secret-answer'),
            tnc       = document.getElementById('tnc');

        var arr = [
                    title.value,
                    fname.value,
                    lname.value,
                    dobyy.value + '-' + dobmm.value + '-' + dobdd.value,
                    $.cookie('residence'),
                    address1.value,
                    address2.value,
                    town.value,
                    state.value,
                    postcode.value,
                    tel.value,
                    question.value,
                    answer.value
                ];

        var errorTitle     = document.getElementById('error-title'),
            errorFname     = document.getElementById('error-fname'),
            errorLname     = document.getElementById('error-lname'),
            errorBirthdate = document.getElementById('error-birthdate'),
            errorResidence = document.getElementById('error-residence'),
            errorAddress1  = document.getElementById('error-address1'),
            errorAddress2  = document.getElementById('error-address2'),
            errorTown      = document.getElementById('error-town'),
            errorState     = document.getElementById('error-state'),
            errorPostcode  = document.getElementById('error-postcode'),
            errorTel       = document.getElementById('error-tel'),
            errorQuestion  = document.getElementById('error-question'),
            errorAnswer    = document.getElementById('error-answer'),
            errorTnc       = document.getElementById('error-tnc');

        var allErrors = [
                            errorTitle,
                            errorFname,
                            errorLname,
                            errorBirthdate,
                            errorResidence,
                            errorAddress1,
                            errorAddress2,
                            errorTown,
                            errorState,
                            errorPostcode,
                            errorTel,
                            errorQuestion,
                            errorAnswer,
                            errorTnc
                        ];

        hideAllErrors(allErrors);

        if (!/^[a-zA-Z]+([\s\-|\.|\'|a-zA-Z]*)*$/.test(fname.value)){
            errorFname.innerHTML = Content.errorMessage('reg', [letters, space, hyphen, period, apost, ' ']);
            Validate.displayErrorMessage(errorFname);
            errorCounter++;
        }

        if (!/^[a-zA-Z]+([\s\-|\.|\'|a-zA-Z]*)*$/.test(lname.value)){
            errorLname.innerHTML = Content.errorMessage('reg', [letters, space, hyphen, period, apost, ' ']);
            Validate.displayErrorMessage(errorLname);
            errorCounter++;
        }

        if (!isValidDate(dobdd.value, dobmm.value, dobyy.value)) {
            errorBirthdate.innerHTML = Content.localize().textErrorBirthdate;
            Validate.displayErrorMessage(errorBirthdate);
            errorCounter++;
        }

        if (!/^[a-zA-Z|\d]+(\s|-|.|'[a-zA-Z]*)*$/.test(address1.value)){
            errorAddress1.innerHTML = Content.errorMessage('reg', [letters, numbers, space, hyphen, period, apost, ' ']);
            Validate.displayErrorMessage(errorAddress1);
            errorCounter++;
        }

        if (!/^[a-zA-Z]+(\s|-|.[a-zA-Z]*)*$/.test(town.value)){
            errorTown.innerHTML = Content.errorMessage('reg', [letters, space, hyphen, period, ' ']);
            Validate.displayErrorMessage(errorTown);
            errorCounter++;
        }

        if(state.offsetParent !== null && state.value === '') {
            errorState.innerHTML = Content.errorMessage('req');
            Validate.displayErrorMessage(errorState);
            errorCounter++;
        }

        if (!/^\d+(-|\d]*)*$/.test(postcode.value)){
            errorPostcode.innerHTML = Content.errorMessage('reg', [numbers, hyphen, ' ']);
            Validate.displayErrorMessage(errorPostcode);
            errorCounter++;
        }

        if (tel.value.length < 6) {
            errorTel.innerHTML = Content.errorMessage('min', 6);
            Validate.displayErrorMessage(errorTel);
            errorCounter++;
        } else if (!/^\+?\d{6,35}$/.test(tel.value)){
            errorTel.innerHTML = Content.errorMessage('reg', [numbers, hyphen, ' ']);
            Validate.displayErrorMessage(errorTel);
            errorCounter++;
        }

        if (answer.value.length < 4) {
            errorAnswer.innerHTML = Content.errorMessage('min', 4);
            Validate.displayErrorMessage(errorAnswer);
            errorCounter++;
        } else if (!/^[a-zA-Z0-9]*(\s|-|.[a-zA-Z0-9]*){4,60}$/.test(answer.value)){
            errorAnswer.innerHTML = Content.errorMessage('reg', [numbers, hyphen, ' ']);
            Validate.displayErrorMessage(errorAnswer);
            errorCounter++;
        }

        if (!tnc.checked){
            errorTnc.innerHTML = Content.errorMessage('req');
            Validate.displayErrorMessage(errorTnc);
            errorCounter++;
        }

        for (i = 0; i < arr.length; i++){
            if (/^$/.test(arr[i]) && i !== 8){
                allErrors[i].innerHTML = Content.errorMessage('req');
                Validate.displayErrorMessage(allErrors[i]);
                errorCounter++;
            }
        }

        if (errorCounter === 0) {
            RealAccOpeningData.getRealAcc(arr);
            hideAllErrors(allErrors);
            return 1;
        }

        return 0;
    }

    return {
        setValues: setValues,
        showError: showError,
        checkValidity: checkValidity
    };
})();<commit_msg>add ui changes<commit_after>var RealAccOpeningUI = (function(){
    "use strict";

    function setValues(dobdd, dobmm, dobyy, state, question){
        generateBirthDate(dobdd, dobmm, dobyy);
        generateState(state);

        var secretQuestions = [
            "Mother's maiden name",
            "Name of your pet",
            "Name of first love",
            "Memorable town/city",
            "Memorable date",
            "Favourite dish",
            "Brand of first car",
            "Favourite artist"
        ];

        for (i = 0; i < secretQuestions.length; i++) {
            appendTextValueChild(question, secretQuestions[i], secretQuestions[i]);
        }

    }

    function showError(opt){
        $('#real-form').remove();
        var error = document.getElementsByClassName('notice-msg')[0];
        if (opt === 'duplicate') {
            error.innerHTML = text.localize("Sorry, you seem to already have a real money account with us. Perhaps you have used a different email address when you registered it. For legal reasons we are not allowed to open multiple real money accounts per person. If you don't remember your account with us, please") + " " + "" + text.localize("contact us") + "";
        } else {
            error.innerHTML = Content.localize().textUnavailableReal;
        }
        error.parentNode.parentNode.parentNode.setAttribute('style', 'display:block');
    }

    function hideAllErrors(allErrors) {
        for (i = 0; i < allErrors.length; i++) {
            Validate.hideErrorMessage(allErrors[i]);
        }
    }

    function checkValidity(){
        var errorCounter = 0;

        var letters = Content.localize().textLetters,
            numbers = Content.localize().textNumbers,
            space   = Content.localize().textSpace,
            hyphen  = Content.localize().textHyphen,
            period  = Content.localize().textPeriod,
            apost   = Content.localize().textApost;

        var title     = document.getElementById('title'),
            fname     = document.getElementById('fname'),
            lname     = document.getElementById('lname'),
            dobdd     = document.getElementById('dobdd'),
            dobmm     = document.getElementById('dobmm'),
            dobyy     = document.getElementById('dobyy'),
            residence = document.getElementById('residence-disabled'),
            address1  = document.getElementById('address1'),
            address2  = document.getElementById('address2'),
            town      = document.getElementById('address-town'),
            state     = document.getElementById('address-state'),
            postcode  = document.getElementById('address-postcode'),
            tel       = document.getElementById('tel'),
            question  = document.getElementById('secret-question'),
            answer    = document.getElementById('secret-answer'),
            tnc       = document.getElementById('tnc');

        var arr = [
                    title.value,
                    fname.value,
                    lname.value,
                    dobyy.value + '-' + dobmm.value + '-' + dobdd.value,
                    $.cookie('residence'),
                    address1.value,
                    address2.value,
                    town.value,
                    state.value,
                    postcode.value,
                    tel.value,
                    question.value,
                    answer.value
                ];

        var errorTitle     = document.getElementById('error-title'),
            errorFname     = document.getElementById('error-fname'),
            errorLname     = document.getElementById('error-lname'),
            errorBirthdate = document.getElementById('error-birthdate'),
            errorResidence = document.getElementById('error-residence'),
            errorAddress1  = document.getElementById('error-address1'),
            errorAddress2  = document.getElementById('error-address2'),
            errorTown      = document.getElementById('error-town'),
            errorState     = document.getElementById('error-state'),
            errorPostcode  = document.getElementById('error-postcode'),
            errorTel       = document.getElementById('error-tel'),
            errorQuestion  = document.getElementById('error-question'),
            errorAnswer    = document.getElementById('error-answer'),
            errorTnc       = document.getElementById('error-tnc');

        var allErrors = [
                            errorTitle,
                            errorFname,
                            errorLname,
                            errorBirthdate,
                            errorResidence,
                            errorAddress1,
                            errorAddress2,
                            errorTown,
                            errorState,
                            errorPostcode,
                            errorTel,
                            errorQuestion,
                            errorAnswer,
                            errorTnc
                        ];

        hideAllErrors(allErrors);

        if (!/^[a-zA-Z]+([\s\-|\.|\'|a-zA-Z]*)*$/.test(fname.value)){
            errorFname.innerHTML = Content.errorMessage('reg', [letters, space, hyphen, period, apost, ' ']);
            Validate.displayErrorMessage(errorFname);
            errorCounter++;
        }

        if (!/^[a-zA-Z]+([\s\-|\.|\'|a-zA-Z]*)*$/.test(lname.value)){
            errorLname.innerHTML = Content.errorMessage('reg', [letters, space, hyphen, period, apost, ' ']);
            Validate.displayErrorMessage(errorLname);
            errorCounter++;
        }

        if (!isValidDate(dobdd.value, dobmm.value, dobyy.value)) {
            errorBirthdate.innerHTML = Content.localize().textErrorBirthdate;
            Validate.displayErrorMessage(errorBirthdate);
            errorCounter++;
        }

        if (!/^[a-zA-Z|\d]+(\s|-|.|'[a-zA-Z]*)*$/.test(address1.value)){
            errorAddress1.innerHTML = Content.errorMessage('reg', [letters, numbers, space, hyphen, period, apost, ' ']);
            Validate.displayErrorMessage(errorAddress1);
            errorCounter++;
        }

        if (!/^[a-zA-Z]+(\s|-|.[a-zA-Z]*)*$/.test(town.value)){
            errorTown.innerHTML = Content.errorMessage('reg', [letters, space, hyphen, period, ' ']);
            Validate.displayErrorMessage(errorTown);
            errorCounter++;
        }

        if(state.offsetParent !== null && state.value === '') {
            errorState.innerHTML = Content.errorMessage('req');
            Validate.displayErrorMessage(errorState);
            errorCounter++;
        }

        if (!/^\d+(-|\d]*)*$/.test(postcode.value)){
            errorPostcode.innerHTML = Content.errorMessage('reg', [numbers, hyphen, ' ']);
            Validate.displayErrorMessage(errorPostcode);
            errorCounter++;
        }

        if (tel.value.length < 6) {
            errorTel.innerHTML = Content.errorMessage('min', 6);
            Validate.displayErrorMessage(errorTel);
            errorCounter++;
        } else if (!/^\+?\d{6,35}$/.test(tel.value)){
            errorTel.innerHTML = Content.errorMessage('reg', [numbers, hyphen, ' ']);
            Validate.displayErrorMessage(errorTel);
            errorCounter++;
        }

        if (answer.value.length < 4) {
            errorAnswer.innerHTML = Content.errorMessage('min', 4);
            Validate.displayErrorMessage(errorAnswer);
            errorCounter++;
        } else if (!/^[a-zA-Z0-9]*(\s|-|.[a-zA-Z0-9]*){4,60}$/.test(answer.value)){
            errorAnswer.innerHTML = Content.errorMessage('reg', [numbers, hyphen, ' ']);
            Validate.displayErrorMessage(errorAnswer);
            errorCounter++;
        }

        if (!tnc.checked){
            errorTnc.innerHTML = Content.errorMessage('req');
            Validate.displayErrorMessage(errorTnc);
            errorCounter++;
        }

        for (i = 0; i < arr.length; i++){
            if (/^$/.test(arr[i]) && i !== 6 && i !== 8){
                allErrors[i].innerHTML = Content.errorMessage('req');
                Validate.displayErrorMessage(allErrors[i]);
                errorCounter++;
            }
        }

        if (errorCounter === 0) {
            RealAccOpeningData.getRealAcc(arr);
            hideAllErrors(allErrors);
            return 1;
        }

        return 0;
    }

    return {
        setValues: setValues,
        showError: showError,
        checkValidity: checkValidity
    };
})();<|endoftext|>


<commit_before>
/**
 * @return {string}
 * @public
 */
Object.prototype.toString = function() {
  return window.String(this.$javaToString());
};
<commit_msg>Add @override annotation to Object.toString.<commit_after>
/**
 * @override
 * @return {string}
 * @public
 */
Object.prototype.toString = function() {
  return window.String(this.$javaToString());
};
<|endoftext|>


<commit_before>chrome.extension.onMessage.addListener(
    function (request, sender, sendResponse) {
        switch (request.action) {
            case 'playNow':
                playCurrentUrl(function () {
                    sendResponse({response: "OK"});
                });
                break;

            case 'queue':
                queueCurrentUrl(function () {
                    sendResponse({response: "OK"});
                });
                break;
            case 'queueList':
                queueList(request.urlList, function () {
                    sendResponse({response: "OK"});
                });
                break;

            case 'removeThis':
                removeThisFromPlaylist(function () {
                    sendResponse({response: "OK"});
                });
                break;

            case 'playNextCurrent':
                playNextCurrentUrl(function () {
                    sendResponse({response: "OK"});
                });
        }

        return true;
    }
);

function doAction(item, callback) {
    getActivePlayerId(function (playerid) {
        if (playerid != null) {
            var action = '{"jsonrpc": "2.0", "method": "' + item + '", "params":{"playerid":' + playerid + '}, "id" : 1}';
            ajaxPost(action, function (result) {
                callback(result);
            });
        } else {
            callback(null);
        }
    });
}

function playCurrentUrl(callback) {
    doAction(actions.Stop, function () {
        queueCurrentUrl(callback);
    });
}

function playNextCurrentUrl(callback) {
    getCurrentUrl(function (tabUrl) {
        getPlaylistPosition(function (position) {
            insertItem(tabUrl, position + 1, function () {
                callback();
            });
        });
    });
}

function queueCurrentUrl(callback) {
    getCurrentUrl(function (tabUrl) {
        queueItem(tabUrl, function () {
            callback();
        });
    });
}

function queueList(urlList, callback) {
    if (urlList.length === 0) {
        callback();
        return;
    }
    queueItems(urlList, function (result) {
        callback();

    });
}

function removeThisFromPlaylist(callback) {
    getPlaylistPosition(function (position) {
        playerGoNext(function () {
            removeItemFromPlaylist(position, function () {
                callback();
            });
        });
    });
}

<commit_msg>Fix a bug where 'Play Now' will not clear the playlist and instead queues the given video and starts from the beginning of the original playlist.<commit_after>chrome.extension.onMessage.addListener(
    function (request, sender, sendResponse) {
        switch (request.action) {
            case 'playNow':
                playCurrentUrl(function () {
                    sendResponse({response: "OK"});
                });
                break;

            case 'queue':
                queueCurrentUrl(function () {
                    sendResponse({response: "OK"});
                });
                break;
            case 'queueList':
                queueList(request.urlList, function () {
                    sendResponse({response: "OK"});
                });
                break;

            case 'removeThis':
                removeThisFromPlaylist(function () {
                    sendResponse({response: "OK"});
                });
                break;

            case 'playNextCurrent':
                playNextCurrentUrl(function () {
                    sendResponse({response: "OK"});
                });
        }

        return true;
    }
);

function doAction(item, callback) {
    getActivePlayerId(function (playerid) {
        if (playerid != null) {
            var action = '{"jsonrpc": "2.0", "method": "' + item + '", "params":{"playerid":' + playerid + '}, "id" : 1}';
            ajaxPost(action, function (result) {
                callback(result);
            });
        } else {
            callback(null);
        }
    });
}

function playCurrentUrl(callback) {
    doAction(actions.Stop, function () {
        clearPlaylist(function() {
            queueCurrentUrl(callback);
        })
    });
}

function playNextCurrentUrl(callback) {
    getCurrentUrl(function (tabUrl) {
        getPlaylistPosition(function (position) {
            insertItem(tabUrl, position + 1, function () {
                callback();
            });
        });
    });
}

function queueCurrentUrl(callback) {
    getCurrentUrl(function (tabUrl) {
        queueItem(tabUrl, function () {
            callback();
        });
    });
}

function queueList(urlList, callback) {
    if (urlList.length === 0) {
        callback();
        return;
    }
    queueItems(urlList, function (result) {
        callback();

    });
}

function removeThisFromPlaylist(callback) {
    getPlaylistPosition(function (position) {
        playerGoNext(function () {
            removeItemFromPlaylist(position, function () {
                callback();
            });
        });
    });
}

<|endoftext|>


<commit_before>import React from "react";
import PropTypes from "prop-types";
import ContextMenu from "./ContextMenu";

export default class ContextMenuWraper extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selected: false,
      offsetTop: null,
      offsetLeft: null
    };
    this._handleRightClick = this._handleRightClick.bind(this);
    this._handleGlobalClick = this._handleGlobalClick.bind(this);
  }

  componentWillUnmount() {
    document.removeEventListener("click", this._handleGlobalClick);
  }

  _handleGlobalClick() {
    this.setState({
      selected: false,
      offsetTop: null,
      offsetLeft: null
    });
    document.removeEventListener("click", this._handleGlobalClick);
  }

  _handleRightClick(e) {
    const { pageX, pageY } = e;
    this.setState({
      selected: true,
      // TODO: We could do an initial render to see if the menu fits here
      // and do a second render if it does not.
      offsetTop: pageY,
      offsetLeft: pageX
    });
    // This used to be a "click" handler, but Firefox would trigger a "click"
    // event on the mouseup of the click that triggered `_handleRightClick` in the
    // first place.
    //
    // If there are multiple right-clicks before there is a global click,
    // the browser will dedupe this binding for us, since the bound function
    // is referentially identical each time.
    document.addEventListener("mousedown", this._handleGlobalClick);
    e.preventDefault();
    e.stopPropagation();
  }

  render() {
    const { children, renderContents, ...passThroughProps } = this.props;
    return (
      <div
        onContextMenu={this._handleRightClick}
        style={{ width: "100%", height: "100%" }}
        {...passThroughProps}
      >
        <ContextMenu
          selected={this.state.selected}
          offsetTop={this.state.offsetTop}
          offsetLeft={this.state.offsetLeft}
        >
          {renderContents()}
        </ContextMenu>
        {children}
      </div>
    );
  }
}

ContextMenuWraper.propTypes = {
  children: PropTypes.any.isRequired,
  renderContents: PropTypes.func.isRequired
};
<commit_msg>Revert "Fix #610"<commit_after>import React from "react";
import PropTypes from "prop-types";
import ContextMenu from "./ContextMenu";

export default class ContextMenuWraper extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selected: false,
      offsetTop: null,
      offsetLeft: null
    };
    this._handleRightClick = this._handleRightClick.bind(this);
    this._handleGlobalClick = this._handleGlobalClick.bind(this);
  }

  componentWillUnmount() {
    document.removeEventListener("click", this._handleGlobalClick);
  }

  _handleGlobalClick() {
    this.setState({
      selected: false,
      offsetTop: null,
      offsetLeft: null
    });
    document.removeEventListener("click", this._handleGlobalClick);
  }

  _handleRightClick(e) {
    const { pageX, pageY } = e;
    this.setState({
      selected: true,
      // TODO: We could do an initial render to see if the menu fits here
      // and do a second render if it does not.
      offsetTop: pageY,
      offsetLeft: pageX
    });
    // Even if you right click multiple times before closeing,
    // we should only end up with one global listener.
    document.addEventListener("click", this._handleGlobalClick);
    e.preventDefault();
    e.stopPropagation();
  }

  render() {
    const { children, renderContents, ...passThroughProps } = this.props;
    return (
      <div
        onContextMenu={this._handleRightClick}
        style={{ width: "100%", height: "100%" }}
        {...passThroughProps}
      >
        <ContextMenu
          selected={this.state.selected}
          offsetTop={this.state.offsetTop}
          offsetLeft={this.state.offsetLeft}
        >
          {renderContents()}
        </ContextMenu>
        {children}
      </div>
    );
  }
}

ContextMenuWraper.propTypes = {
  children: PropTypes.any.isRequired,
  renderContents: PropTypes.func.isRequired
};
<|endoftext|>


<commit_before>function interpret(code) {
  var output = "";
  // TODO: Interpret the code!
  return output;
}

exports.interpret = interpret;<commit_msg>Written code that supports operations, need to test it though<commit_after>function interpret(code) {
  var program = new BefungeProgram(code);
  while (!program.isRunning)
    program.runNextInstruction();
  return program.output;
}

function BefungeProgram(code) {
  var instructions = code.split('\n').map(function (line) { return line.split(''); });
  instructions.get = function () {
    var args = arguments[0] instanceof Array ? arguments[0] : arguments;
    return this[args[0]][args[1]];
  };
  instructions.set = function () {
    var args = arguments[0] instanceof Array ? arguments[0] : arguments;
    this[args[0]][args[1]] = arguments.length - 1;
  };

  var stack = [];
  var output = '';
  var codePointer = [0, 0];
  var direction = '>';
  var asciiMode = false;

  var self = this;

  function addProperty(property, getter) {
    Object.defineProperty(self, property, { get: getter });
  }

  addProperty('stack', function () { return stack.slice(); });
  addProperty('output', function () { return output; });
  addProperty('isRunning', function () {
    var current = instructions.get(codePointer);
    return current != '@' && !current;
  });

  function nextMove() {
    switch (direction) {
      case '<':
        codePointer[0] -= 1;
        break;
      case '>':
        codePointer[0] += 1;
        break;
      case '^':
        codePointer[1] -= 1;
        break;
      case 'v':
        codePointer[1] += 1;
        break;
    }
  }

  function processInstruction(instruction) {
    var a, b;
    if (asciiMode) {
      stack.push(instruction.charCodeAt(0));
      return nextMove();
    } else if (instruction == '@')
      return;
    else if (instruction >= '0' && '9' >= instruction)
      stack.push(instruction);
    else if (instruction == '+')
      stack.push(stack.pop() + stack.pop());
    else if (instruction == '-')
      stack.push(-stack.pop() + stack.pop());
    else if (instruction == '*')
      stack.push(stack.pop() * stack.pop());
    else if (instruction == '/')
      !(a = stack.pop()) ? a : Math.ceil(stack.pop() / a);
    else if (instruction == '%')
      !(a = stack.pop()) ? a : Math.ceil(stack.pop() % a);
    else if (instruction == '!')
      !stack.pop() ? 1 : 0;
    else if (instruction == '`')
      stack.pop() >= stack.pop() ? 0 : 1;
    else if (~'<>^v'.indexOf(instruction))
      direction = instruction;
    else if (instruction == '>')
      codePointer[0] += 1;
    else if (instruction == 'v')
      codePointer[1] += 1;
    else if (instruction == '^')
      codePointer[1] -= 1;
    else if (instruction == '?')
      this.runInstruction('<>v^'[~~(Math.random() * 5)]);
    else if (instruction == '_')
      direction = stack.pop() ? '<' : '>';
    else if (instruction == '|')
      direction = stack.pop() ? '^' : 'v';
    else if (instruction == '"')
      asciiMode = !asciiMode;
    else if (instruction == ':')
      (a = stack.pop()) === undefined ? stack.push(0) : (stack.push(a), stack.push(a));
    else if (instruction == '.')
      output += stack.pop();
    else if (instruction == ',')
      output += stack.pop().charCodeAt(0);
    else if (instruction == '#')
      nextMove();
    else if (instruction == '\\')
      a = stack.pop(), b = stack.pop(), stack.push(b || 0), stack.push(a);
    else if (instruction == '$')
      stack.pop();
    else if (instruction == 'p')
      b = stack.pop(), a = stack.pop(), instructions.set(a, b, stack.pop().fromCharCode());
    else if (instruction == 'g')
      b = stack.pop(), a = stack.pop(), stack.push(instructions.get(a, b).charCodeAt(0));
    else if (instruction == ' ') ;
    else throw 'Unsupported instruction: ' + instruction;
  }

  this.runNextInstruction = function () {
    var current = instructions.get(codePointer);
    processInstruction(current);
    nextMove();
  };
}

BefungeProgram.prototype.constructor = BefungeProgram;

exports.interpret = interpret;<|endoftext|>


<commit_before>/*jslint unparam: true, browser: true, indent: 2 */

;(function ($, window, document, undefined) {
  'use strict';

  Foundation.libs.section = {
    name: 'section',

    version : '4.0.0.alpha',

    settings : {
      deep_linking: true,
      one_up: true,
      callback: function (){}
    },

    init : function (scope, method, options) {
      this.scope = this.scope || scope;
      Foundation.inherit(this, 'throttle data_options');

      if (typeof method === 'object') {
        $.extend(true, this.settings, method);
      }

      if (typeof method != 'string') {
        this.set_active_from_hash();
        if (!this.settings.init) this.events();

        return this.settings.init;
      } else {
        return this[method].call(this, options);
      }
    },

    events : function () {
      var self = this;
      $(this.scope).on('click.fndtn.section', '[data-section] .title', function (e) {
        $.extend(true, self.settings, self.data_options($(this).closest('[data-section]')));
        self.toggle_active.call(this, e, self);
      });

      $(window).on('resize.fndtn.section', self.throttle(function () {
        self.resize.call(this);
      }, 30)).trigger('resize');

      this.settings.init = true;
    },

    toggle_active : function (e, self) {
      var $this = $(this),
          section = $this.closest('section, .section'),
          content = section.find('.content'),
          self = Foundation.libs.section;

      if (!self.settings.deep_linking && content.length > 0) {
          e.preventDefault();
      }

      if (section.hasClass('active')) {
        if (self.small() || self.is_vertical(section.closest('[data-section]'))) {
          section
            .removeClass('active')
            .attr('style', '');
        }
      } else {
        if (self.small() || self.settings.one_up) {
          $this
            .closest('[data-section]')
            .find('section, .section')
            .removeClass('active')
            .attr('style', '');

          section.css('padding-top', self.outerHeight(section.find('.title')) - 3);
        }

        if (self.small()) {
          section.attr('style', '');
        }

        section.addClass('active');
      }

      self.settings.callback();
    },

    resize : function () {
      var sections = $('[data-section]'),
          self = Foundation.libs.section;

        sections.each(function() {
          var active_section = $(this).find('section.active, .section.active');
          if (active_section.length > 1) {
            active_section
              .not(':first')
              .removeClass('active')
              .attr('style', '');
          } else if (active_section.length < 1 && !self.is_vertical($(this))) {
            var first = $(this).find('section, .section').first();
            first.addClass('active');

            if (self.small()) {
              first.attr('style', '');
            } else {
              first.css('padding-top', self.outerHeight(first.find('.title')) - 3);
            }
          }

          if (self.small()) {
            active_section.attr('style', '');
          } else {
            active_section.css('padding-top', self.outerHeight(active_section.find('.title')) - 3);
          }
          self.position_titles($(this));
        });
    },

    is_vertical : function (el) {
      return el.hasClass('vertical-nav');
    },

    set_active_from_hash : function () {
      var hash = window.location.hash.substring(1);

      if (hash.length > 0 && this.settings.deep_linking) {
        $(this.scope)
          .find('[data-section]')
          .find('.content[data-slug="' + hash + '"]')
          .closest('section, .section')
          .addClass('active');
      }
    },

    position_titles : function (section, off) {
      var titles = section.find('.title'),
          previous_width = 0,
          self = this;

      if (typeof off === 'boolean') {
        titles.attr('style', '');
      } else {
        titles.each(function () {
          $(this).css('left', previous_width);
          previous_width += self.outerWidth($(this));
        });
      }
    },

    small : function () {
      if ($('html').hasClass('lt-ie9')) {
        return true;
      }
      return $(this.scope).width() < 769;
    },

    off : function () {
      $(this.scope).off('.fndtn.section');
      $(window).off('.fndtn.section');
      this.settings.init = false;
    }
  };
}(Foundation.zj, this, this.document));
<commit_msg>Fix scope on section.<commit_after>/*jslint unparam: true, browser: true, indent: 2 */

;(function ($, window, document, undefined) {
  'use strict';

  Foundation.libs.section = {
    name: 'section',

    version : '4.0.0.alpha',

    settings : {
      deep_linking: true,
      one_up: true,
      callback: function (){}
    },

    init : function (scope, method, options) {
      this.scope = scope || this.scope;
      Foundation.inherit(this, 'throttle data_options');

      if (typeof method === 'object') {
        $.extend(true, this.settings, method);
      }

      if (typeof method != 'string') {
        this.set_active_from_hash();
        if (!this.settings.init) this.events();

        return this.settings.init;
      } else {
        return this[method].call(this, options);
      }
    },

    events : function () {
      var self = this;
      $(this.scope).on('click.fndtn.section', '[data-section] .title', function (e) {
        $.extend(true, self.settings, self.data_options($(this).closest('[data-section]')));
        self.toggle_active.call(this, e, self);
      });

      $(window).on('resize.fndtn.section', self.throttle(function () {
        self.resize.call(this);
      }, 30)).trigger('resize');

      this.settings.init = true;
    },

    toggle_active : function (e, self) {
      var $this = $(this),
          section = $this.closest('section, .section'),
          content = section.find('.content'),
          self = Foundation.libs.section;

      if (!self.settings.deep_linking && content.length > 0) {
          e.preventDefault();
      }

      if (section.hasClass('active')) {
        if (self.small() || self.is_vertical(section.closest('[data-section]'))) {
          section
            .removeClass('active')
            .attr('style', '');
        }
      } else {
        if (self.small() || self.settings.one_up) {
          $this
            .closest('[data-section]')
            .find('section, .section')
            .removeClass('active')
            .attr('style', '');

          section.css('padding-top', self.outerHeight(section.find('.title')) - 3);
        }

        if (self.small()) {
          section.attr('style', '');
        }

        section.addClass('active');
      }

      self.settings.callback();
    },

    resize : function () {
      var sections = $('[data-section]'),
          self = Foundation.libs.section;

        sections.each(function() {
          var active_section = $(this).find('section.active, .section.active');
          if (active_section.length > 1) {
            active_section
              .not(':first')
              .removeClass('active')
              .attr('style', '');
          } else if (active_section.length < 1 && !self.is_vertical($(this))) {
            var first = $(this).find('section, .section').first();
            first.addClass('active');

            if (self.small()) {
              first.attr('style', '');
            } else {
              first.css('padding-top', self.outerHeight(first.find('.title')) - 3);
            }
          }

          if (self.small()) {
            active_section.attr('style', '');
          } else {
            active_section.css('padding-top', self.outerHeight(active_section.find('.title')) - 3);
          }
          self.position_titles($(this));
        });
    },

    is_vertical : function (el) {
      return el.hasClass('vertical-nav');
    },

    set_active_from_hash : function () {
      var hash = window.location.hash.substring(1);

      if (hash.length > 0 && this.settings.deep_linking) {
        $(this.scope)
          .find('[data-section]')
          .find('.content[data-slug="' + hash + '"]')
          .closest('section, .section')
          .addClass('active');
      }
    },

    position_titles : function (section, off) {
      var titles = section.find('.title'),
          previous_width = 0,
          self = this;

      if (typeof off === 'boolean') {
        titles.attr('style', '');
      } else {
        titles.each(function () {
          $(this).css('left', previous_width);
          previous_width += self.outerWidth($(this));
        });
      }
    },

    small : function () {
      if ($('html').hasClass('lt-ie9')) {
        return true;
      }
      return $(this.scope).width() < 769;
    },

    off : function () {
      $(this.scope).off('.fndtn.section');
      $(window).off('.fndtn.section');
      this.settings.init = false;
    }
  };
}(Foundation.zj, this, this.document));
<|endoftext|>


<commit_before>/*
* jQuery Mobile Framework : "listview" filter extension
* Copyright (c) jQuery Project
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/

(function( $, undefined ) {

$.mobile.listview.prototype.options.filter = false;
$.mobile.listview.prototype.options.filterPlaceholder = "Filter items...";
$.mobile.listview.prototype.options.filterTheme = "c";

$( ":jqmData(role='listview')" ).live( "listviewcreate", function() {

	var list = $( this ),
		listview = list.data( "listview" );

	if ( !listview.options.filter ) {
		return;
	}

	var wrapper = $( "<form>", {
			"class": "ui-listview-filter ui-bar-" + listview.options.filterTheme,
			"role": "search"
	 }),
	search = $( "<input>", {
		placeholder: listview.options.filterPlaceholder
	})
	.attr( "data-" + $.mobile.ns + "type", "search" )
	.jqmData( "lastval", "" )
	.bind( "keyup change", function() {

		var $this = $(this),
			val = this.value.toLowerCase(),
			listItems = null,
			lastval = $this.jqmData( "lastval" ) + "";

		// Change val as lastval for next execution
		$this.jqmData( "lastval" , val );

		change = val.replace( new RegExp( "^" + lastval ) , "" );

		if ( val.length < lastval.length || change.length != ( val.length - lastval.length ) ) {

			// Removed chars or pasted something totaly different, check all items
			listItems = list.children();
		} else {

			// Only chars added, not removed, only use visible subset
			listItems = list.children( ":not(.ui-screen-hidden)" );
		}

		if ( val ) {

			// This handles hiding regular rows without the text we search for
			// and any list dividers without regular rows shown under it
			var item,
				childItems = false,
				itemtext="";

			for ( var i = listItems.length - 1; i >= 0; i-- ) {
				item = $( listItems[i] );
				itemtext = item.jqmData( "filtertext" ) || item.text();

				if ( item.is( "li:jqmData(role=list-divider)" ) ) {

					item.toggleClass( "ui-filter-hidequeue" , !childItems );

					// New bucket!
					childItems = false;

				} else if ( itemtext.toLowerCase().indexOf( val ) === -1 ) {

					//mark to be hidden
					item.toggleClass( "ui-filter-hidequeue" , true );
				} else {

					// There"s a shown item in the bucket
					childItems = true;
				}
			}

			// show items, not marked to be hidden
			listItems
				.filter( ":not(.ui-filter-hidequeue)" )
				.toggleClass("ui-screen-hidden",false);

			// hide items, marked to be hidden
			listItems
				.filter( ".ui-filter-hidequeue" )
				.toggleClass("ui-screen-hidden",true)
				.toggleClass( "ui-filter-hidequeue" , false );

		} else {

			//filtervalue is empty => show all
			listItems.toggleClass("ui-screen-hidden",false);
		}
	})
	.appendTo( wrapper )
	.textinput();

	if ( $( this ).jqmData( "inset" ) ) {
		wrapper.addClass( "ui-listview-filter-inset" );
	}

	wrapper.bind( "submit", function() {
		return false;
	})
	.insertBefore( list );
});

})( jQuery );<commit_msg>jQuery core style guide conformance: jquery.mobile.listview.filter.js 2<commit_after>/*
* jQuery Mobile Framework : "listview" filter extension
* Copyright (c) jQuery Project
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/

(function( $, undefined ) {

$.mobile.listview.prototype.options.filter = false;
$.mobile.listview.prototype.options.filterPlaceholder = "Filter items...";
$.mobile.listview.prototype.options.filterTheme = "c";

$( ":jqmData(role='listview')" ).live( "listviewcreate", function() {

	var list = $( this ),
		listview = list.data( "listview" );

	if ( !listview.options.filter ) {
		return;
	}

	var wrapper = $( "<form>", {
			"class": "ui-listview-filter ui-bar-" + listview.options.filterTheme,
			"role": "search"
		}),
		search = $( "<input>", {
			placeholder: listview.options.filterPlaceholder
		})
		.attr( "data-" + $.mobile.ns + "type", "search" )
		.jqmData( "lastval", "" )
		.bind( "keyup change", function() {

			var $this = $(this),
				val = this.value.toLowerCase(),
				listItems = null,
				lastval = $this.jqmData( "lastval" ) + "",
				childItems = false,
				itemtext = "",
				item;

			// Change val as lastval for next execution
			$this.jqmData( "lastval" , val );

			change = val.replace( new RegExp( "^" + lastval ) , "" );

			if ( val.length < lastval.length || change.length != ( val.length - lastval.length ) ) {

				// Removed chars or pasted something totaly different, check all items
				listItems = list.children();
			} else {

				// Only chars added, not removed, only use visible subset
				listItems = list.children( ":not(.ui-screen-hidden)" );
			}

			if ( val ) {

				// This handles hiding regular rows without the text we search for
				// and any list dividers without regular rows shown under it

				for ( var i = listItems.length - 1; i >= 0; i-- ) {
					item = $( listItems[ i ] );
					itemtext = item.jqmData( "filtertext" ) || item.text();

					if ( item.is( "li:jqmData(role=list-divider)" ) ) {

						item.toggleClass( "ui-filter-hidequeue" , !childItems );

						// New bucket!
						childItems = false;

					} else if ( itemtext.toLowerCase().indexOf( val ) === -1 ) {

						//mark to be hidden
						item.toggleClass( "ui-filter-hidequeue" , true );
					} else {

						// There"s a shown item in the bucket
						childItems = true;
					}
				}

				// Show items, not marked to be hidden
				listItems
					.filter( ":not(.ui-filter-hidequeue)" )
					.toggleClass("ui-screen-hidden",false);

				// Hide items, marked to be hidden
				listItems
					.filter( ".ui-filter-hidequeue" )
					.toggleClass("ui-screen-hidden",true)
					.toggleClass( "ui-filter-hidequeue" , false );

			} else {

				//filtervalue is empty => show all
				listItems.toggleClass("ui-screen-hidden",false);
			}
		})
		.appendTo( wrapper )
		.textinput();

	if ( $( this ).jqmData( "inset" ) ) {
		wrapper.addClass( "ui-listview-filter-inset" );
	}

	wrapper.bind( "submit", function() {
		return false;
	})
	.insertBefore( list );
});

})( jQuery );<|endoftext|>


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

/**
 * Section of the "Audio" panel of the PreferencesDialog related to sound.
 *
 * @author Jesse Greenberg (PhET Interactive Simulations)
 */

import merge from '../../../phet-core/js/merge.js';
import StringUtils from '../../../phetcommon/js/util/StringUtils.js';
import { Text, VBox, VoicingRichText, VoicingText, voicingUtteranceQueue } from '../../../scenery/js/imports.js';
import Checkbox from '../../../sun/js/Checkbox.js';
import soundManager from '../../../tambo/js/soundManager.js';
import Tandem from '../../../tandem/js/Tandem.js';
import joist from '../joist.js';
import joistStrings from '../joistStrings.js';
import PreferencesDialog from './PreferencesDialog.js';
import PreferencesPanelSection from './PreferencesPanelSection.js';
import PreferencesToggleSwitch from './PreferencesToggleSwitch.js';

// constants
const soundsLabelString = joistStrings.preferences.tabs.audio.sounds.title;
const extraSoundsLabelString = joistStrings.preferences.tabs.audio.sounds.extraSounds.title;
const soundDescriptionString = joistStrings.preferences.tabs.audio.sounds.description;
const extraSoundsDescriptionString = joistStrings.preferences.tabs.audio.sounds.extraSounds.description;
const soundsOnString = joistStrings.a11y.preferences.tabs.audio.sounds.soundsOn;
const soundsOffString = joistStrings.a11y.preferences.tabs.audio.sounds.soundsOff;
const extraSoundsOnString = joistStrings.a11y.preferences.tabs.audio.sounds.extraSounds.extraSoundsOn;
const extraSoundsOffString = joistStrings.a11y.preferences.tabs.audio.sounds.extraSounds.extraSoundsOff;
const labelledDescriptionPatternString = joistStrings.a11y.preferences.tabs.labelledDescriptionPattern;

class SoundPanelSection extends PreferencesPanelSection {

  /**
   * @param {Object} audioOptions - configuration for audio preferences, see PreferencesManager
   * @param {Object} [options]
   */
  constructor( audioOptions, options ) {

    options = merge( {

      // {boolean} - Whether or not to include the toggle switch in the title content for this
      // PreferencesPanelSection. It is possible that the toggle for Sound can be redundant when Sound
      // is the only Audio feature supported. In that case, control of Sound should go through the
      // "All Audio" toggle.
      includeTitleToggleSwitch: true,

      // phet-io
      tandem: Tandem.REQUIRED
    }, options );

    const soundLabel = new Text( soundsLabelString, PreferencesDialog.PANEL_SECTION_LABEL_OPTIONS );

    const soundEnabledSwitch = new PreferencesToggleSwitch( soundManager.enabledProperty, false, true, {
      labelNode: soundLabel,
      descriptionNode: new VoicingText( soundDescriptionString, merge( {}, PreferencesDialog.PANEL_SECTION_CONTENT_OPTIONS, {
        readingBlockNameResponse: StringUtils.fillIn( labelledDescriptionPatternString, {
          label: soundsLabelString,
          description: soundDescriptionString
        } )
      } ) ),
      toggleSwitchOptions: {
        visible: options.includeTitleToggleSwitch
      },
      a11yLabel: soundsLabelString,
      tandem: options.tandem.createTandem( 'soundEnabledSwitch' )
    } );

    let enhancedSoundContent = null;
    let enhancedSoundCheckbox = null;
    if ( audioOptions.supportsEnhancedSound ) {
      const enahncedSoundLabel = new Text( extraSoundsLabelString, PreferencesDialog.PANEL_SECTION_CONTENT_OPTIONS );
      enhancedSoundCheckbox = new Checkbox( enahncedSoundLabel, soundManager.enhancedSoundEnabledProperty, {

        // pdom
        labelTagName: 'label',
        labelContent: extraSoundsLabelString,

        // voicing
        voicingNameResponse: extraSoundsLabelString,

        // phet-io
        tandem: options.tandem.createTandem( 'enhancedSoundCheckbox' )
      } );

      const enhancedSoundDescription = new VoicingRichText( extraSoundsDescriptionString, merge( {}, PreferencesDialog.PANEL_SECTION_CONTENT_OPTIONS, {
        lineWrap: 300,
        readingBlockNameResponse: StringUtils.fillIn( labelledDescriptionPatternString, {
          label: extraSoundsLabelString,
          description: extraSoundsDescriptionString
        } )
      } ) );

      enhancedSoundContent = new VBox( {
        children: [ enhancedSoundCheckbox, enhancedSoundDescription ],
        align: 'left',
        spacing: 5
      } );

      soundManager.enabledProperty.link( enabled => {
        enhancedSoundContent.enabled = enabled;
      } );
    }

    super( {
      titleNode: soundEnabledSwitch,
      contentNode: enhancedSoundContent
    } );

    // voicing
    soundManager.enabledProperty.lazyLink( enabled => {
      const alert = enabled ? soundsOnString : soundsOffString;
      voicingUtteranceQueue.addToBack( alert );
      this.alertDescriptionUtterance( alert );
    } );

    soundManager.enhancedSoundEnabledProperty.lazyLink( enabled => {
      const alert = enabled ? extraSoundsOnString : extraSoundsOffString;
      voicingUtteranceQueue.addToBack( alert );
      this.alertDescriptionUtterance( alert );
    } );

    // @private
    this.disposeSoundPanelSection = () => {
      soundEnabledSwitch.dispose();
      enhancedSoundCheckbox && enhancedSoundCheckbox.dispose();
    };
  }

  /**
   * @public
   */
  dispose() {
    this.disposeSoundPanelSection();
    super.dispose();
  }
}

joist.register( 'SoundPanelSection', SoundPanelSection );
export default SoundPanelSection;<commit_msg>replace voicingUtteranceQueue.addToBack usage, see https://github.com/phetsims/scenery/issues/1403<commit_after>// Copyright 2021-2022, University of Colorado Boulder

/**
 * Section of the "Audio" panel of the PreferencesDialog related to sound.
 *
 * @author Jesse Greenberg (PhET Interactive Simulations)
 */

import merge from '../../../phet-core/js/merge.js';
import StringUtils from '../../../phetcommon/js/util/StringUtils.js';
import { Text, VBox, VoicingRichText, VoicingText } from '../../../scenery/js/imports.js';
import Checkbox from '../../../sun/js/Checkbox.js';
import soundManager from '../../../tambo/js/soundManager.js';
import Tandem from '../../../tandem/js/Tandem.js';
import joist from '../joist.js';
import joistStrings from '../joistStrings.js';
import PreferencesDialog from './PreferencesDialog.js';
import PreferencesPanelSection from './PreferencesPanelSection.js';
import PreferencesToggleSwitch from './PreferencesToggleSwitch.js';

// constants
const soundsLabelString = joistStrings.preferences.tabs.audio.sounds.title;
const extraSoundsLabelString = joistStrings.preferences.tabs.audio.sounds.extraSounds.title;
const soundDescriptionString = joistStrings.preferences.tabs.audio.sounds.description;
const extraSoundsDescriptionString = joistStrings.preferences.tabs.audio.sounds.extraSounds.description;
const soundsOnString = joistStrings.a11y.preferences.tabs.audio.sounds.soundsOn;
const soundsOffString = joistStrings.a11y.preferences.tabs.audio.sounds.soundsOff;
const extraSoundsOnString = joistStrings.a11y.preferences.tabs.audio.sounds.extraSounds.extraSoundsOn;
const extraSoundsOffString = joistStrings.a11y.preferences.tabs.audio.sounds.extraSounds.extraSoundsOff;
const labelledDescriptionPatternString = joistStrings.a11y.preferences.tabs.labelledDescriptionPattern;

class SoundPanelSection extends PreferencesPanelSection {

  /**
   * @param {Object} audioOptions - configuration for audio preferences, see PreferencesManager
   * @param {Object} [options]
   */
  constructor( audioOptions, options ) {

    options = merge( {

      // {boolean} - Whether or not to include the toggle switch in the title content for this
      // PreferencesPanelSection. It is possible that the toggle for Sound can be redundant when Sound
      // is the only Audio feature supported. In that case, control of Sound should go through the
      // "All Audio" toggle.
      includeTitleToggleSwitch: true,

      // phet-io
      tandem: Tandem.REQUIRED
    }, options );

    const soundLabel = new Text( soundsLabelString, PreferencesDialog.PANEL_SECTION_LABEL_OPTIONS );

    const soundEnabledSwitch = new PreferencesToggleSwitch( soundManager.enabledProperty, false, true, {
      labelNode: soundLabel,
      descriptionNode: new VoicingText( soundDescriptionString, merge( {}, PreferencesDialog.PANEL_SECTION_CONTENT_OPTIONS, {
        readingBlockNameResponse: StringUtils.fillIn( labelledDescriptionPatternString, {
          label: soundsLabelString,
          description: soundDescriptionString
        } )
      } ) ),
      toggleSwitchOptions: {
        visible: options.includeTitleToggleSwitch
      },
      a11yLabel: soundsLabelString,
      leftValueContextResponse: soundsOffString,
      rightValueContextResponse: soundsOnString,
      tandem: options.tandem.createTandem( 'soundEnabledSwitch' )
    } );

    let enhancedSoundContent = null;
    let enhancedSoundCheckbox = null;
    if ( audioOptions.supportsEnhancedSound ) {
      const enahncedSoundLabel = new Text( extraSoundsLabelString, PreferencesDialog.PANEL_SECTION_CONTENT_OPTIONS );
      enhancedSoundCheckbox = new Checkbox( enahncedSoundLabel, soundManager.enhancedSoundEnabledProperty, {

        // pdom
        labelTagName: 'label',
        labelContent: extraSoundsLabelString,

        // voicing
        voicingNameResponse: extraSoundsLabelString,
        voicingIgnoreVoicingManagerProperties: true, // Always speak Preferences responses so control function is clear

        // both voicing and pdom
        checkedContextResponse: extraSoundsOnString,
        uncheckedContextResponse: extraSoundsOffString,

        // phet-io
        tandem: options.tandem.createTandem( 'enhancedSoundCheckbox' )
      } );

      const enhancedSoundDescription = new VoicingRichText( extraSoundsDescriptionString, merge( {}, PreferencesDialog.PANEL_SECTION_CONTENT_OPTIONS, {
        lineWrap: 300,
        readingBlockNameResponse: StringUtils.fillIn( labelledDescriptionPatternString, {
          label: extraSoundsLabelString,
          description: extraSoundsDescriptionString
        } )
      } ) );

      enhancedSoundContent = new VBox( {
        children: [ enhancedSoundCheckbox, enhancedSoundDescription ],
        align: 'left',
        spacing: 5
      } );

      soundManager.enabledProperty.link( enabled => {
        enhancedSoundContent.enabled = enabled;
      } );
    }

    super( {
      titleNode: soundEnabledSwitch,
      contentNode: enhancedSoundContent
    } );

    // @private
    this.disposeSoundPanelSection = () => {
      soundEnabledSwitch.dispose();
      enhancedSoundCheckbox && enhancedSoundCheckbox.dispose();
    };
  }

  /**
   * @public
   */
  dispose() {
    this.disposeSoundPanelSection();
    super.dispose();
  }
}

joist.register( 'SoundPanelSection', SoundPanelSection );
export default SoundPanelSection;<|endoftext|>