<commit_before>/*
** Module dependencies
*/
var mongoose = require('mongoose');
var utils = require('../utils');
var openfisca = require('../simulation/openfisca');

var Schema = mongoose.Schema;

var ressourceTypes = [
    'revenusSalarie',
    'stage',
    'revenusStageFormationPro',
    'allocationsChomage',
    'allocationSecurisationPro',
    'primeRepriseActivite',
    'aide_logement',
    'af',
    'cf',
    'asf',
    'rsa',
    'aspa',
    'asi',
    'ass',
    'aah',
    'aeeh',
    'pch',
    'paje_base',
    'clca',
    'prepare',
    'indJourMaternite',
    'indJourMaladie',
    'indJourMaladieProf',
    'indJourAccidentDuTravail',
    'indChomagePartiel',
    'indVolontariat',
    'dedommagementAmiante',
    'pensionsAlimentaires',
    'pensionsAlimentairesVersees',
    'prestationCompensatoire',
    'pensionsRetraitesRentes',
    'retraiteCombattant',
    'pensionsInvalidite',
    'bourseEnseignementSup',
    'bourseRecherche',
    'gainsExceptionnels',
    'revenusLocatifs',
    'revenusDuCapital',
    'caAutoEntrepreneur',
    'caMicroEntreprise',
    'autresRevenusTns',
    'caAutresRevenusTns',
    'revenusAgricolesTns',

    // rnc
    'rncRevenusActivite',
    'rncAutresRevenus',
    'rncPensionsRetraitesRentes',
    'fraisReelsDeductibles',
    'rncPensionsAlimentaires',
    'rncPensionsAlimentairesVersees'
];

var RessourceSchema = new Schema({
    periode: { type: String },
    type: { type: String, enum: ressourceTypes },
    montant: { type: Number, required: true }
});

var specificSituations = [
    'demandeur_emploi',
    'etudiant',
    'retraite',
    'handicap',
    'boursier',
    'inapte_travail',
    'autre'
];

var statutsMaritaux = [
    'mariage',
    'pacs',
    'union_libre',
];

var IndividuDef = {
    firstName: String,
    enceinte: Boolean,
    boursier: Boolean,
    statutMarital: { type: String, enum: statutsMaritaux },
    dateArretDeTravail: Date,
    dateDernierContratTravail: Date,
    isolementRecent: Boolean,
    dateDeNaissance: Date,
    specificSituations: [{ type: String, enum: specificSituations }],
    scolarite: { type: String, enum: ['inconnue', 'college', 'lycee'] },
    nationalite: { type: String, enum: ['fr', 'ue', 'autre'] },
    gardeAlternee: Boolean,
    aCharge: Boolean,
    fiscalementIndependant: Boolean,
    habiteChezParents: Boolean,
    place: Boolean,
    perteAutonomie: Boolean,
    assPreconditionRemplie: Boolean,
    role: { type: String, enum: ['demandeur', 'conjoint', 'enfant'] },
    ressources: [RessourceSchema],
    ressourcesYearlyApproximation: Object,
    interruptedRessources: [{ type: String, enum: ressourceTypes }],
    autresRevenusTnsActiviteType: { type: String, enum: ['achat_revente', 'bic', 'bnc'] },
    autresRevenusTnsEmployes: Boolean,
    tauxIncapacite: { type: String, enum: ['nul', 'moins50', 'moins80', 'plus80'] },
    microEntrepriseActiviteType: { type: String, enum: ['achat_revente', 'bic', 'bnc'] },
    autoEntrepreneurActiviteType: { type: String, enum: ['achat_revente', 'bic', 'bnc'] }
};

var IndividuSchema = new Schema(IndividuDef);

var AdresseDef = {
    adresse: String,
    codePostal: String,
    codeInsee: String,
    ville: String,
    pays: String
};

var LogementDef = {
    primoAccedant: Boolean,
    membreFamilleProprietaire: Boolean,
    loyer: Number,
    charges: Number,
    adresse: AdresseDef,
    type: { type: String, enum: ['locataire', 'proprietaire', 'heberge', 'sansDomicile'] },
    inhabitantForThreeYearsOutOfLastFive: Boolean,
    colocation: Boolean,
    participationFrais: Boolean,
    locationType: { type: String, enum: ['foyer', 'nonmeuble', 'meublehotel', 'hlm'] },
    isChambre: Boolean,
};

var SituationSchema = new Schema({
    _updated: Date,
    status: { type: String, default: 'new' },
    dateDeValeur: { type: Date, default: Date.now },
    logement: LogementDef,
    individus: [IndividuSchema],
    patrimoine: {
        captured: Boolean,
        revenusLocatifs: [RessourceSchema],
        valeurLocativeImmoNonLoue: Number,
        valeurLocativeTerrainNonLoue: Number,
        revenusDuCapital: [RessourceSchema],
        epargneSurLivret: Number,
        epargneSansRevenus: Number
    },
    ressourcesYearMoins2Captured: { type: Boolean, default: false },
    rfr: Schema.Types.Mixed,
    token: String
});

SituationSchema.methods = {

    submit: function(done) {
        if (this.status !== 'new') done(new Error('Not a new situation. Cannot be submitted.'));
        this.set('status', 'pending').save(done);
    },

    simulate: function(done) {
        openfisca.simulate(this, done);
    }

};

SituationSchema.pre('save', function(next) {
    if (!this.isNew) next();
    var situation = this;
    utils.generateToken(function(err, generatedToken) {
        if (err) return next(err);
        situation.token = generatedToken;
        next();
    });
});

mongoose.model('Situation', SituationSchema);
<commit_msg>[To Revert] Temporary changes needs by migration<commit_after>/*
** Module dependencies
*/
var mongoose = require('mongoose');
var utils = require('../utils');
var openfisca = require('../simulation/openfisca');

var Schema = mongoose.Schema;

var ressourceTypes = [
    'revenusSalarie',
    'stage',
    'revenusStageFormationPro',
    'allocationsChomage',
    'allocationSecurisationPro',
    'primeRepriseActivite',
    'aide_logement',
    'af',
    'cf',
    'asf',
    'rsa',
    'aspa',
    'asi',
    'ass',
    'aah',
    'aeeh',
    'pch',
    'paje_base',
    'clca',
    'prepare',
    'indJourMaternite',
    'indJourMaladie',
    'indJourMaladieProf',
    'indJourAccidentDuTravail',
    'indChomagePartiel',
    'indVolontariat',
    'dedommagementAmiante',
    'pensionsAlimentaires',
    'pensionsAlimentairesVersees',
    'prestationCompensatoire',
    'pensionsRetraitesRentes',
    'retraiteCombattant',
    'pensionsInvalidite',
    'bourseEnseignementSup',
    'bourseRecherche',
    'gainsExceptionnels',
    'revenusLocatifs',
    'revenusDuCapital',
    'caAutoEntrepreneur',
    'caMicroEntreprise',
    'autresRevenusTns',
    'caAutresRevenusTns',
    'revenusAgricolesTns',

    // rnc
    'rncRevenusActivite',
    'rncAutresRevenus',
    'rncPensionsRetraitesRentes',
    'fraisReelsDeductibles',
    'rncPensionsAlimentaires',
    'rncPensionsAlimentairesVersees'
];

var RessourceSchema = new Schema({
    periode: { type: String },
    type: { type: String, enum: ressourceTypes },
    montant: { type: Number, required: true }
});

var specificSituations = [
    'demandeur_emploi',
    'etudiant',
    'retraite',
    'handicap',
    'boursier',
    'inapte_travail',
    'autre'
];

var statutsMaritaux = [
    'mariage',
    'pacs',
    'union_libre',
];

var IndividuDef = {
    firstName: String,
    enceinte: Boolean,
    boursier: Boolean,
    statutMarital: { type: String, enum: statutsMaritaux },
    dateArretDeTravail: Date,
    dateDernierContratTravail: Date,
    isolementRecent: Boolean,
    dateDeNaissance: Date,
    situationsPro: Object,
    // specificSituations: [{ type: String, enum: specificSituations }],
    specificSituations: Object,
    scolarite: { type: String, enum: ['inconnue', 'college', 'lycee'] },
    nationalite: { type: String, enum: ['fr', 'ue', 'autre'] },
    gardeAlternee: Boolean,
    aCharge: Boolean,
    fiscalementIndependant: Boolean,
    habiteChezParents: Boolean,
    place: Boolean,
    perteAutonomie: Boolean,
    assPreconditionRemplie: Boolean,
    role: { type: String, enum: ['demandeur', 'conjoint', 'enfant'] },
    ressources: [RessourceSchema],
    ressourcesYearlyApproximation: Object,
    interruptedRessources: [{ type: String, enum: ressourceTypes }],
    autresRevenusTnsActiviteType: { type: String, enum: ['achat_revente', 'bic', 'bnc'] },
    autresRevenusTnsEmployes: Boolean,
    tauxIncapacite: { type: String, enum: ['nul', 'moins50', 'moins80', 'plus80'] },
    microEntrepriseActiviteType: { type: String, enum: ['achat_revente', 'bic', 'bnc'] },
    autoEntrepreneurActiviteType: { type: String, enum: ['achat_revente', 'bic', 'bnc'] }
};

var IndividuSchema = new Schema(IndividuDef);

var AdresseDef = {
    adresse: String,
    codePostal: String,
    codeInsee: String,
    ville: String,
    pays: String
};

var LogementDef = {
    primoAccedant: Boolean,
    membreFamilleProprietaire: Boolean,
    loyer: Number,
    charges: Number,
    adresse: AdresseDef,
    type: { type: String, enum: ['locataire', 'proprietaire', 'heberge', 'sansDomicile'] },
    inhabitantForThreeYearsOutOfLastFive: Boolean,
    colocation: Boolean,
    participationFrais: Boolean,
    locationType: { type: String, enum: ['foyer', 'nonmeuble', 'meublehotel', 'hlm'] },
    isChambre: Boolean,
};

var SituationSchema = new Schema({
    _updated: Date,
    status: { type: String, default: 'new' },
    dateDeValeur: { type: Date, default: Date.now },
    logement: LogementDef,
    individus: [IndividuSchema],
    patrimoine: {
        captured: Boolean,
        revenusLocatifs: [RessourceSchema],
        valeurLocativeImmoNonLoue: Number,
        valeurLocativeTerrainNonLoue: Number,
        revenusDuCapital: [RessourceSchema],
        epargneSurLivret: Number,
        epargneSansRevenus: Number
    },
    ressourcesYearMoins2Captured: { type: Boolean, default: false },
    rfr: Schema.Types.Mixed,
    token: String
});

SituationSchema.methods = {

    submit: function(done) {
        if (this.status !== 'new') done(new Error('Not a new situation. Cannot be submitted.'));
        this.set('status', 'pending').save(done);
    },

    simulate: function(done) {
        openfisca.simulate(this, done);
    }

};

SituationSchema.pre('save', function(next) {
    if (!this.isNew) next();
    var situation = this;
    utils.generateToken(function(err, generatedToken) {
        if (err) return next(err);
        situation.token = generatedToken;
        next();
    });
});

mongoose.model('Situation', SituationSchema);
<|endoftext|>


<commit_before>'use strict'

const _ = require('lodash')

const Type = {
  NULL: 0,
  BOOLEAN: 1,
  NUMBER: 2,
  STRING: 3,
  ARRAY: 4,
  OBJECT: 5,
  UNKNOWN: 6
}

const decoderDefaults = {
  optional: false
}

function jsonDecode (dataInput, decoderInput) {
  const dataType = dataToType(dataInput)

  // VOLATILE: what if user has object with type as a key - { type: stuff }
  const isDecoderAsObject = _.isObject(decoderInput) && 'type' in decoderInput
  const decoderInputValue = isDecoderAsObject ? decoderInput.type : decoderInput
  const decoder = Object.assign(
    {},
    decoderDefaults,
    {
      value: decoderInputValue,
      type: decoderToType(decoderInputValue)
    }
  )

  switch (decoder.type) {
    case Type.NULL:
    case Type.BOOLEAN:
    case Type.NUMBER:
    case Type.STRING:
      if (dataType !== decoder.type) {
        throw new TypeError(`Expected data type "${typeToString(decoder.type)}", got data type "${typeToString(dataType)}"`)
      }
      break
    case Type.ARRAY:
      if (decoder.value.length === 0) {
        throw new Error(`Decoder is specified as Array but type of its values is not specified`)
      } else if (decoder.value.length >= 2) {
        throw new Error(`More than one type of Array values is specified`)
      }

      const decoderArrayValue = decoder.value[0]
      const typeArrayDecoder = decoderToType(decoderArrayValue)
      switch (typeArrayDecoder) {
        case Type.NULL:
        case Type.BOOLEAN:
        case Type.NUMBER:
        case Type.STRING:
          for (const arrayValue of dataInput) {
            const typeArrayValue = dataToType(arrayValue)
            if (typeArrayValue !== typeArrayDecoder) {
              throw new TypeError(`Array value is ${arrayValue} does not match the decoder ${typeToString(typeArrayDecoder)}.`)
            }
          }
          break
        case Type.ARRAY:
        case Type.OBJECT:
          for (const arrayValue of dataInput) {
            jsonDecode(arrayValue, decoderArrayValue)
          }
          break
      }
      break
    case Type.OBJECT:

      if (Object.keys(decoder.value).length === 0) {
        throw new Error(`Decoder is specified as Object there are no keys specified in the decoder.`)
      }

      for (const decoderObjectKey in decoder.value) {
        if (!decoder.value.hasOwnProperty(decoderObjectKey)) break

        if (!(decoderObjectKey in dataInput)) {
          throw new Error(`Key "${decoderObjectKey}" is missing in the data ${dataInput}.`)
        }

        const decoderObjectValue = decoder.value[decoderObjectKey]
        const objectValue = dataInput[decoderObjectKey]
        const typeObjectDecoder = decoderToType(decoderObjectValue)
        const typeObjectValue = dataToType(objectValue)

        switch (typeObjectDecoder) {
          case Type.NULL:
          case Type.BOOLEAN:
          case Type.NUMBER:
          case Type.STRING:
            if (typeObjectDecoder !== typeObjectValue) {
              throw new TypeError(`Object value "${objectValue}" is not the same type of the decoder which is "${typeToString(typeObjectDecoder)}".`)
            }
            break
          case Type.ARRAY:
          case Type.OBJECT:
            jsonDecode(objectValue, decoderObjectValue)
            break
        }
      }

      break
    default:
      throw new TypeError(`Unknown decoder type ${decoder.value}.`)
  }

  return dataInput
}

function decoderToType (input) {
  switch (input) {
    case null: return Type.NULL
    case Boolean: return Type.BOOLEAN
    case Number: return Type.NUMBER
    case String: return Type.STRING
    default:
      if (_.isArray(input)) return Type.ARRAY
      else if (_.isObject(input)) return Type.OBJECT
      else return Type.UNKNOWN
  }
}

function dataToType (input) {
  if (_.isNull(input)) return Type.NULL
  else if (_.isBoolean(input)) return Type.BOOLEAN
  else if (_.isNumber(input)) return Type.NUMBER
  else if (_.isString(input)) return Type.STRING
  else if (_.isArray(input)) return Type.ARRAY
  else if (_.isObject(input)) return Type.OBJECT
  else return Type.UNKNOWN
}

function typeToString (type) {
  switch (type) {
    case Type.NULL: return 'null'
    case Type.BOOLEAN: return 'bool'
    case Type.NUMBER: return 'number'
    case Type.STRING: return 'string'
    case Type.ARRAY: return 'array'
    case Type.OBJECT: return 'object'
    case Type.UNKNOWN: return 'unknown'
  }
}

module.exports = jsonDecode
<commit_msg>fix bug where decoding simple types agains collections did not fail<commit_after>'use strict'

const _ = require('lodash')

const Type = {
  NULL: 0,
  BOOLEAN: 1,
  NUMBER: 2,
  STRING: 3,
  ARRAY: 4,
  OBJECT: 5,
  UNKNOWN: 6
}

const decoderDefaults = {
  optional: false
}

function jsonDecode (dataInput, decoderInput) {
  const dataType = dataToType(dataInput)

  // VOLATILE: what if user has object with type as a key - { type: stuff }
  const isDecoderAsObject = _.isObject(decoderInput) && 'type' in decoderInput
  const decoderInputValue = isDecoderAsObject ? decoderInput.type : decoderInput
  const decoder = Object.assign(
    {},
    decoderDefaults,
    {
      value: decoderInputValue,
      type: decoderToType(decoderInputValue)
    }
  )

  if (dataType !== decoder.type) {
    throw new TypeError(`Expected data type "${typeToString(decoder.type)}", got data type "${typeToString(dataType)}"`)
  }

  switch (decoder.type) {
    case Type.NULL:
    case Type.BOOLEAN:
    case Type.NUMBER:
    case Type.STRING:
      break
    case Type.ARRAY:
      if (decoder.value.length === 0) {
        throw new Error(`Decoder is specified as Array but type of its values is not specified`)
      } else if (decoder.value.length >= 2) {
        throw new Error(`More than one type of Array values is specified`)
      }

      const decoderArrayValue = decoder.value[0]
      const typeArrayDecoder = decoderToType(decoderArrayValue)
      switch (typeArrayDecoder) {
        case Type.NULL:
        case Type.BOOLEAN:
        case Type.NUMBER:
        case Type.STRING:
          for (const arrayValue of dataInput) {
            const typeArrayValue = dataToType(arrayValue)
            if (typeArrayValue !== typeArrayDecoder) {
              throw new TypeError(`Array value is ${arrayValue} does not match the decoder ${typeToString(typeArrayDecoder)}.`)
            }
          }
          break
        case Type.ARRAY:
        case Type.OBJECT:
          for (const arrayValue of dataInput) {
            jsonDecode(arrayValue, decoderArrayValue)
          }
          break
      }
      break
    case Type.OBJECT:

      if (Object.keys(decoder.value).length === 0) {
        throw new Error(`Decoder is specified as Object there are no keys specified in the decoder.`)
      }

      for (const decoderObjectKey in decoder.value) {
        if (!decoder.value.hasOwnProperty(decoderObjectKey)) break

        if (!(decoderObjectKey in dataInput)) {
          throw new Error(`Key "${decoderObjectKey}" is missing in the data ${dataInput}.`)
        }

        const decoderObjectValue = decoder.value[decoderObjectKey]
        const objectValue = dataInput[decoderObjectKey]
        const typeObjectDecoder = decoderToType(decoderObjectValue)
        const typeObjectValue = dataToType(objectValue)

        switch (typeObjectDecoder) {
          case Type.NULL:
          case Type.BOOLEAN:
          case Type.NUMBER:
          case Type.STRING:
            if (typeObjectDecoder !== typeObjectValue) {
              throw new TypeError(`Object value "${objectValue}" is not the same type of the decoder which is "${typeToString(typeObjectDecoder)}".`)
            }
            break
          case Type.ARRAY:
          case Type.OBJECT:
            jsonDecode(objectValue, decoderObjectValue)
            break
        }
      }

      break
    default:
      throw new TypeError(`Unknown decoder type ${decoder.value}.`)
  }

  return dataInput
}

function decoderToType (input) {
  switch (input) {
    case null: return Type.NULL
    case Boolean: return Type.BOOLEAN
    case Number: return Type.NUMBER
    case String: return Type.STRING
    default:
      if (_.isArray(input)) return Type.ARRAY
      else if (_.isObject(input)) return Type.OBJECT
      else return Type.UNKNOWN
  }
}

function dataToType (input) {
  if (_.isNull(input)) return Type.NULL
  else if (_.isBoolean(input)) return Type.BOOLEAN
  else if (_.isNumber(input)) return Type.NUMBER
  else if (_.isString(input)) return Type.STRING
  else if (_.isArray(input)) return Type.ARRAY
  else if (_.isObject(input)) return Type.OBJECT
  else return Type.UNKNOWN
}

function typeToString (type) {
  switch (type) {
    case Type.NULL: return 'null'
    case Type.BOOLEAN: return 'bool'
    case Type.NUMBER: return 'number'
    case Type.STRING: return 'string'
    case Type.ARRAY: return 'array'
    case Type.OBJECT: return 'object'
    case Type.UNKNOWN: return 'unknown'
  }
}

module.exports = jsonDecode
<|endoftext|>


<commit_before>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

// An Algorithm for Automatically Fitting Digitized Curves
// by Philip J. Schneider
// from "Graphics Gems", Academic Press, 1990
var PathFitter = Base.extend({
	initialize: function(path, error) {
		this.points = [];
		var segments = path._segments,
			prev;
		// Copy over points from path and filter out adjacent duplicates.
		for (var i = 0, l = segments.length; i < l; i++) {
			var point = segments[i].point.clone();
			if (!prev || !prev.equals(point)) {
				this.points[i] = point;
				prev = point;
			}
		}
		this.error = error;
	},

	fit: function() {
		this.segments = [new Segment(this.points[0])];
		this.fitCubic(0, this.points.length - 1,
				// Left Tangent
				this.points[1].subtract(this.points[0]).normalize(),
				// Right Tangent
				this.points[this.points.length - 2].subtract(
					this.points[this.points.length - 1]).normalize());
		return this.segments;
	},

	// Fit a Bezier curve to a (sub)set of digitized points
	fitCubic: function(first, last, tan1, tan2) {
		//	Use heuristic if region only has two points in it
		if (last - first == 1) {
			var pt1 = this.points[first],
				pt2 = this.points[last],
				dist = pt1.getDistance(pt2) / 3;
			this.addCurve([pt1, pt1.add(tan1.normalize(dist)),
					pt2.add(tan2.normalize(dist)), pt2]);
			return;
		}
		// Parameterize points, and attempt to fit curve
		var uPrime = this.chordLengthParameterize(first, last),
			maxError = Math.max(this.error, this.error * this.error),
			error,
			split;
		// Try 4 iterations
		for (var i = 0; i <= 4; i++) {
			var curve = this.generateBezier(first, last, uPrime, tan1, tan2);
			//	Find max deviation of points to fitted curve
			var max = this.findMaxError(first, last, curve, uPrime);
			if (max.error < this.error) {
				this.addCurve(curve);
				return;
			}
			split = max.index;
			// If error not too large, try reparameterization and iteration
			if (max.error >= maxError)
				break;
			this.reparameterize(first, last, uPrime, curve);
			maxError = max.error;
		}
		// Fitting failed -- split at max error point and fit recursively
		var V1 = this.points[split - 1].subtract(this.points[split]),
			V2 = this.points[split].subtract(this.points[split + 1]),
			tanCenter = V1.add(V2).divide(2).normalize();
		this.fitCubic(first, split, tan1, tanCenter);
		this.fitCubic(split, last, tanCenter.negate(), tan2);
	},

	addCurve: function(curve) {
		var prev = this.segments[this.segments.length - 1];
		prev.setHandleOut(curve[1].subtract(curve[0]));
		this.segments.push(
				new Segment(curve[3], curve[2].subtract(curve[3])));
	},

	// Use least-squares method to find Bezier control points for region.
	generateBezier: function(first, last, uPrime, tan1, tan2) {
		var epsilon = Numerical.TOLERANCE,
			pt1 = this.points[first],
			pt2 = this.points[last],
			// Create the C and X matrices
		 	C = [[0, 0], [0, 0]],
			X = [0, 0];

		for (var i = 0, l = last - first + 1; i < l; i++) {
			var u = uPrime[i],
				t = 1 - u,
				b = 3 * u * t,
				b0 = t * t * t,
				b1 = b * t,
				b2 = b * u,
				b3 = u * u * u,
				a1 = tan1.normalize(b1),
				a2 = tan2.normalize(b2),
				tmp = this.points[first + i]
					.subtract(pt1.multiply(b0 + b1))
					.subtract(pt2.multiply(b2 + b3));
			C[0][0] += a1.dot(a1);
			C[0][1] += a1.dot(a2);
			// C[1][0] += a1.dot(a2);
			C[1][0] = C[0][1];
			C[1][1] += a2.dot(a2);
			X[0] += a1.dot(tmp);
			X[1] += a2.dot(tmp);
		}

		// Compute the determinants of C and X
		var detC0C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1],
			alpha1, alpha2;
		if (Math.abs(detC0C1) > epsilon) {
			// Kramer's rule
			var detC0X  = C[0][0] * X[1]    - C[1][0] * X[0],
				detXC1  = X[0]    * C[1][1] - X[1]    * C[0][1];
			// Derive alpha values
			alpha1 = detXC1 / detC0C1;
			alpha2 = detC0X / detC0C1;
		} else {
			// Matrix is under-determined, try assuming alpha1 == alpha2
			var c0 = C[0][0] + C[0][1],
				c1 = C[1][0] + C[1][1];
			if (Math.abs(c0) > epsilon) {
				alpha1 = alpha2 = X[0] / c0;
			} else if (Math.abs(c0) > epsilon) {
				alpha1 = alpha2 = X[1] / c1;
			} else {
				// Handle below
				alpha1 = alpha2 = 0.;
			}
		}

		// If alpha negative, use the Wu/Barsky heuristic (see text)
		// (if alpha is 0, you get coincident control points that lead to
		// divide by zero in any subsequent NewtonRaphsonRootFind() call.
		var segLength = pt2.getDistance(pt1);
		epsilon *= segLength;
		if (alpha1 < epsilon || alpha2 < epsilon) {
			// fall back on standard (probably inaccurate) formula,
			// and subdivide further if needed.
			alpha1 = alpha2 = segLength / 3;
		}

		// First and last control points of the Bezier curve are
		// positioned exactly at the first and last data points
		// Control points 1 and 2 are positioned an alpha distance out
		// on the tangent vectors, left and right, respectively
		return [pt1, pt1.add(tan1.normalize(alpha1)),
				pt2.add(tan2.normalize(alpha2)), pt2];
	},

	// Given set of points and their parameterization, try to find
	// a better parameterization.
	reparameterize: function(first, last, u, curve) {
		for (var i = first; i <= last; i++) {
			u[i - first] = this.findRoot(curve, this.points[i], u[i - first]);
		}
	},

	// Use Newton-Raphson iteration to find better root.
	findRoot: function(curve, point, u) {
		var curve1 = [],
			curve2 = [];
		// Generate control vertices for Q'
		for (var i = 0; i <= 2; i++) {
			curve1[i] = curve[i + 1].subtract(curve[i]).multiply(3);
		}
		// Generate control vertices for Q''
		for (var i = 0; i <= 1; i++) {
			curve2[i] = curve1[i + 1].subtract(curve1[i]).multiply(2);
		}
		// Compute Q(u), Q'(u) and Q''(u)
		var pt = this.evaluate(3, curve, u),
		 	pt1 = this.evaluate(2, curve1, u),
		 	pt2 = this.evaluate(1, curve2, u),
		 	diff = pt.subtract(point),
			df = pt1.dot(pt1) + diff.dot(pt2);
		// Compute f(u) / f'(u)
		if (Math.abs(df) < Numerical.TOLERANCE)
			return u;
		// u = u - f(u) / f'(u)
		return u - diff.dot(pt1) / df;
	},

	// Evaluate a Bezier curve at a particular parameter value
	evaluate: function(degree, curve, t) {
		// Copy array
		var tmp = curve.slice();
		// Triangle computation
		for (var i = 1; i <= degree; i++) {
			for (var j = 0; j <= degree - i; j++) {
				tmp[j] = tmp[j].multiply(1 - t).add(tmp[j + 1].multiply(t));
			}
		}
		return tmp[0];
	},

	// Assign parameter values to digitized points
	// using relative distances between points.
	chordLengthParameterize: function(first, last) {
		var u = [0];
		for (var i = first + 1; i <= last; i++) {
			u[i - first] = u[i - first - 1]
					+ this.points[i].getDistance(this.points[i - 1]);
		}
		for (var i = 1, m = last - first; i <= m; i++) {
			u[i] /= u[m];
		}
		return u;
	},

	// Find the maximum squared distance of digitized points to fitted curve.
	findMaxError: function(first, last, curve, u) {
		var index = Math.floor((last - first + 1) / 2),
			maxDist = 0;
		for (var i = first + 1; i < last; i++) {
			var P = this.evaluate(3, curve, u[i - first]);
			var v = P.subtract(this.points[i]);
			var dist = v.x * v.x + v.y * v.y; // squared
			if (dist >= maxDist) {
				maxDist = dist;
				index = i;
			}
		}
		return {
			error: maxDist,
			index: index
		};
	}
});
<commit_msg>Fix filtering of duplace points in path fitting code.<commit_after>/*
 * Paper.js
 *
 * This file is part of Paper.js, a JavaScript Vector Graphics Library,
 * based on Scriptographer.org and designed to be largely API compatible.
 * http://paperjs.org/
 * http://scriptographer.org/
 *
 * Distributed under the MIT license. See LICENSE file for details.
 *
 * Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
 * http://lehni.org/ & http://jonathanpuckey.com/
 *
 * All rights reserved.
 */

// An Algorithm for Automatically Fitting Digitized Curves
// by Philip J. Schneider
// from "Graphics Gems", Academic Press, 1990
var PathFitter = Base.extend({
	initialize: function(path, error) {
		this.points = [];
		var segments = path._segments,
			prev;
		// Copy over points from path and filter out adjacent duplicates.
		for (var i = 0, l = segments.length; i < l; i++) {
			var point = segments[i].point.clone();
			if (!prev || !prev.equals(point)) {
				this.points.push(point);
				prev = point;
			}
		}
		this.error = error;
	},

	fit: function() {
		this.segments = [new Segment(this.points[0])];
		this.fitCubic(0, this.points.length - 1,
				// Left Tangent
				this.points[1].subtract(this.points[0]).normalize(),
				// Right Tangent
				this.points[this.points.length - 2].subtract(
					this.points[this.points.length - 1]).normalize());
		return this.segments;
	},

	// Fit a Bezier curve to a (sub)set of digitized points
	fitCubic: function(first, last, tan1, tan2) {
		//	Use heuristic if region only has two points in it
		if (last - first == 1) {
			var pt1 = this.points[first],
				pt2 = this.points[last],
				dist = pt1.getDistance(pt2) / 3;
			this.addCurve([pt1, pt1.add(tan1.normalize(dist)),
					pt2.add(tan2.normalize(dist)), pt2]);
			return;
		}
		// Parameterize points, and attempt to fit curve
		var uPrime = this.chordLengthParameterize(first, last),
			maxError = Math.max(this.error, this.error * this.error),
			error,
			split;
		// Try 4 iterations
		for (var i = 0; i <= 4; i++) {
			var curve = this.generateBezier(first, last, uPrime, tan1, tan2);
			//	Find max deviation of points to fitted curve
			var max = this.findMaxError(first, last, curve, uPrime);
			if (max.error < this.error) {
				this.addCurve(curve);
				return;
			}
			split = max.index;
			// If error not too large, try reparameterization and iteration
			if (max.error >= maxError)
				break;
			this.reparameterize(first, last, uPrime, curve);
			maxError = max.error;
		}
		// Fitting failed -- split at max error point and fit recursively
		var V1 = this.points[split - 1].subtract(this.points[split]),
			V2 = this.points[split].subtract(this.points[split + 1]),
			tanCenter = V1.add(V2).divide(2).normalize();
		this.fitCubic(first, split, tan1, tanCenter);
		this.fitCubic(split, last, tanCenter.negate(), tan2);
	},

	addCurve: function(curve) {
		var prev = this.segments[this.segments.length - 1];
		prev.setHandleOut(curve[1].subtract(curve[0]));
		this.segments.push(
				new Segment(curve[3], curve[2].subtract(curve[3])));
	},

	// Use least-squares method to find Bezier control points for region.
	generateBezier: function(first, last, uPrime, tan1, tan2) {
		var epsilon = Numerical.TOLERANCE,
			pt1 = this.points[first],
			pt2 = this.points[last],
			// Create the C and X matrices
		 	C = [[0, 0], [0, 0]],
			X = [0, 0];

		for (var i = 0, l = last - first + 1; i < l; i++) {
			var u = uPrime[i],
				t = 1 - u,
				b = 3 * u * t,
				b0 = t * t * t,
				b1 = b * t,
				b2 = b * u,
				b3 = u * u * u,
				a1 = tan1.normalize(b1),
				a2 = tan2.normalize(b2),
				tmp = this.points[first + i]
					.subtract(pt1.multiply(b0 + b1))
					.subtract(pt2.multiply(b2 + b3));
			C[0][0] += a1.dot(a1);
			C[0][1] += a1.dot(a2);
			// C[1][0] += a1.dot(a2);
			C[1][0] = C[0][1];
			C[1][1] += a2.dot(a2);
			X[0] += a1.dot(tmp);
			X[1] += a2.dot(tmp);
		}

		// Compute the determinants of C and X
		var detC0C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1],
			alpha1, alpha2;
		if (Math.abs(detC0C1) > epsilon) {
			// Kramer's rule
			var detC0X  = C[0][0] * X[1]    - C[1][0] * X[0],
				detXC1  = X[0]    * C[1][1] - X[1]    * C[0][1];
			// Derive alpha values
			alpha1 = detXC1 / detC0C1;
			alpha2 = detC0X / detC0C1;
		} else {
			// Matrix is under-determined, try assuming alpha1 == alpha2
			var c0 = C[0][0] + C[0][1],
				c1 = C[1][0] + C[1][1];
			if (Math.abs(c0) > epsilon) {
				alpha1 = alpha2 = X[0] / c0;
			} else if (Math.abs(c0) > epsilon) {
				alpha1 = alpha2 = X[1] / c1;
			} else {
				// Handle below
				alpha1 = alpha2 = 0.;
			}
		}

		// If alpha negative, use the Wu/Barsky heuristic (see text)
		// (if alpha is 0, you get coincident control points that lead to
		// divide by zero in any subsequent NewtonRaphsonRootFind() call.
		var segLength = pt2.getDistance(pt1);
		epsilon *= segLength;
		if (alpha1 < epsilon || alpha2 < epsilon) {
			// fall back on standard (probably inaccurate) formula,
			// and subdivide further if needed.
			alpha1 = alpha2 = segLength / 3;
		}

		// First and last control points of the Bezier curve are
		// positioned exactly at the first and last data points
		// Control points 1 and 2 are positioned an alpha distance out
		// on the tangent vectors, left and right, respectively
		return [pt1, pt1.add(tan1.normalize(alpha1)),
				pt2.add(tan2.normalize(alpha2)), pt2];
	},

	// Given set of points and their parameterization, try to find
	// a better parameterization.
	reparameterize: function(first, last, u, curve) {
		for (var i = first; i <= last; i++) {
			u[i - first] = this.findRoot(curve, this.points[i], u[i - first]);
		}
	},

	// Use Newton-Raphson iteration to find better root.
	findRoot: function(curve, point, u) {
		var curve1 = [],
			curve2 = [];
		// Generate control vertices for Q'
		for (var i = 0; i <= 2; i++) {
			curve1[i] = curve[i + 1].subtract(curve[i]).multiply(3);
		}
		// Generate control vertices for Q''
		for (var i = 0; i <= 1; i++) {
			curve2[i] = curve1[i + 1].subtract(curve1[i]).multiply(2);
		}
		// Compute Q(u), Q'(u) and Q''(u)
		var pt = this.evaluate(3, curve, u),
		 	pt1 = this.evaluate(2, curve1, u),
		 	pt2 = this.evaluate(1, curve2, u),
		 	diff = pt.subtract(point),
			df = pt1.dot(pt1) + diff.dot(pt2);
		// Compute f(u) / f'(u)
		if (Math.abs(df) < Numerical.TOLERANCE)
			return u;
		// u = u - f(u) / f'(u)
		return u - diff.dot(pt1) / df;
	},

	// Evaluate a Bezier curve at a particular parameter value
	evaluate: function(degree, curve, t) {
		// Copy array
		var tmp = curve.slice();
		// Triangle computation
		for (var i = 1; i <= degree; i++) {
			for (var j = 0; j <= degree - i; j++) {
				tmp[j] = tmp[j].multiply(1 - t).add(tmp[j + 1].multiply(t));
			}
		}
		return tmp[0];
	},

	// Assign parameter values to digitized points
	// using relative distances between points.
	chordLengthParameterize: function(first, last) {
		var u = [0];
		for (var i = first + 1; i <= last; i++) {
			u[i - first] = u[i - first - 1]
					+ this.points[i].getDistance(this.points[i - 1]);
		}
		for (var i = 1, m = last - first; i <= m; i++) {
			u[i] /= u[m];
		}
		return u;
	},

	// Find the maximum squared distance of digitized points to fitted curve.
	findMaxError: function(first, last, curve, u) {
		var index = Math.floor((last - first + 1) / 2),
			maxDist = 0;
		for (var i = first + 1; i < last; i++) {
			var P = this.evaluate(3, curve, u[i - first]);
			var v = P.subtract(this.points[i]);
			var dist = v.x * v.x + v.y * v.y; // squared
			if (dist >= maxDist) {
				maxDist = dist;
				index = i;
			}
		}
		return {
			error: maxDist,
			index: index
		};
	}
});
<|endoftext|>


<commit_before>const logger = require('../modules/logger')
const config = require('../config/config')
const os = require('os')
const fs = require('fs-extra')
const ns = require('../models/nodeserver')
const childProcess = require('child_process')

module.exports = {
  /*
   * Array of local NodeServer process objects. Corresponds to config.NodeServer[profileNum]
   * {process: child_process.spawn, env: {}, args: {}, profileNum: #}
   */
  nodeProcesses: new Array(11),

  stopChildNodeServer(ns) {
    if (!(this.nodeProcesses[ns.profileNum])) { return }
    logger.debug(`NSChild: Stopping Child NodeServer ${ns.name}`)
    this.nodeProcesses[ns.profileNum].kill()
  },

  runInstallProcess(name) {
    if (name) {
      let nsPath = `${os.homedir()}/.polyglot/nodeservers/${name}/`
      if (fs.existsSync(nsPath + 'server.json')) {
        try {
          let server = require(nsPath + 'server.json')
          if (server.hasOwnProperty('install')) {
            let opts = {
              cwd: nsPath,
              shell: '/bin/bash'
            }
            let runCmd = `./${server.install}`
            let installProcess = childProcess.spawn(runCmd, [], opts)
            installProcess.stdout.on('data', (data) => {
              logger.debug(`NSChild: ${name} Install : ${data}`)
            })
            installProcess.on('close', (code) => {
              logger.debug(`NSChild: ${name} install process exited with cause code: ${code}`)
            })
            installProcess.on('error', (err) => {
              logger.debug(`NSChild: ${name} install process error: ${err}`)
            })
          } else {
            logger.debug(`NSChild: ${name} does not have an install process defined. Run any install scripts for the nodeserver manually if necessary.`)
          }
        } catch (e) {
          logger.error(`NSChild: Install failed - ${e}`)
        }
      }
    }
  },

  runChildNodeServer(ns) {
    if (this.nodeProcesses[ns.profileNum]) { return }
    if (ns.homeDir) {
      if (fs.existsSync(ns.homeDir + 'server.json')) {
        try {
          let server = require(ns.homeDir + 'server.json')
          if (server.hasOwnProperty('type') && server.hasOwnProperty('executable')) {
            let init = JSON.stringify({
              ipAddress: config.settings.ipAddress,
              mqttHost: config.settings.mqttHost,
              mqttPort: config.settings.mqttPort.toString(),
              profileNum: ns.profileNum
            })
            let opts = {
              cwd: ns.homeDir,
              shell: '/bin/bash'
            }
            let runCmd = `./${server.executable}`
            try {
              logger.info(`NS: Starting Local NodeServer ${ns.name} profile number ${ns.profileNum}`)
              this.nodeProcesses[ns.profileNum] = childProcess.spawn(runCmd, [], opts)
              this.nodeProcesses[ns.profileNum].on('EPIPE', (err) => {
                logger.error(`NS: Caught Error trying to write to NodeServer ${ns.name}: ${err}`)
                delete this.nodeProcesses[ns.profileNum]
              })
              this.nodeProcesses[ns.profileNum].on('error', (err) => {
                logger.error(`NSChild: ${err}`)
                delete this.nodeProcesses[ns.profileNum]
              })
              this.nodeProcesses[ns.profileNum].on('close', (code) => {
                logger.debug(`NSChild: ${config.nodeServers[ns.profileNum].name} exited with cause code: ${code}`)
                delete this.nodeProcesses[ns.profileNum]
              })
              this.nodeProcesses[ns.profileNum].stderr.on('data', (data) => {
                logger.error(`NSChild: Error ${data}`)
              })
              this.nodeProcesses[ns.profileNum].stdout.on('data', (data) => {
                if (! data ) return
        				try {
                  this.nodeProcesses[ns.profileNum].stdin.write(init + '\n')
                  // Don't use STDIN/STDOUT pass settings to STDOUT and require MQTT from here.
        					// data = JSON.parse(data.toString())
        				} catch (e) {
        					// logger.error('STDIN: Badly formatted JSON input received. ' + e)
        					//return
        				}
              })
              setTimeout(() => {
                if (this.nodeProcesses[ns.profileNum])
                {
                  this.nodeProcesses[ns.profileNum].stdin.write(init + '\n')
                }

              }, 200)

            } catch (e) {
                logger.debug(`NSChild: Spawn failed with ${e}`)
            }
          } else {
            logger.error(`NSChild: Could not find 'type' or 'executable' in server.json file. Unable to automatically run local NodeServer: ${ns.name} from ${ns.homeDir}`)
          }
        } catch (e) {
          logger.error('NS: Error getting server.json required fields. name and executable are required. - ' + e)
        }
      }
    }
  },

}
<commit_msg>fixed child_node crash bug<commit_after>const logger = require('../modules/logger')
const config = require('../config/config')
const os = require('os')
const fs = require('fs-extra')
const ns = require('../models/nodeserver')
const childProcess = require('child_process')

module.exports = {
  /*
   * Array of local NodeServer process objects. Corresponds to config.NodeServer[profileNum]
   * {process: child_process.spawn, env: {}, args: {}, profileNum: #}
   */
  nodeProcesses: new Array(11),

  stopChildNodeServer(ns) {
    if (!(this.nodeProcesses[ns.profileNum])) { return }
    logger.debug(`NSChild: Stopping Child NodeServer ${ns.name}`)
    this.nodeProcesses[ns.profileNum].kill()
  },

  runInstallProcess(name) {
    if (name) {
      let nsPath = `${os.homedir()}/.polyglot/nodeservers/${name}/`
      if (fs.existsSync(nsPath + 'server.json')) {
        try {
          let server = require(nsPath + 'server.json')
          if (server.hasOwnProperty('install')) {
            let opts = {
              cwd: nsPath,
              shell: '/bin/bash'
            }
            let runCmd = `./${server.install}`
            let installProcess = childProcess.spawn(runCmd, [], opts)
            installProcess.stdout.on('data', (data) => {
              logger.debug(`NSChild: ${name} Install : ${data}`)
            })
            installProcess.on('close', (code) => {
              logger.debug(`NSChild: ${name} install process exited with cause code: ${code}`)
            })
            installProcess.on('error', (err) => {
              logger.debug(`NSChild: ${name} install process error: ${err}`)
            })
          } else {
            logger.debug(`NSChild: ${name} does not have an install process defined. Run any install scripts for the nodeserver manually if necessary.`)
          }
        } catch (e) {
          logger.error(`NSChild: Install failed - ${e}`)
        }
      }
    }
  },

  runChildNodeServer(ns) {
    if (this.nodeProcesses[ns.profileNum]) { return }
    if (ns.homeDir) {
      if (fs.existsSync(ns.homeDir + 'server.json')) {
        try {
          let server = require(ns.homeDir + 'server.json')
          if (server.hasOwnProperty('type') && server.hasOwnProperty('executable')) {
            let init = JSON.stringify({
              ipAddress: config.settings.ipAddress,
              mqttHost: config.settings.mqttHost,
              mqttPort: config.settings.mqttPort.toString(),
              profileNum: ns.profileNum
            })
            let opts = {
              cwd: ns.homeDir,
              shell: '/bin/bash'
            }
            let runCmd = `./${server.executable}`
            try {
              logger.info(`NS: Starting Local NodeServer ${ns.name} profile number ${ns.profileNum}`)
              this.nodeProcesses[ns.profileNum] = childProcess.spawn(runCmd, [], opts)
              this.nodeProcesses[ns.profileNum].on('uncaughtException', (err) => {
                logger.error(`NS: Caught Error trying to write to NodeServer ${ns.name}: ${err}`)
                delete this.nodeProcesses[ns.profileNum]
              })
              this.nodeProcesses[ns.profileNum].on('error', (err) => {
                logger.error(`NSChild: ${err}`)
                delete this.nodeProcesses[ns.profileNum]
              })
              this.nodeProcesses[ns.profileNum].on('close', (code) => {
                logger.debug(`NSChild: ${config.nodeServers[ns.profileNum].name} exited with cause code: ${code}`)
                delete this.nodeProcesses[ns.profileNum]
              })
              this.nodeProcesses[ns.profileNum].stderr.on('data', (data) => {
                logger.error(`NSChild: Error ${data}`)
              })
              this.nodeProcesses[ns.profileNum].stdout.on('data', (data) => {
                if (! data ) return
        				try {
                  this.nodeProcesses[ns.profileNum].stdin.write(init + '\n')
                  // Don't use STDIN/STDOUT pass settings to STDOUT and require MQTT from here.
        					// data = JSON.parse(data.toString())
        				} catch (e) {
        					// logger.error('STDIN: Badly formatted JSON input received. ' + e)
        					return
        				}
              })
              setTimeout(() => {
                if (this.nodeProcesses[ns.profileNum])
                {
                  this.nodeProcesses[ns.profileNum].stdin.write(init + '\n')
                }

              }, 200)

            } catch (e) {
                logger.debug(`NSChild: Spawn failed with ${e}`)
            }
          } else {
            logger.error(`NSChild: Could not find 'type' or 'executable' in server.json file. Unable to automatically run local NodeServer: ${ns.name} from ${ns.homeDir}`)
          }
        } catch (e) {
          logger.error('NS: Error getting server.json required fields. name and executable are required. - ' + e)
        }
      }
    }
  },

}
<|endoftext|>


<commit_before>'use strict';

console.log( 4 );

var Gpio = require('chip-gpio').Gpio,
    request = require( 'request' ),
    jsonfile = require( 'jsonfile' ),
    client = null,

    persist = 'persist.json',
    persistedData = jsonfile.readFileSync( persist ),
    brightness = 255;

// Setup th buttons and rotary encoder
var btn = new Gpio(7, 'in', 'both', {
      debounceTimeout: 500
    }),

    a = new Gpio(0, 'in', 'both',{
        debounceTimeout: 200
    }),

    b = new Gpio(1, 'in', 'both',{
      debounceTimeout: 200
    });

var apiBaseUrl,
    // Set default Values
    brightness = 255;

function setState( on, brightness )
{
  console.log( 'setState', apiBaseUrl );
  request.put( apiBaseUrl + persistedData.username + '/lights/4/state', {
    json: {
      on: on,
      brightness: brightness
    }
  });
}

/*
*  Connect to the Bridge
*/

// Search for the Bridge
request( 'https://www.meethue.com/api/nupnp', function( error, response, body ){
  persistedData.ip = JSON.parse( body )[0].internalipaddress;
  jsonfile.writeFile( persist, persistedData );

  apiBaseUrl = 'http://' + persistedData.ip + '/';
  console.log( apiBaseUrl );

  // Do we need to create a user?
  if( typeof persistedData.username == 'undefined' || ! persistedData.username )
  {
    request.post( apiBaseUrl, {
      json: {
        devicetype: 'chip_hue_switch'
      }
    }, function( error, response, body ){
      persistedData.username = body[0].success.username;
      jsonfile.writeFile( persist, persistedData );
    });
  }
});

btn.watch(function (err, value) {
  console.log('press', value);
  console.log( apiBaseUrl + persistedData.username + '/lights' );

  request( apiBaseUrl + persistedData.username + '/lights', function( error, response, body ){
  	body = JSON.parse( body );
  	var newState = ! body[4].state.on;

    setState( newState, brightness );

  });

});

var previousA, previousB;

function setBrightness()
{
	if( brightness >= 255 ) brightness = 255;
	if( brightness <= 1 ) brightness = 1;

	console.info( 'Setting brightness to ' + brightness );

  setState( true, brightness );
}

a.watch(function (err, value) {
	var direction = '';
	var currentA = a.read();
	var currentB = b.read();

	if( previousA != currentA )
	{
		if( currentA != currentB )
		{
			direction = 'forward';
			brightness = brightness + 2.55;
		}
		else
		{
			direction = 'back';
			brightness = brightness - 2.55;
		}
	}

	setBrightness( brightness );
});

b.watch(function (err, value) {
	var direction = '';
	var currentA = a.read();
	var currentB = b.read();

	if( previousB != currentB )
	{
		if( currentA == currentB )
		{
			direction = 'forward';
			brightness = brightness + 2.55;
		}
		else
		{
			direction = 'back';
			brightness = brightness - 2.55;
		}
	}

	setBrightness( brightness );
});

function exit() {
    btn.unexport();
    a.unexport();
    b.unexport();
    process.exit();
}

process.on('SIGINT', exit);
<commit_msg>Change<commit_after>'use strict';

console.log( 5 );

var Gpio = require('chip-gpio').Gpio,
    request = require( 'request' ),
    jsonfile = require( 'jsonfile' ),
    client = null,

    persist = 'persist.json',
    persistedData = jsonfile.readFileSync( persist ),
    brightness = 255;

// Setup th buttons and rotary encoder
var btn = new Gpio(7, 'in', 'both', {
      debounceTimeout: 500
    }),

    a = new Gpio(0, 'in', 'both',{
        debounceTimeout: 200
    }),

    b = new Gpio(1, 'in', 'both',{
      debounceTimeout: 200
    });

var apiBaseUrl,
    // Set default Values
    brightness = 255;

function setState( on, brightness )
{
  console.log( 'setState', apiBaseUrl );
  request.put( apiBaseUrl + persistedData.username + '/lights/4/state', {
    json: {
      on: on,
      brightness: brightness
    }
  });
}

/*
*  Connect to the Bridge
*/

// Search for the Bridge
request( 'https://www.meethue.com/api/nupnp', function( error, response, body ){
  persistedData.ip = JSON.parse( body )[0].internalipaddress;
  jsonfile.writeFile( persist, persistedData );

  apiBaseUrl = 'http://' + persistedData.ip + '/api/';
  console.log( apiBaseUrl );

  // Do we need to create a user?
  if( typeof persistedData.username == 'undefined' || ! persistedData.username )
  {
    request.post( apiBaseUrl, {
      json: {
        devicetype: 'chip_hue_switch'
      }
    }, function( error, response, body ){
      persistedData.username = body[0].success.username;
      jsonfile.writeFile( persist, persistedData );
    });
  }
});

btn.watch(function (err, value) {
  console.log('press', value);
  console.log( apiBaseUrl + persistedData.username + '/lights' );

  request( apiBaseUrl + persistedData.username + '/lights', function( error, response, body ){
  	body = JSON.parse( body );
  	var newState = ! body[4].state.on;

    setState( newState, brightness );

  });

});

var previousA, previousB;

function setBrightness()
{
	if( brightness >= 255 ) brightness = 255;
	if( brightness <= 1 ) brightness = 1;

	console.info( 'Setting brightness to ' + brightness );

  setState( true, brightness );
}

a.watch(function (err, value) {
	var direction = '';
	var currentA = a.read();
	var currentB = b.read();

	if( previousA != currentA )
	{
		if( currentA != currentB )
		{
			direction = 'forward';
			brightness = brightness + 2.55;
		}
		else
		{
			direction = 'back';
			brightness = brightness - 2.55;
		}
	}

	setBrightness( brightness );
});

b.watch(function (err, value) {
	var direction = '';
	var currentA = a.read();
	var currentB = b.read();

	if( previousB != currentB )
	{
		if( currentA == currentB )
		{
			direction = 'forward';
			brightness = brightness + 2.55;
		}
		else
		{
			direction = 'back';
			brightness = brightness - 2.55;
		}
	}

	setBrightness( brightness );
});

function exit() {
    btn.unexport();
    a.unexport();
    b.unexport();
    process.exit();
}

process.on('SIGINT', exit);
<|endoftext|>


<commit_before>const fs = require('fs');

const helpers = require('../helpers');
const settingsFilePath = 'settingsData.json'

function getSettings() {
  if (fs.existsSync(settingsFilePath)) {
    let data = fs.readFileSync(settingsFilePath);
    return JSON.parse(data);
  }
  return {};
}

function update(argv) {
  let settingsData = getSettings();
  let settingsDataUpdate = Object.create(settingsData);

  if (argv.timezone) {
    settingsDataUpdate.timezone = argv.timezone;
  }

  let settingsJSON = JSON.stringify(settingsDataUpdate);
  if (settingsData.timezone !== settingsDataUpdate.timezone) {
    fs.writeFile(settingsFilePath, settingsJSON, (err) => {
      if (err) throw err;
      helpers.printMessage('The file has been saved!');
    });
  }
};

module.exports = {
  getSettings,
  update
};
<commit_msg>Add info and error messages<commit_after>const fs = require('fs');
const chalk = require('chalk');

const helpers = require('../helpers');
const settingsFilePath = 'settingsData.json';

function getSettings() {
  if (fs.existsSync(settingsFilePath)) {
    let data = fs.readFileSync(settingsFilePath);
    return JSON.parse(data);
  }
  return {};
}

function update(argv) {
  let settingsData = getSettings();
  let settingsDataUpdate = Object.create(settingsData);

  if (argv.timezone) {
    settingsDataUpdate.timezone = argv.timezone;
  }

  let settingsJSON = JSON.stringify(settingsDataUpdate);

  if (settingsData.timezone !== settingsDataUpdate.timezone) {
    return fs.writeFile(settingsFilePath, settingsJSON, (error) => {
      if (error) {
        return helpers.printError(error.message);
      }
      let message = chalk.bgGreen('Success!') + ' ' + 'The file has been saved!';
      helpers.printMessage(message);
    });
  }

  let message = chalk.bgGreen('OK') + ' ' + 'Settings are correct, no changes required.';
  return helpers.printMessage(message);
};

module.exports = {
  getSettings,
  update
};
<|endoftext|>


<commit_before>/*
 * changes to previous injection implementations
 * - no support for data-injection anymore, switch to new data-inject
 * - no support for data-href-next anymore, switch to data-inject: next-href
 * - XXX: add support for forms, see remnants in inject1 and ajaxify
 */
define([
    "jquery",
    "../core/parser",
    "../core/logger",
    "../lib/ajax",
    "../registry",
    "URIjs/URI",
    "jquery_ext", // for :scrollable for autoLoading-visible
    "URIjs/jquery.URI"
], function($, Parser, logger, ajax, registry, URI) {
    var log = logger.getLogger('pat.inject'),
        parser = new Parser("inject");

    //parser.add_argument('selector', 'body');
    parser.add_argument('selector');
    //XXX: (yet) unsupported: parser.add_argument('target', '$selector');
    parser.add_argument('target');
    parser.add_argument('type');
    parser.add_argument('next-href');
    //XXX: (yet) unsupported: parser.add_argument('source', '$selector');
    parser.add_argument('source');
    // XXX: this should not be here but the parser would bail on
    // unknown parameters and expand/collapsible need to pass the url
    // to us
    parser.add_argument('url');
    parser.add_argument('class');

    var _ = {
        name: "inject",
        trigger: "a.pat-inject, form.pat-inject",
        init: function($el, opts) {
            if ($el.length > 1)
                return $el.each(function() { _.init($(this), opts); });

            var cfgs = _.extractConfig($el, opts);
            $el.data('patterns.inject', cfgs);

            // In case next-href is specified the anchor's href will
            // be set to it after the injection is triggered. In case
            // the next href already exists, we do not activate the
            // injection but instead just change the anchors href.
            //
            // XXX: This is used in only one project for linked
            // fullcalendars, it's sanity is wonky and we should
            // probably solve it differently. -- Maybe it's cool
            // after all.
            var $nexthref = $(cfgs[0].nextHref);
            if ($el.is('a') && $nexthref.length > 0) {
                log.debug('Skipping as next href already exists', $nexthref);
                // XXX: reconsider how the injection enters exhausted state
                return $el.attr({href: cfgs[0].nextHref});
            }

            // setup event handlers
            if ($el.is('a'))
                $el.on("click.pat-inject", _.onClick);
            else if ($el.is('form'))
                $el.on("submit.pat-inject", _.onSubmit);

            // XXX: hack to support the old autoLoading-visible class
            if ($el.hasClass("autoLoading-visible"))
                _._initAutoloadVisible($el);

            log.debug('initialised:', $el);

            return $el;
        },
        destroy: function($el) {
            $el.off('.pat-inject');
            $el.data('patterns.inject', null);
            return $el;
        },
        onClick: function(ev) {
            var cfgs = $(this).data('patterns.inject'),
                $el = $(this);
            if (ev)
                ev.preventDefault();
            $el.trigger('patterns-inject-triggered');
            _.execute(cfgs, $el);
        },
        onSubmit: function(ev) {
            var cfgs = $(this).data('patterns.inject'),
                $el = $(this);
            if (ev)
                ev.preventDefault();
            $el.trigger('patterns-inject-triggered');
            _.execute(cfgs, $el);
        },
        extractConfig: function($el, opts) {
            opts = $.extend({}, opts);

            var urlparts, cfgs, defaultSelector;
            // opts has priority, fallback to href/action
            opts.url = opts.url || $el.attr('href') || $el.attr('action') || "";

            // separate selector from url
            urlparts = opts.url.split('#');
            opts.url = urlparts[0];

            // if no selector, check for selector as part of original url
            defaultSelector = urlparts[1] && '#' + urlparts[1] || 'body';

            if (urlparts.length > 2) {
                log.warn('Ignoring additional source ids:', urlparts.slice(2));
            }

            cfgs = parser.parse($el, opts, true);
            cfgs.forEach(function(cfg) {
                cfg.selector = cfg.selector || defaultSelector;
            });
            return cfgs;
        },
        // verify and post-process config
        // XXX: this should return a command instead of messing around on the config
        verifyConfig: function(cfgs) {
            var url = cfgs[0].url;

            // verification for each cfg in the array needs to succeed
            return cfgs.every(function(cfg) {
                // in case of multi-injection, all injections need to use
                // the same url
                if (cfg.url !== url) {
                    log.error('Unsupported different urls for multi-inject');
                    return false;
                }

                // defaults
                cfg.source = cfg.source || cfg.selector;
                cfg.target = cfg.target || cfg.selector;

                if (!_._extractModifiers(cfg))
                    return false;

                // make sure target exist
                cfg.$target = cfg.$target || $(cfg.target);
                if (cfg.$target.length === 0) {
                    if (!cfg.target) {
                        log.error('Need target selector', cfg);
                        return false;
                    }
                    cfg.$target = _._createTarget(cfg.target);
                    cfg.$injected = cfg.$target;
                }
                return true;
            });
        },
        _extractModifiers: function(cfg) {
            var source_re = /^(.+?)(::element)?$/,
                target_re = /^(.+?)(::element)?(::after|::before)?$/,
                source_match = source_re.exec(cfg.source),
                target_match = target_re.exec(cfg.target),
                targetMod, targetPosition;

            // source content or element?
            cfg.source = source_match[1];
            // XXX: turn into source processor
            cfg.sourceMod = source_match[2] ? "element" : "content";

            // will be added while the ajax request is in progress
            cfg.targetLoadClasses = "injecting";

            // target content or element?
            targetMod = target_match[2] ? "element" : "content";
            cfg.target = target_match[1];
            cfg.targetLoadClasses += " injecting-" + targetMod;

            // position relative to target
            targetPosition = (target_match[3] || "::").slice(2);
            if (targetPosition)
                cfg.targetLoadClasses += " injecting-" + targetPosition;

            cfg.action = targetMod + targetPosition;

            // Once we start detecting illegal combinations, we'll
            // return false in case of error
            return true;
        },

        // create a target that matches the selector
        //
        // XXX: so far we only support #target and create a div with
        // that id appended to the body.
        _createTarget: function(selector) {
            var $target;
            if (selector.slice(0,1) !== '#') {
                log.error('only id supported for non-existing target');
                return null;
            }
            $target = $('
').attr({id: selector.slice(1)});
            $('body').append($target);
            return $target;
        },
        execute: function(cfgs, $el) {
            // get a kinda deep copy, we scribble on it
            cfgs = cfgs.map(function(cfg) {
                return $.extend({}, cfg);
            });

            // XXX: this need to get functional, returning a command
            // for internal use, instead of passing on cfgs
            if (!_.verifyConfig(cfgs))
                return;

            // possibility for spinners on targets
            cfgs.forEach(function(cfg) {
                cfg.$target.addClass(cfg.targetLoadClasses);
            });

            var onSuccess = function(ev) {
                var data = ev && ev.jqxhr && ev.jqxhr.responseText;
                if (!data) {
                    log.warn('No response content, aborting', ev);
                    return;
                }
                // list of $source objects, one for each cfg
                var sources = cfgs.map(function(cfg) { return cfg.source; }),
                    sources$ = _._sourcesFromHtml(data, cfgs[0].url, sources);

                cfgs.forEach(function(cfg, idx) {
                    var $source = sources$[idx];

                    if (cfg.sourceMod === "content")
                        $source = $source.contents();

                    // perform injection
                    cfg.$target.each(function() {
                        var $target = $(this),
                            $src = $source.clone(),
                            $injected = cfg.$injected || $src;
                        if (_._inject($src, $target, cfg.action, cfg["class"])) {
                            $injected.data('pat-injected', {origin: cfg.url});
                            $injected.addClass(cfg["class"])
                                .trigger('patterns-injected', cfg);
                        }
                    });
                });

                if (cfgs[0].nextHref) {
                    $el.attr({href: cfgs[0].nextHref});
                    _.destroy($el);

                    // jump to new href target
                    if (!$el.hasClass("autoLoading-visible"))
                        window.location.href = $el.attr('href');
                }
                $el.off('pat-ajax-success.pat-inject');
            };

            $el.on('pat-ajax-success.pat-inject', onSuccess);

            ajax($el, {
                url: cfgs[0].url
            });
        },
        _inject: function($source, $target, action, classes) {
            // action to jquery method mapping, except for "content"
            // and "element"
            var method = {
                contentbefore: "prepend",
                contentafter:  "append",
                elementbefore: "before",
                elementafter:  "after"
            }[action];

            if ($source.length === 0) {
                log.warn('Aborting injection, source not found:', $source);
                return false;
            }
            if ($target.length === 0) {
                log.warn('Aborting injection, target not found:', $target);
                return false;
            }

            if (action === "content")
                $target.empty().append($source);
            else if (action === "element")
                $target.replaceWith($source);
            else
                $target[method]($source);

            return true;
        },
        _sourcesFromHtml: function(html, url, sources) {
            var $html = _._parseRawHtml(html, url);
            return sources.map(function(source) {
                if (source === "body")
                    source = "#__original_body";

                var $source = $html.find(source);

                if ($source.length === 0)
                    log.warn('No source elements for selector:', source, $html);

                return $source;
            });
        },
        _parseRawHtml: function(html, url) {
            url = url || "";
            var $html;
            $html = $('
').html(
                // remove script tags and head and replace body by a div
                html.replace(/


<commit_before>export default class Parser {
  constructor() {
    // noop
  }

  /**
   * @param {string} ua - user agent
   * @returns {void}
   */
  setUA(ua) {
    this.ua = ua;
  }

  /**
   * @returns {cwua.DeviceInfo}
   */
  deviceInfo() {
    return {
      userAgent: this.ua
    };
  }
}
<commit_msg>chore(cw-user-agent): declare regexp<commit_after>const re = {
  apple: {
    phone:  /iPhone/i,
    iPod:   /iPod/i,
    tablet: /iPad/i
  },
  android: {
    phone:  /(?=.*\bAndroid\b)(?=.*\bMobile\b)/i,
    tablet: /Android/i
  },
  windows: {
    phone:  /IEMobile/i,
    tablet: /(?=.*\bWindows\b)(?=.*\bARM\b)/i
  },
  blackberry:    /BlackBerry/i,
  blackberry10:  /BB10/i,
  operaMini:     /Opera Mini/i,
  firefoxMobile: /(?=.*\bFirefox\b)(?=.*\bMobile\b)/i
};

export default class Parser {
  constructor() {
    // noop
  }

  /**
   * @param {string} ua - user agent
   * @returns {void}
   */
  setUA(ua) {
    this.ua = ua;
  }

  /**
   * @returns {cwua.DeviceInfo}
   */
  deviceInfo() {
    return {
      userAgent: this.ua
    };
  }
}
<|endoftext|>


<commit_before>var utils = require('./lib/utils');

/**
 * Expose `Record`
 */

module.exports = Record;

/**
 * Record constructor. Create a new Record with
 * the given `record` properties.
 *
 * @param {Object} `record`
 */
function Record(record) {
  record = record || {};
  this.path = record.path || null;
  this.encoding = record.encoding || null;

  if (typeof record.contents === 'string') {
    this.contents = new Buffer(record.contents, record.encoding);
  } else {
    this.contents = record.contents || null;
  }
}

/**
 * Return `true` if `record.contents` is a buffer
 */
Record.prototype.isBuffer = function () {
  return utils.isBuffer(this.contents);
};

/**
 * Return `true` if `record.contents` is a stream
 */
Record.prototype.isStream = function () {
  return utils.isStream(this.contents);
};

/**
 * Return `true` if `record.contents` is null, with strict equality
 */
Record.prototype.isNull = function () {
  return utils.isNull(this.contents);
};

/**
 * Return the `type` of `record.contents`
 */
Record.prototype.type = function () {
  var type = 'Null';
  if (this.isBuffer()) {
    type = 'Buffer';
  }
  if (this.isStream()) {
    type = this.contents.constructor.name;
    if (type.toLowerCase().search('stream') === -1) {
      type += 'Stream';
    }
  }
  return type;
};

/**
 * Clone a record
 */
Record.prototype.clone = function () {
  var contents = this.contents;
  if (this.isBuffer()) {
    contents = new Buffer(contents.length);
    this.contents.copy(contents);
  }
  return new this.constructor({
    path: this.path,
    encoding: this.encoding,
    contents: contents
  });
};

/**
 * Call `toString()` on `record.contents`.
 */
Record.prototype.toString = function (enc) {
  enc = enc || this.encoding;
  if (!this.isBuffer()) {
    throw new Error('Record#toString() is only valid when `contents` is a Buffer.');
  }
  return this.contents.toString(enc);
};

/**
 * Pipe or write `record.contents` into the stream, or nothing if null.
 */
Record.prototype.pipe = function (stream, opt) {
  opt = opt || {};
  if (typeof opt.end === 'undefined') { opt.end = true; }
  if (this.isStream()) { return this.contents.pipe(stream, opt); }
  if (this.isBuffer()) {
    if (opt.end) {
      stream.end(this.contents);
    } else {
      stream.write(this.contents);
    }
    return stream;
  }
  if (this.isNull()) {
    if (opt.end) { stream.end(); }
    return stream;
  }
};

Record.prototype.inspect = function () {
  return '<Record::' + this.type() + (this.path ? ' path="' + this.path + '"' : '') + '>';
};

Object.defineProperty(Record.prototype, 'contents', {
  get: function () {
    return this._contents;
  },
  set: function (val) {
    if (!utils.isValid(val)) {
      throw new Error('Contents can only be a Buffer, a Stream, or null.');
    }
    this._contents = val;
  }
});
<commit_msg>add `builtins` property. add logic for streams in clone method.<commit_after>var utils = require('./lib/utils');

/**
 * Expose `Record`
 */

module.exports = Record;

/**
 * Record constructor. Create a new Record with
 * the given `record` properties.
 *
 * @param {Object} `record`
 */
function Record(record) {
  record = record || {};
  this.path = record.path || null;
  this.encoding = record.encoding || null;

  if (typeof record.contents === 'string') {
    this.contents = new Buffer(record.contents, record.encoding);
  } else {
    this.contents = record.contents || null;
  }
}

Record.prototype.builtins = ['path', 'encoding', '_contents'];

/**
 * Return `true` if `record.contents` is a buffer
 */
Record.prototype.isBuffer = function () {
  return utils.isBuffer(this.contents);
};

/**
 * Return `true` if `record.contents` is a stream
 */
Record.prototype.isStream = function () {
  return utils.isStream(this.contents);
};

/**
 * Return `true` if `record.contents` is null, with strict equality
 */
Record.prototype.isNull = function () {
  return utils.isNull(this.contents);
};

/**
 * Return the `type` of `record.contents`
 */
Record.prototype.type = function () {
  var type = 'Null';
  if (this.isBuffer()) {
    type = 'Buffer';
  }
  if (this.isStream()) {
    type = this.contents.constructor.name;
    if (type.toLowerCase().search('stream') === -1) {
      type += 'Stream';
    }
  }
  return type;
};

/**
 * Clone a record
 */
Record.prototype.clone = function (opt) {
  var contents;
  if (this.isBuffer()) {
    if(opt && opt.contents) {
      contents = new Buffer(contents.length);
      this.contents.copy(contents);
    } else {
      contents = this.contents;
    }
  } else if (this.isStream()) {
    this.contents = utils.passThrough(this.contents);
    contents = utils.passThrough(this.contents);
  }

  return new Record({
    path: this.path,
    encoding: this.encoding,
    contents: contents
  });
};

/**
 * Call `toString()` on `record.contents`.
 */
Record.prototype.toString = function (enc) {
  enc = enc || this.encoding;
  if (!this.isBuffer()) {
    throw new Error('Record#toString() is only valid when `contents` is a Buffer.');
  }
  return this.contents.toString(enc);
};

/**
 * Pipe or write `record.contents` into the stream, or nothing if null.
 */
Record.prototype.pipe = function (stream, opt) {
  opt = opt || {};
  if (typeof opt.end === 'undefined') { opt.end = true; }
  if (this.isStream()) { return this.contents.pipe(stream, opt); }
  if (this.isBuffer()) {
    if (opt.end) {
      stream.end(this.contents);
    } else {
      stream.write(this.contents);
    }
    return stream;
  }
  if (this.isNull()) {
    if (opt.end) { stream.end(); }
    return stream;
  }
};

Record.prototype.inspect = function () {
  return '<Record::' + this.type() + (this.path ? ' path="' + this.path + '"' : '') + '>';
};

Object.defineProperty(Record.prototype, 'contents', {
  get: function () {
    return this._contents;
  },
  set: function (val) {
    if (!utils.isValid(val)) {
      throw new Error('Contents can only be a Buffer, a Stream, or null.');
    }
    this._contents = val;
  }
});
<|endoftext|>


<commit_before>module.exports = function() {

};<commit_msg>added code<commit_after>'use strict';

const Hoek = require('hoek');
const React = require('react');
const ReactDOMServer = require('react-dom/server');
const TypeScript = require('typescript');
const TypescriptSimple = require('typescript-simple');
const fs = require('fs');
const UglifyJS = require("uglify-js");
const path = require('path');
const C = require('ansi-to-html');
const convert = new C();
const colors = require('colors/safe');
const striptags = require('striptags');

const DEFAULTS = {
    doctype: '<!DOCTYPE html>',
    renderMethod: 'renderToStaticMarkup',
    removeCache: process.env.NODE_ENV !== 'production',
    experimentalDecorators: true,
    target:TypeScript.ScriptTarget.ES5,
    jsx: TypeScript.JsxEmit.React,
    module: TypeScript.ModuleKind.AMD,
    removeComments: true,
    consoleErrors: true,
    noEmit: false,
    outFile: 'build/servoutput.js'
};

let define;

const cols = (process.stdout && typeof process.stdout.getWindowSize === 'function') ? process.stdout.getWindowSize()[0] : 25;

let consoleErrors;

const compile = function compile(template, compileOpts) {

    compileOpts = Hoek.applyToDefaults(DEFAULTS, compileOpts);

    return function runtime(context, renderOpts) {

        renderOpts = Hoek.applyToDefaults(compileOpts, renderOpts);
        let output = renderOpts.doctype;
        let out;
        let errors = [];
        let fatalCount = 0;

        consoleErrors = compileOpts.consoleErrors;

        try {
            // https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#a-minimal-compiler
            // https://github.com/Microsoft/TypeScript/wiki/Compiler-Options
            // http://json.schemastore.org/tsconfig

            let files = [];
            files.push(compileOpts.filename);

            out = compileTypeScript(files, compileOpts);

            if (typeof define !== 'function') {
                define = require('amdefine')(module)
            };

            let san = out.outputFiles[0].text;

            let m = getModuleFromFullPath(compileOpts.filename);

            let tsexec = eval(san);

            define(function(require) {
                var dep = require(m);

                let Element = React.createFactory(dep.default);

                let ElContext = Element(context);

                output += ReactDOMServer[compileOpts.renderMethod](ElContext);

                if(out.debug && out.debug != '') errors.push({runtime: getRuntimeError(out.debug)});
            });

        } catch (e) {
            if(out.debug && out.debug != '') errors.push({runtime: getRuntimeError(out.debug)});
            errors.unshift({fatal: getFatalError(e, compileOpts.filename)});
            fatalCount += 1;
        }

        define = null;

        if(errors.length){
            output += formatErrors(fatalCount, compileOpts.filename, errors);
        }

        return output;
    };

};

function compileTypeScript(fileNames, options) {

    function writeFile(fileName, data, writeByteOrderMark) {
        outputFiles.push({
            sourceName: fileName,
            name: fileName,
            writeByteOrderMark: writeByteOrderMark,
            text: data
        });
    }

    // TODO https://nodejs.org/api/fs.html#fs_fs_watch_filename_options_listener
    // This is for eventually caching the code and to also prevent production code from recompiling every page load
    /*
    fs.watch(fileNames[0], (event, filename) => {
        console.log(`event is: ${event}`);
        if (filename) {
            console.log(`filename provided: ${filename}`);
        } else {
            console.log('filename not provided');
        }
    });
    */

    let outputFiles = [];

    let program = TypeScript.createProgram(fileNames, options);

    let source = program.getSourceFile(fileNames[0]);

    let emitResult = program.emit(source, writeFile);

    let allDiagnostics = TypeScript.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);

    let debug = '';

    allDiagnostics.forEach(diagnostic => {
        let d = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
        let line = d.line;
        let character = d.character;
        let message = TypeScript.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
        let dir = path.dirname(diagnostic.file.fileName);
        let file = path.basename(diagnostic.file.fileName);
        let dbmessage = escapeHTML(message);
        debug += `${dir}/<span style="color: #993333; font-weight: bold;">${file}</span>\t\t<span style="font-weight: bold;">(${line + 1},${character + 1}): ${dbmessage}</span><br />`;
    });

    let exitCode = emitResult.emitSkipped ? 1 : 0;

    return {
        debug,
        emitResult,
        outputFiles
    };
}

const getModuleFromFullPath = function(p){
    return path.dirname(p).split('/').pop() + '/' + path.basename(p, '.tsx');
}

const formatErrors = function(fatal, path, errors){
    let m = getModuleFromFullPath(path);
    let output = '';

    // Complete HTML Page
    if(fatal){
        output += '<title>Error ' + m + '</title>';
        output += '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">';
        output += '';

    }

    output += '
';
    //output += '
FILE
';
    //output += '
' + path + '
';
    output += '
ERRORS
';

    // Error List output
    output += '
';

    let runtimeCount = 0;
    let pageCount = 0;

    for(var i = 0; i < errors.length; i += 1) {
        let e = errors[i];
        for(let prop in e) {
            switch(prop){
                case 'runtime':
                    if(!runtimeCount) {
                        output += 'Runtime Error
';
                        runtimeCount += 1;
                    }
                    break;
                case 'fatal':
                    if(!pageCount){
                        output += 'Fatal Error
';
                        pageCount += 1;
                    }
                    break;
            }

            output += e[prop] + '
';
        }

    }

    // END Error List output
    output += '
';

    // END Complete HTML Page
    if(fatal) output += '';

    return output;
}

const getFatalError = function(error, p){
    if(consoleErrors){
        console.error(createConsoleHeader('Fatal Error'));
        console.error(error); // Error: L1: Type 'string' is not assignable to type 'number'.
    }
    let output = '';

    let dir = path.dirname(p);
    let file = path.basename(p);

    output += `${dir}/<span style="color: #993333; font-weight: bold;">${file}</span><br />`;
    output += '' + error + '
';
    if (error.codeFrame != undefined || error.codeFrame != null) output += convert.toHtml(error.codeFrame) + '\n';
    return output;
}

const getRuntimeError = function(error){
    if(consoleErrors){
        console.error(createConsoleHeader('Runtime Error'));
        var regex = /
/gi;
        console.error(striptags(error.replace(regex, '\n'))); // Error: L1: Type 'string' is not assignable to type 'number'.
    }
    let output = '';
    output += error + '\n';
    return output;
}

const escapeHTML = function(s) {
    return s.replace(/&/g, '&')
            .replace(/"/g, '"')
            .replace(/</g, '<')
            .replace(/>/g, '>');
}

const createConsoleHeader = function(m){
    let o = '\n' + m + ' ';
    let delta = cols - (m.length + 1);
    for(let i = 0; i < delta; i += 1){
        o += '═';
    }
    return colors.red(o);
}

module.exports = {
    compile: compile
};<|endoftext|>


<commit_before>'use strict';

let GitHubApi = require('github');
let Promise = require('bluebird');
let creds = require('./creds.js').creds;

exports.handler = (event, context, callback) => {
  // if no command was specified, then exit
  if ((event === undefined) || (event.cmd === undefined) || (event.cmd === '')) {
    callback(new Error('Missing cmd parameter'))
  } else {
    // init github api
    let user = creds.user;
    let token = creds.token;
    let github = new GitHubApi({
      // required
      version: '3.0.0',
      // optional
      debug: true,
      protocol: 'https',
      host: 'api.github.com',
      pathPrefix: '',
      timeout: 5000,
      headers: {
        'user-agent': user
      }
    });
    github.authenticate({
      type: 'oauth',
      token: token
    });
    // main switch
    switch (event.cmd) {
    case 'getAll':
      // get all repos of the authenticated user
      Promise.promisify(github.repos.getAll)({ per_page: 100 })
        .then((resp) => { callback(null, response) })
        .catch((error) => { callback(error) });
      break;
    case 'getCommits':
      // get the commits of a repo
      // if no repo was provided, then exit
      if (event.reponame === undefined) {
        callback(new Error('Missing repo parameters'))
      } else {
        let reponame = event.reponame;
        Promise.promisify(github.repos.getCommits)({ user: user, repo: reponame })
          .then((resp) => { debugger; callback(null, response) })
          .catch((error) => { callback(error) });
      }
      break;
    case 'getCommit':
      // get the content of a commit
      // if no repo/sha were provided, then exit
      if ((event.reponame === undefined) || (event.commitsha === undefined)) {
        callback(new Error('Missing repo/sha parameters'))
      } else {
        let reponame = event.reponame;
        let commitsha = event.commitsha;
        Promise.promisify(github.repos.getCommit)({ user: user, repo: reponame, sha: commitsha })
          .then((resp) => { debugger; callback(null, response) })
          .catch((error) => { callback(error) });
      }
      break;
    case 'getContent':
      // get the content of a file
      // if no repo/path/ref were provided, then exit
      if ((event.reponame === undefined) || (event.path === undefined) || (event.ref === undefined)) {
        callback(new Error('Missing repo/path/ref parameters'))
      } else {
        let reponame = event.reponame;
        let path = event.path;
        let ref = event.ref;
        Promise.promisify(github.repos.getContent)({ user: user, repo: reponame, path: path, ref: ref })
          .then((resp) => { debugger; callback(null, response) })
          .catch((error) => { callback(error) });
      }
      break;
    case 'getTree':
      // get the content of a tree
      // if no repo/sha were provided, then exit
      if ((event.reponame === undefined) || (event.sha === undefined)) {
        callback(new Error('Missing repo/sha parameters'))
      } else {
        let reponame = event.reponame;
        let sha = event.sha;
        Promise.promisify(github.gitdata.getTree)({ user: user, repo: reponame, sha: sha, recursive: true })
          .then((resp) => { debugger; callback(null, response) })
          .catch((error) => { callback(error) });
      }
      break;
    default:
    }
  }
}

exports.handler({ cmd: 'getAll' });
<commit_msg>more forgotten things<commit_after>'use strict';

let GitHubApi = require('github');
let Promise = require('bluebird');
let creds = require('./creds.js').creds;

exports.handler = (event, context, callback) => {
  // if no command was specified, then exit
  if ((event === undefined) || (event.cmd === undefined) || (event.cmd === '')) {
    callback(new Error('Missing cmd parameter'))
  } else {
    // init github api
    let user = creds.user;
    let token = creds.token;
    let github = new GitHubApi({
      // required
      version: '3.0.0',
      // optional
      debug: true,
      protocol: 'https',
      host: 'api.github.com',
      pathPrefix: '',
      timeout: 5000,
      headers: {
        'user-agent': user
      }
    });
    github.authenticate({
      type: 'oauth',
      token: token
    });
    // main switch
    switch (event.cmd) {
    case 'getAll':
      // get all repos of the authenticated user
      Promise.promisify(github.repos.getAll)({ per_page: 100 })
        .then((response) => { callback(null, response) })
        .catch((error) => { callback(error) });
      break;
    case 'getCommits':
      // get the commits of a repo
      // if no repo was provided, then exit
      if (event.reponame === undefined) {
        callback(new Error('Missing repo parameters'))
      } else {
        let reponame = event.reponame;
        Promise.promisify(github.repos.getCommits)({ user: user, repo: reponame })
          .then((response) => { callback(null, response) })
          .catch((error) => { callback(error) });
      }
      break;
    case 'getCommit':
      // get the content of a commit
      // if no repo/sha were provided, then exit
      if ((event.reponame === undefined) || (event.commitsha === undefined)) {
        callback(new Error('Missing repo/sha parameters'))
      } else {
        let reponame = event.reponame;
        let commitsha = event.commitsha;
        Promise.promisify(github.repos.getCommit)({ user: user, repo: reponame, sha: commitsha })
          .then((response) => { callback(null, response) })
          .catch((error) => { callback(error) });
      }
      break;
    case 'getContent':
      // get the content of a file
      // if no repo/path/ref were provided, then exit
      if ((event.reponame === undefined) || (event.path === undefined) || (event.ref === undefined)) {
        callback(new Error('Missing repo/path/ref parameters'))
      } else {
        let reponame = event.reponame;
        let path = event.path;
        let ref = event.ref;
        Promise.promisify(github.repos.getContent)({ user: user, repo: reponame, path: path, ref: ref })
          .then((response) => { callback(null, response) })
          .catch((error) => { callback(error) });
      }
      break;
    case 'getTree':
      // get the content of a tree
      // if no repo/sha were provided, then exit
      if ((event.reponame === undefined) || (event.sha === undefined)) {
        callback(new Error('Missing repo/sha parameters'))
      } else {
        let reponame = event.reponame;
        let sha = event.sha;
        Promise.promisify(github.gitdata.getTree)({ user: user, repo: reponame, sha: sha, recursive: true })
          .then((response) => { callback(null, response) })
          .catch((error) => { callback(error) });
      }
      break;
    default:
    }
  }
}

exports.handler({ cmd: 'getAll' });
<|endoftext|>


<commit_before>import React from 'react'
import {
  Box,
  Container,
  Image,
  Text,
  mediaQueries,
  cx
} from '@hackclub/design-system'
import { wk } from '../theme'

const Base = Box.extend`
  position: relative;
  &:before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: -64px;
    z-index: -1;
    background-color: ${props => cx(props.offset || 'gray.1')};
    ${wk('clip-path: polygon(0% 0%, 100% 0, 100% 75%, 0 100%)')};
  }

  img {
    border-radius: 8px;
    max-width: 96%;
    transform: translate(0, 64px);
  }
`

export default props => (
  <Base mt={64 * -3} pt={256} pb={160} id="about" {...props}>
    <Box mx="auto" align="center">
      <Container maxWidth={48} align="left" px={3} id="section">
        <Text f={[2, 4]} my={2}>
          What it looks like. Every week, you and around 20
          other students come together to build. Meetings are like
          mini-hackathons. People are working on projects, you lead workshops to
          introduce new technologies, you and your co-leads are constantly
          mentoring. Your members start with no experience.
        </Text>
        <Text f={[2, 4]} my={2}>
          How it works. You, a student who knows how to code,
          get 1 - 2 others to start a Hack Club. You apply, we accept you, you
          use the community’s open source materials and remote office hours with
          the staff to get your club started.
        </Text>
        <Text f={[2, 4]} my={2}>
          Our philosophy. We think people learn best when they
          take control of their own education. At Hack Club, there are no
          teachers. No lectures. Your job is to facilitate and provide guidance
          through mentoring. Hack Club is heavily inspired by unschooling.
        </Text>
      </Container>
      <Image w={512} mx="auto" src="/about_hacking.jpg" />
    </Box>
  </Base>
)
<commit_msg>Shorten About section<commit_after>import React from 'react'
import {
  Box,
  Container,
  Card,
  Text,
  mediaQueries,
  cx
} from '@hackclub/design-system'
import { wk } from '../theme'

const Base = Box.extend`
  position: relative;
  &:before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: -64px;
    z-index: -1;
    background-color: ${props => cx(props.offset || 'gray.1')};
    ${wk('clip-path: polygon(0% 0%, 100% 0, 100% 75%, 0 100%)')};
  }

  img {
    border-radius: 8px;
    max-width: 96%;
    width: 32rem;
    ${mediaQueries[1]} {
      transform: translate(0, 2rem);
    }
  }
`

Card.img = Card.withComponent('img')

export default props => (
  <Base mt={64 * -3} pt={256} pb={4} id="about" {...props}>
    <Box mx="auto" align="center">
      <Container maxWidth={48} align="left" px={3} mb={[4, 0]} id="section">
        <Text f={[2, 4]}>
          What it looks like. Every week, you and around 20
          other students come together to build. Meetings are like
          mini-hackathons. People are working on projects, you lead workshops to
          introduce new technologies, you and your co-leads are constantly
          mentoring. Your members start with no experience.
        </Text>
        <Text f={[2, 4]} my={2}>
          How it works. You, a student who knows how to code,
          get 1 - 2 others to start a Hack Club. You apply, we accept you, you
          use the community’s open source materials and remote office hours with
          the staff to get your club started.
        </Text>
        <Text f={[2, 4]}>
          Our philosophy. We think people learn best when they
          take control of their own education. At Hack Club, there are no
          teachers. No lectures. Your job is to facilitate and provide guidance
          through mentoring. Hack Club is heavily inspired by unschooling.
        </Text>
      </Container>
      <Card.img boxShadowSize="lg" mx="auto" src="/about_hacking.jpg" />
    </Box>
  </Base>
)
<|endoftext|>


<commit_before>/* global define */
(function (root, upcast) {
	'use strict';

    // Utilities
    // ------------

    // Guard a 'type' argument
	const guardTypeArg = type => {
		if (typeof type !== 'string') {
			throw new TypeError('Invalid argument: type is expected to be a string');
		}
	};

    // Type aliases
    // ------------

    // Define aliases
	const alias = {
		a: 'array',
		arr: 'array',
		array: 'array',
		b: 'boolean',
		bool: 'boolean',
		boolean: 'boolean',
		null: 'null',
		n: 'number',
		num: 'number',
		number: 'number',
		o: 'object',
		obj: 'object',
		object: 'object',
		s: 'string',
		str: 'string',
		string: 'string',
		undefined: 'undefined'
	};
	upcast.alias = alias;

    // Resolve type aliases
	const resolve = type => upcast.alias[type] || type;
	upcast.resolve = resolve;

    // Get type
    // --------

    // Get an object's type
	const type = val => {
		if (val === null) {
			return 'null';
		}
		if (Object.prototype.toString.call(val) === '[object Array]') {
			return 'array';
		}
		return typeof val;
	};
	upcast.type = type;

    // Check type
    // ----------

    // Check whether an object is of a certain type
	const is = (val, type) => {
		guardTypeArg(type);
		return (upcast.type(val) === upcast.resolve(type));
	};
	upcast.is = is;

    // Cast
    // ----

    // Cast an object to a given type
	const to = (val, type) => {
		guardTypeArg(type);

        // Get type and return if already correct
		type = upcast.resolve(type);
		const from = upcast.type(val);
		if (type === from) {
			return val;
		}

        // Get a caster and cast!
		if (!to.cast[type]) {
			return val;
		}
		const caster = to.cast[type][from] || to.cast[type];
		return caster(val);
	};
	upcast.to = to;

    // Default casters
	const cast = {
		array(val) {
			return [val];
		},
		boolean(val) {
			return (Boolean(val));
		},
		function(val) {
			return function () {
				return val;
			};
		},
		null: () => null,
		number: val => Number(val),
		object: val => new Object(val), // eslint-disable-line no-new-object
		string: val => String(val),
		undefined: () => undefined
	};
	to.cast = cast;

    // Special casters
	cast.array.null = () => [];
	cast.array.undefined = () => [];
	cast.array.string = val => val.split('');
	cast.boolean.array = val => val.length > 0;
	cast.number.array = val => to(to(val, 'string'), 'number');
	cast.number.string = val => {
		const num = Number(val, 10);
		return (isNaN(num) ? 0 : num);
	};
	cast.number.undefined = () => 0;
	cast.string.array = val => val.join('');
	cast.string.null = () => '';
	cast.string.undefined = () => '';

    // Exports
    // -------

	if (typeof define !== 'undefined' && define.amd) {
		// AMD
		define([], () => {
			return upcast;
		});
	} else if (typeof module !== 'undefined' && module.exports) {
		// CommonJS
		module.exports = upcast;
	} else {
		// Script tag
		root.upcast = upcast;
	}
})(this, {});
<commit_msg>switch to using class<commit_after>// Guard a 'type' argument
const guardTypeArg = type => {
	if (typeof type !== 'string') {
		throw new TypeError('Invalid argument: type is expected to be a string');
	}
};

class Upcast {
	constructor() {
		// Define aliases
		this.alias = {
			a: 'array',
			arr: 'array',
			array: 'array',
			b: 'boolean',
			bool: 'boolean',
			boolean: 'boolean',
			null: 'null',
			n: 'number',
			num: 'number',
			number: 'number',
			o: 'object',
			obj: 'object',
			object: 'object',
			s: 'string',
			str: 'string',
			string: 'string',
			undefined: 'undefined'
		};

		// Default casters
		this.cast = {
			array(val) {
				return [val];
			},
			boolean(val) {
				return (Boolean(val));
			},
			function(val) {
				return function () {
					return val;
				};
			},
			null: () => null,
			number: val => Number(val),
			object: val => new Object(val), // eslint-disable-line no-new-object
			string: val => String(val),
			undefined: () => undefined
		};

		// Special casters
		this.cast.array.null = () => [];
		this.cast.array.undefined = () => [];
		this.cast.array.string = val => val.split('');
		this.cast.boolean.array = val => val.length > 0;
		this.cast.number.array = val => this.to(this.to(val, 'string'), 'number');
		this.cast.number.string = val => {
			const num = Number(val, 10);
			return (isNaN(num) ? 0 : num);
		};
		this.cast.number.undefined = () => 0;
		this.cast.string.array = val => val.join('');
		this.cast.string.null = () => '';
		this.cast.string.undefined = () => '';
	}

	// Resolve type aliases
	resolve(type) {
		if (!this.alias[type] && !type) {
			throw new Error(`Unknown type or alias: ${type}`);
		}
		return this.alias[type] || type;
	}

	// Get an object's type
	type(val) {
		if (val === null) {
			return 'null';
		}
		if (Object.prototype.toString.call(val) === '[object Array]') {
			return 'array';
		}
		return typeof val;
	}

	// Check whether an object is of a certain type
	is(val, type) {
		guardTypeArg(type);
		return (this.type(val) === this.resolve(type));
	}

	// Cast an object to a given type
	to(val, type) {
		guardTypeArg(type);

		// Get type and return if already correct
		type = this.resolve(type);
		const from = this.type(val);
		if (type === from) {
			return val;
		}

		// Get a caster and cast!
		if (!this.cast[type]) {
			return val;
		}
		const caster = this.cast[type][from] || this.cast[type];
		return caster(val);
	}
}

module.exports = new Upcast();
<|endoftext|>


<commit_before>import React from "react";
import { Line } from "react-chartjs-2";

export class Chart extends React.Component {
  render() {
    return(

Edistyminen

      <Line
        data={this.props.data}
        width="auto"
        height="auto"
        options={this.props.options}
      />

)
  };
};<commit_msg>Reverted chart to functional component<commit_after>import React from "react";
import { Line } from "react-chartjs-2";

export const Chart = props => (

Edistyminen

      <Line
        data={props.data}
        width="auto"
        height="auto"
        options={props.options}
      />

);
<|endoftext|>


<commit_before>// A near-exact reimplementation of sys.pump, but
// sys.pump fails in regards to correct encoding between buffers.
var pump = function(readStream, writeStream, callback) {
  var callbackCalled = false;

  function call(a, b, c) {
    if (callback && !callbackCalled) {
      callback(a, b, c);
      callbackCalled = true;
    }
  }

  if (!readStream.pause) {
    readStream.pause = function() {readStream.emit('pause');};
  }

  if (!readStream.resume) {
    readStream.resume = function() {readStream.emit('resume');};
  }

  readStream.addListener('data', function(chunk) {
    if (writeStream.write(chunk, readStream._decoder.encoding) === false) readStream.pause();
  });

  writeStream.addListener('pause', function() {
    readStream.pause();
  });

  writeStream.addListener('drain', function() {
    readStream.resume();
  });

  writeStream.addListener('resume', function() {
    readStream.resume();
  });

  readStream.addListener('end', function() {
    writeStream.end();
    writeStream.on('close', call);
  });

  readStream.addListener('close', function() {
    call();
  });

  readStream.addListener('error', function(err) {
    writeStream.end();
    call(err);
  });

  writeStream.addListener('error', function(err) {
    readStream.destroy();
    call(err);
  });
};

module.exports = { pump: pump };
<commit_msg>Correctly handle filesystem-level errors<commit_after>// A near-exact reimplementation of sys.pump, but
// sys.pump fails in regards to correct encoding between buffers.
var pump = function(readStream, writeStream, callback) {
  var callbackCalled = false;

  function call(a, b, c) {
    if (callback && !callbackCalled) {
      callback(a, b, c);
      callbackCalled = true;
    }
  }

  if (!readStream.pause) {
    readStream.pause = function() {readStream.emit('pause');};
  }

  if (!readStream.resume) {
    readStream.resume = function() {readStream.emit('resume');};
  }

  readStream.addListener('data', function(chunk) {
    if (writeStream.write(chunk, readStream._decoder.encoding) === false) readStream.pause();
  });

  writeStream.addListener('pause', function() {
    readStream.pause();
  });

  writeStream.addListener('drain', function() {
    readStream.resume();
  });

  writeStream.addListener('resume', function() {
    readStream.resume();
  });

  readStream.addListener('end', function() {
    writeStream.end();
    writeStream.on('close', call);
  });

  readStream.addListener('close', function() {
    call();
  });

  readStream.addListener('error', function(err) {
    writeStream.end();
    call(err);
  });

  writeStream.addListener('error', function(err) {
    call(err);
  });
};

module.exports = { pump: pump };
<|endoftext|>