<commit_before>import supertest from 'supertest';
import path from 'path';
import { expect } from 'chai';
import fs from 'fs';
import rimraf from 'rimraf';

const port = 8000;
const projectBasePath = __dirname;
const variationsBasePath = path.join(__dirname, 'variations');
const request = supertest.agent(`http://localhost:${port}`);

describe('variations server', () => {
  let server;

  beforeEach(() => {
    delete require.cache[require.resolve('./server')];
    server = require('../server'); // eslint-disable-line global-require
    server.start(projectBasePath, variationsBasePath, port);
  });

  afterEach((done) => {
    server.stop(done);
  });

  describe('get', () => {
    it('should get all data for a valid component with variations data', (done) => {
      request
        .get('/components/ComponentA.js')
        .expect('Content-type', /json/)
        .expect(200)
        .end((err, res) => {
          expect(res.status).to.equal(200);
          expect(res.body.error).to.be.false; // eslint-disable-line no-unused-expressions
          expect(res.body.data).to.have.keys(['v-firstVariation', 'v-secondVariation']);

          let firstVariation;
          eval(`firstVariation = ${res.body.data['v-firstVariation']}`); // eslint-disable-line no-eval, max-len
          const expected = {
            props: {
              className: {
                value: 'component-a',
              },
              age: {
                value: 22,
                min: 0,
                max: 140,
              },
            },
            state: {
              focusedAge: {
                value: 19,
                min: 0,
                max: 140,
              },
            },
          };
          expect(firstVariation).to.deep.equal(expected); // eslint-disable-line no-undef

          let secondVariation;
          eval(`secondVariation = ${res.body.data['v-secondVariation']}`); // eslint-disable-line no-eval, max-len
          const secondExpected = {
            props: {
              age: {
                value: null,
              },
            },
            state: {
              focusedAge: {
                value: 10,
              },
            },
          };
          expect(secondVariation).to.deep.equal(secondExpected); // eslint-disable-line no-undef
          done();
        });
    });

    it('should return an empty data object in case the component does not exist', (done) => {
      request
        .get('/components/ComponentNotAvailable.js')
        .expect('Content-type', /json/)
        .expect(404)
        .end((err, res) => {
          expect(res.status).to.equal(404);
          done();
        });
    });
  });

  describe('delete', () => {
    it('should remove the variation', (done) => {
      const variationPath = path.join(variationsBasePath, 'ComponentA', 'toBeRemoved.js');
      fs.closeSync(fs.openSync(variationPath, 'w'));

      request
        .delete('/components/ComponentA.js?variation=toBeRemoved')
        .expect('Content-type', /json/)
        .expect(200)
        .end((err, res) => {
          expect(res.status).to.equal(200);
          done();
        });
    });

    it('should fail in case the component does not exist', (done) => {
      request
        .delete('/components/ComponentNotAvailable.js')
        .expect('Content-type', /json/)
        .expect(404)
        .end((err, res) => {
          expect(res.status).to.equal(404);
          done();
        });
    });

    it('should fail in case the variation does not exist', (done) => {
      request
        .delete('/components/ComponentA.js?variation=notAvailableVariation')
        .expect('Content-type', /json/)
        .expect(404)
        .end((err, res) => {
          expect(res.status).to.equal(404);
          done();
        });
    });
  });

  describe('post', () => {
    describe('write new variation', () => {
      const variationComponentPath = path.join(variationsBasePath, 'ComponentB');
      const variationPath = path.join(variationComponentPath, 'newVariation.js');
      const code = `{
        props: {
          name: {
            value: 'Ada Lovelace',
          },
          onClick: {
            value: () => true,
          },
        },
      };`;

      afterEach((done) => {
        rimraf(variationComponentPath, done);
      });

      it('should create a new file with the provided data', (done) => {
        request
          .post('/components/ComponentB/index.js')
          .type('json')
          .send({
            variation: 'newVariation',
            code,
          })
          .expect(200)
          .end((err, res) => {
            expect(res.status).to.equal(200);
            fs.readFile(variationPath, { encoding: 'utf8' }, (_, fileContent) => {
              expect(`module.exports = ${code}`).to.equal(fileContent);
              done();
            });
          });
      });
    });

    describe('overwrite existing variation', () => {
      const variationPath = path.join(variationsBasePath, 'ComponentA', 'existingVariation.js');
      const code = `{
        props: {
          name: {
            value: 'Marie Curie',
          },
          onSelect: {
            value: () => true,
          },
        },
      };`;

      afterEach((done) => {
        fs.unlink(variationPath, () => {
          done();
        });
      });

      it('should overwrite the existing file with the provided data', (done) => {
        fs.closeSync(fs.openSync(variationPath, 'w'));

        request
          .post('/components/ComponentA.js')
          .type('json')
          .send({
            variation: 'existingVariation',
            code,
          })
          .expect(200)
          .end((err, res) => {
            expect(res.status).to.equal(200);
            fs.readFile(variationPath, { encoding: 'utf8' }, (_, fileContent) => {
              expect(`module.exports = ${code}`).to.equal(fileContent);
              done();
            });
          });
      });
    });

    it('should fail in case the component does not exist', (done) => {
      request
        .post('/components/ComponentNotAvailable.js')
        .expect('Content-type', /json/)
        .expect(404)
        .end((err, res) => {
          expect(res.status).to.equal(404);
          done();
        });
    });
  });
});
<commit_msg>use other port for test server than development server<commit_after>import supertest from 'supertest';
import path from 'path';
import { expect } from 'chai';
import fs from 'fs';
import rimraf from 'rimraf';

const port = 8003;
const projectBasePath = __dirname;
const variationsBasePath = path.join(__dirname, 'variations');
const request = supertest.agent(`http://localhost:${port}`);

describe('variations server', () => {
  let server;

  beforeEach(() => {
    delete require.cache[require.resolve('./server')];
    server = require('../server'); // eslint-disable-line global-require
    server.start(projectBasePath, variationsBasePath, port);
  });

  afterEach((done) => {
    server.stop(done);
  });

  describe('get', () => {
    it('should get all data for a valid component with variations data', (done) => {
      request
        .get('/components/ComponentA.js')
        .expect('Content-type', /json/)
        .expect(200)
        .end((err, res) => {
          expect(res.status).to.equal(200);
          expect(res.body.error).to.be.false; // eslint-disable-line no-unused-expressions
          expect(res.body.data).to.have.keys(['v-firstVariation', 'v-secondVariation']);

          let firstVariation;
          eval(`firstVariation = ${res.body.data['v-firstVariation']}`); // eslint-disable-line no-eval, max-len
          const expected = {
            props: {
              className: {
                value: 'component-a',
              },
              age: {
                value: 22,
                min: 0,
                max: 140,
              },
            },
            state: {
              focusedAge: {
                value: 19,
                min: 0,
                max: 140,
              },
            },
          };
          expect(firstVariation).to.deep.equal(expected); // eslint-disable-line no-undef

          let secondVariation;
          eval(`secondVariation = ${res.body.data['v-secondVariation']}`); // eslint-disable-line no-eval, max-len
          const secondExpected = {
            props: {
              age: {
                value: null,
              },
            },
            state: {
              focusedAge: {
                value: 10,
              },
            },
          };
          expect(secondVariation).to.deep.equal(secondExpected); // eslint-disable-line no-undef
          done();
        });
    });

    it('should return an empty data object in case the component does not exist', (done) => {
      request
        .get('/components/ComponentNotAvailable.js')
        .expect('Content-type', /json/)
        .expect(404)
        .end((err, res) => {
          expect(res.status).to.equal(404);
          done();
        });
    });
  });

  describe('delete', () => {
    it('should remove the variation', (done) => {
      const variationPath = path.join(variationsBasePath, 'ComponentA', 'toBeRemoved.js');
      fs.closeSync(fs.openSync(variationPath, 'w'));

      request
        .delete('/components/ComponentA.js?variation=toBeRemoved')
        .expect('Content-type', /json/)
        .expect(200)
        .end((err, res) => {
          expect(res.status).to.equal(200);
          done();
        });
    });

    it('should fail in case the component does not exist', (done) => {
      request
        .delete('/components/ComponentNotAvailable.js')
        .expect('Content-type', /json/)
        .expect(404)
        .end((err, res) => {
          expect(res.status).to.equal(404);
          done();
        });
    });

    it('should fail in case the variation does not exist', (done) => {
      request
        .delete('/components/ComponentA.js?variation=notAvailableVariation')
        .expect('Content-type', /json/)
        .expect(404)
        .end((err, res) => {
          expect(res.status).to.equal(404);
          done();
        });
    });
  });

  describe('post', () => {
    describe('write new variation', () => {
      const variationComponentPath = path.join(variationsBasePath, 'ComponentB');
      const variationPath = path.join(variationComponentPath, 'newVariation.js');
      const code = `{
        props: {
          name: {
            value: 'Ada Lovelace',
          },
          onClick: {
            value: () => true,
          },
        },
      };`;

      afterEach((done) => {
        rimraf(variationComponentPath, done);
      });

      it('should create a new file with the provided data', (done) => {
        request
          .post('/components/ComponentB/index.js')
          .type('json')
          .send({
            variation: 'newVariation',
            code,
          })
          .expect(200)
          .end((err, res) => {
            expect(res.status).to.equal(200);
            fs.readFile(variationPath, { encoding: 'utf8' }, (_, fileContent) => {
              expect(`module.exports = ${code}`).to.equal(fileContent);
              done();
            });
          });
      });
    });

    describe('overwrite existing variation', () => {
      const variationPath = path.join(variationsBasePath, 'ComponentA', 'existingVariation.js');
      const code = `{
        props: {
          name: {
            value: 'Marie Curie',
          },
          onSelect: {
            value: () => true,
          },
        },
      };`;

      afterEach((done) => {
        fs.unlink(variationPath, () => {
          done();
        });
      });

      it('should overwrite the existing file with the provided data', (done) => {
        fs.closeSync(fs.openSync(variationPath, 'w'));

        request
          .post('/components/ComponentA.js')
          .type('json')
          .send({
            variation: 'existingVariation',
            code,
          })
          .expect(200)
          .end((err, res) => {
            expect(res.status).to.equal(200);
            fs.readFile(variationPath, { encoding: 'utf8' }, (_, fileContent) => {
              expect(`module.exports = ${code}`).to.equal(fileContent);
              done();
            });
          });
      });
    });

    it('should fail in case the component does not exist', (done) => {
      request
        .post('/components/ComponentNotAvailable.js')
        .expect('Content-type', /json/)
        .expect(404)
        .end((err, res) => {
          expect(res.status).to.equal(404);
          done();
        });
    });
  });
});
<|endoftext|>


<commit_before> define([
    'jquery',
    'gizmo/superdesk',
    config.guiJs('livedesk', 'views/postposts'),

    'tmpl!livedesk>blogtype/blogtype',
    'tmpl!livedesk>blogtype/delete-blogtype-modal',
], function( $, Gizmo, PostPostsView ) {
    if(!$('#delete-blogtype').length) {
        $.tmpl('livedesk>blogtype/delete-blogtype-modal', {}, function(e,o){
            $('body').append(o);
        });
    }
   return Gizmo.View.extend({
        tmplData: {},
        tagName: 'li',
        namespace: 'livedesk',
        events: {
            '[name="remove-blogtype"]': { 'click': 'removeBlogTypeDialog' },
            '[name="edit-blogtype"]': { 'click': 'editBlogType' }
        },
        init: function(){
            var self = this;
            self.model.on('delete', self.remove, self);
            self.model.on('update', self.render, self);
            self.render();
        },
        editBlogType: function(evt) {
            evt.preventDefault();
            var self = this;
            self._parent.configBlogType.model = self.model;
            self._parent.configBlogType.render();
            self._parent.configBlogType.el.find('#add-blogtype').modal('show');
        },
        remove: function(evt){
            evt.preventDefault();
            this.el.remove();
        },
        removeBlogTypeDialog: function() {
            var self = this;
            $('#delete-blogtype #blogtype-name').text(self.model.get('Name'));
            $('#delete-blogtype .yes')
                .off(this.getEvent('click'))
                .on(this.getEvent('click'), function(){
                    self.model.remove().sync();
                });
        },
        render: function(evt, data){
            var self = this,
                el,
                data = { BlogType: self.model.feed() };
            $.extend( data, self.tmplData );
            $.tmpl('livedesk>blogtype/blogtype', data, function(e,o){
                self.setElement(o);
                $(self.el).on(self.getEvent('click')+'test', 'h3', function(){
                        var li = $(this).parent().parent();
                        li.find('.blogtype-content').toggle(300);
                        li.toggleClass("collapse-open");
                });
                self.postPosts = new PostPostsView({
                    el: $('

').appendTo(self.el.find('.blogtype-content')),
                    collection: self.model.get('Post')
                });
            });
        }
    });
});
<commit_msg>LB-667 : Add new blog modal - styling improvement<commit_after> define([
    'jquery',
    'gizmo/superdesk',
    config.guiJs('livedesk', 'views/postposts'),

    'tmpl!livedesk>blogtype/blogtype',
    'tmpl!livedesk>blogtype/delete-blogtype-modal',
], function( $, Gizmo, PostPostsView ) {
    if(!$('#delete-blogtype').length) {
        $.tmpl('livedesk>blogtype/delete-blogtype-modal', {}, function(e,o){
            $('body').append(o);
        });
    }
   return Gizmo.View.extend({
        tmplData: {},
        tagName: 'li',
        namespace: 'livedesk',
        events: {
            '[name="remove-blogtype"]': { 'click': 'removeBlogTypeDialog' },
            '[name="edit-blogtype"]': { 'click': 'editBlogType' }
        },
        init: function(){
            var self = this;
            self.model.on('delete', self.remove, self);
            self.model.on('update', self.render, self);
            self.render();
        },
        editBlogType: function(evt) {
            evt.preventDefault();
            var self = this;
            self._parent.configBlogType.model = self.model;
            self._parent.configBlogType.render();
            self._parent.configBlogType.el.find('#add-blogtype').modal('show');
        },
        remove: function(evt){
            evt.preventDefault();
            this.el.remove();
        },
        removeBlogTypeDialog: function() {
            var self = this;
            $('#delete-blogtype #blogtype-name').text(self.model.get('Name'));
            $('#delete-blogtype .yes')
                .off(this.getEvent('click'))
                .on(this.getEvent('click'), function(){
                    self.model.remove().sync();
                });
        },
        render: function(evt, data){
            var self = this,
                el,
                data = { BlogType: self.model.feed() };
            $.extend( data, self.tmplData );
            $.tmpl('livedesk>blogtype/blogtype', data, function(e,o){
                self.setElement(o);
                $(self.el).on(self.getEvent('click')+'test', 'h3', function(){
                        var li = $(this).parent().parent();
                        li.find('.blogtype-content').toggle();
                        li.toggleClass("collapse-open");
                });
                self.postPosts = new PostPostsView({
                    el: $('

').appendTo(self.el.find('.blogtype-content')),
                    collection: self.model.get('Post')
                });
            });
        }
    });
});
<|endoftext|>


<commit_before>/**
 * GeoKnow Generator
 *    Configuration management
 *
 * @author Vadim Zaslawski
 *
 * enable SPARQL Update
 * ISQL:
 *   GRANT SPARQL_UPDATE TO "SPARQL"
 *   GRANT EXECUTE ON DB.DBA.L_O_LOOK TO "SPARQL"
 *
 * enable CORS
 *
 * usage:
 *   setEndpoint(url)          - set SPARQL endpoint, should be called initially
 *   getEndpoint()             - get SPARQL endpoint
 *   getNS()                   - get base namespace
 *   getGraph()                - get graph name
 *   read()                    - load settings
 *   getSettings()             - get loaded settings
 *   write()                   - save settings after editing getSettings() result
 *   select(property, value)   - select settings, e.g.: select("rdf:type", "lds:StackComponent")
 *   createGraph(name)         - create graph
 *   dropGraph(name)           - delete graph
 */

"use strict";

angular.module("app.configuration", [])
.factory("Config", function($q, $http, flash)
{
	$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";

	var ENDPOINT  = "http://144.76.166.111:8890/sparql";
	var NS        = "http://generator.geoknow.eu/";
	var GRAPH_URI = NS + "settingsGraph";

	var namespaces =
	{
		"http://dbpedia.org/resource/"                     : "dbpedia:",
		"http://purl.org/dc/elements/1.1/"                 : "dc:",
		"http://purl.org/dc/terms/"                        : "dcterms:",
		"http://xmlns.com/foaf/0.1/"                       : "foaf:",
		"http://linkeddata.org/integrated-stack-schema/"   : "lds:",
		"http://www.w3.org/1999/02/22-rdf-syntax-ns#"      : "rdf:",
		"http://www.w3.org/2000/01/rdf-schema#"            : "rdfs:",
		"http://www.w3.org/ns/sparql-service-description#" : "sd:",
		"http://rdfs.org/ns/void#"                         : "void:"
	};
	namespaces[NS] = ":";

	var GRAPH    = "<" + GRAPH_URI + ">";
	var EOL      = "\n";
	var PREFIXES = "";
	for (var namespace in namespaces)
		PREFIXES += "PREFIX " + namespaces[namespace] + " <" + namespace + ">" + EOL;

	var settings = {};
	var isLoaded = false;

	var request = function(query, success)
	{
		var deferred = $q.defer();

		$http.post(ENDPOINT, $.param(
		{
			format: "application/sparql-results+json",
			query:  query
		}))
		.success(function(data)
		{
			try
			{
				deferred.resolve(success ? success(data) : data.results.bindings[0]["callret-0"].value);
			}
			catch (e)
			{
				deferred.reject(e);

			}
		})
		.error(function(data, status)
		{
			var message = data || ENDPOINT + " not found";
			deferred.reject(message);
			flash.error = message;
		});

		return deferred.promise;
	};

	var ns = function(v)
	{
		var value = v.value || v;

		if (!v.type || v.type == "uri")
		{
			var namespace = /.*[#\/]/.exec(value);
			if (namespace)
			{
				var prefix = namespaces[namespace = namespace[0]];
				if (prefix)
					return prefix + value.slice(namespace.length);
			}
		}

		return value;
	};

	var setEndpoint = function(url)
	{
		ENDPOINT = url;
	};

	var getEndpoint = function()
	{
		return ENDPOINT;
	};

	var getNS = function()
	{
		return NS;
	};

	var getGraph = function()
	{
		return GRAPH;
	};

	var getSettings = function()
	{
		return settings;
	};

	var select = function(property, value)
	{
		property = ns(property);
		value    = ns(value);

		var elements = {};

		for (var resource in settings)
		{
			var element = settings[resource];
			var prop = element[property];
			if (prop)
				for (var i in prop)
					if (prop[i] == value)
					{
						elements[resource] = element;
						break;
					}
		}

		return elements;
	};

	var read = function()
	{
		if (isLoaded)
		{
			var deferred = $q.defer();
			deferred.resolve(settings);
			return deferred.promise;
		}

		return request("SELECT * FROM " + GRAPH + EOL
		+	"WHERE { ?s ?p ?o }" + EOL
		+	"ORDER BY ?s ?p ?o",
			function(data)
			{
				var bindings = data.results.bindings;
				var triples  = [];

				for (var i in bindings)
				{
					var binding = bindings[i];
					triples.push([ ns(binding.s), ns(binding.p), ns(binding.o) ]);
				}

				settings = {};

				var bnodes = {};

				for (var i in triples)
				{
					var triple = triples[i],
						s = triple[0],
						p = triple[1],
						o = triple[2];

					if (/^nodeID:\/\//.test(s))
					{
						var id  = s.slice(9),
						map = bnodes[id] = bnodes[id] || {};
					}
					else
					{
						var map = settings[s] || (settings[s] = {});
					}

					if (/^nodeID:\/\//.test(o))
					{
						var id = o.slice(9);
						o = bnodes[id] = bnodes[id] || {};
					}

					(map[p] || (map[p] = [])).push(o);
				}

				isLoaded = true;

				return settings;
			}
		);
	};

	var write = function()
	{
		var wrap = function(s)
		{
			return /^https?:\/\//.test(s) ? "<" + s + ">" : !/^\w*:/.test(s) ? '"' + s + '"' : s;
		};

		var data = "",
			bnodeIndex = 0;

		var walk = function(s, map)
		{
			for (var p in map)
			{
				var arr = map[p];
				for (var i in arr)
				{
					var o = arr[i];
					if (typeof o === "string")
						data += wrap(s) + " " + wrap(p) + " " + wrap(o) + " ." + EOL;
					else
					{
						var bnode = "_:b" + ++bnodeIndex;
						data += wrap(s) + " " + wrap(p) + " " + bnode + " ." + EOL;
						walk(bnode, o);
					}
				}
			}
		};

		for (var s in settings)
			walk(s, settings[s]);

		return request(PREFIXES
		+	"DROP SILENT GRAPH "   + GRAPH + EOL
		+	"CREATE SILENT GRAPH " + GRAPH + EOL
		+	"INSERT INTO "         + GRAPH + EOL
		+	"{" + EOL
		+	data
		+	"}");
	};

	var createGraph = function(name)
	{
		return request("CREATE SILENT GRAPH <" + name + ">");
	};

	var dropGraph = function(name)
	{
		return request("DROP SILENT GRAPH <" + name + ">");
	};

	return {
		setEndpoint : setEndpoint,
		getEndpoint : getEndpoint,
		getNS       : getNS,
		getGraph    : getGraph,
		getSettings : getSettings,
		select      : select,
		read        : read,
		write       : write,
		createGraph : createGraph,
		dropGraph   : dropGraph
	};
});
/*
.controller("ConfigCtrl", function($scope, Config)
{
	$scope.settings = Config.read();
});
*/<commit_msg>Support for nested blank nodes for Config.select().<commit_after>/**
 * GeoKnow Generator
 *    Configuration management
 *
 * @author Vadim Zaslawski
 *
 * enable SPARQL Update
 * ISQL:
 *   GRANT SPARQL_UPDATE TO "SPARQL"
 *   GRANT EXECUTE ON DB.DBA.L_O_LOOK TO "SPARQL"
 *
 * enable CORS
 *
 * usage:
 *   setEndpoint(url)          - set SPARQL endpoint, should be called initially
 *   getEndpoint()             - get SPARQL endpoint
 *   getNS()                   - get base namespace
 *   getGraph()                - get graph name
 *   read()                    - load settings
 *   getSettings()             - get loaded settings
 *   write()                   - save settings after editing getSettings() result
 *   select(property, value)   - select settings, e.g.: select("rdf:type", "lds:StackComponent")
 *   createGraph(name)         - create graph
 *   dropGraph(name)           - delete graph
 */

// TODO handle shared blank nodes

"use strict";

angular.module("app.configuration", [])
.factory("Config", function($q, $http, flash)
{
	$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8";

	var ENDPOINT  = "http://144.76.166.111:8890/sparql";
	var NS        = "http://generator.geoknow.eu/resource/";
	var GRAPH_URI = NS + "settingsGraph";

	var namespaces =
	{
		"http://dbpedia.org/resource/"                     : "dbpedia:",
		"http://purl.org/dc/elements/1.1/"                 : "dc:",
		"http://purl.org/dc/terms/"                        : "dcterms:",
		"http://xmlns.com/foaf/0.1/"                       : "foaf:",
		"http://linkeddata.org/integrated-stack-schema/"   : "lds:",
		"http://www.w3.org/1999/02/22-rdf-syntax-ns#"      : "rdf:",
		"http://www.w3.org/2000/01/rdf-schema#"            : "rdfs:",
		"http://www.w3.org/ns/sparql-service-description#" : "sd:",
		"http://rdfs.org/ns/void#"                         : "void:"
	};
	namespaces[NS] = ":";

	var GRAPH    = "<" + GRAPH_URI + ">";
	var EOL      = "\n";
	var PREFIXES = "";
	for (var namespace in namespaces)
		PREFIXES += "PREFIX " + namespaces[namespace] + " <" + namespace + ">" + EOL;

	var settings = {};
	var isLoaded = false;

	var request = function(query, success)
	{
		var deferred = $q.defer();

		$http.post(ENDPOINT, $.param(
		{
			format: "application/sparql-results+json",
			query:  query
		}))
		.success(function(data)
		{
			try
			{
				deferred.resolve(success ? success(data) : data.results.bindings[0]["callret-0"].value);
			}
			catch (e)
			{
				deferred.reject(e);

			}
		})
		.error(function(data, status)
		{
			var message = data || ENDPOINT + " not found";
			deferred.reject(message);
			flash.error = message;
		});

		return deferred.promise;
	};

	var ns = function(v)
	{
		var value = v.value || v;

		if (!v.type || v.type == "uri")
		{
			var namespace = /.*[#\/]/.exec(value);
			if (namespace)
			{
				var prefix = namespaces[namespace = namespace[0]];
				if (prefix)
					return prefix + value.slice(namespace.length);
			}
		}

		return value;
	};

	var setEndpoint = function(url)
	{
		ENDPOINT = url;
	};

	var getEndpoint = function()
	{
		return ENDPOINT;
	};

	var getNS = function()
	{
		return NS;
	};

	var getGraph = function()
	{
		return GRAPH;
	};

	var getSettings = function()
	{
		return settings;
	};

	var select = function(property, value)
	{
		property = ns(property);
		value    = ns(value);

		var elements = {};
		var resource;

		var walk = function(element)
		{
			for (var key in element)
			{
				var prop = element[key];
				if (prop)
					if (key == property)
						for (var i in prop)
						{
							var val = prop[i];
							if (val == value)
							{
								elements[resource] = element;
								break;
							}
						}
					else
						for (var i in prop)
						{
							var val = prop[i];
							if (typeof val === "object")
								walk(val);
						}
			}
		};

		for (resource in settings)
			walk(settings[resource]);

		return elements;
	};

	var read = function()
	{
		if (isLoaded)
		{
			var deferred = $q.defer();
			deferred.resolve(settings);
			return deferred.promise;
		}

		return request("SELECT * FROM " + GRAPH + EOL
		+	"WHERE { ?s ?p ?o }" + EOL
		+	"ORDER BY ?s ?p ?o",
			function(data)
			{
				var bindings = data.results.bindings;
				var triples  = [];

				for (var i in bindings)
				{
					var binding = bindings[i];
					triples.push([ ns(binding.s), ns(binding.p), ns(binding.o) ]);
				}

				settings = {};

				var bnodes = {};

				for (var i in triples)
				{
					var triple = triples[i],
						s = triple[0],
						p = triple[1],
						o = triple[2];

					if (/^nodeID:\/\//.test(s))
					{
						var id  = s.slice(9),
						map = bnodes[id] = bnodes[id] || {};
					}
					else
					{
						var map = settings[s] || (settings[s] = {});
					}

					if (/^nodeID:\/\//.test(o))
					{
						var id = o.slice(9);
						o = bnodes[id] = bnodes[id] || {};
					}

					(map[p] || (map[p] = [])).push(o);
				}

				isLoaded = true;

				return settings;
			}
		);
	};

	var write = function()
	{
		var wrap = function(s)
		{
			return /^https?:\/\//.test(s) ? "<" + s + ">" : !/^\w*:/.test(s) ? '"' + s + '"' : s;
		};

		var data = "",
			bnodeIndex = 0;

		var walk = function(s, map)
		{
			for (var p in map)
			{
				var arr = map[p];
				for (var i in arr)
				{
					var o = arr[i];
					if (typeof o === "string")
						data += wrap(s) + " " + wrap(p) + " " + wrap(o) + " ." + EOL;
					else
					{
						var bnode = "_:b" + ++bnodeIndex;
						data += wrap(s) + " " + wrap(p) + " " + bnode + " ." + EOL;
						walk(bnode, o);
					}
				}
			}
		};

		for (var s in settings)
			walk(s, settings[s]);

		return request(PREFIXES
		+	"DROP SILENT GRAPH "   + GRAPH + EOL
		+	"CREATE SILENT GRAPH " + GRAPH + EOL
		+	"INSERT INTO "         + GRAPH + EOL
		+	"{" + EOL
		+	data
		+	"}");
	};

	var createGraph = function(name)
	{
		return request("CREATE SILENT GRAPH <" + name + ">");
	};

	var dropGraph = function(name)
	{
		return request("DROP SILENT GRAPH <" + name + ">");
	};

	return {
		setEndpoint : setEndpoint,
		getEndpoint : getEndpoint,
		getNS       : getNS,
		getGraph    : getGraph,
		getSettings : getSettings,
		select      : select,
		read        : read,
		write       : write,
		createGraph : createGraph,
		dropGraph   : dropGraph
	};
});
/*
.controller("ConfigCtrl", function($scope, Config)
{
	$scope.settings = Config.read();
});
*/<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

function initMap(mapLocation) {
  let myLatLng = {lat: mapLocation.lat, lng: mapLocation.lng};
  map = new google.maps.Map(document.getElementById('map'), {
    center: myLatLng,
    mapTypeControl: false
  });
}

function createMarker(listing, cardNumber) {
  let marker = new google.maps.Marker({
    position: {lat: listing.mapLocation.lat, lng: listing.mapLocation.lng},
  });
  bounds.extend(marker.getPosition());

  marker.addListener('click', function() {
    map.setCenter(marker.getPosition());
    map.setZoom(18);
    let firstCardId = document.getElementById('results-content').firstChild.id;
    // If card is not on the current page
    if ((cardNumber-firstCardId < 0) || (cardNumber-firstCardId >= 3)) {
      displayCards(Math.floor((cardNumber-firstCardId)/3)*3);
    }

    let currentCard = document.getElementById(cardNumber);
    // Corresponding card flashes for 5 seconds
    currentCard.style.backgroundColor = '#b3ffb3';
    setTimeout(function() {
      currentCard.style.backgroundColor = '#fff';
    }, 5000);
  });
  marker.setMap(map);
}<commit_msg>Change marker card highlight to border instead of fill<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

function initMap(mapLocation) {
  let myLatLng = {lat: mapLocation.lat, lng: mapLocation.lng};
  map = new google.maps.Map(document.getElementById('map'), {
    center: myLatLng,
    mapTypeControl: false
  });
}

function createMarker(listing, cardNumber) {
  let marker = new google.maps.Marker({
    position: {lat: listing.mapLocation.lat, lng: listing.mapLocation.lng},
  });
  bounds.extend(marker.getPosition());

  marker.addListener('click', function() {
    map.setCenter(marker.getPosition());
    map.setZoom(18);
    let firstCardId = document.getElementById('results-content').firstChild.id;
    // If card is not on the current page
    if ((cardNumber-firstCardId < 0) || (cardNumber-firstCardId >= 3)) {
      displayCards(Math.floor((cardNumber-firstCardId)/3)*3);
    }

    let currentCard = document.getElementById(cardNumber);
    // Corresponding card flashes for 5 seconds
    currentCard.style.border = '8px solid #b3ffb3';
    setTimeout(function() {
      currentCard.style.border = 'none';
    }, 5000);
  });
  marker.setMap(map);
}<|endoftext|>


<commit_before>Console = Ember.Object.extend({
	baseConsole: undefined,
	author: undefined,
	tags: [],
	mutedTags: [],
	filter: undefined,

	log: function() {
		if(this.baseConsole !== undefined) {

			var args = [];

			for (var i = 0; i < arguments.length; i++) {
				args.push(arguments[i]);
			};

			if(this.tags !== undefined) {
				for (var i = this.tags.length - 1; i >= 0 ; i--) {
					if (this.mutedTags.contains(this.tags[i])) { return; };
					args.unshift("["+ this.tags[i] +"]");
				};
			}

			if(this.filter !== "" && this.filter !== undefined) {
				for (var i = 0; i < args.length; i++) {
					if(typeof args[i] === "string") {
						var regex = new RegExp(this.filter);
						if(regex.test(args[i])) {
							return;
						}
					}
				};
			};

			this.baseConsole.log.apply(this.baseConsole, args);
		}
	},

	addTag: function(tag){
		this.tags.push(tag);
	},

	removeTag: function(tag){
		for (var i = 0; i < this.tags.length; i++) {
			if(this.tags[i] === tag) {
				this.tags.splice(i, 1);
				return;
			}
		};
	},

	flushTags: function(){
		this.tags = [];
		this.tags.push(this.author);
	},

	setAuthor: function(author) {
		this.author = author;
		this.tags.push(this.author);
	},

	muteTag: function(tag) {
		this.mutedTags.push(tag);
	},

	unmuteTag: function(tag) {
		for (var i = 0; i < this.mutedTags.length; i++) {
			if(this.mutedTags[i] === tag) {
				this.mutedTags.splice(i, 1);
				return;
			}
		};
	},

	filterMessages: function(regex) {
		this.filter = regex;
	}
});

console = Console.create({
	baseConsole: console
});

console.log("m1", console);
console.setAuthor("a1");
console.addTag("t1");
console.addTag("t2");
console.log("m2", console);
console.removeTag("t1");
console.log("m3", console);
console.flushTags();
console.log("m4", console);

console.addTag("t3");
console.log("Object instantiated");

window.setInterval(function(){
	console.log("m5");
},1000);
<commit_msg>automate author name setting and add "save settings to localstorage" feature<commit_after>Console = Ember.Object.extend({
	baseConsole: undefined,
	author: undefined,
	tags: [],
	mutedTags: [],
	filter: undefined,

	init: function() {
		if(localStorage.getItem("console.mutedTags") !== undefined) {
			console.log("load settings from localStorage, if possible");
			this.mutedTags = localStorage.getItem("console.mutedTags").split(",");
			this.filter = localStorage.getItem("console.filter");
		}
		var scripts = document.getElementsByTagName("script");
		var scriptName = (document.currentScript || scripts[scripts.length - 1]).src;
		scriptName = scriptName.split("/");
		scriptName = scriptName[scriptName.length - 1];

		this.setAuthor(scriptName);
	},

	log: function() {
		if(this.baseConsole !== undefined) {

			var args = [];

			for (var i = 0; i < arguments.length; i++) {
				args.push(arguments[i]);
			};

			if(this.tags !== undefined) {
				for (var i = this.tags.length - 1; i >= 0 ; i--) {
					if (this.mutedTags.contains(this.tags[i])) { return; };
					args.unshift("["+ this.tags[i] +"]");
				};
			}

			if(this.filter !== "" && this.filter !== undefined && this.filter !== null) {
				for (var i = 0; i < args.length; i++) {
					if(typeof args[i] === "string") {
						var regex = new RegExp(this.filter);
						if(regex.test(args[i])) {
							return;
						}
					}
				};
			};

			this.baseConsole.log.apply(this.baseConsole, args);
		}
	},

	addTag: function(tag){
		this.tags.push(tag);
	},

	removeTag: function(tag){
		for (var i = 0; i < this.tags.length; i++) {
			if(this.tags[i] === tag) {
				this.tags.splice(i, 1);
				return;
			}
		};
	},

	flushTags: function(){
		this.tags = [];
		this.tags.push(this.author);
	},

	setAuthor: function(author) {
		this.author = author;
		this.tags.push(this.author);
	},

	muteTag: function(tag) {
		this.mutedTags.push(tag);
	},

	unmuteTag: function(tag) {
		for (var i = 0; i < this.mutedTags.length; i++) {
			if(this.mutedTags[i] === tag) {
				this.mutedTags.splice(i, 1);
				return;
			}
		};
	},

	filterMessages: function(regex) {
		this.filter = regex;
	},

	saveSettings: function() {
		localStorage.setItem("console.mutedTags", this.mutedTags);
		localStorage.setItem("console.filter", this.filter);
	}
});

console = Console.create({
	baseConsole: console
});

console.log("m1", console);
console.addTag("t1");
console.addTag("t2");
console.log("m2", console);
console.removeTag("t1");
console.log("m3", console);
console.flushTags();
console.log("m4", console);

console.addTag("t3");
console.log("Object instantiated");

window.setInterval(function(){
	console.log("m5");
},1000);
<|endoftext|>


<commit_before>//to access filesystem
const fs = require('fs');
//to format filepath
const path = require('path');

var commonUtil = require("../common/commonUtil");
var commonSearchUtil = require("../common/commonSearchUtil");
var searchDriveUtil = require("./searchDriveUtil");
var searchProgressManager = require("../searchPathUtils/searchProgressManager");
var complementProgressManager = require("./complementProgressManager");
var complementSortManager = require("./complementSortManager");

//param: "C:\AAA\BBB"
//return ["C:\AAA", "BBB"]
function extractKeywords(formattedQuery){
	//search candidates to complement
	var splittedQuery =
		commonSearchUtil.separatePath(formattedQuery,false);

	var currentDirectory;
	var searchKeyword;
	var lengthOfSplittedQuery = splittedQuery.length;
	if(lengthOfSplittedQuery == 0){
		currentDirectory = "";
		searchKeyword = "";
	}else if(lengthOfSplittedQuery == 1){
		currentDirectory = "";
		searchKeyword = splittedQuery[0];
	}else{// length >= 2
		currentDirectory = "";
		for(index = 0 ; index < lengthOfSplittedQuery - 1 ; index++){
			currentDirectory = currentDirectory + splittedQuery[index] + "\\";
		}
		//currentDirectory.pop();
		searchKeyword = splittedQuery[lengthOfSplittedQuery - 1];
	}
	return [currentDirectory, searchKeyword];
}

//ex tags: ["",""]
//param : "ABCDE", ["AB","D"]
function evaluate(originalCandidate, keyword){
	var eval = 0;
	var innerOriginalCandidate = originalCandidate;
	for(var indexOfKeyword = 0, lengthOfKeyword = keyword.length ; indexOfKeyword < lengthOfKeyword ; indexOfKeyword++){
		var foundPos = innerOriginalCandidate.toLocaleLowerCase().indexOf(keyword[indexOfKeyword].toLocaleLowerCase());
		if(foundPos == -1){
			eval = eval - 1;
		}else{
			eval = eval + 1;
			innerOriginalCandidate = innerOriginalCandidate.substring(foundPos + 1);
		}
	}
	return eval;
}
function emphasize(originalCandidate, keyword){
	var tag = ["",""];
	var empFlag = false;
	//var eval = 0;
	var emphasizedCandidate = "";
	var innerOriginalCandidate = originalCandidate;
	for(var indexOfKeyword = 0, lengthOfKeyword = keyword.length ; indexOfKeyword < lengthOfKeyword ; indexOfKeyword++){
		var foundPos = innerOriginalCandidate.toLocaleLowerCase().indexOf(keyword[indexOfKeyword].toLocaleLowerCase());
		if(foundPos == -1){
			//eval = eval - 1;
			if(indexOfKeyword == lengthOfKeyword - 1){
				if(empFlag == true){
					emphasizedCandidate = emphasizedCandidate + tag[1];
				}
				emphasizedCandidate = emphasizedCandidate + innerOriginalCandidate;
			}
		}else{
			//eval = eval + 1;
			if(empFlag == false){
				emphasizedCandidate = emphasizedCandidate + innerOriginalCandidate.substring(0, foundPos);
				emphasizedCandidate = emphasizedCandidate + tag[0];
				emphasizedCandidate = emphasizedCandidate + innerOriginalCandidate[foundPos];
				innerOriginalCandidate = innerOriginalCandidate.substring(foundPos + 1);
				empFlag = true;
			}else{
				if(foundPos > 0){ emphasizedCandidate = emphasizedCandidate + tag[1]; }
				emphasizedCandidate = emphasizedCandidate + innerOriginalCandidate.substring(0, foundPos);
				if(foundPos > 0){ emphasizedCandidate = emphasizedCandidate + tag[0]; }
				emphasizedCandidate = emphasizedCandidate + innerOriginalCandidate[foundPos];
				innerOriginalCandidate = innerOriginalCandidate.substring(foundPos + 1);
			}
			if(empFlag == true && indexOfKeyword == lengthOfKeyword - 1){
				emphasizedCandidate = emphasizedCandidate + tag[1];
				emphasizedCandidate = emphasizedCandidate + innerOriginalCandidate;
			}
		}
	}
	return emphasizedCandidate;
}

function addComplementCandidateToRes
(currentDirectory, state, candidate, searchKeyword, emphasizedCandidate, res){
	if(emphasizedCandidate.length > 0 || searchKeyword.length == 0){
		const commandHeader = commonUtil.commandHeader;

		var descriptionMessage =
			//"Set this path : \"" + foundCandidates[index].path + "\"";
			"Set this path : \"" + candidate + "\"";
		//var redirect;
		var innerId, innerTitle, innerIcon, innerRedirect, innerGroup;
		//switch(foundCandidates[index].state){
		switch(state){
			case "drive":
				innerTitle = "";
				innerId =
					commandHeader + " " +
					currentDirectory + candidate + "\\";
				innerIcon = "#fa fa-hdd-o";
				innerRedirect = innerId;
				innerGroup = "Complement Pathes : Drive";
				break;
			case "file":
				innerTitle = ".\\";
				innerId =
					commandHeader + " " +
					currentDirectory + candidate;
				innerIcon = "#fa fa-file";
				innerRedirect = innerId;
				innerGroup = "Complement Pathes : File";
				break;
			case "folder":
				innerTitle = ".\\";
				innerId =
					commandHeader + " " +
					currentDirectory + candidate + "\\";
				innerIcon = "#fa fa-folder";
				innerRedirect = innerId;
				innerGroup = "Complement Pathes : Folder";
				break;
		}

		if(searchKeyword.length == 0){
			innerTitle = innerTitle + candidate;
		}else{
			innerTitle = innerTitle + emphasizedCandidate;
		}

		//add to res
		res.add(
			{
				id: innerId,
				payload: 'complement',
				title: innerTitle,
				icon: innerIcon,
				desc: descriptionMessage,
				redirect:innerRedirect,
				group: innerGroup
			}
		);
	}
}

function complementDrives(availableDrives, searchKeyword, res){
	//reset
	complementProgressManager.reset();
	complementSortManager.reset();
	//search available path to complement
	var currentDirectory = "";
	var len = availableDrives.length;
	complementProgressManager.setComplementCandidateNum(len);

	//listup available drives
	for (var index = 0; index < len ; index++){
		if(availableDrives[index].isAvailable == true){
			var originalCandidate = availableDrives[index].driveName;
			var eval = evaluate(originalCandidate, searchKeyword);
			if(eval > 0 || searchKeyword.length == 0){
				//add to res
				complementProgressManager.addAddedComplementCandidateNum();
				complementSortManager.add(currentDirectory, originalCandidate, eval, searchKeyword, "drive");
			}
		}
		complementProgressManager.addProgress();
	}
	checkProgress(res, currentDirectory);
}
function complementFileOrFolder(currentDirectory, searchKeyword, res) {
	//reset
	complementProgressManager.reset();
	complementSortManager.reset();

	//check the status of currentpath async
	fs.stat(currentDirectory, function(err, stats){
		if(err){
			//console.log("err");
		}else if(stats.isDirectory()){
			//when only currentPath is folder
			//exec fs.readdir (get child folder/files)
			fs.readdir(currentDirectory, function(err, list){
				var len = list.length;
				complementProgressManager.setComplementCandidateNum(len)
				if(err){
					//console.log("err");
					checkProgress(res, currentDirectory);
				}else{
					if(searchKeyword.length == 0){
						for(var index = 0; index < len ; index++) {
							let originalCandidate = list[index];
							//add to res
							fs.stat(currentDirectory + originalCandidate, function(err, stats){
								if(err){
									//console.log("err");
									//do nothing
								}else if(stats.isFile() == true){
									complementProgressManager.addAddedComplementCandidateNum();
									complementSortManager.add(currentDirectory, originalCandidate, 0, searchKeyword, "file");
								}else{
									complementProgressManager.addAddedComplementCandidateNum();
									complementSortManager.add(currentDirectory, originalCandidate, 0, searchKeyword, "folder");
								}
								complementProgressManager.addProgress();
								checkProgress(res, currentDirectory);
							});
						}
					}else{
						for(var index = 0, len = list.length ; index < len ; index++) {
							let originalCandidate = list[index];
							//filter
							let innerSearchKeyword = searchKeyword;

							let eval = evaluate(originalCandidate, innerSearchKeyword);
							if(eval > 0){
								//add to res
								fs.stat(currentDirectory + originalCandidate, function(err, stats) {
									if(err){
										//do nothing
									}else if (stats.isFile() == true) {
										complementProgressManager.addAddedComplementCandidateNum();
										complementSortManager.add(currentDirectory, originalCandidate, eval, searchKeyword, "file");
									} else {
										complementProgressManager.addAddedComplementCandidateNum();
										complementSortManager.add(currentDirectory, originalCandidate, eval, searchKeyword, "folder");
									}
									complementProgressManager.addProgress();
									checkProgress(res, currentDirectory);
								});
							}else{
								complementProgressManager.addProgress();
								checkProgress(res, currentDirectory);
							}
						}
					}
				}
			});
		}else{
			//console.log("else");
		}
	});
}

var searchCandidates = function(formattedQuery, availableDrives, res){

	var keywords = extractKeywords(formattedQuery);
	var currentDirectory = keywords[0];
	var searchKeyword = keywords[1];
	//search available path to complement
	//check if the current directory is empty or not
	//empty (suggest available drives)
	if(currentDirectory == ""){
		complementDrives(availableDrives, searchKeyword, res);
	}else{//not empty (suggest available child folder/files)
		complementFileOrFolder(currentDirectory, searchKeyword, res);
	}
	//Search Available Drives again.
	searchDriveUtil.searchAvailableDrivesAsync();
}

function addNotFoundCommand(res, currentDirectory){
	res.add(
		{
			id: commonUtil.commandHeader + " " + currentDirectory,
			icon: "#fa fa-undo",
			payload: 'notfound',
			redirect: commonUtil.commandHeader + " " + currentDirectory,
			title: "No file/folder was not found.",
			desc: "Back to parent folder : " + currentDirectory,
			group: "File/Folder Not Found"
		}
	);
}
function addSortedCandidates(res){
	var sortedCandidates = complementSortManager.getSortedCandidates();
	for (var index = 0, len = sortedCandidates.length; index < len; index++) {
		var candidate = sortedCandidates[index];
		var currentDirectory = candidate.currentDirectory;
		var originalCandidate = candidate.originalCandidate;
		var keyword = candidate.keyword;
		var state = candidate.state;
		addComplementCandidateToRes(
			currentDirectory, state, originalCandidate,
			keyword, emphasize(originalCandidate, keyword), res
		);
	}
}

function checkProgress(res, currentDirectory){
	if(searchProgressManager.isSearchCompleted() == true && complementProgressManager.isComplementCompleted() == true){
		if(searchProgressManager.isPathAdded() == false && complementProgressManager.isComplementAdded() == false){
			addNotFoundCommand(res, currentDirectory);
		}else{
			addSortedCandidates(res);
		}
	}
}

exports.searchCandidates = searchCandidates;<commit_msg>standardized order of candidates(drive -> folder -> file)<commit_after>//to access filesystem
const fs = require('fs');
//to format filepath
const path = require('path');

var commonUtil = require("../common/commonUtil");
var commonSearchUtil = require("../common/commonSearchUtil");
var searchDriveUtil = require("./searchDriveUtil");
var searchProgressManager = require("../searchPathUtils/searchProgressManager");
var complementProgressManager = require("./complementProgressManager");
var complementSortManager = require("./complementSortManager");

//param: "C:\AAA\BBB"
//return ["C:\AAA", "BBB"]
function extractKeywords(formattedQuery){
	//search candidates to complement
	var splittedQuery =
		commonSearchUtil.separatePath(formattedQuery,false);

	var currentDirectory;
	var searchKeyword;
	var lengthOfSplittedQuery = splittedQuery.length;
	if(lengthOfSplittedQuery == 0){
		currentDirectory = "";
		searchKeyword = "";
	}else if(lengthOfSplittedQuery == 1){
		currentDirectory = "";
		searchKeyword = splittedQuery[0];
	}else{// length >= 2
		currentDirectory = "";
		for(index = 0 ; index < lengthOfSplittedQuery - 1 ; index++){
			currentDirectory = currentDirectory + splittedQuery[index] + "\\";
		}
		//currentDirectory.pop();
		searchKeyword = splittedQuery[lengthOfSplittedQuery - 1];
	}
	return [currentDirectory, searchKeyword];
}

//ex tags: ["",""]
//param : "ABCDE", ["AB","D"]
function evaluate(originalCandidate, keyword){
	var eval = 0;
	var innerOriginalCandidate = originalCandidate;
	for(var indexOfKeyword = 0, lengthOfKeyword = keyword.length ; indexOfKeyword < lengthOfKeyword ; indexOfKeyword++){
		var foundPos = innerOriginalCandidate.toLocaleLowerCase().indexOf(keyword[indexOfKeyword].toLocaleLowerCase());
		if(foundPos == -1){
			eval = eval - 1;
		}else{
			eval = eval + 1;
			innerOriginalCandidate = innerOriginalCandidate.substring(foundPos + 1);
		}
	}
	return eval;
}
function emphasize(originalCandidate, keyword){
	var tag = ["",""];
	var empFlag = false;
	//var eval = 0;
	var emphasizedCandidate = "";
	var innerOriginalCandidate = originalCandidate;
	for(var indexOfKeyword = 0, lengthOfKeyword = keyword.length ; indexOfKeyword < lengthOfKeyword ; indexOfKeyword++){
		var foundPos = innerOriginalCandidate.toLocaleLowerCase().indexOf(keyword[indexOfKeyword].toLocaleLowerCase());
		if(foundPos == -1){
			//eval = eval - 1;
			if(indexOfKeyword == lengthOfKeyword - 1){
				if(empFlag == true){
					emphasizedCandidate = emphasizedCandidate + tag[1];
				}
				emphasizedCandidate = emphasizedCandidate + innerOriginalCandidate;
			}
		}else{
			//eval = eval + 1;
			if(empFlag == false){
				emphasizedCandidate = emphasizedCandidate + innerOriginalCandidate.substring(0, foundPos);
				emphasizedCandidate = emphasizedCandidate + tag[0];
				emphasizedCandidate = emphasizedCandidate + innerOriginalCandidate[foundPos];
				innerOriginalCandidate = innerOriginalCandidate.substring(foundPos + 1);
				empFlag = true;
			}else{
				if(foundPos > 0){ emphasizedCandidate = emphasizedCandidate + tag[1]; }
				emphasizedCandidate = emphasizedCandidate + innerOriginalCandidate.substring(0, foundPos);
				if(foundPos > 0){ emphasizedCandidate = emphasizedCandidate + tag[0]; }
				emphasizedCandidate = emphasizedCandidate + innerOriginalCandidate[foundPos];
				innerOriginalCandidate = innerOriginalCandidate.substring(foundPos + 1);
			}
			if(empFlag == true && indexOfKeyword == lengthOfKeyword - 1){
				emphasizedCandidate = emphasizedCandidate + tag[1];
				emphasizedCandidate = emphasizedCandidate + innerOriginalCandidate;
			}
		}
	}
	return emphasizedCandidate;
}

function addComplementCandidateToRes
(currentDirectory, state, candidate, searchKeyword, emphasizedCandidate, res){
	if(emphasizedCandidate.length > 0 || searchKeyword.length == 0){
		const commandHeader = commonUtil.commandHeader;

		var descriptionMessage =
			//"Set this path : \"" + foundCandidates[index].path + "\"";
			"Set this path : \"" + candidate + "\"";
		//var redirect;
		var innerId, innerTitle, innerIcon, innerRedirect, innerGroup;
		//switch(foundCandidates[index].state){
		switch(state){
			case "drive":
				innerTitle = "";
				innerId =
					commandHeader + " " +
					currentDirectory + candidate + "\\";
				innerIcon = "#fa fa-hdd-o";
				innerRedirect = innerId;
				innerGroup = "Complement Pathes : Drive";
				break;
			case "file":
				innerTitle = ".\\";
				innerId =
					commandHeader + " " +
					currentDirectory + candidate;
				innerIcon = "#fa fa-file";
				innerRedirect = innerId;
				innerGroup = "Complement Pathes : File";
				break;
			case "folder":
				innerTitle = ".\\";
				innerId =
					commandHeader + " " +
					currentDirectory + candidate + "\\";
				innerIcon = "#fa fa-folder";
				innerRedirect = innerId;
				innerGroup = "Complement Pathes : Folder";
				break;
		}

		if(searchKeyword.length == 0){
			innerTitle = innerTitle + candidate;
		}else{
			innerTitle = innerTitle + emphasizedCandidate;
		}

		//add to res
		res.add(
			{
				id: innerId,
				payload: 'complement',
				title: innerTitle,
				icon: innerIcon,
				desc: descriptionMessage,
				redirect:innerRedirect,
				group: innerGroup
			}
		);
	}
}

function complementDrives(availableDrives, searchKeyword, res){
	//reset
	complementProgressManager.reset();
	complementSortManager.reset();
	//search available path to complement
	var currentDirectory = "";
	var len = availableDrives.length;
	complementProgressManager.setComplementCandidateNum(len);

	//listup available drives
	for (var index = 0; index < len ; index++){
		if(availableDrives[index].isAvailable == true){
			var originalCandidate = availableDrives[index].driveName;
			var eval = evaluate(originalCandidate, searchKeyword);
			if(eval > 0 || searchKeyword.length == 0){
				//add to res
				complementProgressManager.addAddedComplementCandidateNum();
				complementSortManager.add(currentDirectory, originalCandidate, eval, searchKeyword, "drive");
			}
		}
		complementProgressManager.addProgress();
	}
	checkProgress(res, currentDirectory);
}
function complementFileOrFolder(currentDirectory, searchKeyword, res) {
	//reset
	complementProgressManager.reset();
	complementSortManager.reset();

	//check the status of currentpath async
	fs.stat(currentDirectory, function(err, stats){
		if(err){
			//console.log("err");
		}else if(stats.isDirectory()){
			//when only currentPath is folder
			//exec fs.readdir (get child folder/files)
			fs.readdir(currentDirectory, function(err, list){
				var len = list.length;
				complementProgressManager.setComplementCandidateNum(len)
				if(err){
					//console.log("err");
					checkProgress(res, currentDirectory);
				}else{
					if(searchKeyword.length == 0){
						for(var index = 0; index < len ; index++) {
							let originalCandidate = list[index];
							//add to res
							fs.stat(currentDirectory + originalCandidate, function(err, stats){
								if(err){
									//console.log("err");
									//do nothing
								}else if(stats.isFile() == true){
									complementProgressManager.addAddedComplementCandidateNum();
									complementSortManager.add(currentDirectory, originalCandidate, 0, searchKeyword, "file");
								}else{
									complementProgressManager.addAddedComplementCandidateNum();
									complementSortManager.add(currentDirectory, originalCandidate, 0, searchKeyword, "folder");
								}
								complementProgressManager.addProgress();
								checkProgress(res, currentDirectory);
							});
						}
					}else{
						for(var index = 0, len = list.length ; index < len ; index++) {
							let originalCandidate = list[index];
							//filter
							let innerSearchKeyword = searchKeyword;

							let eval = evaluate(originalCandidate, innerSearchKeyword);
							if(eval > 0){
								//add to res
								fs.stat(currentDirectory + originalCandidate, function(err, stats) {
									if(err){
										//do nothing
									}else if (stats.isFile() == true) {
										complementProgressManager.addAddedComplementCandidateNum();
										complementSortManager.add(currentDirectory, originalCandidate, eval, searchKeyword, "file");
									} else {
										complementProgressManager.addAddedComplementCandidateNum();
										complementSortManager.add(currentDirectory, originalCandidate, eval, searchKeyword, "folder");
									}
									complementProgressManager.addProgress();
									checkProgress(res, currentDirectory);
								});
							}else{
								complementProgressManager.addProgress();
								checkProgress(res, currentDirectory);
							}
						}
					}
				}
			});
		}else{
			//console.log("else");
		}
	});
}

var searchCandidates = function(formattedQuery, availableDrives, res){

	var keywords = extractKeywords(formattedQuery);
	var currentDirectory = keywords[0];
	var searchKeyword = keywords[1];
	//search available path to complement
	//check if the current directory is empty or not
	//empty (suggest available drives)
	if(currentDirectory == ""){
		complementDrives(availableDrives, searchKeyword, res);
	}else{//not empty (suggest available child folder/files)
		complementFileOrFolder(currentDirectory, searchKeyword, res);
	}
	//Search Available Drives again.
	searchDriveUtil.searchAvailableDrivesAsync();
}

function addNotFoundCommand(res, currentDirectory){
	res.add(
		{
			id: commonUtil.commandHeader + " " + currentDirectory,
			icon: "#fa fa-undo",
			payload: 'notfound',
			redirect: commonUtil.commandHeader + " " + currentDirectory,
			title: "No file/folder was not found.",
			desc: "Back to parent folder : " + currentDirectory,
			group: "File/Folder Not Found"
		}
	);
}
function addCandidatesOfEachState(res, state, sortedCandidates){
	var len = sortedCandidates.length;
	for (var index = 0; index < len; index++) {
		var candidate = sortedCandidates[index];
		var innerState = candidate.state;
		if(innerState == state){
			var currentDirectory = candidate.currentDirectory;
			var originalCandidate = candidate.originalCandidate;
			var keyword = candidate.keyword;
			addComplementCandidateToRes(
				currentDirectory, innerState, originalCandidate,
				keyword, emphasize(originalCandidate, keyword), res
			);
		}
	}
}
function addSortedCandidates(res){
	var sortedCandidates = complementSortManager.getSortedCandidates();
	//add drives
	addCandidatesOfEachState(res, "drive", sortedCandidates);
	//add folders
	addCandidatesOfEachState(res, "folder", sortedCandidates);
	//add files
	addCandidatesOfEachState(res, "file", sortedCandidates);
}

function checkProgress(res, currentDirectory){
	if(searchProgressManager.isSearchCompleted() == true && complementProgressManager.isComplementCompleted() == true){
		if(searchProgressManager.isPathAdded() == false && complementProgressManager.isComplementAdded() == false){
			addNotFoundCommand(res, currentDirectory);
		}else{
			addSortedCandidates(res);
		}
	}
}

exports.searchCandidates = searchCandidates;<|endoftext|>


<commit_before>export default class NormalDistribution {
  /**
   * The constructor, assumes a standardized normal distribution if
   *   there are no parameters given
   * @param {number} [mean=0] - the mean average
   * @param {number} [standardDeviation=1] - the standard deviation
   */
  constructor(mean = 0, standardDeviation = 1) {
    this._mean = mean;
    this._standardDeviation = standardDeviation;
  }

  /**
   * Getter for the mean average of the distribution
   * @type {number}
   */
  get mean() {
    return this._mean;
  }

  /**
   * Getter for the standard deviation of the distribution
   * @type {number}
   */
  get standardDeviation() {
    return this._standardDeviation;
  }

  /**
   * Setter for the mean average of the distribution
   * @type {number}
   */
  set mean(mean) {
    this._mean = mean;
  }

  /**
   * Setter for the standard deviation of the distribution
   * @type {number}
   */
  set standardDeviation(standardDeviation) {
    this._standardDeviation = standardDeviation;
  }

  /**
   * @param {number} value - the number to convert to a z-score
   * @return {number} the z-score of the value
   */
  zScore(value) {
    return (value - this.mean) / this.standardDeviation;
  }

  /**
   * Return the probability of finding x in the distribution
   * @param {number} value - the value to evaluate
   * @return {number} the probability
   */
  pdf(value) {
    const dividend = Math.pow(
      Math.E,
      -Math.pow(value - this.mean, 2) /
        (2 * Math.pow(this.standardDeviation, 2))
    );
    const divisor = this.standardDeviation * Math.sqrt(2 * Math.PI);
    return dividend / divisor;
  }

  /**
   * Return the cumalitive probability for everything left of the value
   * @param {number} value - the value to evaluate
   * @return {number} the cumulative total
   */
  cdf(value) {
    let zScore = this.zScore(value);
    zScore = this._round(zScore, 2);

    if (zScore === 0) {
      return 0.5;
    } else if (zScore <= -3.5) {
      return 0;
    } else if (zScore >= 3.5) {
      return 1;
    }

    const zTable = NormalDistribution.zTable;
    const absZScore = Math.abs(zScore);
    const zRow = Math.floor(absZScore * 10) / 10;
    const zCol = this._round((Math.round(absZScore * 100) % 10) / 100, 2);
    const zColIndex = zTable.z.indexOf(zCol);
    const absPercentile = zTable[zRow.toString()][zColIndex];

    return zScore < 0 ? 1 - absPercentile : absPercentile;
  }

  /**
   * Return the probability of a value in the distribution being
   *   between two values
   * @param {number} value1 - the first boundary
   * @param {number} value2 - the second boundary
   * @return {number} the probability
   */
  probabilityBetween(value1, value2) {
    return Math.abs(this.cdf(value1) - this.cdf(value2));
  }

  /**
   * Returns an object representing the standardized z-table
   * @return {Object} the zTable
   */

  // prettier-ignore
  static get zTable() {
    return {
      "z"  :  [0     , 0.01  , 0.02  , 0.03  , 0.04,   0.05  , 0.06  , 0.07  , 0.08  , 0.09  ],
      "0"  :  [0.5000, 0.5040, 0.5080, 0.5120, 0.5160, 0.5199, 0.5239, 0.5279, 0.5319, 0.5359],
      "0.1":  [0.5398, 0.5438, 0.5478, 0.5517, 0.5557, 0.5596, 0.5636, 0.5675, 0.5714, 0.5753],
      "0.2":  [0.5793, 0.5832, 0.5871, 0.5910, 0.5948, 0.5987, 0.6026, 0.6064, 0.6103, 0.6141],
      "0.3":  [0.6179, 0.6217, 0.6255, 0.6293, 0.6331, 0.6368, 0.6406, 0.6443, 0.6480, 0.6517],
      "0.4":  [0.6554, 0.6591, 0.6628, 0.6664, 0.6700, 0.6736, 0.6772, 0.6808, 0.6844, 0.6879],
      "0.5":  [0.6915, 0.6950, 0.6985, 0.7019, 0.7054, 0.7088, 0.7123, 0.7157, 0.7190, 0.7224],
      "0.6":  [0.7257, 0.7291, 0.7324, 0.7357, 0.7389, 0.7422, 0.7454, 0.7486, 0.7517, 0.7549],
      "0.7":  [0.7580, 0.7611, 0.7642, 0.7673, 0.7704, 0.7734, 0.7764, 0.7794, 0.7823, 0.7852],
      "0.8":  [0.7881, 0.7910, 0.7939, 0.7967, 0.7995, 0.8023, 0.8051, 0.8078, 0.8106, 0.8133],
      "0.9":  [0.8159, 0.8186, 0.8212, 0.8238, 0.8264, 0.8289, 0.8315, 0.8340, 0.8365, 0.8389],
      "1"  :  [0.8413, 0.8438, 0.8461, 0.8485, 0.8508, 0.8531, 0.8554, 0.8577, 0.8599, 0.8621],
      "1.1":  [0.8643, 0.8665, 0.8686, 0.8708, 0.8729, 0.8749, 0.8770, 0.8790, 0.8810, 0.8830],
      "1.2":  [0.8849, 0.8869, 0.8888, 0.8907, 0.8925, 0.8944, 0.8962, 0.8980, 0.8997, 0.9015],
      "1.3":  [0.9032, 0.9049, 0.9066, 0.9082, 0.9099, 0.9115, 0.9131, 0.9147, 0.9162, 0.9177],
      "1.4":  [0.9192, 0.9207, 0.9222, 0.9236, 0.9251, 0.9265, 0.9279, 0.9292, 0.9306, 0.9319],
      "1.5":  [0.9332, 0.9345, 0.9357, 0.9370, 0.9382, 0.9394, 0.9406, 0.9418, 0.9429, 0.9441],
      "1.6":  [0.9452, 0.9463, 0.9474, 0.9484, 0.9495, 0.9505, 0.9515, 0.9525, 0.9535, 0.9545],
      "1.7":  [0.9554, 0.9564, 0.9573, 0.9582, 0.9591, 0.9599, 0.9608, 0.9616, 0.9625, 0.9633],
      "1.8":  [0.9641, 0.9649, 0.9656, 0.9664, 0.9671, 0.9678, 0.9686, 0.9693, 0.9699, 0.9706],
      "1.9":  [0.9713, 0.9719, 0.9726, 0.9732, 0.9738, 0.9744, 0.9750, 0.9756, 0.9761, 0.9767],
      "2"  :  [0.9772, 0.9778, 0.9783, 0.9788, 0.9793, 0.9798, 0.9803, 0.9808, 0.9812, 0.9817],
      "2.1":  [0.9821, 0.9826, 0.9830, 0.9834, 0.9838, 0.9842, 0.9846, 0.9850, 0.9854, 0.9857],
      "2.2":  [0.9861, 0.9864, 0.9868, 0.9871, 0.9875, 0.9878, 0.9881, 0.9884, 0.9887, 0.9890],
      "2.3":  [0.9893, 0.9896, 0.9898, 0.9901, 0.9904, 0.9906, 0.9909, 0.9911, 0.9913, 0.9916],
      "2.4":  [0.9918, 0.9920, 0.9922, 0.9925, 0.9927, 0.9929, 0.9931, 0.9932, 0.9934, 0.9936],
      "2.5":  [0.9938, 0.9940, 0.9941, 0.9943, 0.9945, 0.9946, 0.9948, 0.9949, 0.9951, 0.9952],
      "2.6":  [0.9953, 0.9955, 0.9956, 0.9957, 0.9959, 0.9960, 0.9961, 0.9962, 0.9963, 0.9964],
      "2.7":  [0.9965, 0.9966, 0.9967, 0.9968, 0.9969, 0.9970, 0.9971, 0.9972, 0.9973, 0.9974],
      "2.8":  [0.9974, 0.9975, 0.9976, 0.9977, 0.9977, 0.9978, 0.9979, 0.9979, 0.9980, 0.9981],
      "2.9":  [0.9981, 0.9982, 0.9982, 0.9983, 0.9984, 0.9984, 0.9985, 0.9985, 0.9986, 0.9986],
      "3"  :  [0.9987, 0.9987, 0.9987, 0.9988, 0.9988, 0.9989, 0.9989, 0.9989, 0.9990, 0.9990],
      "3.1":  [0.9990, 0.9991, 0.9991, 0.9991, 0.9992, 0.9992, 0.9992, 0.9992, 0.9993, 0.9993],
      "3.2":  [0.9993, 0.9993, 0.9994, 0.9994, 0.9994, 0.9994, 0.9994, 0.9995, 0.9995, 0.9995],
      "3.3":  [0.9995, 0.9995, 0.9995, 0.9996, 0.9996, 0.9996, 0.9996, 0.9996, 0.9996, 0.9997],
      "3.4":  [0.9997, 0.9997, 0.9997, 0.9997, 0.9997, 0.9997, 0.9997, 0.9997, 0.9997, 0.9998]
    }
  }

  /**
   * Rounds a value to a specified amount of decimal places
   * @param {number} value - the value to be rounded
   * @param {number} decimalPlaces - the amount of decimal places to round to
   * @return {number} the rounded number
   */
  _round(value, decimalPlaces) {
    const factor = Math.pow(10, decimalPlaces);
    return Math.round(value * factor) / factor;
  }
}
<commit_msg>Tidy and remove redundant getters / setters<commit_after>/**
 * Rounds a value to a specified amount of decimal places
 * @param {number} value - the value to be rounded
 * @param {number} decimalPlaces - the amount of decimal places to round to
 * @return {number} the rounded number
 */

const round = (value, decimalPlaces) => {
  const factor = Math.pow(10, decimalPlaces);
  return Math.round(value * factor) / factor;
};

export default class NormalDistribution {
  /**
   * The constructor, assumes a standardized normal distribution if
   *   there are no parameters given
   * @param {number} [mean=0] - the mean average
   * @param {number} [standardDeviation=1] - the standard deviation
   */
  constructor(mean = 0, standardDeviation = 1) {
    this.mean = mean;
    this.standardDeviation = standardDeviation;
  }

  /**
   * @param {number} value - the number to convert to a z-score
   * @return {number} the z-score of the value
   */
  zScore(value) {
    return (value - this.mean) / this.standardDeviation;
  }

  /**
   * Return the probability of finding x in the distribution
   * @param {number} value - the value to evaluate
   * @return {number} the probability
   */
  pdf(value) {
    const dividend =
      Math.E ** -((value - this.mean) ** 2 / (2 * this.standardDeviation ** 2));
    const divisor = this.standardDeviation * Math.sqrt(2 * Math.PI);
    return dividend / divisor;
  }

  /**
   * Return the cumalitive probability for everything left of the value
   * @param {number} value - the value to evaluate
   * @return {number} the cumulative total
   */
  cdf(value) {
    let zScore = this.zScore(value);
    zScore = round(zScore, 2);

    if (zScore === 0) {
      return 0.5;
    } else if (zScore <= -3.5) {
      return 0;
    } else if (zScore >= 3.5) {
      return 1;
    }

    const zTable = NormalDistribution.zTable;
    const absZScore = Math.abs(zScore);
    const zRow = Math.floor(absZScore * 10) / 10;
    const zCol = round((Math.round(absZScore * 100) % 10) / 100, 2);
    const zColIndex = zTable.z.indexOf(zCol);
    const absPercentile = zTable[zRow.toString()][zColIndex];

    return zScore < 0 ? 1 - absPercentile : absPercentile;
  }

  /**
   * Return the probability of a value in the distribution being
   *   between two values
   * @param {number} value1 - the first boundary
   * @param {number} value2 - the second boundary
   * @return {number} the probability
   */
  probabilityBetween(value1, value2) {
    return Math.abs(this.cdf(value1) - this.cdf(value2));
  }

  /**
   * Returns an object representing the standardized z-table
   * @return {Object} the zTable
   */

  // prettier-ignore
  static get zTable() {
    return {
      "z"  :  [0     , 0.01  , 0.02  , 0.03  , 0.04,   0.05  , 0.06  , 0.07  , 0.08  , 0.09  ],
      "0"  :  [0.5000, 0.5040, 0.5080, 0.5120, 0.5160, 0.5199, 0.5239, 0.5279, 0.5319, 0.5359],
      "0.1":  [0.5398, 0.5438, 0.5478, 0.5517, 0.5557, 0.5596, 0.5636, 0.5675, 0.5714, 0.5753],
      "0.2":  [0.5793, 0.5832, 0.5871, 0.5910, 0.5948, 0.5987, 0.6026, 0.6064, 0.6103, 0.6141],
      "0.3":  [0.6179, 0.6217, 0.6255, 0.6293, 0.6331, 0.6368, 0.6406, 0.6443, 0.6480, 0.6517],
      "0.4":  [0.6554, 0.6591, 0.6628, 0.6664, 0.6700, 0.6736, 0.6772, 0.6808, 0.6844, 0.6879],
      "0.5":  [0.6915, 0.6950, 0.6985, 0.7019, 0.7054, 0.7088, 0.7123, 0.7157, 0.7190, 0.7224],
      "0.6":  [0.7257, 0.7291, 0.7324, 0.7357, 0.7389, 0.7422, 0.7454, 0.7486, 0.7517, 0.7549],
      "0.7":  [0.7580, 0.7611, 0.7642, 0.7673, 0.7704, 0.7734, 0.7764, 0.7794, 0.7823, 0.7852],
      "0.8":  [0.7881, 0.7910, 0.7939, 0.7967, 0.7995, 0.8023, 0.8051, 0.8078, 0.8106, 0.8133],
      "0.9":  [0.8159, 0.8186, 0.8212, 0.8238, 0.8264, 0.8289, 0.8315, 0.8340, 0.8365, 0.8389],
      "1"  :  [0.8413, 0.8438, 0.8461, 0.8485, 0.8508, 0.8531, 0.8554, 0.8577, 0.8599, 0.8621],
      "1.1":  [0.8643, 0.8665, 0.8686, 0.8708, 0.8729, 0.8749, 0.8770, 0.8790, 0.8810, 0.8830],
      "1.2":  [0.8849, 0.8869, 0.8888, 0.8907, 0.8925, 0.8944, 0.8962, 0.8980, 0.8997, 0.9015],
      "1.3":  [0.9032, 0.9049, 0.9066, 0.9082, 0.9099, 0.9115, 0.9131, 0.9147, 0.9162, 0.9177],
      "1.4":  [0.9192, 0.9207, 0.9222, 0.9236, 0.9251, 0.9265, 0.9279, 0.9292, 0.9306, 0.9319],
      "1.5":  [0.9332, 0.9345, 0.9357, 0.9370, 0.9382, 0.9394, 0.9406, 0.9418, 0.9429, 0.9441],
      "1.6":  [0.9452, 0.9463, 0.9474, 0.9484, 0.9495, 0.9505, 0.9515, 0.9525, 0.9535, 0.9545],
      "1.7":  [0.9554, 0.9564, 0.9573, 0.9582, 0.9591, 0.9599, 0.9608, 0.9616, 0.9625, 0.9633],
      "1.8":  [0.9641, 0.9649, 0.9656, 0.9664, 0.9671, 0.9678, 0.9686, 0.9693, 0.9699, 0.9706],
      "1.9":  [0.9713, 0.9719, 0.9726, 0.9732, 0.9738, 0.9744, 0.9750, 0.9756, 0.9761, 0.9767],
      "2"  :  [0.9772, 0.9778, 0.9783, 0.9788, 0.9793, 0.9798, 0.9803, 0.9808, 0.9812, 0.9817],
      "2.1":  [0.9821, 0.9826, 0.9830, 0.9834, 0.9838, 0.9842, 0.9846, 0.9850, 0.9854, 0.9857],
      "2.2":  [0.9861, 0.9864, 0.9868, 0.9871, 0.9875, 0.9878, 0.9881, 0.9884, 0.9887, 0.9890],
      "2.3":  [0.9893, 0.9896, 0.9898, 0.9901, 0.9904, 0.9906, 0.9909, 0.9911, 0.9913, 0.9916],
      "2.4":  [0.9918, 0.9920, 0.9922, 0.9925, 0.9927, 0.9929, 0.9931, 0.9932, 0.9934, 0.9936],
      "2.5":  [0.9938, 0.9940, 0.9941, 0.9943, 0.9945, 0.9946, 0.9948, 0.9949, 0.9951, 0.9952],
      "2.6":  [0.9953, 0.9955, 0.9956, 0.9957, 0.9959, 0.9960, 0.9961, 0.9962, 0.9963, 0.9964],
      "2.7":  [0.9965, 0.9966, 0.9967, 0.9968, 0.9969, 0.9970, 0.9971, 0.9972, 0.9973, 0.9974],
      "2.8":  [0.9974, 0.9975, 0.9976, 0.9977, 0.9977, 0.9978, 0.9979, 0.9979, 0.9980, 0.9981],
      "2.9":  [0.9981, 0.9982, 0.9982, 0.9983, 0.9984, 0.9984, 0.9985, 0.9985, 0.9986, 0.9986],
      "3"  :  [0.9987, 0.9987, 0.9987, 0.9988, 0.9988, 0.9989, 0.9989, 0.9989, 0.9990, 0.9990],
      "3.1":  [0.9990, 0.9991, 0.9991, 0.9991, 0.9992, 0.9992, 0.9992, 0.9992, 0.9993, 0.9993],
      "3.2":  [0.9993, 0.9993, 0.9994, 0.9994, 0.9994, 0.9994, 0.9994, 0.9995, 0.9995, 0.9995],
      "3.3":  [0.9995, 0.9995, 0.9995, 0.9996, 0.9996, 0.9996, 0.9996, 0.9996, 0.9996, 0.9997],
      "3.4":  [0.9997, 0.9997, 0.9997, 0.9997, 0.9997, 0.9997, 0.9997, 0.9997, 0.9997, 0.9998]
    }
  }
}
<|endoftext|>


<commit_before>chrome.webNavigation.onBeforeNavigate.addListener(function(request) {
  var regex = /.*:\/.*(\/|\.)(m|mobile)\..*\/.*/i;

  if(request.url.match(regex)) {
    console.log(request.url);
    if (shouldRedirect(request.url)) {
      var newUrl = request.url.replace(/(m|mobile)\./i, "");
      chrome.tabs.query({'active': true}, function(tabs) {
        chrome.tabs.update(request.tabId, {url:newUrl});
      });
    }
  }
});

var notificationOptions = {
    type:'basic',
    title:'Mobile Redirect',
    message:'Redirecting to non-mobile version of this site.',
    iconUrl:'icon.png',
    buttons : [
                { title:'Add exception' } ,
                { title:'Ignore' }
              ]
}

var shouldRedirect = function (urlString) {
  var storageKey = getStorageString(urlString);
  var savedValue = chrome.storage.sync.get(storageKey, function(items) {
    //TODO retrieve the value from the items object
    console.log(items);
  });

  if (savedValue == "false") {
    return false;
  }
  if (savedValue == null) {
    var obj = {};
    obj[storageKey] = "true";
    // TODO: Add callback where user has option to disable it for this url
    chrome.notifications.create('notificationId', notificationOptions, function(id) {});
    if (false) {
      obj[storageKey] = "false";
    }
    chrome.storage.sync.set(obj);
  }
  return true;
}

var getStorageString = function (key) {
  // Domain name, e.g. "m.wikipedia.org"
  var domain = key.replace(/.*:\/\//i, "").replace(/\/.*/i,"");
  return "uk.co.uitwaaien.mobileredirect." + domain;
}
<commit_msg>Implemented feature to select if we should redirect or not<commit_after>chrome.webNavigation.onBeforeNavigate.addListener(function(request) {
  var regex = /.*:\/.*(\/|\.)(m|mobile)\..*\/.*/i;

  if(request.url.match(regex)) {
    console.log(request.url);
    checkRedirect(request);
  }
});

var notificationOptions = {
    type:'basic',
    title:'Mobile Redirect',
    message:'Redirecting to non-mobile version of this site.',
    iconUrl:'icon.png',
    buttons : [
                { title:'Never redirect'},
                { title:'Always redirect'}
              ]
}

var checkRedirect = function (request) {
  var storageKey = getStorageString(request.url);
  var value = null;
  chrome.storage.sync.get(storageKey, function(items) {
    value = items[storageKey];
    if (value == null) {
      redirect(request);
      chrome.notifications.create('notificationId', notificationOptions, function(id) {});
      chrome.notifications.onButtonClicked.addListener(function(notificationId, buttonIndex) {
         if (notificationId == 'notificationId') {
           var obj = {};
           if (buttonIndex == 0) {
              obj[storageKey] = "false";
           } else {
              obj[storageKey] = "true";
           }
           chrome.storage.sync.set(obj);
         }
      });
    } else if (value == "true") {
       redirect(request);
    }
  });
  return true;
}

var redirect = function(request) {
    var newUrl = request.url.replace(/(m|mobile)\./i, "");
      chrome.tabs.query({'active': true}, function(tabs) {
        chrome.tabs.update(request.tabId, {url:newUrl});
      });
}

var getStorageString = function (key) {
  // Domain name, e.g. "m.wikipedia.org"
  var domain = key.replace(/.*:\/\//i, "").replace(/\/.*/i,"");
  return "uk.co.uitwaaien.mobileredirect." + domain;
}
<|endoftext|>


<commit_before>/* eslint-disable quote-props, no-magic-numbers */
import Ember from 'ember';

const {
	Component,
	computed,
	inject: { service },
	observer,
	on,
	run: { later },
	String: { camelize }
} = Ember;

export const ANIMATION_DELAY = 400;

/**
 * Component to wrap modal objects.
 *
 * @extends Ember.Component
 */
export default Component.extend({

	/**
	 * Modal service inject.
	 *
	 * @property modal
	 * @type Object
	 */
	modal: service('modal'),

	/**
	 * HTML class name bindings.
	 *
	 * @property classNameBindings
	 * @type Array
	 */
	classNameBindings: ['model.options.hasOverlay:modal-overlay:modal-view'],

	/**
	 * HTML attributes bindings.
	 *
	 * @property attributeBindings
	 * @type Array
	 */
	attributeBindings: ['data-modal-show', 'role', 'data-id'],

	/**
	 * HTML role.
	 *
	 * @property role
	 * @type String
	 */
	role: 'dialog',

	/**
	 * Modal is visible/hidden.
	 *
	 * @property visible
	 * @type Boolean
	 */
	visible: false,

	/**
	 * `data-id` attribute of wrapper element
	 *
	 * @property data-id
	 * @type {String}
	 */
	'data-id': null,

	/**
	 * Modal is visible/hidden. This property is read from CSS.
	 *
	 * @property data-modal-show
	 * @type Boolean
	 */
	'data-modal-show': computed('visible', function() {
		return String(this.get('visible'));
	}),

	/**
	 * Animation appearance delay.
	 *
	 * @property animationDelay
	 * @type Number
	 */
	animationDelay: 25,

	/**
	 * On did insert element, scroll to top and set element as visible.
	 *
	 * @method didInsertElement
	 */
	didInsertElement() {
		this._super();

		const animationDelay = this.get('animationDelay');

		later(() => {
			if (!this.isDestroyed) {
				this.set('visible', true);
			}
		}, animationDelay);

		this.set('data-id', camelize(this.get('model.fullname')));
	},

	/**
	 * When the promise has been settled, close the view.
	 *
	 * @method hasBeenSettled
	 * @private
	 */
	_hasBeenSettled: on('init', function() {
		this.get('model.promise').always(() => {
			this._close();
		});
	}),

	/**
	 * Observes the visible property to toggle actions.
	 *
	 * @method visibleDidChange
	 */
	visibleDidChange: observer('visible', function() {
		const visible = this.get('visible');

		if (visible) {
			this.didOpen();
		} else {
			this.willClose();
		}
	}),

	/**
	 * Resolve current promise and close modal.
	 *
	 * @method resolve
	 */
	resolve() {
		const deferred = this.get('model.deferred');

		deferred.resolveWith(this, arguments);
	},

	/**
	 * Reject current promise and close modal.
	 *
	 * @method reject
	 */
	reject() {
		const deferred = this.get('model.deferred');

		deferred.rejectWith(this, arguments);
	},

	/**
	 * Open action.
	 *
	 * @method open
	 * @return Boolean
	 */
	didOpen() {},

	/**
	 * Close action.
	 *
	 * @method close
	 * @return Boolean
	 */
	willClose() {},

	/**
	 * Set modal as not visible and remove modal from array later.
	 *
	 * @method _close
	 * @private
	 */
	_close() {
		// Close modal.
		this.set('visible', false);

		// Remove modal from array.
		later(this, this._remove, ANIMATION_DELAY);
	},

	/**
	 * Remove itself from service.
	 *
	 * @method _remove
	 * @private
	 */
	_remove() {
		this.get('modal.content').removeObject(this.get('model'));
	},

	actions: {

		/**
		 * Action to resolve the underlying modal promise directly from the,
		 * template, using the passed arguments as resolution values
		 *
		 * @method resolve
		 */
		resolve() {
			this.resolve(...arguments);
		},

		/**
		 * Action to reject the underlying modal promise directly from the,
		 * template, using the passed arguments as rejection values
		 *
		 * @method reject
		 */
		reject() {
			this.reject(...arguments);
		}
	}
});
<commit_msg>Removed trailing commas from documentation<commit_after>/* eslint-disable quote-props, no-magic-numbers */
import Ember from 'ember';

const {
	Component,
	computed,
	inject: { service },
	observer,
	on,
	run: { later },
	String: { camelize }
} = Ember;

export const ANIMATION_DELAY = 400;

/**
 * Component to wrap modal objects.
 *
 * @extends Ember.Component
 */
export default Component.extend({

	/**
	 * Modal service inject.
	 *
	 * @property modal
	 * @type Object
	 */
	modal: service('modal'),

	/**
	 * HTML class name bindings.
	 *
	 * @property classNameBindings
	 * @type Array
	 */
	classNameBindings: ['model.options.hasOverlay:modal-overlay:modal-view'],

	/**
	 * HTML attributes bindings.
	 *
	 * @property attributeBindings
	 * @type Array
	 */
	attributeBindings: ['data-modal-show', 'role', 'data-id'],

	/**
	 * HTML role.
	 *
	 * @property role
	 * @type String
	 */
	role: 'dialog',

	/**
	 * Modal is visible/hidden.
	 *
	 * @property visible
	 * @type Boolean
	 */
	visible: false,

	/**
	 * `data-id` attribute of wrapper element
	 *
	 * @property data-id
	 * @type {String}
	 */
	'data-id': null,

	/**
	 * Modal is visible/hidden. This property is read from CSS.
	 *
	 * @property data-modal-show
	 * @type Boolean
	 */
	'data-modal-show': computed('visible', function() {
		return String(this.get('visible'));
	}),

	/**
	 * Animation appearance delay.
	 *
	 * @property animationDelay
	 * @type Number
	 */
	animationDelay: 25,

	/**
	 * On did insert element, scroll to top and set element as visible.
	 *
	 * @method didInsertElement
	 */
	didInsertElement() {
		this._super();

		const animationDelay = this.get('animationDelay');

		later(() => {
			if (!this.isDestroyed) {
				this.set('visible', true);
			}
		}, animationDelay);

		this.set('data-id', camelize(this.get('model.fullname')));
	},

	/**
	 * When the promise has been settled, close the view.
	 *
	 * @method hasBeenSettled
	 * @private
	 */
	_hasBeenSettled: on('init', function() {
		this.get('model.promise').always(() => {
			this._close();
		});
	}),

	/**
	 * Observes the visible property to toggle actions.
	 *
	 * @method visibleDidChange
	 */
	visibleDidChange: observer('visible', function() {
		const visible = this.get('visible');

		if (visible) {
			this.didOpen();
		} else {
			this.willClose();
		}
	}),

	/**
	 * Resolve current promise and close modal.
	 *
	 * @method resolve
	 */
	resolve() {
		const deferred = this.get('model.deferred');

		deferred.resolveWith(this, arguments);
	},

	/**
	 * Reject current promise and close modal.
	 *
	 * @method reject
	 */
	reject() {
		const deferred = this.get('model.deferred');

		deferred.rejectWith(this, arguments);
	},

	/**
	 * Open action.
	 *
	 * @method open
	 * @return Boolean
	 */
	didOpen() {},

	/**
	 * Close action.
	 *
	 * @method close
	 * @return Boolean
	 */
	willClose() {},

	/**
	 * Set modal as not visible and remove modal from array later.
	 *
	 * @method _close
	 * @private
	 */
	_close() {
		// Close modal.
		this.set('visible', false);

		// Remove modal from array.
		later(this, this._remove, ANIMATION_DELAY);
	},

	/**
	 * Remove itself from service.
	 *
	 * @method _remove
	 * @private
	 */
	_remove() {
		this.get('modal.content').removeObject(this.get('model'));
	},

	actions: {

		/**
		 * Action to resolve the underlying modal promise directly from the
		 * template, using the passed arguments as resolution values
		 *
		 * @method resolve
		 */
		resolve() {
			this.resolve(...arguments);
		},

		/**
		 * Action to reject the underlying modal promise directly from the
		 * template, using the passed arguments as rejection values
		 *
		 * @method reject
		 */
		reject() {
			this.reject(...arguments);
		}
	}
});
<|endoftext|>


<commit_before>import { merge } from './updates.js';
import * as symbols from './symbols.js';
import { deepContains } from './utilities.js';

// Symbols for private data members on an element.
const closeListenerKey = Symbol('closeListener');

/**
 * This mixin makes an overlay behave like a popup by dismissing it when certain
 * user interactions occur.
 *
 * This mixin expects the component to provide:
 *
 * * An open/close API compatible with `OpenCloseMixin`.
 *
 * The mixin provides these features to the component:
 *
 * * Event handlers that close the element presses the Esc key, moves the focus
 *   outside the element, scrolls the document, resizes the document, or
 *   switches focus away from the document.
 * * A default ARIA role of `alert`.
 *
 * For modal overlays, use `DialogModalityMixin` instead. See the documentation
 * of that mixin for a comparison of modality behaviors.
 *
 * @module PopupModalityMixin
 */
export default function PopupModalityMixin(Base) {

  // The class prototype added by the mixin.
  class PopupModality extends Base {

    constructor() {
      // @ts-ignore
      super();
      this.addEventListener('blur', async (event) => {
        if (!ownEvent(this, event)) {
          this[symbols.raiseChangeEvents] = true;
          await this.close();
          this[symbols.raiseChangeEvents] = false;
        }
      });
      this[closeListenerKey] = async (event) => {
        if (!ownEvent(this, event)) {
          this[symbols.raiseChangeEvents] = true;
          await this.close();
          this[symbols.raiseChangeEvents] = false;
        }
      };
    }

    componentDidUpdate(previousState) {
      if (super.componentDidUpdate) { super.componentDidUpdate(previousState); }
      if (!this.closed) {
        // Wait before wiring up events – if the popup was opened because the
        // user clicked something, that opening click event may still be
        // bubbling up, and we only want to start listening after it's been
        // processed. Alternatively, if the popup caused the page to scroll, we
        // don't want to immediately close because the page scrolled (only if
        // the user scrolls).
        const callback = 'requestIdleCallback' in window ?
          window['requestIdleCallback'] :
          setTimeout;
        callback(() => {
          // It's conceivable the popup was closed before the timeout completed,
          // so double-check that it's still opened before listening to events.
          if (!this.closed) {
            addEventListeners(this);
          }
        });
      } else {
        removeEventListeners(this);
      }
    }

    get defaultState() {
      return Object.assign({}, super.defaultState, {
        role: 'alert'
      });
    }

    // Close on Esc key.
    [symbols.keydown](event) {
      let handled = false;

      switch (event.keyCode) {
        case 27: // Escape
          this.close();
          handled = true;
          break;
      }

      // Prefer mixin result if it's defined, otherwise use base result.
      return handled || (super.keydown && super.keydown(event)) || false;
    }

    get updates() {
      const original = this.state.original;
      const role = original.attributes && original.attributes.role || this.state.role;
      return merge(super.updates, {
        attributes: {
          role
        }
      });
    }

  }

  return PopupModality;
}

function addEventListeners(element) {
  document.addEventListener('keydown', element[closeListenerKey]);
  window.addEventListener('blur', element[closeListenerKey]);
  window.addEventListener('resize', element[closeListenerKey]);
  window.addEventListener('scroll', element[closeListenerKey]);
}

// Return true if the event came from within the element or from the element
// itself; false otherwise.
function ownEvent(element, event) {
  const eventSource = event.composedPath()[0];
  return element === eventSource || deepContains(element, eventSource);
}

function removeEventListeners(element) {
  document.removeEventListener('keydown', element[closeListenerKey]);
  window.removeEventListener('blur', element[closeListenerKey]);
  window.removeEventListener('resize', element[closeListenerKey]);
  window.removeEventListener('scroll', element[closeListenerKey]);
}
<commit_msg>PopupModalityMixin closes on blur if the new focused element isn't inside the popup.<commit_after>import { deepContains, ownEvent } from './utilities.js';
import { merge } from './updates.js';
import * as symbols from './symbols.js';

const implicitCloseListenerKey = Symbol('implicitCloseListener');

/**
 * This mixin makes an overlay behave like a popup by dismissing it when certain
 * user interactions occur.
 *
 * This mixin expects the component to provide:
 *
 * * An open/close API compatible with `OpenCloseMixin`.
 *
 * The mixin provides these features to the component:
 *
 * * Event handlers that close the element presses the Esc key, moves the focus
 *   outside the element, scrolls the document, resizes the document, or
 *   switches focus away from the document.
 * * A default ARIA role of `alert`.
 *
 * For modal overlays, use `DialogModalityMixin` instead. See the documentation
 * of that mixin for a comparison of modality behaviors.
 *
 * @module PopupModalityMixin
 */
export default function PopupModalityMixin(Base) {

  // The class prototype added by the mixin.
  class PopupModality extends Base {

    constructor() {
      // @ts-ignore
      super();

      // If we lose focus, and the new focus isn't inside us, then close.
      this.addEventListener('blur', async (event) => {
        // What has the focus now?
        const newFocusedElement = event.relatedTarget || document.activeElement;
        /** @type {any} */
        const cast = this;
        if (!deepContains(cast, newFocusedElement)) {
          this[symbols.raiseChangeEvents] = true;
          await this.close();
          this[symbols.raiseChangeEvents] = false;
        }
      });

      // Close handlers for window events.
      this[implicitCloseListenerKey] = async (event) => {
        /** @type {any} */
        const cast = this;
        if (!ownEvent(cast, event)) {
          this[symbols.raiseChangeEvents] = true;
          await this.close();
          this[symbols.raiseChangeEvents] = false;
        }
      };
    }

    componentDidUpdate(previousState) {
      if (super.componentDidUpdate) { super.componentDidUpdate(previousState); }
      if (!this.closed) {
        // Wait before wiring up events – if the popup was opened because the
        // user clicked something, that opening click event may still be
        // bubbling up, and we only want to start listening after it's been
        // processed. Alternatively, if the popup caused the page to scroll, we
        // don't want to immediately close because the page scrolled (only if
        // the user scrolls).
        const callback = 'requestIdleCallback' in window ?
          window['requestIdleCallback'] :
          setTimeout;
        callback(() => {
          // It's conceivable the popup was closed before the timeout completed,
          // so double-check that it's still opened before listening to events.
          if (!this.closed) {
            addEventListeners(this);
          }
        });
      } else {
        removeEventListeners(this);
      }
    }

    get defaultState() {
      return Object.assign({}, super.defaultState, {
        role: 'alert'
      });
    }

    // Close on Esc key.
    [symbols.keydown](event) {
      let handled = false;

      switch (event.keyCode) {
        case 27: // Escape
          this.close();
          handled = true;
          break;
      }

      // Prefer mixin result if it's defined, otherwise use base result.
      return handled || (super.keydown && super.keydown(event)) || false;
    }

    get updates() {
      const original = this.state.original;
      const role = original.attributes && original.attributes.role || this.state.role;
      return merge(super.updates, {
        attributes: {
          role
        }
      });
    }

  }

  return PopupModality;
}

function addEventListeners(element) {
  // Window blur event tracks loss of focus of *window*, not just element.
  window.addEventListener('blur', element[implicitCloseListenerKey]);
  window.addEventListener('resize', element[implicitCloseListenerKey]);
  window.addEventListener('scroll', element[implicitCloseListenerKey]);
}

function removeEventListeners(element) {
  window.removeEventListener('blur', element[implicitCloseListenerKey]);
  window.removeEventListener('resize', element[implicitCloseListenerKey]);
  window.removeEventListener('scroll', element[implicitCloseListenerKey]);
}
<|endoftext|>


<commit_before>/* global hoodie */
import Ember from 'ember';

function wrapHoodiePromise(promise) {
    return new Ember.RSVP.Promise(function (resolve, reject) {
        promise.then(resolve, reject);
    });
}

export
default Ember.Object.extend({
    hasValidSession: false,

    initializeListeners: function () {
        Ember.run.next(this, function () {
            this._setSession();
        });

        Ember.run.later(this, function () {
            this._setSession();
        }, 10);

        var auth = this;

        hoodie.account.on('authenticated signin signup', function (user) {
            auth.set('hasValidSession', true);
            auth.set('user', user);
        });

        hoodie.account.on('unauthenticated signout', function (user) {
            auth.set('hasValidSession', false);
            auth.set('user', user);
        });
    }.on('init'),

    _setSession: function () {
        this.set('hasValidSession', hoodie.account.hasValidSession());
    },

    signIn: function (username, password) {
        return wrapHoodiePromise(hoodie.account.signIn(username, password));
    },

    signUp: function (username, password) {
        return wrapHoodiePromise(hoodie.account.signUp(username, password));
    },

    signOut: function (options) {
        return wrapHoodiePromise(hoodie.account.signOut(options));
    }
});<commit_msg>rewritten initializing sessiondata. now without next or later - running<commit_after>/* global hoodie */
import Ember from 'ember';

function wrapHoodiePromise(promise) {
    return new Ember.RSVP.Promise(function (resolve, reject) {
        promise.then(resolve, reject);
    });
}

export
default Ember.Object.extend({
    hasValidSession: false,

    initializeListeners: function () {
        var auth = this;

        hoodie.account.on('authenticated signin signup', function (user) {
            auth.updateSession();
        });

        hoodie.account.on('unauthenticated signout', function (user) {
            auth.updateSession();
        });

        this.updateSession();
    }.on('init'),

    updateSession: function () {
        var user;

        if (hoodie.account.hasAccount()) {
            user = {
                email: hoodie.account.username
            }
        }

        this.set('hasValidSession', hoodie.account.hasAccount());
        this.set('user', user);
    },

    signIn: function (username, password) {
        return wrapHoodiePromise(hoodie.account.signIn(username, password));
    },

    signUp: function (username, password) {
        return wrapHoodiePromise(hoodie.account.signUp(username, password));
    },

    signOut: function (options) {
        return wrapHoodiePromise(hoodie.account.signOut(options));
    }
});<|endoftext|>