<commit_before>
const RG = require('../rg');

const System = {};
System.Base = require('./system.base');

/* System which handles time-based effects like poisoning etc. It also handles
 * expiration of effects. This is a special system because its updates are
 * scheduled by the scheduler to guarantee a specific execution interval. */
System.TimeEffects = function(compTypes) {
    System.Base.call(this, RG.SYS.TIME_EFFECTS, compTypes);
    this.compTypesAny = true;

    // Dispatch table used to call a handler function for each component
    const _dtable = {};
    let _expiredEffects = [];

    this.update = function() {
        for (const e in this.entities) {
            if (!e) {continue;}
            const ent = this.entities[e];

            // Process timed effects like poison etc.
            for (let i = 0; i < compTypes.length; i++) {
                if (compTypes[i] !== 'Expiration') {
                    if (ent.has(compTypes[i])) {
                        // Call dispatch table function
                        _dtable[compTypes[i]](ent);
                    }
                }
            }
            // Process expiration effects/duration of Expiration itself
            if (ent.has('Expiration')) {_decreaseDuration(ent);}
        }

        // Remove expired effects (mutates this.entities, so done outside for)
        // Removes Expiration, as well as comps like Poison/Stun/Disease etc.
        for (let j = 0; j < _expiredEffects.length; j++) {
            const compID = _expiredEffects[j][0];
            const entRem = _expiredEffects[j][1];
            entRem.remove(compID);
        }
        _expiredEffects = [];
    };

    /* Decreases the remaining duration in the component by one.*/
    const _decreaseDuration = ent => {
        const expirComps = ent.getList('Expiration');
        expirComps.forEach(tEff => {
            tEff.decrDuration();

            // Remove Expiration only if other components are removed
            if (!tEff.hasEffects()) {
                _expiredEffects.push([tEff.getID(), ent]);
            }
        });
    };

    /* Applies the poison effect to the entity.*/
    const _applyPoison = ent => {
        const poison = ent.get('Poison');

        if (ent.get('Health').isDead()) {
            _expiredEffects.push([poison.getID(), ent]);
            if (ent.has('Expiration')) {
                const te = ent.get('Expiration');
                if (te.hasEffect(poison)) {
                    te.removeEffect(poison);
                }
            }
        }
        else if (RG.isSuccess(poison.getProb())) {
            const poisonDmg = poison.rollDamage();
            const dmg = new RG.Component.Damage(poisonDmg, RG.DMG.POISON);
            dmg.setSource(poison.getSource());
            ent.add('Damage', dmg);
        }
    };

    /* Decreases duration in Fading comp, then remove the entity if duration is
     * 0. */
    const _applyFading = ent => {
        const fadingComp = ent.get('Fading');
        fadingComp.decrDuration();
        if (fadingComp.getDuration() <= 0) {
            if (RG.isActor(ent)) {
                const cell = ent.getCell();
                const level = ent.getLevel();
                if (level.removeActor(ent)) {
                    RG.POOL.emitEvent(RG.EVT_ACTOR_KILLED, {actor: ent});
                    const msg = `${ent.getName()} disappears.`;
                    RG.gameMsg({cell, msg});
                }
                else {
                    const json = JSON.stringify(ent);
                    RG.err('System.TimeEffects', '_applyFading',
                        `Could not remove actor from level: ${json}`);
                }
            }
            else {
                RG.err('System.TimeEffects', '_applyFading',
                    'Fading not handled for non-actors yet.');
            }
            ent.remove(fadingComp);
        }
    };

    const _applyHeat = ent => {
        if (ent.has('Coldness')) {
            const cell = ent.getCell();
            ent.removeAll('Coldness');
            const msg = `Thanks to heat, ${ent.getName()} stops shivering`;
            RG.gameMsg({cell, msg});
        }
        ent.removeAll('Heat');
    };

    // TODO
    const _applyColdness = ent => {
        if (ent.has('BodyTemp')) {
            const tempComp = ent.get('BodyTemp');
            tempComp.decr();
            if (tempComp.isFrozen()) {
                const dmgComp = new RG.Component.Damage(1, RG.DMG.COLD);
                ent.add(dmgComp);
            }
        }
    };

    _dtable.Poison = _applyPoison;
    _dtable.Fading = _applyFading;
    _dtable.Heat = _applyHeat;
    _dtable.Coldness = _applyColdness;

    /* Used for debug printing.*/
    this.printMatchedType = function(ent) {
        for (let i = 0; i < this.compTypes.length; i++) {
            if (ent.has(this.compTypes[i])) {
                RG.debug(this.compTypes[i], 'Has component');
            }
        }
    };

};
RG.extend2(System.TimeEffects, System.Base);

module.exports = System.TimeEffects;
<commit_msg>Removed string arg to add().<commit_after>
const RG = require('../rg');

const System = {};
System.Base = require('./system.base');

/* System which handles time-based effects like poisoning etc. It also handles
 * expiration of effects. This is a special system because its updates are
 * scheduled by the scheduler to guarantee a specific execution interval. */
System.TimeEffects = function(compTypes) {
    System.Base.call(this, RG.SYS.TIME_EFFECTS, compTypes);
    this.compTypesAny = true;

    // Dispatch table used to call a handler function for each component
    const _dtable = {};
    let _expiredEffects = [];

    this.update = function() {
        for (const e in this.entities) {
            if (!e) {continue;}
            const ent = this.entities[e];

            // Process timed effects like poison etc.
            for (let i = 0; i < compTypes.length; i++) {
                if (compTypes[i] !== 'Expiration') {
                    if (ent.has(compTypes[i])) {
                        // Call dispatch table function
                        _dtable[compTypes[i]](ent);
                    }
                }
            }
            // Process expiration effects/duration of Expiration itself
            if (ent.has('Expiration')) {_decreaseDuration(ent);}
        }

        // Remove expired effects (mutates this.entities, so done outside for)
        // Removes Expiration, as well as comps like Poison/Stun/Disease etc.
        for (let j = 0; j < _expiredEffects.length; j++) {
            const compID = _expiredEffects[j][0];
            const entRem = _expiredEffects[j][1];
            entRem.remove(compID);
        }
        _expiredEffects = [];
    };

    /* Decreases the remaining duration in the component by one.*/
    const _decreaseDuration = ent => {
        const expirComps = ent.getList('Expiration');
        expirComps.forEach(tEff => {
            tEff.decrDuration();

            // Remove Expiration only if other components are removed
            if (!tEff.hasEffects()) {
                _expiredEffects.push([tEff.getID(), ent]);
            }
        });
    };

    /* Applies the poison effect to the entity.*/
    const _applyPoison = ent => {
        const poison = ent.get('Poison');

        if (ent.get('Health').isDead()) {
            _expiredEffects.push([poison.getID(), ent]);
            if (ent.has('Expiration')) {
                const te = ent.get('Expiration');
                if (te.hasEffect(poison)) {
                    te.removeEffect(poison);
                }
            }
        }
        else if (RG.isSuccess(poison.getProb())) {
            const poisonDmg = poison.rollDamage();
            const dmgComp = new RG.Component.Damage(poisonDmg, RG.DMG.POISON);
            dmgComp.setSource(poison.getSource());
            ent.add(dmgComp);
        }
    };

    /* Decreases duration in Fading comp, then remove the entity if duration is
     * 0. */
    const _applyFading = ent => {
        const fadingComp = ent.get('Fading');
        fadingComp.decrDuration();
        if (fadingComp.getDuration() <= 0) {
            if (RG.isActor(ent)) {
                const cell = ent.getCell();
                const level = ent.getLevel();
                if (level.removeActor(ent)) {
                    RG.POOL.emitEvent(RG.EVT_ACTOR_KILLED, {actor: ent});
                    const msg = `${ent.getName()} disappears.`;
                    RG.gameMsg({cell, msg});
                }
                else {
                    const json = JSON.stringify(ent);
                    RG.err('System.TimeEffects', '_applyFading',
                        `Could not remove actor from level: ${json}`);
                }
            }
            else {
                RG.err('System.TimeEffects', '_applyFading',
                    'Fading not handled for non-actors yet.');
            }
            ent.remove(fadingComp);
        }
    };

    const _applyHeat = ent => {
        if (ent.has('Coldness')) {
            const cell = ent.getCell();
            ent.removeAll('Coldness');
            const msg = `Thanks to heat, ${ent.getName()} stops shivering`;
            RG.gameMsg({cell, msg});
        }
        ent.removeAll('Heat');
    };

    // TODO
    const _applyColdness = ent => {
        if (ent.has('BodyTemp')) {
            const tempComp = ent.get('BodyTemp');
            tempComp.decr();
            if (tempComp.isFrozen()) {
                const dmgComp = new RG.Component.Damage(1, RG.DMG.COLD);
                ent.add(dmgComp);
            }
        }
    };

    _dtable.Poison = _applyPoison;
    _dtable.Fading = _applyFading;
    _dtable.Heat = _applyHeat;
    _dtable.Coldness = _applyColdness;

    /* Used for debug printing.*/
    this.printMatchedType = function(ent) {
        for (let i = 0; i < this.compTypes.length; i++) {
            if (ent.has(this.compTypes[i])) {
                RG.debug(this.compTypes[i], 'Has component');
            }
        }
    };

};
RG.extend2(System.TimeEffects, System.Base);

module.exports = System.TimeEffects;
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright The Closure Library Authors.
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Defines for goog.labs.userAgent.
 */

goog.module('goog.labs.userAgent');

/**
 * @define {string} Optional runtime override for the USE_CLIENT_HINTS flag.
 * If this is set (for example, to 'foo.bar') then any value of USE_CLIENT_HINTS
 * will be overridden by `globalThis.foo.bar` if it is non-null.
 * This flag will be removed in December 2021.
 */
const USE_CLIENT_HINTS_OVERRIDE =
    goog.define('goog.labs.userAgent.USE_CLIENT_HINTS_OVERRIDE', '');

/**
 * @define {boolean} If true, use navigator.userAgentData
 * TODO(user) Flip flag in 2021/12.
 */
const USE_CLIENT_HINTS =
    goog.define('goog.labs.userAgent.USE_CLIENT_HINTS', false);

// TODO(user): Replace the IIFE with a simple null-coalescing operator.
// NOTE: This can't be done with a helper function, or else we risk an inlining
// back-off causing a huge code size regression if a non-inlined helper function
// prevents the optimizer from detecting the (possibly large) dead code paths.
/** @const {boolean} */
exports.USE_CLIENT_HINTS = (() => {
  const override = USE_CLIENT_HINTS_OVERRIDE ?
         goog.getObjectByName(USE_CLIENT_HINTS_OVERRIDE) :
         null;
  return override != null ? override : USE_CLIENT_HINTS;
})();
<commit_msg>Automated rollback of commit b37f89c4493438fff27c471cb4e97b753d819277.<commit_after>/**
 * @license
 * Copyright The Closure Library Authors.
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Defines for goog.labs.userAgent.
 */

goog.module('goog.labs.userAgent');

/**
 * @define {boolean} If true, use navigator.userAgentData
 * TODO(user) Flip flag in 2021/12.
 */
const USE_CLIENT_HINTS =
    goog.define('goog.labs.userAgent.USE_CLIENT_HINTS', false);
exports.USE_CLIENT_HINTS = USE_CLIENT_HINTS;
<|endoftext|>


<commit_before>var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');
var passport = require('passport');
var flash = require('connect-flash');
var router = express.Router();
var config = require('./config');

/*
 	App configuration
*/

exports.config = function(app){
	app.use(express.static(__dirname + '/public'));
	app.set('port', config.server.port);
	app.use(cookieParser());
	app.use(bodyParser.json());
}<commit_msg>fixed server config file<commit_after>var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');
var passport = require('passport');
var flash = require('connect-flash');
var router = express.Router();
var config = require('./config');

/*
 	App configuration
*/

exports.config = function(app){
	app.use(express.static(__dirname + '/public'));
	app.set('port', config.server.port);
	app.use(cookieParser());
	app.use(session({
		secret: 'node-express-mongo-seed-secret',
		saveUninitialized: true,
		resave: true
	}));
	app.use(passport.initialize());
	app.use(passport.session());
	app.use(bodyParser.urlencoded({
		extended: true
	}));
	app.use(bodyParser.json());
	app.use(flash());
}<|endoftext|>


<commit_before>/**
 * Created by Evrim Persembe on 8/31/16.
 */

/* global desc:true, task:true, fail:true, complete:true, jake:true, directory:true */

(function () {
  "use strict";

  var semver = require("semver");
  var jshint = require("simplebuild-jshint");
  var karma  = require("simplebuild-karma");
  var shell  = require("shelljs");

  var KARMA_CONFIG  = "karma.conf.js";
  var GENERATED_DIR = "generated";
  var DIST_DIR      = GENERATED_DIR + "/dist";

  /* General-purpose tasks */

  desc("Start the Karma server");
  task("karma", function() {
    console.log("Starting Karma server:");

    karma.start({
      configFile: KARMA_CONFIG
    }, complete, fail);
  }, { async: true });

  desc("Default build");
  task("default", [ "node_version", "lint", "test" ], function() {
    console.log("BUILD OK!");
  });

  desc("Run a local server");
  task("run", [ "build" ], function() {
    jake.exec("node node_modules/.bin/http-server " + DIST_DIR, { interactive: true });
  }, { async: true });

  desc("Erase all generated files");
  task("clean", function() {
    console.log("Erasing generated files: .");

    shell.rm("-rf", GENERATED_DIR);
  });

  /* Supporting tasks */

  desc("Check Node version");
  task("node_version", function() {
    console.log("Checking Node version: .");

    var packageJson     = require("./package.json");
    var expectedVersion = packageJson.engines.node;
    var actualVersion   = process.version;

    if (semver.neq(expectedVersion, actualVersion)) {
      fail("Incorrect Node version: expected " + expectedVersion + ", but was " + process.version + ".");
    }
  });

  desc("Lint the JavaScript code");
  task("lint", function() {
    process.stdout.write("Linting JavaScript: ");

    // Get the JSHint options from package.json so
    // we can use the same settings in JetBrains IDEs.
    // TODO: Rename this variable to "lintOptions".
    var packageJson = require("./package.json");

    jshint.checkFiles({
      files: [ "Jakefile.js", "src/**/*.js" ],
      options: packageJson.jshintConfig,
      globals: packageJson.jshintConfig.globals
    }, complete, fail);
  }, { async: true });

  desc("Run tests");
  task("test", function() {
    console.log("Testing JavaScript:");

    karma.run({
      configFile: KARMA_CONFIG,
      expectedBrowsers: [
        "Chrome 52.0.2743 (Mac OS X 10.11.6)",
        "IE 9.0.0 (Windows 7 0.0.0)",
        "Safari 9.1.2 (Mac OS X 10.11.6)",
        "Firefox 48.0.0 (Mac OS X 10.11.0)",
        "Mobile Safari 9.0.0 (iOS 9.3.0)"
      ],
      strict: !process.env.loose
    }, complete, fail);
  }, { async: true });

  desc("Build distribution directory");
  task("build", [ DIST_DIR ], function() {
    console.log("Building distribution directory: .");

    shell.rm("-rf", DIST_DIR + "/*");
    shell.cp("src/content/*", DIST_DIR);

    jake.exec("node node_modules/.bin/browserify src/javascript/app.js -o " + DIST_DIR + "/bundle.js",
      { interactive: true },
      complete);
  }, { async: true });

  directory(DIST_DIR);
}());<commit_msg>Refactor lint options and globals in the Jakefile<commit_after>/**
 * Created by Evrim Persembe on 8/31/16.
 */

/* global desc:true, task:true, fail:true, complete:true, jake:true, directory:true */

(function () {
  "use strict";

  var semver = require("semver");
  var jshint = require("simplebuild-jshint");
  var karma  = require("simplebuild-karma");
  var shell  = require("shelljs");

  var KARMA_CONFIG  = "karma.conf.js";
  var GENERATED_DIR = "generated";
  var DIST_DIR      = GENERATED_DIR + "/dist";

  /* General-purpose tasks */

  desc("Start the Karma server");
  task("karma", function() {
    console.log("Starting Karma server:");

    karma.start({
      configFile: KARMA_CONFIG
    }, complete, fail);
  }, { async: true });

  desc("Default build");
  task("default", [ "node_version", "lint", "test" ], function() {
    console.log("BUILD OK!");
  });

  desc("Run a local server");
  task("run", [ "build" ], function() {
    jake.exec("node node_modules/.bin/http-server " + DIST_DIR, { interactive: true });
  }, { async: true });

  desc("Erase all generated files");
  task("clean", function() {
    console.log("Erasing generated files: .");

    shell.rm("-rf", GENERATED_DIR);
  });

  /* Supporting tasks */

  desc("Check Node version");
  task("node_version", function() {
    console.log("Checking Node version: .");

    var packageJson     = require("./package.json");
    var expectedVersion = packageJson.engines.node;
    var actualVersion   = process.version;

    if (semver.neq(expectedVersion, actualVersion)) {
      fail("Incorrect Node version: expected " + expectedVersion + ", but was " + process.version + ".");
    }
  });

  desc("Lint the JavaScript code");
  task("lint", function() {
    process.stdout.write("Linting JavaScript: ");

    // Get the JSHint options from package.json so
    // we can use the same settings in JetBrains IDEs.
    var lintOptions = require("./package.json").jshintConfig;
    var lintGlobals = lintOptions.globals;

    jshint.checkFiles({
      files: [ "Jakefile.js", "src/**/*.js" ],
      options: lintOptions,
      globals: lintGlobals
    }, complete, fail);
  }, { async: true });

  desc("Run tests");
  task("test", function() {
    console.log("Testing JavaScript:");

    karma.run({
      configFile: KARMA_CONFIG,
      expectedBrowsers: [
        "Chrome 52.0.2743 (Mac OS X 10.11.6)",
        "IE 9.0.0 (Windows 7 0.0.0)",
        "Safari 9.1.2 (Mac OS X 10.11.6)",
        "Firefox 48.0.0 (Mac OS X 10.11.0)",
        "Mobile Safari 9.0.0 (iOS 9.3.0)"
      ],
      strict: !process.env.loose
    }, complete, fail);
  }, { async: true });

  desc("Build distribution directory");
  task("build", [ DIST_DIR ], function() {
    console.log("Building distribution directory: .");

    shell.rm("-rf", DIST_DIR + "/*");
    shell.cp("src/content/*", DIST_DIR);

    jake.exec("node node_modules/.bin/browserify src/javascript/app.js -o " + DIST_DIR + "/bundle.js",
      { interactive: true },
      complete);
  }, { async: true });

  directory(DIST_DIR);
}());<|endoftext|>


<commit_before>import angular from 'angular';
import angularMeteor from 'angular-meteor';
import { Meteor } from 'meteor/meteor'
import template from '../templates/quizCreationForm.html';

import { Questions } from '../publishers/questionPublisher.js';
import QML2HTML from '../interpreter/QML2HTML.js';

class NewQuizController{
	constructor($scope) {
		$scope.viewModel(this);

		/*Materialize collapsible initialization*/
		$(document).ready(function(){
			$('.collapsible').collapsible({
			  accordion : false
			});
		});

		this.questions = [];
		this.categories= [];
		this.time;
		this.title;
		this.description;

		this.subscribe('questions');

		this.helpers({
			questionList() {
				return Questions.find({}, {"sort" : [['createdAt', 'desc']]});
			}
		});
	}

	toggleSelection(question){
		var idpos= this.questions.indexOf(question._id);
		var categoryPos = this.categories.map(function(c) {return c.category; }).indexOf(question.category);

		if(idpos > -1){
			this.questions.splice(idpos,1);

			if(categoryPos > -1){
				if(this.categories[categoryPos].counter > 1){
					this.categories[categoryPos].counter--;
				}
				else{
					this.categories.splice(categoryPos,1);
				}
			}
		}
		else{
			this.questions.push(question._id);
			if(categoryPos == -1){
				this.categories.push({category: question.category, counter: 1});
			}
			else{
				this.categories[categoryPos].counter++;
			}
		}
	}

	saveQuiz(title, questions, categories, description, time){

		if(title == undefined || time == undefined ){
			QzMessage.showText(0, "Compila tutti i campi");
		}
		else if(questions.length == 0 || categories.length==0){
			QzMessage.showText(0, "Seleziona almeno una domanda");
		}
		else{
			if(description == "" || description == null){
				QzMessage.showText(1, "La descrizione del Quiz è vuota");
			}
			categories=  this.categories.map(function(item){ return item.category});
			Meteor.call("quizzes.insert", title, questions, categories, description, time);
			QzMessage.showText(2,'Il tuo quiz è stato salvato!');
			this.questions = [];
			this.categories = [];
			this.time = null;
			this.title = "";
			this.description = "";
		}
	}

	getQuestionDetails(QMLtext){
		var questionDetails = QML2HTML(QMLtext);
		if(questionDetails)
			return questionDetails;
		else
			console.log("Error nel caricamento dei dettagli del quiz");
	}

	getFullQuestionType(shortType){
		var fullType;
		switch(shortType){
			case "VF":
				fullType = "Vero o Falso";
				break;
			case "MU":
				fullType = "Risposta multipla (unica risposta esatta)";
				break;
			case "MX":
				fullType = "Risposta multipla (più risposte esatte)";
				break;
			case "AS":
				fullType = "Associazione";
				break;
			case "OD":
				fullType = "Ordinamento";
				break;
			default:
				fullType =shortType;
				break;
		}
		return fullType;
	}

	getCorrectAnswer(question)
	{
		var answer = "";
		//return question.QMLtext.substring(11, 13);
		switch(this.getFullQuestionType(this.getQuestionDetails(question.QMLtext).type)){
			case "Vero o Falso":
				if(question.QMLtext.indexOf('<answer isRight="yes"></answer>') > 0)
					answer = "Vero";
				else
					answer = "Falso";
				break;
			case "Risposta multipla (unica risposta esatta)":
				answer = question.QMLtext.substring(question.QMLtext.search('<answer isRight="yes">')+22, question.QMLtext.indexOf("</answer>", question.QMLtext.search('<answer isRight="yes">')+22));
				break;
			case "Risposta multipla (più risposte esatte)":
				var ls = question.QMLtext.split('<answer isRight="yes">');
				var ls1 = [];
				for(var i = 1; i < ls.length; i++)
				{
					ls1.push(" " + ls[i].split('</answer>')[0].trim());

				}
				answer = ls1.toString().trim();
				break;
			case "Associazione":
				ls = question.QMLtext.split('<answer set="A" pos=');
				ls1 = question.QMLtext.split('<answer set="B" pos=');
				var ls_1 = []; var ls1_1 = [];
				for(var i = 1; i < ls.length || i < ls1.length; i++)
				{
					//ls_1 contiene le risposte del gruppo A in modo disordinato
					//ls1_1 contiene le risposte del gruppo B in modo disordinato
					if(i < ls.length)
						ls_1.push(ls[i].split('</answer>')[0].trim());
					if(i < ls1.length)
						ls1_1.push(ls1[i].split('</answer>')[0].trim());
				}
				ls_1.sort(); ls1_1.sort();

				for(var i = 0; i < ls_1.length; i++)
				{
					var j; var trovato = false;
					for(j = 0; j < ls1_1.length && !trovato; j++)
					{
						if(ls_1[i].split('>')[0] == ls1_1[j].split('>')[0])
						{
							trovato = true;
						}
					}
					answer += ls_1[i].substring(ls_1[i].indexOf('>') + 1) + " ==> ";
					if(trovato)
						answer += ls1_1[j].substring(ls1_1[j].indexOf('>') + 1);
					else
						answer += "    ";
					if(i < ls_1.length - 1)
						answer += ', ';
				}
				break;
			case "Ordinamento":

				break;
		}

		return answer;
	}
}

export default angular.module('quizCreationForm', [
  angularMeteor
])
  .component('quizCreationForm', {
    templateUrl: 'imports/templates/quizCreationForm.html',
    controller: ['$scope', NewQuizController]
  });
<commit_msg>ora QuizCreation mostra le risposte dell'ordinamento<commit_after>import angular from 'angular';
import angularMeteor from 'angular-meteor';
import { Meteor } from 'meteor/meteor'
import template from '../templates/quizCreationForm.html';

import { Questions } from '../publishers/questionPublisher.js';
import QML2HTML from '../interpreter/QML2HTML.js';

class NewQuizController{
	constructor($scope) {
		$scope.viewModel(this);

		/*Materialize collapsible initialization*/
		$(document).ready(function(){
			$('.collapsible').collapsible({
			  accordion : false
			});
		});

		this.questions = [];
		this.categories= [];
		this.time;
		this.title;
		this.description;

		this.subscribe('questions');

		this.helpers({
			questionList() {
				return Questions.find({}, {"sort" : [['createdAt', 'desc']]});
			}
		});
	}

	toggleSelection(question){
		var idpos= this.questions.indexOf(question._id);
		var categoryPos = this.categories.map(function(c) {return c.category; }).indexOf(question.category);

		if(idpos > -1){
			this.questions.splice(idpos,1);

			if(categoryPos > -1){
				if(this.categories[categoryPos].counter > 1){
					this.categories[categoryPos].counter--;
				}
				else{
					this.categories.splice(categoryPos,1);
				}
			}
		}
		else{
			this.questions.push(question._id);
			if(categoryPos == -1){
				this.categories.push({category: question.category, counter: 1});
			}
			else{
				this.categories[categoryPos].counter++;
			}
		}
	}

	saveQuiz(title, questions, categories, description, time){

		if(title == undefined || time == undefined ){
			QzMessage.showText(0, "Compila tutti i campi");
		}
		else if(questions.length == 0 || categories.length==0){
			QzMessage.showText(0, "Seleziona almeno una domanda");
		}
		else{
			if(description == "" || description == null){
				QzMessage.showText(1, "La descrizione del Quiz è vuota");
			}
			categories=  this.categories.map(function(item){ return item.category});
			Meteor.call("quizzes.insert", title, questions, categories, description, time);
			QzMessage.showText(2,'Il tuo quiz è stato salvato!');
			this.questions = [];
			this.categories = [];
			this.time = null;
			this.title = "";
			this.description = "";
		}
	}

	getQuestionDetails(QMLtext){
		var questionDetails = QML2HTML(QMLtext);
		if(questionDetails)
			return questionDetails;
		else
			console.log("Error nel caricamento dei dettagli del quiz");
	}

	getFullQuestionType(shortType){
		var fullType;
		switch(shortType){
			case "VF":
				fullType = "Vero o Falso";
				break;
			case "MU":
				fullType = "Risposta multipla (unica risposta esatta)";
				break;
			case "MX":
				fullType = "Risposta multipla (più risposte esatte)";
				break;
			case "AS":
				fullType = "Associazione";
				break;
			case "OD":
				fullType = "Ordinamento";
				break;
			default:
				fullType =shortType;
				break;
		}
		return fullType;
	}

	getCorrectAnswer(question)
	{
		var answer = "";
		//return question.QMLtext.substring(11, 13);
		switch(this.getFullQuestionType(this.getQuestionDetails(question.QMLtext).type)){
			case "Vero o Falso":
				if(question.QMLtext.indexOf('<answer isRight="yes"></answer>') > 0)
					answer = "Vero";
				else
					answer = "Falso";
				break;
			case "Risposta multipla (unica risposta esatta)":
				answer = question.QMLtext.substring(question.QMLtext.search('<answer isRight="yes">')+22, question.QMLtext.indexOf("</answer>", question.QMLtext.search('<answer isRight="yes">')+22));
				break;
			case "Risposta multipla (più risposte esatte)":
				var ls = question.QMLtext.split('<answer isRight="yes">');
				var ls1 = [];
				for(var i = 1; i < ls.length; i++)
				{
					ls1.push(" " + ls[i].split('</answer>')[0].trim());

				}
				answer = ls1.toString().trim();
				break;
			case "Associazione":
				var ls = question.QMLtext.split('<answer set="A" pos=');
				var ls1 = question.QMLtext.split('<answer set="B" pos=');
				var ls_1 = []; var ls1_1 = [];
				for(var i = 1; i < ls.length || i < ls1.length; i++)
				{
					if(i < ls.length)
						ls_1.push(ls[i].split('</answer>')[0].trim());
					if(i < ls1.length)
						ls1_1.push(ls1[i].split('</answer>')[0].trim());
				}
				ls_1.sort(); ls1_1.sort();

				for(var i = 0; i < ls_1.length; i++)
				{
					var j; var trovato = false;
					for(j = 0; j < ls1_1.length && !trovato; j++)
					{
						if(ls_1[i].split('>')[0] == ls1_1[j].split('>')[0])
						{
							trovato = true;
						}
					}
					answer += ls_1[i].substring(ls_1[i].indexOf('>') + 1) + " ==> ";
					if(trovato)
						answer += ls1_1[j].substring(ls1_1[j].indexOf('>') + 1);
					else
						answer += "    ";
					if(i < ls_1.length - 1)
						answer += ', ';
				}
				break;
			case "Ordinamento":
				var ls = question.QMLtext.split('<answer pos=');
				ls.sort();
				for(var i = 0; i < ls.length - 1; i++)
				{
					answer += ls[i].substring(ls[i].indexOf('>') + 1, ls[i].indexOf('</answer>')) + " ==> ";
				}
				answer = answer.substring(0, answer.length - 5);
				break;
		}

		return answer;
	}
}

export default angular.module('quizCreationForm', [
  angularMeteor
])
  .component('quizCreationForm', {
    templateUrl: 'imports/templates/quizCreationForm.html',
    controller: ['$scope', NewQuizController]
  });
<|endoftext|>


<commit_before>'use strict';

var AdmZip = require('adm-zip');
var fs = require('fs');
var mkdir = require('mkdirp');
var mout = require('mout');
var path = require('path');
var pipeline = require('stream-combiner');
var rm = require('rimraf');
var tar = require('tar');
var temp = require('temp');
var zlib = require('zlib');

/**
 * Initialize Decompress with options
 *
 * Options:
 *
 *   - `ext` String with file name, MIME type, etc
 *   - `path` Path to extract to
 *
 * @param {Object} opts
 * @api private
 */

function Decompress(opts) {
    opts = opts || {};
    opts.strip = opts.strip || 0;
    this.opts = opts;
    this.path = opts.path || process.cwd();
    this.ext = opts.ext || '';
    this.strip = opts.strip >= 0 ? opts.strip : 0;
    this.extractors = {
        '.zip': this._extractZip,
        '.tar': this._extractTar,
        '.tar.gz': this._extractTarGz,
        '.tgz': this._extractTarGz,
        'application/zip': this._extractZip,
        'application/x-tar': this._extractTar,
        'application/x-tgz': this._extractTarGz
    };
    this.extractorTypes = Object.keys(this.extractors);
    this.extractor = this._getExtractor(this.ext);
}

/**
 * Extract an archive
 *
 * @api public
 */

Decompress.prototype.extract = function () {
    var self = this;
    var stream = this.extractor();

    if (!fs.existsSync(this.path)) {
        mkdir.sync(self.path);
    }

    return stream;
};

/**
 * Check if a file can be extracted
 *
 * @param {String} src
 * @param {String} mime
 * @api public
 */

Decompress.prototype.canExtract = function (src, mime) {
    if (this._getExtractor(src)) {
        return true;
    }

    if (mime && this._getExtractor(mime)) {
        return true;
    }

    return false;
};

/**
 * Get the extractor for a desired file
 *
 * @param {String} src
 * @api private
 */

Decompress.prototype._getExtractor = function (src) {
    src = src.toLowerCase();

    var ext = mout.array.find(this.extractorTypes, function (ext) {
        return mout.string.endsWith(src, ext);
    });

    return ext ? this.extractors[ext] : null;
};

/**
 * Extract a zip file
 *
 * @api private
 */

Decompress.prototype._extractZip = function () {
    var self = this;
    var tempFile = temp.path({ suffix: '.zip' });
    var stream = fs.createWriteStream(tempFile).on('close', function () {
        var zip = new AdmZip(tempFile);
        var zipEntries = zip.getEntries();
        var destFile;

        zipEntries.forEach(function (entry) {
            destFile = entry.entryName.toString().split('/').slice(self.strip).join('/');

            if (destFile || destFile.length) {
                zip.extractEntryTo(entry.entryName.toString(), path.join(self.path, destFile), true, true);
            }
        });
    });

    return stream.on('close', function () {
        rm.sync(tempFile);
    });
};

/**
 * Extract a tar file
 *
 * @api private
 */

Decompress.prototype._extractTar = function () {
    var stream = tar.Extract(this.opts);
    return stream;
};

/**
 * Extract a tar.gz file
 *
 * @api private
 */

Decompress.prototype._extractTarGz = function () {
    var stream = zlib.Unzip();
    var dest = tar.Extract(this.opts);
    return pipeline(stream, dest);
};

/**
 * Module exports
 */

module.exports.extract = function (opts) {
    var decompress = new Decompress(opts);
    return decompress.extract();
};

module.exports.canExtract = function (src, mime) {
    var decompress = new Decompress();
    return decompress.canExtract(src, mime);
};
<commit_msg>Fix zip issue where files got extracted to the wrong location<commit_after>'use strict';

var AdmZip = require('adm-zip');
var fs = require('fs');
var mkdir = require('mkdirp');
var mout = require('mout');
var path = require('path');
var pipeline = require('stream-combiner');
var rm = require('rimraf');
var tar = require('tar');
var temp = require('temp');
var zlib = require('zlib');

/**
 * Initialize Decompress with options
 *
 * Options:
 *
 *   - `ext` String with file name, MIME type, etc
 *   - `path` Path to extract to
 *
 * @param {Object} opts
 * @api private
 */

function Decompress(opts) {
    opts = opts || {};
    opts.strip = opts.strip || 0;
    this.opts = opts;
    this.path = opts.path || process.cwd();
    this.ext = opts.ext || '';
    this.strip = opts.strip >= 0 ? opts.strip : 0;
    this.extractors = {
        '.zip': this._extractZip,
        '.tar': this._extractTar,
        '.tar.gz': this._extractTarGz,
        '.tgz': this._extractTarGz,
        'application/zip': this._extractZip,
        'application/x-tar': this._extractTar,
        'application/x-tgz': this._extractTarGz
    };
    this.extractorTypes = Object.keys(this.extractors);
    this.extractor = this._getExtractor(this.ext);
}

/**
 * Extract an archive
 *
 * @api public
 */

Decompress.prototype.extract = function () {
    var self = this;
    var stream = this.extractor();

    if (!fs.existsSync(this.path)) {
        mkdir.sync(self.path);
    }

    return stream;
};

/**
 * Check if a file can be extracted
 *
 * @param {String} src
 * @param {String} mime
 * @api public
 */

Decompress.prototype.canExtract = function (src, mime) {
    if (this._getExtractor(src)) {
        return true;
    }

    if (mime && this._getExtractor(mime)) {
        return true;
    }

    return false;
};

/**
 * Get the extractor for a desired file
 *
 * @param {String} src
 * @api private
 */

Decompress.prototype._getExtractor = function (src) {
    src = src.toLowerCase();

    var ext = mout.array.find(this.extractorTypes, function (ext) {
        return mout.string.endsWith(src, ext);
    });

    return ext ? this.extractors[ext] : null;
};

/**
 * Extract a zip file
 *
 * @api private
 */

Decompress.prototype._extractZip = function () {
    var self = this;
    var tempFile = temp.path({ suffix: '.zip' });
    var stream = fs.createWriteStream(tempFile).on('close', function () {
        var zip = new AdmZip(tempFile);
        var zipEntries = zip.getEntries();

        zipEntries.forEach(function (entry) {
            var destFile = entry.entryName.toString().split('/').slice(self.strip).join('/');
            var destDir = path.dirname(destFile);

            if (destFile || destFile.length) {
                zip.extractEntryTo(entry.entryName.toString(), path.join(self.path, destDir), false, true);
            }
        });
    });

    return stream.on('close', function () {
        rm.sync(tempFile);
    });
};

/**
 * Extract a tar file
 *
 * @api private
 */

Decompress.prototype._extractTar = function () {
    var stream = tar.Extract(this.opts);
    return stream;
};

/**
 * Extract a tar.gz file
 *
 * @api private
 */

Decompress.prototype._extractTarGz = function () {
    var stream = zlib.Unzip();
    var dest = tar.Extract(this.opts);
    return pipeline(stream, dest);
};

/**
 * Module exports
 */

module.exports.extract = function (opts) {
    var decompress = new Decompress(opts);
    return decompress.extract();
};

module.exports.canExtract = function (src, mime) {
    var decompress = new Decompress();
    return decompress.canExtract(src, mime);
};
<|endoftext|>


<commit_before>var AudioChannel = function(args) {
  this.context = AudioContext ? new AudioContext() : new webkitAudioContext();
  this.oscill = this.context.createOscillator();
  this.gain = this.context.createGain();

  this.oscill.connect(this.gain);
  this.gain.connect(this.context.destination);

  if(args) {
    this.oscill.frequency.value = args.freq ? args.freq : 220;
    this.gain.gain.value = args.gain ? args.gain : 0.05;
  }
}
<commit_msg>Add AudioChannel.playSong<commit_after>var AudioChannel = function(args) {
  this.context = AudioContext ? new AudioContext() : new webkitAudioContext();
  this.oscill = this.context.createOscillator();
  this.gain = this.context.createGain();

  this.oscill.connect(this.gain);
  this.gain.connect(this.context.destination);

  if(args) {
    this.oscill.frequency.value = args.freq ? args.freq : 220;
    this.oscill.type = args.wave ? args.wave : "triangle";
    this.gain.gain.value = args.gain ? args.gain : 0.05;
  }
}
AudioChannel.prototype.playSong = function(song) {
  this.oscill.start();
  var playNextNote = function(song) {
    this.oscill.frequency.value = song[0].freq;
    if(song[1]) {
      setTimeout(playNextNote.bind(this, song.slice(1)), song[0].length);
    }
    else {
      setTimeout(function() {
        this.gain.gain.value = 0;
      }.bind(this), song[0].length);
    }
  }.bind(this);
  playNextNote(song);
}
<|endoftext|>


<commit_before>describe('cms.base.js', function () {
    it('creates CMS namespace', function () {
        expect(CMS).toBeDefined();
        expect(CMS).toEqual(jasmine.any(Object));
        expect(CMS.API).toEqual(jasmine.any(Object));
        expect(CMS.KEYS).toEqual(jasmine.any(Object));
        expect(CMS.BREAKPOINTS).toEqual(jasmine.any(Object));
        expect(CMS.$).toEqual(jQuery);
    });
});
<commit_msg>initial structure for cms.base.test.js<commit_after>describe('cms.base.js', function () {
    it('creates CMS namespace', function () {
        expect(CMS).toBeDefined();
        expect(CMS).toEqual(jasmine.any(Object));
        expect(CMS.API).toEqual(jasmine.any(Object));
        expect(CMS.KEYS).toEqual(jasmine.any(Object));
        expect(CMS.BREAKPOINTS).toEqual(jasmine.any(Object));
        expect(CMS.$).toEqual(jQuery);
        expect(CMS.Class).toEqual(Class);
    });

    describe('CMS.API', function () {
        it('exists', function () {
            expect(CMS.API.Helpers).toEqual(jasmine.any(Object));
            // this expectation is here so no one ever forgets to add a test
            expect(Object.keys(CMS.API.Helpers).length).toEqual(16);
        });

        describe('.reloadBrowser()', function () {

        });

        describe('.preventSubmit()', function () {

        });

        describe('.csrf()', function () {

        });

        describe('.setSettings()', function () {

        });

        describe('.getSettings()', function () {

        });

        describe('.makeURL()', function () {

        });

        describe('.debounce()', function () {

        });

        describe('.throttle()', function () {

        });

        describe('.secureConfirm()', function () {

        });

        describe('.addEventListener()', function () {

        });

        describe('.removeEventListener()', function () {

        });

        describe('.dispatchEvent()', function () {

        });

        describe('.once()', function () {

        });

        describe('.preventTouchScrolling()', function () {

        });

        describe('.allowTouchScrolling()', function () {

        });
    });
});
<|endoftext|>


<commit_before>'use babel'

import {Emitter, CompositeDisposable} from 'atom'
import {PanelElement} from './elements/panel'
import {getMessageElement} from './elements/message'

export class Panel {
  constructor() {
    this.element = new PanelElement()
    this.subscriptions = new CompositeDisposable()
    this.emitter = new Emitter()
    this.visibility = true
    this.visibleMessages = 0
    this.panel = atom.workspace.addBottomPanel({
      item: this.element.element,
      visible: this.visibility,
      priority: 500
    })
    this.messages = []
    this.editorElements = {}
    this.messageElements = new Map()

    this.subscriptions.add(this.element)
    this.subscriptions.add(this.emitter)

    this.element.onDidDestroy(() => {
      this.destroy()
    })
    this.subscriptions.add(atom.workspace.onDidChangeActivePaneItem(paneItem => {
      this.visibility = paneItem && typeof paneItem.getText === 'function'
      const currentVisibility = this.panel.isVisible()
      if (this.visibility && !currentVisibility) {
        this.panel.show()
      } else if (!this.visibility && currentVisibility) {
        this.panel.hide()
      }
    }))

    this.getEditorElement(null) // <-- For messages with no file path
    // Todo: Clear and reconstruct everything when the fire nation attacks (aka showIssuesFromAllFiles, or pane changes)
  }
  getEditorElement(path) {
    if (this.editorElements[path]) {
      return this.editorElements[path]
    }
    const element = document.createElement('div')
    element.setAttribute('data-path', path)
    // ^ helps while debugging
    this.element.content.appendChild(element)
    this.editorElements[path] = element
    return element
  }
  updateMessages({added, removed, messages}) {
    const activeEditor = atom.workspace.getActiveTextEditor()
    const activePath = (activeEditor ? activeEditor.getPath() : null) || NaN
    const editorElements = this.editorElements
    const addedLength = added.length
    const removedLength = removed.length

    if (addedLength)
    for (let i = 0; i < addedLength; ++i) {
      const message = added[i]
      const messageElement = getMessageElement(message)
      if (activePath === message.filePath) {
        const editorElement = editorElements[message.filePath] || this.getEditorElement(message.filePath)
        this.messageElements.set(message, messageElement)

        editorElement.appendChild(messageElement.element)
        this.visibleMessages++
      }
    }

    if (removedLength)
    for (let i = 0; i < removedLength; ++i) {
      const message = removed[i]
      const messageElement = this.messageElements.get(message)
      if (messageElement) {
        messageElement.element.remove()
        messageElement.dispose()
        this.messageElements.delete(message)
        this.visibleMessages--
      }
    }

    if (addedLength || removedLength)
    for (let path in this.editorElements) {
      const editorElement = this.editorElements[path]
      if (path !== 'null' && editorElement !== null && !editorElement.childNodes.length) {
        editorElement.remove()
        this.editorElements[path] = null
      }
    }

    const content = this.element.content
    if (this.visibleMessages && content.classList.contains('empty')) {
      content.classList.remove('empty')
    } else if (!this.visibleMessages && !content.classList.contains('empty')) {
      content.classList.add('empty')
    }
    this.messages = messages
  }
  onDidDestroy(callback) {
    return this.emitter.on('did-destroy', callback)
  }
  destroy() {
    this.emitter.emit('did-destroy')
    this.dispose()
  }
  dispose() {
    this.messages = null
    this.editorElements = null
    this.panel.destroy()
    this.subscriptions.dispose()
  }
}
<commit_msg>:art: Respect showIssuesFromAllFiles config in panel<commit_after>'use babel'

import {Emitter, CompositeDisposable} from 'atom'
import {PanelElement} from './elements/panel'
import {getMessageElement} from './elements/message'

export class Panel {
  constructor() {
    this.element = new PanelElement()
    this.subscriptions = new CompositeDisposable()
    this.emitter = new Emitter()
    this.panel = atom.workspace.addBottomPanel({
      item: this.element.element,
      visible: this.visibility,
      priority: 500
    })
    this.messages = []
    this.messageElements = new Map()
    this.editorElements = {}
    this.visibility = true
    this.visibleMessages = 0
    this.showAll = atom.config.get('linter-ui-default.showIssuesFromAllFiles')

    this.subscriptions.add(this.element)
    this.subscriptions.add(this.emitter)

    this.element.onDidDestroy(() => {
      this.destroy()
    })
    this.subscriptions.add(atom.workspace.onDidChangeActivePaneItem(paneItem => {
      this.visibility = paneItem && typeof paneItem.getText === 'function'
      const currentVisibility = this.panel.isVisible()
      if (this.visibility && !currentVisibility) {
        this.panel.show()
      } else if (!this.visibility && currentVisibility) {
        this.panel.hide()
      }
    }))

    this.getEditorElement(null) // <-- For messages with no file path
    // Todo: Clear and reconstruct everything when the fire nation attacks (aka showIssuesFromAllFiles, or pane changes)
  }
  getEditorElement(path) {
    if (this.editorElements[path]) {
      return this.editorElements[path]
    }
    const element = document.createElement('div')
    element.setAttribute('data-path', path)
    // ^ helps while debugging
    this.element.content.appendChild(element)
    this.editorElements[path] = element
    return element
  }
  updateMessages({added, removed, messages}) {
    const activeEditor = atom.workspace.getActiveTextEditor()
    const activePath = (activeEditor ? activeEditor.getPath() : null) || NaN
    const editorElements = this.editorElements
    const addedLength = added.length
    const removedLength = removed.length

    if (addedLength)
    for (let i = 0; i < addedLength; ++i) {
      const message = added[i]
      const messageElement = getMessageElement(message)
      if (this.showAll || activePath === message.filePath) {
        const editorElement = editorElements[message.filePath] || this.getEditorElement(message.filePath)
        this.messageElements.set(message, messageElement)

        editorElement.appendChild(messageElement.element)
        this.visibleMessages++
      }
    }

    if (removedLength)
    for (let i = 0; i < removedLength; ++i) {
      const message = removed[i]
      const messageElement = this.messageElements.get(message)
      if (messageElement) {
        messageElement.element.remove()
        messageElement.dispose()
        this.messageElements.delete(message)
        this.visibleMessages--
      }
    }

    if (addedLength || removedLength)
    for (let path in this.editorElements) {
      const editorElement = this.editorElements[path]
      if (path !== 'null' && editorElement !== null && !editorElement.childNodes.length) {
        editorElement.remove()
        this.editorElements[path] = null
      }
    }

    const content = this.element.content
    if (this.visibleMessages && content.classList.contains('empty')) {
      content.classList.remove('empty')
    } else if (!this.visibleMessages && !content.classList.contains('empty')) {
      content.classList.add('empty')
    }
    this.messages = messages
  }
  onDidDestroy(callback) {
    return this.emitter.on('did-destroy', callback)
  }
  destroy() {
    this.emitter.emit('did-destroy')
    this.dispose()
  }
  dispose() {
    this.messages = null
    this.editorElements = null
    this.panel.destroy()
    this.subscriptions.dispose()
  }
}
<|endoftext|>


<commit_before>import AsyncStorage from '@react-native-community/async-storage';

export const SETTINGS_KEYS = {
  APP_VERSION: 'AppVersion',
  CURRENT_LANGUAGE: 'CurrentLanguage',
  MOST_RECENT_USERNAME: 'MostRecentUsername',
  SUPPLYING_STORE_ID: 'SupplyingStoreId',
  SUPPLYING_STORE_NAME_ID: 'SupplyingStoreNameId',
  LAST_POST_PROCESSING_FAILED: 'LastPostProcessingFailed',
  SYNC_IS_INITIALISED: 'SyncIsInitialised',
  SYNC_PRIOR_FAILED: 'SyncPriorFailed',
  SYNC_URL: 'SyncURL',
  SYNC_SITE_ID: 'SyncSiteId',
  SYNC_SERVER_ID: 'SyncServerId',
  SYNC_SITE_NAME: 'SyncSiteName',
  SYNC_SITE_PASSWORD_HASH: 'SyncSitePasswordHash',
  THIS_STORE_ID: 'ThisStoreId',
  THIS_STORE_NAME_ID: 'ThisStoreNameId',
  THIS_STORE_TAGS: 'ThisStoreTags',
  THIS_STORE_CUSTOM_DATA: 'ThisStoreCustomData',
  CONSUMPTION_LOOKBACK_PERIOD: 'monthlyConsumptionLookBackPeriod',
  CONSUMPTION_ENFORCE_LOOKBACK: 'monthlyConsumptionEnforceLookBackPeriod',
  MONTHS_LEAD_TIME: 'monthsLeadTime',
  VACCINE_MODULE: 'usesVaccineModule',
  DISPENSARY_MODULE: 'usesDispensaryModule',
  DASHBOARD_MODULE: 'usesDashboardModule',
  CASH_REGISTER_MODULE: 'usesCashRegisterModule',
  PAYMENT_MODULE: 'usesPaymentModule',
  SUPPLIER_CREDIT_MODULE: 'usesSupplierCreditModule',
};

export const STORE_CUSTOM_DATA_KEYS = {
  CONSUMPTION_LOOKBACK_PERIOD: SETTINGS_KEYS.CONSUMPTION_LOOKBACK_PERIOD,
  CONSUMPTION_ENFORCE_LOOKBACK: SETTINGS_KEYS.CONSUMPTION_ENFORCE_LOOKBACK,
  MONTHS_LEAD_TIME: SETTINGS_KEYS.MONTHS_LEAD_TIME,
  VACCINE_MODULE: SETTINGS_KEYS.VACCINE_MODULE,
  DISPENSARY_MODULE: SETTINGS_KEYS.DISPENSARY_MODULE,
  DASHBOARD_MODULE: SETTINGS_KEYS.DASHBOARD_MODULE,
  CASH_REGISTER_MODULE: SETTINGS_KEYS.CASH_REGISTER_MODULE,
  PAYMENT_MODULE: SETTINGS_KEYS.PAYMENT_MODULE,
  SUPPLIER_CREDIT_MODULE: SETTINGS_KEYS.SUPPLIER_CREDIT_MODULE,
};

export const getAppVersion = async () => {
  const appVersion = await AsyncStorage.getItem(SETTINGS_KEYS.APP_VERSION);
  return appVersion;
};
<commit_msg>Add constants<commit_after>import AsyncStorage from '@react-native-community/async-storage';

export const SETTINGS_KEYS = {
  APP_VERSION: 'AppVersion',
  CURRENT_LANGUAGE: 'CurrentLanguage',
  MOST_RECENT_USERNAME: 'MostRecentUsername',
  SUPPLYING_STORE_ID: 'SupplyingStoreId',
  SUPPLYING_STORE_NAME_ID: 'SupplyingStoreNameId',
  LAST_POST_PROCESSING_FAILED: 'LastPostProcessingFailed',
  SYNC_IS_INITIALISED: 'SyncIsInitialised',
  SYNC_PRIOR_FAILED: 'SyncPriorFailed',
  SYNC_URL: 'SyncURL',
  SYNC_SITE_ID: 'SyncSiteId',
  SYNC_SERVER_ID: 'SyncServerId',
  SYNC_SITE_NAME: 'SyncSiteName',
  SYNC_SITE_PASSWORD_HASH: 'SyncSitePasswordHash',
  THIS_STORE_ID: 'ThisStoreId',
  THIS_STORE_NAME_ID: 'ThisStoreNameId',
  THIS_STORE_TAGS: 'ThisStoreTags',
  THIS_STORE_CUSTOM_DATA: 'ThisStoreCustomData',
  CONSUMPTION_LOOKBACK_PERIOD: 'monthlyConsumptionLookBackPeriod',
  CONSUMPTION_ENFORCE_LOOKBACK: 'monthlyConsumptionEnforceLookBackPeriod',
  MONTHS_LEAD_TIME: 'monthsLeadTime',
  VACCINE_MODULE: 'usesVaccineModule',
  DISPENSARY_MODULE: 'usesDispensaryModule',
  DASHBOARD_MODULE: 'usesDashboardModule',
  CASH_REGISTER_MODULE: 'usesCashRegisterModule',
  PAYMENT_MODULE: 'usesPaymentModule',
  SUPPLIER_CREDIT_MODULE: 'usesSupplierCreditModule',
  PATIENT_TYPES: 'usesPatientTypes',
};

export const STORE_CUSTOM_DATA_KEYS = {
  CONSUMPTION_LOOKBACK_PERIOD: SETTINGS_KEYS.CONSUMPTION_LOOKBACK_PERIOD,
  CONSUMPTION_ENFORCE_LOOKBACK: SETTINGS_KEYS.CONSUMPTION_ENFORCE_LOOKBACK,
  MONTHS_LEAD_TIME: SETTINGS_KEYS.MONTHS_LEAD_TIME,
  VACCINE_MODULE: SETTINGS_KEYS.VACCINE_MODULE,
  DISPENSARY_MODULE: SETTINGS_KEYS.DISPENSARY_MODULE,
  DASHBOARD_MODULE: SETTINGS_KEYS.DASHBOARD_MODULE,
  CASH_REGISTER_MODULE: SETTINGS_KEYS.CASH_REGISTER_MODULE,
  PAYMENT_MODULE: SETTINGS_KEYS.PAYMENT_MODULE,
  SUPPLIER_CREDIT_MODULE: SETTINGS_KEYS.SUPPLIER_CREDIT_MODULE,
};

export const getAppVersion = async () => {
  const appVersion = await AsyncStorage.getItem(SETTINGS_KEYS.APP_VERSION);
  return appVersion;
};
<|endoftext|>


<commit_before>const { Canvas, createCanvas, Image, ImageData, loadImage } = require('canvas');
const { JSDOM } = require('jsdom');
const { writeFileSync, existsSync, mkdirSync } = require("fs");
// This is our program. This time we use JavaScript async / await and promises to handle asynchronicity.
(async () => {
  // before loading opencv.js we emulate a minimal HTML DOM. See the function declaration below.
  installDOM();
  await loadOpenCV();
  // using node-canvas, we an image file to an object compatible with HTML DOM Image and therefore with cv.imread()
  const image = await loadImage('./color_example.jpg');
  const src = cv.imread(image);
  //const dst = new cv.Mat();
  //let dst = new cv.Mat(src.rows, src.cols, src.type());
  let dst = cv.Mat.zeros(src.cols, src.rows, cv.CV_8U);
//  cv.cvtColor(src, src, cv.COLOR_RGB2GRAY, 0);
  cv.cvtColor(src, dst, cv.COLOR_RGBA2GRAY, 0);
//  cv.cvtColor(src, dst, cv.COLOR_RGBA2GRAY, 0);
  cv.Canny(dst, dst, 50, 150, 3, false);
  const canvas = createCanvas(image.width, image.height);
  cv.imshow(canvas, dst);
  writeFileSync('canny.jpg', canvas.toBuffer('image/jpeg', { quality: 0.95 } ));
  src.delete();
  dst.delete();
})();
// Load opencv.js just like before but using Promise instead of callbacks:
function loadOpenCV() {
  return new Promise(resolve => {
    global.Module = {
      onRuntimeInitialized: resolve
    };
    global.cv = require('./opencv340.js');
  });
}
// Using jsdom and node-canvas we define some global variables to emulate HTML DOM.
// Although a complete emulation can be archived, here we only define those globals used
// by cv.imread() and cv.imshow().
function installDOM() {
  const dom = new JSDOM();
  global.document = dom.window.document;
  // The rest enables DOM image and canvas and is provided by node-canvas
  global.Image = Image;
  global.HTMLCanvasElement = Canvas;
  global.ImageData = ImageData;
  global.HTMLImageElement = Image;
}
<commit_msg>Fixed opencv version for node<commit_after>const { Canvas, createCanvas, Image, ImageData, loadImage } = require('canvas');
const { JSDOM } = require('jsdom');
const { writeFileSync, existsSync, mkdirSync } = require("fs");
// This is our program. This time we use JavaScript async / await and promises to handle asynchronicity.
(async () => {
  // before loading opencv.js we emulate a minimal HTML DOM. See the function declaration below.
  installDOM();
  await loadOpenCV();
  // using node-canvas, we an image file to an object compatible with HTML DOM Image and therefore with cv.imread()
  const image = await loadImage('./color_example.jpg');
  const src = cv.imread(image);
  //const dst = new cv.Mat();
  //let dst = new cv.Mat(src.rows, src.cols, src.type());
  let dst = cv.Mat.zeros(src.cols, src.rows, cv.CV_8U);
//  cv.cvtColor(src, src, cv.COLOR_RGB2GRAY, 0);
  cv.cvtColor(src, dst, cv.COLOR_RGBA2GRAY, 0);
//  cv.cvtColor(src, dst, cv.COLOR_RGBA2GRAY, 0);
  cv.Canny(dst, dst, 50, 150, 3, false);
  const canvas = createCanvas(image.width, image.height);
  cv.imshow(canvas, dst);
  writeFileSync('canny.jpg', canvas.toBuffer('image/jpeg', { quality: 0.95 } ));
  src.delete();
  dst.delete();
})();
// Load opencv.js just like before but using Promise instead of callbacks:
function loadOpenCV() {
  return new Promise(resolve => {
    global.Module = {
      onRuntimeInitialized: resolve
    };
    global.cv = require('./opencv.js');
  });
}
// Using jsdom and node-canvas we define some global variables to emulate HTML DOM.
// Although a complete emulation can be archived, here we only define those globals used
// by cv.imread() and cv.imshow().
function installDOM() {
  const dom = new JSDOM();
  global.document = dom.window.document;
  // The rest enables DOM image and canvas and is provided by node-canvas
  global.Image = Image;
  global.HTMLCanvasElement = Canvas;
  global.ImageData = ImageData;
  global.HTMLImageElement = Image;
}
<|endoftext|>


<commit_before>
import ReactDOM from 'react-dom'

import SocialLogin from '../src'

const handleSocialLogin = (user, err) => {
  console.log(user)
  console.log(err)
}

const SocialButton = SocialLogin(({ onClick, provider }) => (
  <button onClick={onClick}>Login with {provider}</button>
))

ReactDOM.render(

    <FBButton provider='facebook' appId='209060642824026' onLoginSuccess={handleSocialLogin} />

,
  document.getElementById('app')
)

import ReactDOM from 'react-dom'

import SocialLogin from '../src'

const handleSocialLogin = (user, err) => {
  console.log(user)
  console.log(err)
}

const SocialButton = SocialLogin(({ onClick, provider }) => (
  <button onClick={onClick}>Login with {provider}</button>
))

ReactDOM.render(

    <FBButton provider='facebook' appId='209060642824026' onLoginSuccess={handleSocialLogin} />

,
  document.getElementById('app')
)
<commit_msg>Update demo<commit_after>import React, { Component } from 'react'
import ReactDOM from 'react-dom'

import SocialLogin from '../src'

const handleSocialLogin = (user, err) => {
  console.log(user)
  console.log(err)
}

const PureButton = (props) => (
  <button {...props}>Login with Facebook</button>
)

class Button extends Component {
  render () {
    return (
      <button {...this.props}>Login with Facebook</button>
    )
  }
}

const PureSocialButton = SocialLogin(PureButton)
const SocialButton = SocialLogin(Button)

ReactDOM.render(

    <PureSocialButton provider='facebook' appId='1724499281174401' onLoginSuccess={handleSocialLogin} />
    <SocialButton provider='linkedin' appId='1724499281174401' onLoginSuccess={handleSocialLogin} />

,
  document.getElementById('app')
)
<|endoftext|>


<commit_before>'use strict';
angular.module('jtt_aping')
    .config(['$provide', function ($provide) {
        $provide.value('apingDefaultSettings', {
            apingApiKeys: {}
        });
    }])
    .value('apingResults', {})
    .directive('aping', ['apingResults', 'apingDefaultSettings', 'apingUtilityHelper', '$templateRequest', '$compile', function (apingResults, apingDefaultSettings, apingUtilityHelper, $templateRequest, $compile) {
        return {
            restrict: 'E',
            transclude: true,
            template: '<ng-transclude></ng-transclude>',
            scope: {
                model: '@',
                getNativeData: '@',
                items: '@',
                maxItems: '@',
                orderBy: '@',
                orderReverse: '@',
                templateUrl: '@',
                payloadJson: '@',
                removeDoubles: '@',
                mergeDoubles: '@',
                idBy: '@',
                resultProperty: '@', // legacy
                resultName: '@',
                valueName: '@',
                protocol: '@'
            },
            link: function (scope, element, attrs, controller, transcludeFn) {

                var templatePath = scope.templateUrl;

                scope.$watch('templateUrl', function () {
                    renderTemplate(scope.templateUrl);
                });

                if (angular.isUndefined(templatePath)) {
                    if (angular.isDefined(apingDefaultSettings.templateUrl)) {
                        templatePath = apingDefaultSettings.templateUrl;
                        renderTemplate(templatePath);
                    }
                }

                function renderTemplate(_templatePath) {
                    if (angular.isDefined(_templatePath) && _templatePath !== '$NONE') {
                        $templateRequest(_templatePath).then(function (html) {
                            var template = angular.element(html);
                            element.empty().append(template);
                            $compile(template)(scope);
                        });
                    } else {
                        transcludeFn(scope, function (clone, innerScope) {
                            element.html('');
                            element.append(clone);
                            $compile(clone)(innerScope);
                        });
                    }
                    scope.$broadcast('apiNG.templateRendered');
                }
            },
            controller: ['$scope', function ($scope) {

                if(angular.isUndefined($scope.resultName)) {
                    if (angular.isUndefined($scope.resultProperty)) {
                        $scope.resultName = 'results';
                    } else {
                        $scope.resultName = $scope.resultProperty;
                    }
                }

                $scope[$scope.resultName] = [];
                $scope.payload = $scope.payloadJson ? apingUtilityHelper.replaceSingleQuotesAndParseJson($scope.payloadJson) : {};

                /**
                 * return current appSettings by merging 'apingDefaultSettings' and '$scope params'
                 * @returns {Object}
                 */
                this.getAppSettings = function () {

                    var items;
                    var maxItems;
                    var getNativeData;
                    var orderReverse;
                    var orderBy;
                    var removeDoubles;
                    var mergeDoubles;
                    var valueName;
                    var idBy;
                    var protocol;

                    if (angular.isDefined($scope.valueName)) {
                        valueName = $scope.valueName;
                    } else {
                        valueName = undefined;
                    }

                    if (angular.isDefined($scope.items)) {
                        items = $scope.items;
                    } else if (angular.isDefined(apingDefaultSettings.items)) {
                        items = apingDefaultSettings.items;
                    } else {
                        items = undefined;
                    }

                    if (angular.isDefined($scope.maxItems)) {
                        maxItems = $scope.maxItems;
                    } else if (angular.isDefined(apingDefaultSettings.maxItems)) {
                        maxItems = apingDefaultSettings.maxItems;
                    } else {
                        maxItems = undefined;
                    }

                    if (angular.isDefined($scope.getNativeData)) {
                        getNativeData = $scope.getNativeData;
                    } else if (angular.isDefined(apingDefaultSettings.getNativeData)) {
                        getNativeData = apingDefaultSettings.getNativeData;
                    } else {
                        getNativeData = false;
                    }

                    if (angular.isDefined($scope.maxItems)) {
                        maxItems = $scope.maxItems;
                    } else if (angular.isDefined(apingDefaultSettings.maxItems)) {
                        maxItems = apingDefaultSettings.maxItems;
                    } else {
                        maxItems = undefined;
                    }

                    if (angular.isDefined($scope.orderBy)) {
                        orderBy = $scope.orderBy;
                    } else if (angular.isDefined(apingDefaultSettings.orderBy)) {
                        orderBy = apingDefaultSettings.orderBy;
                    } else {
                        orderBy = undefined;
                    }

                    if (angular.isDefined($scope.orderReverse)) {
                        orderReverse = $scope.orderReverse;
                    } else if (angular.isDefined(apingDefaultSettings.orderReverse)) {
                        orderReverse = apingDefaultSettings.orderReverse;
                    } else {
                        orderReverse = false;
                    }

                    if (angular.isDefined($scope.removeDoubles)) {
                        removeDoubles = $scope.removeDoubles;
                    } else if (angular.isDefined(apingDefaultSettings.removeDoubles)) {
                        removeDoubles = apingDefaultSettings.removeDoubles;
                    } else {
                        removeDoubles = false;
                    }

                    if (angular.isDefined($scope.mergeDoubles)) {
                        mergeDoubles = $scope.mergeDoubles;
                    } else if (angular.isDefined(apingDefaultSettings.mergeDoubles)) {
                        mergeDoubles = apingDefaultSettings.mergeDoubles;
                    } else {
                        mergeDoubles = false;
                    }

                    if (angular.isDefined($scope.idBy)) {
                        idBy = $scope.idBy;
                    } else if (angular.isDefined(apingDefaultSettings.idBy)) {
                        idBy = apingDefaultSettings.idBy;
                    } else {
                        idBy = undefined;
                    }

                    if (angular.isDefined($scope.protocol)) {
                        protocol = $scope.protocol;
                    } else if (angular.isDefined(apingDefaultSettings.protocol)) {
                        protocol = apingDefaultSettings.protocol;
                    } else {
                        protocol = undefined;
                    }

                    return {
                        model: $scope.model || apingDefaultSettings.model || 'native',
                        getNativeData: getNativeData,
                        items: items,
                        maxItems: maxItems,
                        orderBy: orderBy,
                        orderReverse: orderReverse,
                        removeDoubles: removeDoubles,
                        mergeDoubles: mergeDoubles,
                        idBy: idBy,
                        valueName: valueName,
                        protocol: protocol
                    };
                };

                /**
                 * merge current '$scope.results' with '_array' and sorts, limits and filters the data
                 *
                 * @param _array
                 */
                this.concatToResults = function (_array) {
                    if(angular.isUndefined($scope.resultName)) {
                        if (angular.isUndefined($scope.resultProperty)) {
                            $scope.resultName = 'results';
                        } else {
                            $scope.resultName = $scope.resultProperty;
                        }
                    }

                    var tempArray = $scope[$scope.resultName].concat(_array);

                    var appSettings = this.getAppSettings();

                    if (angular.isDefined(appSettings.idBy)) {
                        tempArray = apingUtilityHelper.createIdByPropertiesForArray(tempArray, appSettings.idBy);
                        if (appSettings.mergeDoubles === true || appSettings.mergeDoubles === 'true') {
                            tempArray = apingUtilityHelper.mergeDuplicateObjectsFromArray(
                                tempArray,
                                (appSettings.orderBy === false || appSettings.orderBy === 'false' || appSettings.orderBy === '$NONE')
                            );
                        }
                    }

                    //remove doubles
                    if (appSettings.removeDoubles === true || appSettings.removeDoubles === 'true') {
                        if (appSettings.mergeDoubles !== true && appSettings.mergeDoubles !== 'true') {
                            tempArray = apingUtilityHelper.removeDuplicateObjectsFromArray(
                                tempArray,
                                (appSettings.orderBy === false || appSettings.orderBy === 'false' || appSettings.orderBy === '$NONE'),
                                angular.isDefined(appSettings.idBy)
                            );
                        }
                    }

                    //order array
                    if (angular.isDefined(appSettings.orderBy) && appSettings.orderBy !== false && appSettings.orderBy !== 'false' && appSettings.orderBy !== '$NONE') {
                        //order random
                        if (appSettings.orderBy === '$RANDOM') {
                            tempArray = apingUtilityHelper.shuffleArray(tempArray);
                        }
                        //order by attribute
                        else {
                            tempArray.sort(apingUtilityHelper.sortArrayByProperty(appSettings.orderBy));
                        }
                    }

                    //order reverse
                    if ((appSettings.orderReverse === true || appSettings.orderReverse === 'true') && appSettings.orderBy !== '$RANDOM') {
                        tempArray.reverse();
                    }

                    //crop spare
                    if (appSettings.maxItems > -1 && tempArray.length > appSettings.maxItems) {
                        tempArray = tempArray.splice(0, appSettings.maxItems);
                    }

                    if (angular.isDefined(appSettings.valueName)) {
                        apingResults[appSettings.valueName] = tempArray;
                    }

                    $scope[$scope.resultName] = tempArray;

                    $scope.$broadcast('apiNG.resultMerged', {resultName: $scope.resultName, valueName: $scope.valueName});
                    $scope.$emit('apiNG.resultMerged', {resultName: $scope.resultName, valueName: $scope.valueName});
                };
                this.apply = function () {
                    $scope.$apply();
                };
            }]
        };
    }]);<commit_msg>#112: added possibility to call aping as attribute<commit_after>'use strict';
angular.module('jtt_aping')
    .config(['$provide', function ($provide) {
        $provide.value('apingDefaultSettings', {
            apingApiKeys: {}
        });
    }])
    .value('apingResults', {})
    .directive('aping', ['apingResults', 'apingDefaultSettings', 'apingUtilityHelper', '$templateRequest', '$compile', function (apingResults, apingDefaultSettings, apingUtilityHelper, $templateRequest, $compile) {
        return {
            restrict: 'EA',
            transclude: true,
            template: '<ng-transclude></ng-transclude>',
            scope: {
                model: '@',
                getNativeData: '@',
                items: '@',
                maxItems: '@',
                orderBy: '@',
                orderReverse: '@',
                templateUrl: '@',
                payloadJson: '@',
                removeDoubles: '@',
                mergeDoubles: '@',
                idBy: '@',
                resultProperty: '@', // legacy
                resultName: '@',
                valueName: '@',
                protocol: '@'
            },
            link: function (scope, element, attrs, controller, transcludeFn) {

                var templatePath = scope.templateUrl;

                scope.$watch('templateUrl', function () {
                    renderTemplate(scope.templateUrl);
                });

                if (angular.isUndefined(templatePath)) {
                    if (angular.isDefined(apingDefaultSettings.templateUrl)) {
                        templatePath = apingDefaultSettings.templateUrl;
                        renderTemplate(templatePath);
                    }
                }

                function renderTemplate(_templatePath) {
                    if (angular.isDefined(_templatePath) && _templatePath !== '$NONE') {
                        $templateRequest(_templatePath).then(function (html) {
                            var template = angular.element(html);
                            element.empty().append(template);
                            $compile(template)(scope);
                        });
                    } else {
                        transcludeFn(scope, function (clone, innerScope) {
                            element.html('');
                            element.append(clone);
                            $compile(clone)(innerScope);
                        });
                    }
                    scope.$broadcast('apiNG.templateRendered');
                }
            },
            controller: ['$scope', function ($scope) {

                if(angular.isUndefined($scope.resultName)) {
                    if (angular.isUndefined($scope.resultProperty)) {
                        $scope.resultName = 'results';
                    } else {
                        $scope.resultName = $scope.resultProperty;
                    }
                }

                $scope[$scope.resultName] = [];
                $scope.payload = $scope.payloadJson ? apingUtilityHelper.replaceSingleQuotesAndParseJson($scope.payloadJson) : {};

                /**
                 * return current appSettings by merging 'apingDefaultSettings' and '$scope params'
                 * @returns {Object}
                 */
                this.getAppSettings = function () {

                    var items;
                    var maxItems;
                    var getNativeData;
                    var orderReverse;
                    var orderBy;
                    var removeDoubles;
                    var mergeDoubles;
                    var valueName;
                    var idBy;
                    var protocol;

                    if (angular.isDefined($scope.valueName)) {
                        valueName = $scope.valueName;
                    } else {
                        valueName = undefined;
                    }

                    if (angular.isDefined($scope.items)) {
                        items = $scope.items;
                    } else if (angular.isDefined(apingDefaultSettings.items)) {
                        items = apingDefaultSettings.items;
                    } else {
                        items = undefined;
                    }

                    if (angular.isDefined($scope.maxItems)) {
                        maxItems = $scope.maxItems;
                    } else if (angular.isDefined(apingDefaultSettings.maxItems)) {
                        maxItems = apingDefaultSettings.maxItems;
                    } else {
                        maxItems = undefined;
                    }

                    if (angular.isDefined($scope.getNativeData)) {
                        getNativeData = $scope.getNativeData;
                    } else if (angular.isDefined(apingDefaultSettings.getNativeData)) {
                        getNativeData = apingDefaultSettings.getNativeData;
                    } else {
                        getNativeData = false;
                    }

                    if (angular.isDefined($scope.maxItems)) {
                        maxItems = $scope.maxItems;
                    } else if (angular.isDefined(apingDefaultSettings.maxItems)) {
                        maxItems = apingDefaultSettings.maxItems;
                    } else {
                        maxItems = undefined;
                    }

                    if (angular.isDefined($scope.orderBy)) {
                        orderBy = $scope.orderBy;
                    } else if (angular.isDefined(apingDefaultSettings.orderBy)) {
                        orderBy = apingDefaultSettings.orderBy;
                    } else {
                        orderBy = undefined;
                    }

                    if (angular.isDefined($scope.orderReverse)) {
                        orderReverse = $scope.orderReverse;
                    } else if (angular.isDefined(apingDefaultSettings.orderReverse)) {
                        orderReverse = apingDefaultSettings.orderReverse;
                    } else {
                        orderReverse = false;
                    }

                    if (angular.isDefined($scope.removeDoubles)) {
                        removeDoubles = $scope.removeDoubles;
                    } else if (angular.isDefined(apingDefaultSettings.removeDoubles)) {
                        removeDoubles = apingDefaultSettings.removeDoubles;
                    } else {
                        removeDoubles = false;
                    }

                    if (angular.isDefined($scope.mergeDoubles)) {
                        mergeDoubles = $scope.mergeDoubles;
                    } else if (angular.isDefined(apingDefaultSettings.mergeDoubles)) {
                        mergeDoubles = apingDefaultSettings.mergeDoubles;
                    } else {
                        mergeDoubles = false;
                    }

                    if (angular.isDefined($scope.idBy)) {
                        idBy = $scope.idBy;
                    } else if (angular.isDefined(apingDefaultSettings.idBy)) {
                        idBy = apingDefaultSettings.idBy;
                    } else {
                        idBy = undefined;
                    }

                    if (angular.isDefined($scope.protocol)) {
                        protocol = $scope.protocol;
                    } else if (angular.isDefined(apingDefaultSettings.protocol)) {
                        protocol = apingDefaultSettings.protocol;
                    } else {
                        protocol = undefined;
                    }

                    return {
                        model: $scope.model || apingDefaultSettings.model || 'native',
                        getNativeData: getNativeData,
                        items: items,
                        maxItems: maxItems,
                        orderBy: orderBy,
                        orderReverse: orderReverse,
                        removeDoubles: removeDoubles,
                        mergeDoubles: mergeDoubles,
                        idBy: idBy,
                        valueName: valueName,
                        protocol: protocol
                    };
                };

                /**
                 * merge current '$scope.results' with '_array' and sorts, limits and filters the data
                 *
                 * @param _array
                 */
                this.concatToResults = function (_array) {
                    if(angular.isUndefined($scope.resultName)) {
                        if (angular.isUndefined($scope.resultProperty)) {
                            $scope.resultName = 'results';
                        } else {
                            $scope.resultName = $scope.resultProperty;
                        }
                    }

                    var tempArray = $scope[$scope.resultName].concat(_array);

                    var appSettings = this.getAppSettings();

                    if (angular.isDefined(appSettings.idBy)) {
                        tempArray = apingUtilityHelper.createIdByPropertiesForArray(tempArray, appSettings.idBy);
                        if (appSettings.mergeDoubles === true || appSettings.mergeDoubles === 'true') {
                            tempArray = apingUtilityHelper.mergeDuplicateObjectsFromArray(
                                tempArray,
                                (appSettings.orderBy === false || appSettings.orderBy === 'false' || appSettings.orderBy === '$NONE')
                            );
                        }
                    }

                    //remove doubles
                    if (appSettings.removeDoubles === true || appSettings.removeDoubles === 'true') {
                        if (appSettings.mergeDoubles !== true && appSettings.mergeDoubles !== 'true') {
                            tempArray = apingUtilityHelper.removeDuplicateObjectsFromArray(
                                tempArray,
                                (appSettings.orderBy === false || appSettings.orderBy === 'false' || appSettings.orderBy === '$NONE'),
                                angular.isDefined(appSettings.idBy)
                            );
                        }
                    }

                    //order array
                    if (angular.isDefined(appSettings.orderBy) && appSettings.orderBy !== false && appSettings.orderBy !== 'false' && appSettings.orderBy !== '$NONE') {
                        //order random
                        if (appSettings.orderBy === '$RANDOM') {
                            tempArray = apingUtilityHelper.shuffleArray(tempArray);
                        }
                        //order by attribute
                        else {
                            tempArray.sort(apingUtilityHelper.sortArrayByProperty(appSettings.orderBy));
                        }
                    }

                    //order reverse
                    if ((appSettings.orderReverse === true || appSettings.orderReverse === 'true') && appSettings.orderBy !== '$RANDOM') {
                        tempArray.reverse();
                    }

                    //crop spare
                    if (appSettings.maxItems > -1 && tempArray.length > appSettings.maxItems) {
                        tempArray = tempArray.splice(0, appSettings.maxItems);
                    }

                    if (angular.isDefined(appSettings.valueName)) {
                        apingResults[appSettings.valueName] = tempArray;
                    }

                    $scope[$scope.resultName] = tempArray;

                    $scope.$broadcast('apiNG.resultMerged', {resultName: $scope.resultName, valueName: $scope.valueName});
                    $scope.$emit('apiNG.resultMerged', {resultName: $scope.resultName, valueName: $scope.valueName});
                };
                this.apply = function () {
                    $scope.$apply();
                };
            }]
        };
    }]);<|endoftext|>


<commit_before>const { resolve } = require('path')
const webpack = require('webpack')
const middleware = require('webpack-dev-middleware')
const conf = require('./webpack.server.js')
const compiler = webpack(conf)
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const url = require('url')
app.use(bodyParser.text({ type: '*/*' }))

const { exec } = require('child_process')

/**
 * Constants.
 */
var SERVER_SOFTWARE = 'Node/' + process.version
var SERVER_PROTOCOL = 'HTTP/1.1'
var GATEWAY_INTERFACE = 'CGI/1.1'

const perl = (req, res) => {
  const file = resolve.apply(null, [__dirname].concat(req.url.split('/')))

  if (!req.hasOwnProperty('uri')) {
    req.uri = url.parse(req.url)
  }

  var host = (req.headers.host || '').split(':')
  var address = host[0]
  var port = host[1]

  var env = {}

  // These meta-variables below can be overwritten by a
  // user's 'env' object in options
  Object.assign(env, {
    GATEWAY_INTERFACE: GATEWAY_INTERFACE,
    SCRIPT_NAME: file,
    SERVER_NAME: address || 'unknown',
    SERVER_PORT: port || 80,
    SERVER_PROTOCOL: SERVER_PROTOCOL,
    SERVER_SOFTWARE: SERVER_SOFTWARE,
  })

  // The client HTTP request headers are attached to the env as well,
  // in the format: "User-Agent" -> "HTTP_USER_AGENT"
  for (var header in req.headers) {
    var name = 'HTTP_' + header.toUpperCase().replace(/-/g, '_')
    env[name] = req.headers[header]
  }

  // These final environment variables take precedence over user-specified ones.
  env.REQUEST_METHOD = req.method.toUpperCase()
  env.QUERY_STRING = req.uri.query || ''
  env.REMOTE_ADDR = req.connection.remoteAddress
  env.REMOTE_PORT = req.connection.remotePort
  if ('content-length' in req.headers) {
    env.CONTENT_LENGTH = req.headers['content-length']
  }
  if ('content-type' in req.headers) {
    env.CONTENT_TYPE = req.headers['content-type']
  }
  if ('authorization' in req.headers) {
    var auth = req.headers.authorization.split(' ')
    env.AUTH_TYPE = auth[0]
  }

  const sendErr = msg => res.status(500).send(msg || 'Request Failed')
  exec(
    `carton exec ${file} 'POSTDATA=${req.body}'`,
    { cwd: file.substring(0, file.lastIndexOf('/')), maxBuffer: Infinity, env },
    (err, stdout, stderr) => {
      try {
        if (err) {
          console.error(err)
          sendErr(err.message)
        } else if (stderr) {
          console.error(stderr)
          sendErr(stderr)
        } else if (stdout) {
          const payload = stdout.replace(/^[^\{]*/g, '')
          payload ? res.json(JSON.parse(payload)) : res.status(200).send('OK')
        } else {
          res.status(400).send('Request Failed')
        }
      } catch (err) {
        sendErr('Request Failed')
      }
    }
  )
}

app.get('/', (req, res) => {
  res.sendFile(resolve(__dirname, 'index.html'))
})

app.use(require('webpack-hot-middleware')(compiler))
const serveWebpack = middleware(compiler, {
  publicPath: '/dist/',
})
app.get(/.*/, (req, res, next) => {
  if (/\/vendors/.test(req.url) || /\/resources/.test(req.url) || /\/node_modules/.test(req.url)) {
    res.sendFile(resolve.apply(null, [__dirname].concat(req.url.replace(/\?.*$/, '').split('/'))))
  } else {
    serveWebpack(req, res, next)
  }
})

app.post(/\.pl/, perl)

app.listen(process.env.PORT || 9090, () =>
  console.log(`SQE server listening on port ${process.env.PORT || 9090}!`)
)
<commit_msg>stringify env as a series of exports<commit_after>const { resolve } = require('path')
const webpack = require('webpack')
const middleware = require('webpack-dev-middleware')
const conf = require('./webpack.server.js')
const compiler = webpack(conf)
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const url = require('url')
app.use(bodyParser.json({ type: 'application/json' }))

const { exec } = require('child_process')

/**
 * Constants.
 */
var SERVER_SOFTWARE = 'Node/' + process.version
var SERVER_PROTOCOL = 'HTTP/1.1'
var GATEWAY_INTERFACE = 'CGI/1.1'

const perl = (req, res) => {
  const file = resolve.apply(null, [__dirname].concat(req.url.split('/')))

  if (!req.hasOwnProperty('uri')) {
    req.uri = url.parse(req.url)
  }

  var host = (req.headers.host || '').split(':')
  var address = host[0]
  var port = host[1]

  var env = {}

  // These meta-variables below can be overwritten by a
  // user's 'env' object in options
  Object.assign(env, {
    GATEWAY_INTERFACE: GATEWAY_INTERFACE,
    SCRIPT_NAME: file,
    SERVER_NAME: address || 'unknown',
    SERVER_PORT: port || 80,
    SERVER_PROTOCOL: SERVER_PROTOCOL,
    SERVER_SOFTWARE: SERVER_SOFTWARE,
  })

  // The client HTTP request headers are attached to the env as well,
  // in the format: "User-Agent" -> "HTTP_USER_AGENT"
  for (var header in req.headers) {
    var name = 'HTTP_' + header.toUpperCase().replace(/-/g, '_')
    env[name] = req.headers[header]
  }

  // These final environment variables take precedence over user-specified ones.
  env.REQUEST_METHOD = req.method.toUpperCase()
  env.QUERY_STRING = req.uri.query || ''
  env.REMOTE_ADDR = req.connection.remoteAddress
  env.REMOTE_PORT = req.connection.remotePort
  if ('content-length' in req.headers) {
    env.CONTENT_LENGTH = req.headers['content-length']
  }
  if ('content-type' in req.headers) {
    env.CONTENT_TYPE = req.headers['content-type']
  }
  if ('authorization' in req.headers) {
    var auth = req.headers.authorization.split(' ')
    env.AUTH_TYPE = auth[0]
  }

  var stringifiedEnv = []
  for (var k in env) {
    stringifiedEnv.push(`export ${k}="${('' + env[k]).replace(';', ';')}"`)
  }

  const sendErr = msg => res.status(500).send(msg || 'Request Failed')
  exec(
    `${stringifiedEnv.join(' && ')} && carton exec ${file} 'POSTDATA=${JSON.stringify(req.body)}'`,
    { cwd: file.substring(0, file.lastIndexOf('/')), maxBuffer: Infinity },
    (err, stdout, stderr) => {
      try {
        if (err) {
          console.error(err)
          sendErr(err.message)
        } else if (stderr) {
          console.error(stderr)
          sendErr(stderr)
        } else if (stdout) {
          const payload = stdout.replace(/^[^\{]*/g, '')
          payload ? res.json(JSON.parse(payload)) : res.status(200).send('OK')
        } else {
          res.status(400).send('Request Failed')
        }
      } catch (err) {
        sendErr('Request Failed')
      }
    }
  )
}

app.get('/', (req, res) => {
  res.sendFile(resolve(__dirname, 'index.html'))
})

app.use(require('webpack-hot-middleware')(compiler))
const serveWebpack = middleware(compiler, {
  publicPath: '/dist/',
})
app.get(/.*/, (req, res, next) => {
  if (/\/vendors/.test(req.url) || /\/resources/.test(req.url) || /\/node_modules/.test(req.url)) {
    res.sendFile(resolve.apply(null, [__dirname].concat(req.url.replace(/\?.*$/, '').split('/'))))
  } else {
    serveWebpack(req, res, next)
  }
})

app.post(/\.pl/, perl)

app.listen(process.env.PORT || 9090, () =>
  console.log(`SQE server listening on port ${process.env.PORT || 9090}!`)
)
<|endoftext|>


<commit_before>sparqplug.out.table = {type:"out","title":"Table Viewer","description":"View results in a table.","icon":"","css":"sparqplug.out.table.css"};
plugins['urn:sparqplug:sparqlenvironment.out.table:0.1'] = sparqplug.out.table;

sparqplug.out.table.load = function (selector) {
	$(selector).addClass('sparqplug-out-table');
}

sparqplug.out.table.updateUI = function (selector) {
	$(selector).empty();

	$.each(environment.latestResults,function (index, panelResults) {
		$.each(panelResults,function (index, resultObject) {
			$.each(resultObject.results,function (index, row) {
				var table = $('
');

				var keys = Object.keys(results[0]);

				var tr = $('
');

				$.each(row,function (key, values) {
					td = $('',{
						text: values.value//$.resolvePrefix(,dataset)
					}).data('obj',values.value).click(function () {
						environment.triggerEvent('selectedObject',{'object':values.value});
						//environment.detailObject($(this).data('obj'));
					});
					tr.append(td);
				});

				table.append(tr);

				var th = $('
');

				$.each(keys, function (index, key) {
					th.append(''+key+'	');
				});

				table.prepend(th);

				$(selector).append(table);

			});
		});
	});

}
<commit_msg>fix setting keys<commit_after>sparqplug.out.table = {type:"out","title":"Table Viewer","description":"View results in a table.","icon":"","css":"sparqplug.out.table.css"};
plugins['urn:sparqplug:sparqlenvironment.out.table:0.1'] = sparqplug.out.table;

sparqplug.out.table.load = function (selector) {
	$(selector).addClass('sparqplug-out-table');
}

sparqplug.out.table.updateUI = function (selector) {
	$(selector).empty();

	$.each(environment.latestResults,function (index, panelResults) {
		$.each(panelResults,function (index, resultObject) {
			var table = $('
');

			var keys = Object.keys(resultObject.results[0]);

			$.each(resultObject.results,function (index, row) {

				var tr = $('
');

				$.each(row,function (key, values) {
					td = $('',{
						text: values.value//$.resolvePrefix(,dataset)
					}).data('obj',values.value).click(function () {
						environment.triggerEvent('selectedObject',{'object':values.value});
						//environment.detailObject($(this).data('obj'));
					});
					tr.append(td);
				});

				table.append(tr);

			});
			var th = $('
');

			$.each(keys, function (index, key) {
				th.append(''+key+'	');
			});

			table.prepend(th);

			$(selector).append(table);
		});
	});

}
<|endoftext|>