<commit_before>var VError, async, mongoose, jsonSelect, nconf, courses, calendar, history, Schema, schema;

VError = require('verror');
async = require('async');
mongoose = require('mongoose');
jsonSelect = require('mongoose-json-select');
courses = require('dacos-courses-driver');
calendar = require('dacos-calendar-driver');
history = require('dacos-history-driver');
nconf = require('nconf');
Schema = mongoose.Schema;

schema = new Schema({
  'enrollment' : {
    'type'     : Schema.ObjectId,
    'ref'      : 'Enrollment',
    'required' : true
  },
  'discipline' : {
    'type'     : String,
    'required' : true
  },
  'offering'   : {
    'type'     : String,
    'required' : true
  },
  'status'     : {
    'type'    : String,
    'enum'    : [ 'new', 'approved', 'rejected', 'quit' ],
    'default' : 'new'
  },
  'comment'    : {
    'type' : String
  },
  'priority'   : {
    'type' : Number
  },
  'createdAt'  : {
    'type'    : Date,
    'default' : Date.now
  },
  'updatedAt'  : {
    'type' : Date
  }
}, {
  'collection' : 'requirements',
  'strict'     : true,
  'toJSON'     : {
    'virtuals' : true
  }
});

schema.index({
  'enrollment' : 1,
  'discipline' : 1,
  'offering'   : 1
}, {
  'unique' : true
});

schema.plugin(jsonSelect, {
  '_id'        : 0,
  'enrollment' : 1,
  'discipline' : 1,
  'offering'   : 1,
  'status'     : 1,
  'comment'    : 1,
  'priority'   : 1,
  'createdAt'  : 1,
  'updatedAt'  : 1
});

schema.pre('save', function setRequirementUpdatedAt(next) {
  'use strict';

  this.updatedAt = new Date();
  next();
});

schema.pre('save', function setPriorityScore(next) {
  'use strict';

  var priorityScore;

  this.populate('enrollment');
  this.populate(function () {
    getDisciplineInformation(this.enrollment, this.discipline, this.offering, function (blockType, isAhead, isReserved) {

      // Calculating priority score
      if (blockType === 'required') {
        // Obligatory discipline
        if (isAhead) {
          if (isReserved) {
            priorityScore = 6;
          } else {
            priorityScore = 3;
          }
        } else {
          if (isReserved) {
            priorityScore = 9;
          } else {
            priorityScore = 7;
          }
        }
      } else if (blockType === 'optional') {
        // Optional discipline
        if (isAhead) {
          if (isReserved) {
            priorityScore = 5;
          } else {
            priorityScore = 2;
          }
        } else {
          if (isReserved) {
            priorityScore = 8;
          } else {
            priorityScore = 4;
          }
        }
      } else if (blockType === 'extra') {
        // Extra-curricular discipline
        if (isAhead) {
          if (isReserved) {
            priorityScore = 1;
          } else {
            priorityScore = 0;
          }
        } else {
          // TODO check why this is equal to the last conditional
          if (isReserved) {
            priorityScore = 1;
          } else {
            priorityScore = 0;
          }
        }
      }

      this.priority = priorityScore;
      //console.log(this.priority);

      next();
    }.bind(this));
  }.bind(this));
});

function getDisciplineInformation(enrollment, discipline, disciplineOffering, next) {
  'use strict';

  var blockType , isAhead, isReserved;

  blockType = 'optional';
  isAhead = false;
  isReserved = false;

  history.currentHistory(enrollment.user, function (error, currentHistory) {

    if (error) {
      error = new VError(error, 'Error when trying to get the history');
      return next(error);
    }

    if (!currentHistory) {
      return next(false);
    }

    courses.blocks(currentHistory.year, currentHistory.course + ' ' + currentHistory.modality, function (error, blocks) {
      if (error) {
        return next('');
      }

      async.some(blocks, function(block) {

        courses.requirement(currentHistory.year, currentHistory.course + ' ' + currentHistory.modality, block.code, this.discipline, function (error, requirement) {
          if (requirement) {
            var currentDate = new Date();

            var currentSemester;
            if (currentDate.getMonth() < 6) {
              currentSemester = 1;
            } else if(currentDate.getMonth() > 6) {
              currentSemester = 2;
            } else {
              currentSemester = currentDate.getDay() < 15 ? 1 : 2;
            }

            //TODO figure out how to get the offering reservation

            var userSemester = (currentDate.getFullYear() - currentHistory.year) * 2 + currentSemester;
            //var offeringReservations = disciplineOffering && disciplineOffering.reservations || [];

            blockType = block.type;
            //isAhead = offeringReservations.some(function (offeringReservation) { return offeringReservation === historyId; });
            isReserved = requirement && (userSemester < requirement.suggestedSemester);

            //requirement.code

            next(true);
          }
          else {
            next(false);
          }
        });
      }, function(result) {
        next(blockType, isAhead, isReserved);
      });
    });
  });
}

/**
 * verifica se uma solicitação de aumento de limite de créditos deve ser aberta
 */
schema.pre('save', function openCreditRaiseRequestIfNecessary(next) {
  'use strict';

  this.populate('enrollment');
  this.populate(function () {
    var user = this.enrollment.user;
    history.currentHistory(user, function (error, currentHistory) {
      if (error) {
        error = new VError(error, 'Error when trying to get the history');
        return next(error);
      }

      if (!currentHistory) {
        return next(false);
      }

      courses.modality(currentHistory.year, currentHistory.course + '-' + currentHistory.modality, function (error, modality) {
        if (error) {
          error = new VError(error, 'Error when trying to get the modality');
          return next(error);
        }

        if (!modality) {
          return next(new VError(error, 'Modality not found'));
        }

        var query;
        query = this.model('Requirement').find();
        query.where('enrollment').equals(this.enrollment._id);
        query.where('_id').ne(this._id);
        query.exec(function foundRequirements(error, requirements) {
          requirements.push(this);

          async.reduce(requirements, 0, function (sum, disciplineRequirement, next) {
            courses.discipline(disciplineRequirement.discipline, function (error, discipline) {
              next(error, discipline ? discipline.credits + sum : 0);
            }.bind(this));
          }.bind(this), function (error, credits) {
            if (error) {
              error = new VError(error, 'Error when trying to sum the credits');
              return next(error);
            }

            if (credits > modality.creditLimit) {
              this.enrollment.creditRaiseRequest.credits = credits;
              this.enrollment.creditRaiseRequest.date = new Date();
              this.enrollment.creditRaiseRequest.status = 'pending';
              this.enrollment.save(next);
            }
            else {
              next();
            }
          }.bind(this));
        }.bind(this));
      }.bind(this));
    }.bind(this));
  }.bind(this));
});

schema.path('offering').validate(function validateIfDisciplineOfferingExists(value, next) {
  'use strict';

  courses.offering(this.discipline, this.offering, function foundDisciplineOffering(error, offering) {
    next(!error && !!offering);
  });
}, 'discipline offering not found');

schema.path('discipline').validate(function validateDisciplineRequirement(value, next) {
  'use strict';

  async.waterfall([function (next) {
    this.populate('enrollment');
    this.populate(next);
  }.bind(this), function (_, next) {
    async.parallel({
      'discipline': function (next) {
        courses.discipline(this.discipline, next);
      }.bind(this),
      'histories' : function (next) {
        history.histories(this.enrollment.user, next);
      }.bind(this)
    }, next);
  }.bind(this), function (data, next) {
    async.every(data.histories, function (userHistory) {
      if (data.discipline.requirements.length > 0) {
        data.discipline.requirements.forEach(function (disciplineRequirement) {
          history.discipline(this.enrollment.user, userHistory.year, disciplineRequirement.code, function (error, disciplineHistory) {
            next(!!error || (disciplineHistory && [1, 2, 3, 4, 7, 10, 11, 12, 13, 14, 15, 16, 20].lastIndexOf(disciplineHistory.status) > -1));
          }.bind(this));
        }.bind(this));
      }
      else {
        next();
      }
    }.bind(this), next);
  }.bind(this)], next);
}, 'discipline requirement not fulfilled');

schema.path('status').validate(function validateIfRequirementCanBeQuit(value, next) {
  'use strict';
  var todayDate, year;
  todayDate = new Date();
  year = todayDate.getFullYear();

  if (this.status === 'quit') {
    calendar.betweenEvents(todayDate, year, 'discipline-quit-starts', year, 'discipline-quit-ends', next);
  }
  else {
    next();
  }
}, 'outside of discipline quit period');

schema.path('discipline').validate(function validateDisciplineApproval(value, next) {
  'use strict';

  async.waterfall([function (next) {
    this.populate('enrollment');
    this.populate(next);
  }.bind(this), function (_, next) {
    async.parallel({
      'histories'  : function (next) {
        history.histories(this.enrollment.user, next);
      }.bind(this),
      'discipline' : function (next) {
        courses.discipline(this.discipline, next);
      }.bind(this)
    }, next);
  }.bind(this), function (data, next) {
    async.every(data.histories, function (userHistory, next) {
      history.discipline(this.enrollment.user, userHistory.year, data.discipline.code, function (error, disciplineHistory) {
        next(!!error || !(disciplineHistory && [1, 2, 3, 4, 7, 10, 11, 12, 13, 14, 15, 16, 20].lastIndexOf(disciplineHistory.status) > -1));
      }.bind(this));
    }.bind(this), next);
  }.bind(this)], next);
}, 'user was already approved on discipline');

schema.path('offering').validate(function validateIfRequirementHasTimeConflict(value, next) {
  'use strict';

  async.waterfall([function (next) {
    this.populate('enrollment');
    this.populate(next);
  }.bind(this), function (_, next) {
    async.parallel({
      'offering'    : function (next) {
        courses.offering(this.discipline, this.offering, next);
      }.bind(this),
      'requirements': function (next) {
        var query;

        query = this.model('Requirement').find();
        query.where('enrollment').equals(this.enrollment._id);
        query.where('_id').ne(this._id);
        query.where('discipline').ne(this.discipline);
        query.exec(next);
      }.bind(this)
    }, next);
  }.bind(this), function (data, next) {
    async.every(data.requirements, function (requirement, next) {
      courses.offering(requirement.discipline, requirement.offering, function foundDisciplineOffering(error, offeringConflict) {
        var conflict = data.offering.schedules.some(function (schedule) {
          return offeringConflict.schedules.some(function (otherSchedule) {
            return (schedule.weekday === otherSchedule.weekday && schedule.hour === otherSchedule.hour);
          });
        });

        next(!!error || !conflict);
      });
    }.bind(this), next);
  }.bind(this)], next);
}, 'discipline with time conflict');

module.exports = mongoose.model('Requirement', schema);
<commit_msg>Verificar se uma solicitação de aumento de limite de créditos deve ser aberta #1 - Refactoring<commit_after>var VError, async, mongoose, jsonSelect, nconf, courses, calendar, history, Schema, schema;

VError = require('verror');
async = require('async');
mongoose = require('mongoose');
jsonSelect = require('mongoose-json-select');
courses = require('dacos-courses-driver');
calendar = require('dacos-calendar-driver');
history = require('dacos-history-driver');
nconf = require('nconf');
Schema = mongoose.Schema;

schema = new Schema({
  'enrollment' : {
    'type'     : Schema.ObjectId,
    'ref'      : 'Enrollment',
    'required' : true
  },
  'discipline' : {
    'type'     : String,
    'required' : true
  },
  'offering'   : {
    'type'     : String,
    'required' : true
  },
  'status'     : {
    'type'    : String,
    'enum'    : [ 'new', 'approved', 'rejected', 'quit' ],
    'default' : 'new'
  },
  'comment'    : {
    'type' : String
  },
  'priority'   : {
    'type' : Number
  },
  'createdAt'  : {
    'type'    : Date,
    'default' : Date.now
  },
  'updatedAt'  : {
    'type' : Date
  }
}, {
  'collection' : 'requirements',
  'strict'     : true,
  'toJSON'     : {
    'virtuals' : true
  }
});

schema.index({
  'enrollment' : 1,
  'discipline' : 1,
  'offering'   : 1
}, {
  'unique' : true
});

schema.plugin(jsonSelect, {
  '_id'        : 0,
  'enrollment' : 1,
  'discipline' : 1,
  'offering'   : 1,
  'status'     : 1,
  'comment'    : 1,
  'priority'   : 1,
  'createdAt'  : 1,
  'updatedAt'  : 1
});

schema.pre('save', function setRequirementUpdatedAt(next) {
  'use strict';

  this.updatedAt = new Date();
  next();
});

schema.pre('save', function setPriorityScore(next) {
  'use strict';

  var priorityScore;

  this.populate('enrollment');
  this.populate(function () {
    getDisciplineInformation(this.enrollment, this.discipline, this.offering, function (blockType, isAhead, isReserved) {

      // Calculating priority score
      if (blockType === 'required') {
        // Obligatory discipline
        if (isAhead) {
          if (isReserved) {
            priorityScore = 6;
          } else {
            priorityScore = 3;
          }
        } else {
          if (isReserved) {
            priorityScore = 9;
          } else {
            priorityScore = 7;
          }
        }
      } else if (blockType === 'optional') {
        // Optional discipline
        if (isAhead) {
          if (isReserved) {
            priorityScore = 5;
          } else {
            priorityScore = 2;
          }
        } else {
          if (isReserved) {
            priorityScore = 8;
          } else {
            priorityScore = 4;
          }
        }
      } else if (blockType === 'extra') {
        // Extra-curricular discipline
        if (isAhead) {
          if (isReserved) {
            priorityScore = 1;
          } else {
            priorityScore = 0;
          }
        } else {
          // TODO check why this is equal to the last conditional
          if (isReserved) {
            priorityScore = 1;
          } else {
            priorityScore = 0;
          }
        }
      }

      this.priority = priorityScore;
      //console.log(this.priority);

      next();
    }.bind(this));
  }.bind(this));
});

function getDisciplineInformation(enrollment, discipline, disciplineOffering, next) {
  'use strict';

  var blockType , isAhead, isReserved;

  blockType = 'optional';
  isAhead = false;
  isReserved = false;

  history.currentHistory(enrollment.user, function (error, currentHistory) {

    if (error) {
      error = new VError(error, 'Error when trying to get the history');
      return next(error);
    }

    if (!currentHistory) {
      return next(false);
    }

    courses.blocks(currentHistory.year, currentHistory.course + ' ' + currentHistory.modality, function (error, blocks) {
      if (error) {
        return next('');
      }

      async.some(blocks, function(block) {

        courses.requirement(currentHistory.year, currentHistory.course + ' ' + currentHistory.modality, block.code, this.discipline, function (error, requirement) {
          if (requirement) {
            var currentDate = new Date();

            var currentSemester;
            if (currentDate.getMonth() < 6) {
              currentSemester = 1;
            } else if(currentDate.getMonth() > 6) {
              currentSemester = 2;
            } else {
              currentSemester = currentDate.getDay() < 15 ? 1 : 2;
            }

            //TODO figure out how to get the offering reservation

            var userSemester = (currentDate.getFullYear() - currentHistory.year) * 2 + currentSemester;
            //var offeringReservations = disciplineOffering && disciplineOffering.reservations || [];

            blockType = block.type;
            //isAhead = offeringReservations.some(function (offeringReservation) { return offeringReservation === historyId; });
            isReserved = requirement && (userSemester < requirement.suggestedSemester);

            //requirement.code

            next(true);
          }
          else {
            next(false);
          }
        });
      }, function(result) {
        next(blockType, isAhead, isReserved);
      });
    });
  });
}

/**
 * Verifica se uma solicitação de aumento de limite de créditos deve ser aberta
 */
schema.pre('save', function openCreditRaiseRequestIfNecessary(next) {
  'use strict';

  async.waterfall([function (next) {
    this.populate('enrollment');
    this.populate(next);
  }.bind(this), function (_, next) {
    async.parallel({
      'requirements': function (next) {
        var query;
        query = this.model('Requirement').find();
        query.where('enrollment').equals(this.enrollment._id);
        query.where('_id').ne(this._id);
        query.exec(next);
      }.bind(this),
      'modality'   : function (next) {
        async.waterfall([function (next) {
          history.currentHistory(this.enrollment.user, next);
        }.bind(this), function (currentHistory, next) {
          courses.modality(currentHistory.year, currentHistory.course + '-' + currentHistory.modality, next);
        }.bind(this)], next);
      }.bind(this)
    }, next);
  }.bind(this), function (data, next) {
    // sum the actual requirement together with all other requirements
    data.requirements.push(this);

    async.reduce(data.requirements, 0, function (sum, disciplineRequirement, next) {
      courses.discipline(disciplineRequirement.discipline, function (error, discipline) {
        next(error, discipline ? discipline.credits + sum : 0);
      }.bind(this));
    }.bind(this), function (error, credits) {
      if (error) {
        error = new VError(error, 'Error when trying to sum the credits');
        return next(error);
      }

      if (credits <= data.modality.creditLimit) {
        return next();
      }

      this.enrollment.creditRaiseRequest.credits = credits;
      this.enrollment.creditRaiseRequest.date = new Date();
      this.enrollment.creditRaiseRequest.status = 'pending';
      this.enrollment.save(next);
    }.bind(this));
  }.bind(this)], next);
});

schema.path('offering').validate(function validateIfDisciplineOfferingExists(value, next) {
  'use strict';

  courses.offering(this.discipline, this.offering, function foundDisciplineOffering(error, offering) {
    next(!error && !!offering);
  });
}, 'discipline offering not found');

schema.path('discipline').validate(function validateDisciplineRequirement(value, next) {
  'use strict';

  async.waterfall([function (next) {
    this.populate('enrollment');
    this.populate(next);
  }.bind(this), function (_, next) {
    async.parallel({
      'discipline': function (next) {
        courses.discipline(this.discipline, next);
      }.bind(this),
      'histories' : function (next) {
        history.histories(this.enrollment.user, next);
      }.bind(this)
    }, next);
  }.bind(this), function (data, next) {
    async.every(data.histories, function (userHistory) {
      if (data.discipline.requirements.length > 0) {
        data.discipline.requirements.forEach(function (disciplineRequirement) {
          history.discipline(this.enrollment.user, userHistory.year, disciplineRequirement.code, function (error, disciplineHistory) {
            next(!!error || (disciplineHistory && [1, 2, 3, 4, 7, 10, 11, 12, 13, 14, 15, 16, 20].lastIndexOf(disciplineHistory.status) > -1));
          }.bind(this));
        }.bind(this));
      }
      else {
        next();
      }
    }.bind(this), next);
  }.bind(this)], next);
}, 'discipline requirement not fulfilled');

schema.path('status').validate(function validateIfRequirementCanBeQuit(value, next) {
  'use strict';
  var todayDate, year;
  todayDate = new Date();
  year = todayDate.getFullYear();

  if (this.status === 'quit') {
    calendar.betweenEvents(todayDate, year, 'discipline-quit-starts', year, 'discipline-quit-ends', next);
  }
  else {
    next();
  }
}, 'outside of discipline quit period');

schema.path('discipline').validate(function validateDisciplineApproval(value, next) {
  'use strict';

  async.waterfall([function (next) {
    this.populate('enrollment');
    this.populate(next);
  }.bind(this), function (_, next) {
    async.parallel({
      'histories'  : function (next) {
        history.histories(this.enrollment.user, next);
      }.bind(this),
      'discipline' : function (next) {
        courses.discipline(this.discipline, next);
      }.bind(this)
    }, next);
  }.bind(this), function (data, next) {
    async.every(data.histories, function (userHistory, next) {
      history.discipline(this.enrollment.user, userHistory.year, data.discipline.code, function (error, disciplineHistory) {
        next(!!error || !(disciplineHistory && [1, 2, 3, 4, 7, 10, 11, 12, 13, 14, 15, 16, 20].lastIndexOf(disciplineHistory.status) > -1));
      }.bind(this));
    }.bind(this), next);
  }.bind(this)], next);
}, 'user was already approved on discipline');

schema.path('offering').validate(function validateIfRequirementHasTimeConflict(value, next) {
  'use strict';

  async.waterfall([function (next) {
    this.populate('enrollment');
    this.populate(next);
  }.bind(this), function (_, next) {
    async.parallel({
      'offering'    : function (next) {
        courses.offering(this.discipline, this.offering, next);
      }.bind(this),
      'requirements': function (next) {
        var query;

        query = this.model('Requirement').find();
        query.where('enrollment').equals(this.enrollment._id);
        query.where('_id').ne(this._id);
        query.where('discipline').ne(this.discipline);
        query.exec(next);
      }.bind(this)
    }, next);
  }.bind(this), function (data, next) {
    async.every(data.requirements, function (requirement, next) {
      courses.offering(requirement.discipline, requirement.offering, function foundDisciplineOffering(error, offeringConflict) {
        var conflict = data.offering.schedules.some(function (schedule) {
          return offeringConflict.schedules.some(function (otherSchedule) {
            return (schedule.weekday === otherSchedule.weekday && schedule.hour === otherSchedule.hour);
          });
        });

        next(!!error || !conflict);
      });
    }.bind(this), next);
  }.bind(this)], next);
}, 'discipline with time conflict');

module.exports = mongoose.model('Requirement', schema);
<|endoftext|>


<commit_before>/* Copyright (c) 2016 Ron Smeral. See the file LICENSE for copying permission. */
/*
* Emulates a proximity sensor by using the light sensor.
* (Obvious caveat - doesn't work well in dimly lit environments).
*
* Emits two events:
* 'near' - when an object approaches
* 'far' - when an object moves away
*/

var AVG_WND = 10;
var FLIP_FACTOR = 2;

var lightArr, lightDif, lightAvg, near, c, ivl;

var params = {
  // update frequency (Hz)
  freq: 2
};

var Proximity = {};

var mergeObj = function(tgt, src){Object.keys(src).forEach(e=>tgt[e]=src[e])};

function updateLightStats(l) {
  lightArr[c++%AVG_WND] = l;
  let lightMin = lightArr.reduce((min, v) => Math.min(min, v), 1);
  let lightMax = lightArr.reduce((max, v) => Math.max(max, v), 0);
  lightDif = lightMax-lightMin;
  lightAvg = E.sum(lightArr) / lightArr.length;
}

function proximity() {
  let l = Puck.light();
  if(!near) {
    if(lightAvg - l > FLIP_FACTOR * lightDif) {
      near = true;
      Proximity.emit("near");
    } else updateLightStats(l);
  } else {
    if(lightAvg - l < FLIP_FACTOR * lightDif) {
      near = false;
      Proximity.emit("far");
    }
  }
}

function start() {
  lightArr = [0.5];
  lightDif = 0;
  lightAvg = 0;
  near = false;
  c = 1;
  ivl = setInterval(proximity, 1000/params.freq);
}

function stop() {
  if(ivl) clearInterval(ivl);
  ivl = null;
}

Proximity.start = start;
Proximity.stop = stop;

exports = function(_params) {
  mergeObj(params, _params);
  return Proximity;
};
<commit_msg>Proximity: improved perf and reliability, reduced footprint<commit_after>/* Copyright (c) 2016 Ron Smeral. See the file LICENSE for copying permission. */
/*
* Emulates a proximity sensor by using the light sensor.
* (Obvious caveat - doesn't work well in dimly lit environments).
*
* Emits two events:
* 'near' - when an object approaches
* 'far' - when an object moves away
*/

var arr, avg, near, c, d, ivl;

var params = {
  // update frequency (Hz)
  // higher freq. increases responsiveness, but decreases reliability
  freq: 2,
  // average window size
  // smaller window increases responsiveness, but decreases reliability
  denoise: 3,
  // flip threshold as percentage  of average light (value in <0,1>)
  thresh: 0.8,
  // minimum number of milliseconds between flips
  debounce: 200
};

var Prox = {
  start: function(){
    arr = new Float32Array(params.denoise);
    avg = Puck.light();
    near = -1;
    c = d = 0;
    arr[c++] = avg;
    ivl = setInterval(prox, 1000/params.freq, params.thresh, params.denoise, params.debounce/1000,arr);
  },
  stop: function(){
    if(ivl) clearInterval(ivl);
    ivl = null;
  }
};

function prox(th,dn,db,ar) {
  let l = Puck.light();

  if((near*(l-avg*th) > 0) && getTime()-d > db) {
    near *= -1;
    Prox.emit(near>0?"near":"far");
    d=getTime();
  }
  if(near<0) {
    ar[c++%dn] = l;
    avg = E.sum(ar)/dn;
  }
}

exports = function(_params) {
  Object.keys(_params).forEach(e=>params[e]=_params[e]);
  return Prox;
};
<|endoftext|>


<commit_before>//
//  Author: Vlad Seryakov vseryakov@gmail.com
//  Sep 2013
//

var path = require('path');
var util = require('util');
var fs = require('fs');
var http = require('http');
var url = require('url');
var bkjs = require('backendjs');
var db = bkjs.db;
var api = bkjs.api;
var app = bkjs.app;
var ipc = bkjs.ipc;
var msg = bkjs.msg;
var core = bkjs.core;
var lib = bkjs.lib;
var logger = bkjs.logger;

// Status management
var mod = {
    name: "bk_status",
    args: [
        { name: "interval", type: "number", min: 0, max: 86400000, descr: "Number of milliseconds between status record updates, presence is considered offline if last access was more than this interval ago" },
    ],
    tables: {
        bk_status: {
            id: { primary: 1, pub: 1 },                        // account id
            status: { pub: 1 },                                // status, online, offline, away
            name: { pub: 1 },
            atime: { type: "now", pub: 1 },                   // last access time
            mtime: { type: "now", pub: 1 },                   // last update time
        },
    },
    // Intervals between updating presence status table
    statusInterval: 90000,
};
module.exports = mod;

// Returns status record for given account, used in /status/get API call.
// It always returns status object even if it was never set before, on return the record contains
// a property `online` set to true of false according to the idle period and actual status.
//
// If id is an array, then return all status records for specified list of account ids.
//
// If status was explicitely set to `offline` then it is considered offline until changed to other value,
// for other cases `status` property is not used, it is supposed for the application extention.
//
mod.get = function(id, options, callback)
{
    if (typeof options == "function") callback = options, options = null;
    var now = Date.now();

    if (Array.isArray(id)) {
        db.list("bk_status", id, options, function(err, rows) {
            if (err) return callback(err);
            rows = rows.filter(function(row) {
                row.online = now - row.atime < mod.statusInterval && row.status != "offline" ? true : false;
            });
            callback(err, rows);
        });
    } else {
        db.get("bk_status", { id: id }, options, function(err, status, info) {
            if (err) return callback(err);
            if (!status) status = { id: id, status: "", online: false, atime: 0, mtime: 0 };
            status.online = now - status.atime < mod.statusInterval && status.status != "offline" ? true : false;
            status._cached = info.cached;
            callback(err, status);
        });
    }
}

// Maintain online status, update to db every status-interval seconds, only update the db if last update happened
// longer than `status-interval` milliseconds ago, keep atime up-to-date in the cache on every status update.
//
// On return and if it was flushed to db the `atime` will be equal to `mtime`.
//
// *NOTE: All properties from the `obj` will be saved in the bk_status record, existing properties will be overriden*
mod.update = function(status, options, callback)
{
    if (typeof options == "function") callback = options, options = null;
    if (status.online && status.atime - status.mtime < mod.statusInterval && status._cached) {
        status.atime = Date.now();
        db.putCache("bk_status", status, options);
        lib.tryCall(callback, null, status);
    } else {
        db.put("bk_status", status, { info_obj: 1 }, function(err, data, info)  {
            lib.tryCall(callback, err, info.obj);
        });
    }
}

mod.del = function(status, options, callback)
{
    if (typeof options == "function") callback = options, options = null;
    db.del("bk_status", status, callback);
}

// This methods is suitable for background jobs
mod.bkDeleteAccount = function(req, callback)
{
    if (req.options.keep_all || req.options.keep_status) return callback();
    db.del("bk_status", { id: req.account.id }, req.options, callback);
}

<commit_msg>interval corrected<commit_after>//
//  Author: Vlad Seryakov vseryakov@gmail.com
//  Sep 2013
//

var path = require('path');
var util = require('util');
var fs = require('fs');
var http = require('http');
var url = require('url');
var bkjs = require('backendjs');
var db = bkjs.db;
var api = bkjs.api;
var app = bkjs.app;
var ipc = bkjs.ipc;
var msg = bkjs.msg;
var core = bkjs.core;
var lib = bkjs.lib;
var logger = bkjs.logger;

// Status management
var mod = {
    name: "bk_status",
    tables: {
        bk_status: {
            id: { primary: 1, pub: 1 },                        // account id
            status: { pub: 1 },                                // status, online, offline, away
            name: { pub: 1 },
            atime: { type: "now", pub: 1 },                   // last access time
            mtime: { type: "now", pub: 1 },                   // last update time
        },
    },
    // Intervals between updating presence status table
    args: [
        { name: "interval", type: "number", min: 60000, max: 86400000, descr: "Number of milliseconds between status record updates, presence is considered offline if last access was more than this interval ago" },
    ],
    interval: 900000,
};
module.exports = mod;

// Returns status record for given account, used in /status/get API call.
// It always returns status object even if it was never set before, on return the record contains
// a property `online` set to true of false according to the idle period and actual status.
//
// If id is an array, then return all status records for specified list of account ids.
//
// If status was explicitely set to `offline` then it is considered offline until changed to other value,
// for other cases `status` property is not used, it is supposed for the application extention.
//
mod.get = function(id, options, callback)
{
    if (typeof options == "function") callback = options, options = null;
    var now = Date.now();

    if (Array.isArray(id)) {
        db.list("bk_status", id, options, function(err, rows) {
            if (err) return callback(err);
            rows = rows.filter(function(row) {
                row.online = now - row.atime < mod.statusInterval && row.status != "offline" ? true : false;
            });
            callback(err, rows);
        });
    } else {
        db.get("bk_status", { id: id }, options, function(err, status, info) {
            if (err) return callback(err);
            if (!status) status = { id: id, status: "", online: false, atime: 0, mtime: 0 };
            status.online = now - status.atime < mod.statusInterval && status.status != "offline" ? true : false;
            status._cached = info.cached;
            callback(err, status);
        });
    }
}

// Maintain online status, update to db every status-interval seconds, only update the db if last update happened
// longer than `status-interval` milliseconds ago, keep atime up-to-date in the cache on every status update.
//
// On return and if it was flushed to db the `atime` will be equal to `mtime`.
//
// *NOTE: All properties from the `obj` will be saved in the bk_status record, existing properties will be overriden*
mod.update = function(status, options, callback)
{
    if (typeof options == "function") callback = options, options = null;
    if (status.online && status.atime - status.mtime < mod.statusInterval && status._cached) {
        status.atime = Date.now();
        db.putCache("bk_status", status, options);
        lib.tryCall(callback, null, status);
    } else {
        db.put("bk_status", status, { info_obj: 1 }, function(err, data, info)  {
            lib.tryCall(callback, err, info.obj);
        });
    }
}

mod.del = function(status, options, callback)
{
    if (typeof options == "function") callback = options, options = null;
    db.del("bk_status", status, callback);
}

// This methods is suitable for background jobs
mod.bkDeleteAccount = function(req, callback)
{
    if (req.options.keep_all || req.options.keep_status) return callback();
    db.del("bk_status", { id: req.account.id }, req.options, callback);
}

<|endoftext|>


<commit_before>/**
 * Order should be a String (with the property name assumed ascending)
 * or an Array or property String names.
 *
 * Examples:
 *
 * 1. 'property1' (ORDER BY property1 ASC)
 * 2. '-property1' (ORDER BY property1 DESC)
 * 3. [ 'property1' ] (ORDER BY property1 ASC)
 * 4. [ '-property1' ] (ORDER BY property1 DESC)
 * 5. [ 'property1', 'A' ] (ORDER BY property1 ASC)
 * 6. [ 'property1', 'Z' ] (ORDER BY property1 DESC)
 * 7. [ '-property1', 'A' ] (ORDER BY property1 ASC)
 * 8. [ 'property1', 'property2' ] (ORDER BY property1 ASC, property2 ASC)
 * 9. [ 'property1', '-property2' ] (ORDER BY property1 ASC, property2 DESC)
 * ...
 */
exports.standardizeOrder = function (order) {
	if (typeof order === "string") {
		if (order[0] === "-") {
			return [ [ order.substr(1), "Z" ] ];
		}
		return [ [ order, "A" ] ];
	}

	var new_order = [], minus;

	for (var i = 0; i < order.length; i++) {
		minus = (order[i][0] === "-");

		if (i < order.length - 1 && [ "A", "Z" ].indexOf(order[i + 1].toUpperCase()) >= 0) {
			new_order.push([
				(minus ? order[i].substr(1) : order[i]),
				order[i + 1]
			]);
			i += 1;
		} else if (minus) {
			new_order.push([ order[i].substr(1), "Z" ]);
		} else {
			new_order.push([ order[i], "A" ]);
		}
	}

	return new_order;
};

/**
 * Operations
 * A) Build an index of associations, with their name as the key
 * B) Check for any conditions with a key in the association index
 * C) Ensure that our condition supports array values
 * D) Remove original condition (not DB compatible)
 * E) Convert our association fields into an array, indexes are the same as model.id
 * F) Itterate through values for the condition, only accept instances of the same type as the association
 */
exports.checkConditions = function (conditions, one_associations) {
    var k, i, j;

    // A)
    var associations = {};
    for (i = 0; i < one_associations.length; i++) {
        associations[one_associations[i].name] = one_associations[i];
    }

    for (k in conditions) {
        // B)
        if (!associations.hasOwnProperty(k)) continue;

        // C)
        var values = conditions[k];
        if (!Array.isArray(values)) values = [values];

        // D)
        delete conditions[k];

        // E)
        var association_fields = Object.keys(associations[k].field);
        var model = associations[k].model;

        // F)
        for (i = 0; i < values.length; i++) {
            if (values[i].isInstance && values[i].model().uid === model.uid) {
                if (association_fields.length === 1) {
                    if (typeof conditions[association_fields[0]] === 'undefined')
                        conditions[association_fields[0]] = values[i][model.id[0]];
                    else if(Array.isArray(conditions[association_fields[0]]))
                        conditions[association_fields[0]].push(values[i][model.id[0]]);
                    else
                        conditions[association_fields[0]] = [conditions[association_fields[0]], values[i][model.id[0]]];
                } else {
                    var _conds = {};
                    for (j = 0; j < association_fields.length; i++) {
                        _conds[association_fields[j]] = values[i][model.id[j]];
                    }

                    conditions.or = conditions.or || [];
                    conditions.or.push(_conds);
                }
            }
        }
    }

    return conditions;
};

/**
 * Gets all the values within an object or array, optionally
 * using a keys array to get only specific values
 */
exports.values = function (obj, keys) {
	var i, k, vals = [];

	if (keys) {
		for (i = 0; i < keys.length; i++) {
			vals.push(obj[keys[i]]);
		}
	} else if (Array.isArray(obj)) {
		for (i = 0; i < obj.length; i++) {
			vals.push(obj[i]);
		}
	} else {
		for (k in obj) {
			if (!/[0-9]+/.test(k)) {
				vals.push(obj[k]);
			}
		}
	}
	return vals;
};

exports.hasValues = function (obj, keys) {
	for (var i = 0; i < keys.length; i++) {
		if (!obj[keys[i]]) return false;
	}
	return true;
};

exports.populateConditions = function (model, fields, source, target, overwrite) {
    for (var i = 0; i < model.id.length; i++) {
        if (typeof target[fields[i]] === 'undefined' || overwrite !== false) {
            target[fields[i]] = source[model.id[i]];
        } else if (Array.isArray(target[fields[i]])) {
            target[fields[i]].push(source[model.id[i]]);
        } else {
            target[fields[i]] = [target[fields[i]], source[model.id[i]]];
        }
    }
};

exports.getConditions = function (model, fields, from) {
    var conditions = {};

    exports.populateConditions(model, fields, from, conditions);

    return conditions;
};

exports.wrapFieldObject = function (obj, model, altName, alternatives) {
	if (!obj) {
		var assoc_key = model.settings.get("properties.association_key");

		if (typeof assoc_key === "function") {
			obj = assoc_key(altName.toLowerCase(), 'id');
		} else {
			obj = assoc_key.replace("{name}", altName.toLowerCase())
			               .replace("{field}", 'id');
		}
	}

	for (var k in obj) {
		if (!/[0-9]+/.test(k) && obj.hasOwnProperty(k)) {
			return obj;
		}
	}

	var new_obj = {};

	new_obj[obj] = alternatives[obj] || alternatives[model.id[0]] || { type: 'number', unsigned: true, rational: false };

	return new_obj;
};

exports.formatField = function (model, name, required, reversed) {
	var fields = {}, field_opts, field_name;
	var keys = model.id;
	var assoc_key = model.settings.get("properties.association_key");

	for (var i = 0; i < keys.length; i++) {
		if (reversed) {
			field_name = keys[i];
		} else if (typeof assoc_key === "function") {
			field_name = assoc_key(name.toLowerCase(), keys[i]);
		} else {
			field_name = assoc_key.replace("{name}", name.toLowerCase())
			                      .replace("{field}", keys[i]);
		}

		if (model.properties.hasOwnProperty(keys[i])) {
			var p = model.properties[keys[i]];

			field_opts = {
				type     : p.type || "number",
				size     : p.size || 4,
				rational : p.rational || false,
				unsigned : p.unsigned || true,
				time     : p.time || false,
				big      : p.big || false,
				values   : p.values || null,
				required : required
			};
		} else {
			field_opts = {
				type     : "number",
				unsigned : true,
				rational : false,
				size     : 4,
				required : required
			};
		}

		fields[field_name] = field_opts;
	}

	return fields;
};

exports.getRealPath = function (path_str, stack_index) {
	var path = require("path"); // for now, load here (only when needed)
	var cwd = process.cwd();
	var err = new Error();
	var tmp = err.stack.split(/\r?\n/)[typeof stack_index !== "undefined" ? stack_index : 3], m;

	if ((m = tmp.match(/^\s*at\s+(.+):\d+:\d+$/)) !== null) {
		cwd = path.dirname(m[1]);
	} else if ((m = tmp.match(/^\s*at\s+module\.exports\s+\((.+?)\)/)) !== null) {
		cwd = path.dirname(m[1]);
	} else if ((m = tmp.match(/^\s*at\s+.+\s+\((.+):\d+:\d+\)$/)) !== null) {
		cwd = path.dirname(m[1]);
	}

	if (path_str[0] !== path.sep) {
		path_str = cwd + "/" + path_str;
	}
	if (path_str.substr(-1) === path.sep) {
		path_str += "index";
	}

	return path_str;
};
<commit_msg>Spaces -> tabs<commit_after>/**
 * Order should be a String (with the property name assumed ascending)
 * or an Array or property String names.
 *
 * Examples:
 *
 * 1. 'property1' (ORDER BY property1 ASC)
 * 2. '-property1' (ORDER BY property1 DESC)
 * 3. [ 'property1' ] (ORDER BY property1 ASC)
 * 4. [ '-property1' ] (ORDER BY property1 DESC)
 * 5. [ 'property1', 'A' ] (ORDER BY property1 ASC)
 * 6. [ 'property1', 'Z' ] (ORDER BY property1 DESC)
 * 7. [ '-property1', 'A' ] (ORDER BY property1 ASC)
 * 8. [ 'property1', 'property2' ] (ORDER BY property1 ASC, property2 ASC)
 * 9. [ 'property1', '-property2' ] (ORDER BY property1 ASC, property2 DESC)
 * ...
 */
exports.standardizeOrder = function (order) {
	if (typeof order === "string") {
		if (order[0] === "-") {
			return [ [ order.substr(1), "Z" ] ];
		}
		return [ [ order, "A" ] ];
	}

	var new_order = [], minus;

	for (var i = 0; i < order.length; i++) {
		minus = (order[i][0] === "-");

		if (i < order.length - 1 && [ "A", "Z" ].indexOf(order[i + 1].toUpperCase()) >= 0) {
			new_order.push([
				(minus ? order[i].substr(1) : order[i]),
				order[i + 1]
			]);
			i += 1;
		} else if (minus) {
			new_order.push([ order[i].substr(1), "Z" ]);
		} else {
			new_order.push([ order[i], "A" ]);
		}
	}

	return new_order;
};

/**
 * Operations
 * A) Build an index of associations, with their name as the key
 * B) Check for any conditions with a key in the association index
 * C) Ensure that our condition supports array values
 * D) Remove original condition (not DB compatible)
 * E) Convert our association fields into an array, indexes are the same as model.id
 * F) Itterate through values for the condition, only accept instances of the same type as the association
 */
exports.checkConditions = function (conditions, one_associations) {
	var k, i, j;

	// A)
	var associations = {};
	for (i = 0; i < one_associations.length; i++) {
		associations[one_associations[i].name] = one_associations[i];
	}

	for (k in conditions) {
		// B)
		if (!associations.hasOwnProperty(k)) continue;

		// C)
		var values = conditions[k];
		if (!Array.isArray(values)) values = [values];

		// D)
		delete conditions[k];

		// E)
		var association_fields = Object.keys(associations[k].field);
		var model = associations[k].model;

		// F)
		for (i = 0; i < values.length; i++) {
			if (values[i].isInstance && values[i].model().uid === model.uid) {
				if (association_fields.length === 1) {
					if (typeof conditions[association_fields[0]] === 'undefined') {
						conditions[association_fields[0]] = values[i][model.id[0]];
					} else if(Array.isArray(conditions[association_fields[0]])) {
						conditions[association_fields[0]].push(values[i][model.id[0]]);
					} else {
						conditions[association_fields[0]] = [conditions[association_fields[0]], values[i][model.id[0]]];
					}
				} else {
					var _conds = {};
					for (j = 0; j < association_fields.length; i++) {
						_conds[association_fields[j]] = values[i][model.id[j]];
					}

					conditions.or = conditions.or || [];
					conditions.or.push(_conds);
				}
			}
		}
	}

	return conditions;
};

/**
 * Gets all the values within an object or array, optionally
 * using a keys array to get only specific values
 */
exports.values = function (obj, keys) {
	var i, k, vals = [];

	if (keys) {
		for (i = 0; i < keys.length; i++) {
			vals.push(obj[keys[i]]);
		}
	} else if (Array.isArray(obj)) {
		for (i = 0; i < obj.length; i++) {
			vals.push(obj[i]);
		}
	} else {
		for (k in obj) {
			if (!/[0-9]+/.test(k)) {
				vals.push(obj[k]);
			}
		}
	}
	return vals;
};

exports.hasValues = function (obj, keys) {
	for (var i = 0; i < keys.length; i++) {
		if (!obj[keys[i]]) return false;
	}
	return true;
};

exports.populateConditions = function (model, fields, source, target, overwrite) {
	for (var i = 0; i < model.id.length; i++) {
		if (typeof target[fields[i]] === 'undefined' || overwrite !== false) {
			target[fields[i]] = source[model.id[i]];
		} else if (Array.isArray(target[fields[i]])) {
			target[fields[i]].push(source[model.id[i]]);
		} else {
			target[fields[i]] = [target[fields[i]], source[model.id[i]]];
		}
	}
};

exports.getConditions = function (model, fields, from) {
	var conditions = {};

	exports.populateConditions(model, fields, from, conditions);

	return conditions;
};

exports.wrapFieldObject = function (obj, model, altName, alternatives) {
	if (!obj) {
		var assoc_key = model.settings.get("properties.association_key");

		if (typeof assoc_key === "function") {
			obj = assoc_key(altName.toLowerCase(), 'id');
		} else {
			obj = assoc_key.replace("{name}", altName.toLowerCase())
			               .replace("{field}", 'id');
		}
	}

	for (var k in obj) {
		if (!/[0-9]+/.test(k) && obj.hasOwnProperty(k)) {
			return obj;
		}
	}

	var new_obj = {};

	new_obj[obj] = alternatives[obj] || alternatives[model.id[0]] || { type: 'number', unsigned: true, rational: false };

	return new_obj;
};

exports.formatField = function (model, name, required, reversed) {
	var fields = {}, field_opts, field_name;
	var keys = model.id;
	var assoc_key = model.settings.get("properties.association_key");

	for (var i = 0; i < keys.length; i++) {
		if (reversed) {
			field_name = keys[i];
		} else if (typeof assoc_key === "function") {
			field_name = assoc_key(name.toLowerCase(), keys[i]);
		} else {
			field_name = assoc_key.replace("{name}", name.toLowerCase())
			                      .replace("{field}", keys[i]);
		}

		if (model.properties.hasOwnProperty(keys[i])) {
			var p = model.properties[keys[i]];

			field_opts = {
				type     : p.type || "number",
				size     : p.size || 4,
				rational : p.rational || false,
				unsigned : p.unsigned || true,
				time     : p.time || false,
				big      : p.big || false,
				values   : p.values || null,
				required : required
			};
		} else {
			field_opts = {
				type     : "number",
				unsigned : true,
				rational : false,
				size     : 4,
				required : required
			};
		}

		fields[field_name] = field_opts;
	}

	return fields;
};

exports.getRealPath = function (path_str, stack_index) {
	var path = require("path"); // for now, load here (only when needed)
	var cwd = process.cwd();
	var err = new Error();
	var tmp = err.stack.split(/\r?\n/)[typeof stack_index !== "undefined" ? stack_index : 3], m;

	if ((m = tmp.match(/^\s*at\s+(.+):\d+:\d+$/)) !== null) {
		cwd = path.dirname(m[1]);
	} else if ((m = tmp.match(/^\s*at\s+module\.exports\s+\((.+?)\)/)) !== null) {
		cwd = path.dirname(m[1]);
	} else if ((m = tmp.match(/^\s*at\s+.+\s+\((.+):\d+:\d+\)$/)) !== null) {
		cwd = path.dirname(m[1]);
	}

	if (path_str[0] !== path.sep) {
		path_str = cwd + "/" + path_str;
	}
	if (path_str.substr(-1) === path.sep) {
		path_str += "index";
	}

	return path_str;
};
<|endoftext|>


<commit_before>/*
 *
 * CS3283/4 - query.js
 * This class deals with query statements for the facade storage
 * This class will communicate with sqlCommands to get a certain command for
 *
 */

import SqlCommands from 'src/database/sql-related/sqlCommands';
import exceptions from 'src/database/exceptions';
import constants from 'src/database/constants';
import StringManipulator from 'src/database/stringManipulation';

const stringManipulator = new StringManipulator();

const sqlCommands = new SqlCommands();

// dummy function to init sequence running for code aesthetic below
function initPromiseSequence() {
  return new Promise((resolve, reject) =>
    resolve()
  );
}

export default class query {
  static constructor() {}

  static getAllFilesAndFolders() {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) => {
        const promiseArr = [];
        initPromiseSequence()
        .then(() =>
          sqlCommands.getFullTableData(constants.ENTITIES_FILE_MANAGER)
          .then(fileArr => promiseArr.push(fileArr))
          .catch(sqlError => reject(sqlError)))
        .then(() =>
          sqlCommands.getFullTableData(constants.ENTITIES_FOLDER)
          .then(folderArr => promiseArr.push(folderArr))
          .catch(sqlError => reject(sqlError)))
        .then(() => resolve(promiseArr))
        .catch(sqlErr => reject(sqlErr));
      });
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static isTableExistsInDatabase(tableName) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        sqlCommands.getFullTableData(tableName)
        .then(() => resolve(true))
        .catch(sqlErr => resolve(false))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static getFullTableData(tableName) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        sqlCommands.getFullTableData(tableName)
        .then(data => resolve(data))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static searchString(searchString) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) => {
        const promiseArr = [];

        initPromiseSequence()
        .then(() => sqlCommands.partialSearchFileName(searchString)
          .then(fileArr => promiseArr.push(fileArr))
          .catch(sqlError => reject(sqlError)))
        .then(() => sqlCommands.partialSearchFolderName(searchString)
          .then(folderArr => promiseArr.push(folderArr))
          .catch(sqlError => reject(sqlError)))
        .then(() => resolve(promiseArr))
        .catch(sqlErr => reject(sqlErr));
      });
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static loadFolder(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) => {
        const promiseArr = [];

        initPromiseSequence()
        .then(() => sqlCommands.loadFilesFromFolder(folderId)
          .then(fileArr => promiseArr.push(fileArr))
          .catch(sqlError => reject(sqlError)))
        .then(() => sqlCommands.loadFoldersFromFolder(folderId)
          .then(folderArr => promiseArr.push(folderArr))
          .catch(sqlError => reject(sqlError)))
        .then(() => resolve(promiseArr))
        .catch(sqlError => reject(sqlError));
      });
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static loadFile(fileId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        sqlCommands.loadFile(fileId)
        .then(data => resolve(data))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }
}
<commit_msg>Add handling of ' " ' handling in loadFile.js<commit_after>/*
 *
 * CS3283/4 - query.js
 * This class deals with query statements for the facade storage
 * This class will communicate with sqlCommands to get a certain command for
 *
 */

import SqlCommands from 'src/database/sql-related/sqlCommands';
import exceptions from 'src/database/exceptions';
import constants from 'src/database/constants';
import StringManipulator from 'src/database/stringManipulation';

const stringManipulator = new StringManipulator();

const sqlCommands = new SqlCommands();

// dummy function to init sequence running for code aesthetic below
function initPromiseSequence() {
  return new Promise((resolve, reject) =>
    resolve()
  );
}

export default class query {
  static constructor() {}

  static getAllFilesAndFolders() {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) => {
        const promiseArr = [];
        initPromiseSequence()
        .then(() =>
          sqlCommands.getFullTableData(constants.ENTITIES_FILE_MANAGER)
          .then(fileArr => promiseArr.push(fileArr))
          .catch(sqlError => reject(sqlError)))
        .then(() =>
          sqlCommands.getFullTableData(constants.ENTITIES_FOLDER)
          .then(folderArr => promiseArr.push(folderArr))
          .catch(sqlError => reject(sqlError)))
        .then(() => resolve(promiseArr))
        .catch(sqlErr => reject(sqlErr));
      });
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static isTableExistsInDatabase(tableName) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        sqlCommands.getFullTableData(tableName)
        .then(() => resolve(true))
        .catch(sqlErr => resolve(false))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static getFullTableData(tableName) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        sqlCommands.getFullTableData(tableName)
        .then(data => resolve(data))
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static searchString(searchString) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) => {
        const promiseArr = [];

        initPromiseSequence()
        .then(() => sqlCommands.partialSearchFileName(searchString)
          .then(fileArr => promiseArr.push(fileArr))
          .catch(sqlError => reject(sqlError)))
        .then(() => sqlCommands.partialSearchFolderName(searchString)
          .then(folderArr => promiseArr.push(folderArr))
          .catch(sqlError => reject(sqlError)))
        .then(() => resolve(promiseArr))
        .catch(sqlErr => reject(sqlErr));
      });
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static loadFolder(folderId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) => {
        const promiseArr = [];

        initPromiseSequence()
        .then(() => sqlCommands.loadFilesFromFolder(folderId)
          .then(fileArr => promiseArr.push(fileArr))
          .catch(sqlError => reject(sqlError)))
        .then(() => sqlCommands.loadFoldersFromFolder(folderId)
          .then(folderArr => promiseArr.push(folderArr))
          .catch(sqlError => reject(sqlError)))
        .then(() => resolve(promiseArr))
        .catch(sqlError => reject(sqlError));
      });
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }

  static loadFile(fileId) {
    if (typeof Promise === 'function') {
      return new Promise((resolve, reject) =>
        sqlCommands.loadFile(fileId)
        .then((fileContent) => {
          fileContent = stringManipulator.replaceAll(fileContent, '\\"', '"');
          resolve(fileContent);
        })
        .catch(sqlError => reject(sqlError))
      );
    } else {
      throw new exceptions.PromiseFunctionNotDefined();
    }
  }
}
<|endoftext|>


<commit_before>import Delta from 'rich-text/lib/delta';
import Parchment from 'parchment';
import Quill from '../core/quill';
import logger from '../core/logger';
import Module from '../core/module';
import { BlockEmbed } from '../blots/block';

import { AlignStyle } from '../formats/align';
import { BackgroundStyle } from '../formats/background';
import { ColorStyle } from '../formats/color';
import { DirectionStyle } from '../formats/direction';
import { FontStyle } from '../formats/font';
import { SizeStyle } from '../formats/size';

let debug = logger('quill:clipboard');

const STYLE_ATTRIBUTORS = [
  AlignStyle,
  BackgroundStyle,
  ColorStyle,
  DirectionStyle,
  FontStyle,
  SizeStyle
].reduce(function(memo, attr) {
  memo[attr.keyName] = attr;
  return memo;
}, {});

class Clipboard extends Module {
  constructor(quill, options) {
    if (options.matchers !== Clipboard.DEFAULTS.matchers) {
      options.matchers = Clipboard.DEFAULTS.matchers.concat(options.matchers);
    }
    super(quill, options);
    this.quill.root.addEventListener('copy', this.onCopy.bind(this));
    this.quill.root.addEventListener('cut', this.onCut.bind(this));
    this.quill.root.addEventListener('paste', this.onPaste.bind(this));
    this.container = this.quill.addContainer('ql-clipboard');
    this.container.setAttribute('contenteditable', true);
    this.container.setAttribute('tabindex', -1);
    this.matchers = [];
    this.options.matchers.forEach((pair) => {
      this.addMatcher(...pair);
    });
  }

  addMatcher(selector, matcher) {
    this.matchers.push([selector, matcher]);
  }

  clean() {
    let treeWalker = document.createTreeWalker(this.container, NodeFilter.SHOW_COMMENT);
    let comments = [];
    while(treeWalker.nextNode()) {
      comments.push(treeWalker.currentNode);
    }
    comments.forEach(function(node) {
      if (node != null && node.parentNode != null) {
        node.parentNode.removeChild(node);
      }
    });
    this.container.normalize();
  }

  convert(html) {
    const DOM_KEY = '__ql-matcher';
    if (typeof html === 'string') {
      this.container.innerHTML = html;
    }
    this.clean();
    this.matchers.forEach((pair) => {
      let [selector, matcher] = pair;
      if (typeof selector === 'string') {
        [].forEach.call(this.container.querySelectorAll(selector), (node) => {
          // TODO use weakmap
          node[DOM_KEY] = node[DOM_KEY] || [];
          node[DOM_KEY].push(matcher);
        });
      }
    });
    let traverse = (node) => {  // Post-order
      return [].reduce.call(node.childNodes || [], (delta, childNode) => {
        let childrenDelta = traverse(childNode);
        childrenDelta = this.matchers.reduce(function(childrenDelta, pair) {
          let [type, matcher] = pair;
          if (type === true || childNode.nodeType === type) {
            childrenDelta = matcher(childNode, childrenDelta);
          }
          return childrenDelta;
        }, childrenDelta);
        childrenDelta = (childNode[DOM_KEY] || []).reduce(function(childrenDelta, matcher) {
          return matcher(childNode, childrenDelta);
        }, childrenDelta);
        return delta.concat(childrenDelta);
      }, new Delta());
    };
    let delta = traverse(this.container);
    // Remove trailing newline
    if (deltaEndsWith(delta, '\n') && delta.ops[delta.ops.length - 1].attributes == null) {
      delta = delta.compose(new Delta().retain(delta.length() - 1).delete(1));
    }
    debug.info('convert', this.container.innerHTML, delta);
    this.container.innerHTML = '';
    return delta;
  }

  onCopy(e) {
    let range = this.quill.getSelection();
    if (range == null || range.length === 0 || e.defaultPrevented) return;
    let clipboard = e.clipboardData || window.clipboardData;
    clipboard.setData('text', this.quill.getText(range));
    if (e.clipboardData) {  // IE11 does not let us set non-text data
      clipboard.setData('application/json', JSON.stringify(this.quill.getContents(range)));
    }
    e.preventDefault();
  }

  onCut(e) {
    if (e.defaultPrevented) return;
    this.onCopy(e);
    let range = this.quill.getSelection();
    this.quill.deleteText(range, Quill.sources.USER);
    this.quill.setSelection(range.index, Quill.sources.SILENT);
  }

  onPaste(e) {
    if (e.defaultPrevented) return;
    let range = this.quill.getSelection();
    let clipboard = e.clipboardData || window.clipboardData;
    let delta = new Delta().retain(range.index).delete(range.length);
    let done = (delta) => {
      this.quill.updateContents(delta, Quill.sources.USER);
      // range.length contributes to delta.length()
      this.quill.setSelection(delta.length() - range.length, Quill.sources.SILENT);
      this.quill.selection.scrollIntoView();
    };
    let intercept = (delta, callback) => {
      this.container.focus();
      setTimeout(() => {
        let html = this.container.innerHTML;
        delta = delta.concat(this.convert());
        callback(delta);
      }, 1);
    };
    // Firefox types is an iterable, not array
    // IE11 types can be null
    if ([].indexOf.call(clipboard.types || [], 'application/json') > -1) {
      try {
        let pasteJSON = JSON.parse(clipboard.getData('application/json'));
        done(delta.concat(pasteJSON));
      } catch(err) {
        intercept(delta, done);
      }
      e.preventDefault();
    } else {
      intercept(delta, done);
    }
  }
}
Clipboard.DEFAULTS = {
  matchers: [
    [Node.TEXT_NODE, matchText],
    [Node.ELEMENT_NODE, matchNewline],
    [Node.ELEMENT_NODE, matchBlot],
    [Node.ELEMENT_NODE, matchSpacing],
    [Node.ELEMENT_NODE, matchAttributor],
    ['b', matchAlias.bind(matchAlias, 'bold')],
    ['i', matchAlias.bind(matchAlias, 'italic')]
  ]
};

function computeStyle(node) {
  if (node.nodeType !== Node.ELEMENT_NODE) return {};
  const DOM_KEY = '__ql-computed-style';
  return node[DOM_KEY] || (node[DOM_KEY] = window.getComputedStyle(node));
}

function deltaEndsWith(delta, text) {
  let endText = "";
  for (let i = delta.ops.length - 1; i >= 0 && endText.length < text.length; --i) {
    let op  = delta.ops[i];
    if (typeof op.insert !== 'string') break;
    endText = op.insert + endText;
  }
  return endText.slice(-1*text.length) === text;
}

function isLine(node) {
  if (node.childNodes.length === 0) return false;   // Exclude embed blocks
  let style = computeStyle(node);
  return ['block', 'list-item'].indexOf(style.display) > -1;
}

function matchAlias(format, node, delta) {
  return delta.compose(new Delta().retain(delta.length(), { [format]: true }));
}

function matchAttributor(node, delta) {
  let attributes = Parchment.Attributor.Attribute.keys(node);
  let classes = Parchment.Attributor.Class.keys(node);
  let styles = Parchment.Attributor.Style.keys(node);
  let formats = {};
  attributes.concat(classes).concat(styles).forEach((name) => {
    let attr = Parchment.query(name, Parchment.Scope.ATTRIBUTE) || STYLE_ATTRIBUTORS[name];
    if (attr != null) {
      formats[attr.attrName] = attr.value(node);
    }
  });
  if (Object.keys(formats).length > 0) {
    delta = delta.compose(new Delta().retain(delta.length(), formats));
  }
  return delta;
}

function matchBlot(node, delta) {
  let match = Parchment.query(node);
  if (match == null) return delta;
  if (match.prototype instanceof Parchment.Embed) {
    let embed = {};
    let value = match.value(node);
    if (value != null) {
      embed[match.blotName] = value;
      delta.insert(embed, match.formats(node));
      if (match.prototype instanceof BlockEmbed) {
        let newlineDelta = matchAttributor(node, new Delta().insert('\n'));
        delta = delta.concat(newlineDelta);
      }
    }
  } else if (typeof match.formats === 'function') {
    let formats = { [match.blotName]: match.formats(node) };
    delta = delta.compose(new Delta().retain(delta.length(), formats));
  }
  return delta;
}

function matchNewline(node, delta) {
  if (!isLine(node)) return delta;
  if (computeStyle(node).whiteSpace.startsWith('pre') || !deltaEndsWith(delta, '\n')) {
    delta.insert('\n');
  }
  return delta;
}

function matchSpacing(node, delta) {
  if (isLine(node) &&
      node.nextElementSibling != null &&
      node.nextElementSibling.offsetTop > node.offsetTop + node.offsetHeight*1.25 &&
      !deltaEndsWith(delta, '\n\n')) {
    delta.insert('\n');
  }
  return delta;
}

function matchText(node, delta) {
  let text = node.data;
  // Word represents empty line with <o:p> </o:p>
  if (node.parentNode.tagName === 'O:P') {
    return delta.insert(text.trim());
  }
  if (!computeStyle(node.parentNode).whiteSpace.startsWith('pre')) {
    function replacer(collapse, match) {
      match = match.replace(/[^\u00a0]/g, '');    // \u00a0 is nbsp;
      return match.length < 1 && collapse ? ' ' : match;
    }
    text = text.replace(/\r\n/g, ' ').replace(/\n/g, ' ');
    text = text.replace(/\s\s+/g, replacer.bind(replacer, true));  // collapse whitespace
    if ((node.previousSibling == null && isLine(node.parentNode)) ||
        (node.previousSibling != null && isLine(node.previousSibling))) {
      text = text.replace(/^\s+/, replacer.bind(replacer, false));
    }
    if ((node.nextSibling == null && isLine(node.parentNode)) ||
        (node.nextSibling != null && isLine(node.nextSibling))) {
      text = text.replace(/\s+$/, replacer.bind(replacer, false));
    }
  }
  return delta.insert(text);
}

export { Clipboard as default, matchAttributor, matchBlot, matchNewline, matchSpacing, matchText };
<commit_msg>match styles some applications use<commit_after>import Delta from 'rich-text/lib/delta';
import Parchment from 'parchment';
import Quill from '../core/quill';
import logger from '../core/logger';
import Module from '../core/module';
import { BlockEmbed } from '../blots/block';

import { AlignStyle } from '../formats/align';
import { BackgroundStyle } from '../formats/background';
import { ColorStyle } from '../formats/color';
import { DirectionStyle } from '../formats/direction';
import { FontStyle } from '../formats/font';
import { SizeStyle } from '../formats/size';

let debug = logger('quill:clipboard');

const STYLE_ATTRIBUTORS = [
  AlignStyle,
  BackgroundStyle,
  ColorStyle,
  DirectionStyle,
  FontStyle,
  SizeStyle
].reduce(function(memo, attr) {
  memo[attr.keyName] = attr;
  return memo;
}, {});

class Clipboard extends Module {
  constructor(quill, options) {
    if (options.matchers !== Clipboard.DEFAULTS.matchers) {
      options.matchers = Clipboard.DEFAULTS.matchers.concat(options.matchers);
    }
    super(quill, options);
    this.quill.root.addEventListener('copy', this.onCopy.bind(this));
    this.quill.root.addEventListener('cut', this.onCut.bind(this));
    this.quill.root.addEventListener('paste', this.onPaste.bind(this));
    this.container = this.quill.addContainer('ql-clipboard');
    this.container.setAttribute('contenteditable', true);
    this.container.setAttribute('tabindex', -1);
    this.matchers = [];
    this.options.matchers.forEach((pair) => {
      this.addMatcher(...pair);
    });
  }

  addMatcher(selector, matcher) {
    this.matchers.push([selector, matcher]);
  }

  clean() {
    let treeWalker = document.createTreeWalker(this.container, NodeFilter.SHOW_COMMENT);
    let comments = [];
    while(treeWalker.nextNode()) {
      comments.push(treeWalker.currentNode);
    }
    comments.forEach(function(node) {
      if (node != null && node.parentNode != null) {
        node.parentNode.removeChild(node);
      }
    });
    this.container.normalize();
  }

  convert(html) {
    const DOM_KEY = '__ql-matcher';
    if (typeof html === 'string') {
      this.container.innerHTML = html;
    }
    this.clean();
    this.matchers.forEach((pair) => {
      let [selector, matcher] = pair;
      if (typeof selector === 'string') {
        [].forEach.call(this.container.querySelectorAll(selector), (node) => {
          // TODO use weakmap
          node[DOM_KEY] = node[DOM_KEY] || [];
          node[DOM_KEY].push(matcher);
        });
      }
    });
    let traverse = (node) => {  // Post-order
      return [].reduce.call(node.childNodes || [], (delta, childNode) => {
        let childrenDelta = traverse(childNode);
        childrenDelta = this.matchers.reduce(function(childrenDelta, pair) {
          let [type, matcher] = pair;
          if (type === true || childNode.nodeType === type) {
            childrenDelta = matcher(childNode, childrenDelta);
          }
          return childrenDelta;
        }, childrenDelta);
        childrenDelta = (childNode[DOM_KEY] || []).reduce(function(childrenDelta, matcher) {
          return matcher(childNode, childrenDelta);
        }, childrenDelta);
        return delta.concat(childrenDelta);
      }, new Delta());
    };
    let delta = traverse(this.container);
    // Remove trailing newline
    if (deltaEndsWith(delta, '\n') && delta.ops[delta.ops.length - 1].attributes == null) {
      delta = delta.compose(new Delta().retain(delta.length() - 1).delete(1));
    }
    debug.info('convert', this.container.innerHTML, delta);
    this.container.innerHTML = '';
    return delta;
  }

  onCopy(e) {
    let range = this.quill.getSelection();
    if (range == null || range.length === 0 || e.defaultPrevented) return;
    let clipboard = e.clipboardData || window.clipboardData;
    clipboard.setData('text', this.quill.getText(range));
    if (e.clipboardData) {  // IE11 does not let us set non-text data
      clipboard.setData('application/json', JSON.stringify(this.quill.getContents(range)));
    }
    e.preventDefault();
  }

  onCut(e) {
    if (e.defaultPrevented) return;
    this.onCopy(e);
    let range = this.quill.getSelection();
    this.quill.deleteText(range, Quill.sources.USER);
    this.quill.setSelection(range.index, Quill.sources.SILENT);
  }

  onPaste(e) {
    if (e.defaultPrevented) return;
    let range = this.quill.getSelection();
    let clipboard = e.clipboardData || window.clipboardData;
    let delta = new Delta().retain(range.index).delete(range.length);
    let done = (delta) => {
      this.quill.updateContents(delta, Quill.sources.USER);
      // range.length contributes to delta.length()
      this.quill.setSelection(delta.length() - range.length, Quill.sources.SILENT);
      this.quill.selection.scrollIntoView();
    };
    let intercept = (delta, callback) => {
      this.container.focus();
      setTimeout(() => {
        let html = this.container.innerHTML;
        delta = delta.concat(this.convert());
        callback(delta);
      }, 1);
    };
    // Firefox types is an iterable, not array
    // IE11 types can be null
    if ([].indexOf.call(clipboard.types || [], 'application/json') > -1) {
      try {
        let pasteJSON = JSON.parse(clipboard.getData('application/json'));
        done(delta.concat(pasteJSON));
      } catch(err) {
        intercept(delta, done);
      }
      e.preventDefault();
    } else {
      intercept(delta, done);
    }
  }
}
Clipboard.DEFAULTS = {
  matchers: [
    [Node.TEXT_NODE, matchText],
    [Node.ELEMENT_NODE, matchNewline],
    [Node.ELEMENT_NODE, matchBlot],
    [Node.ELEMENT_NODE, matchSpacing],
    [Node.ELEMENT_NODE, matchAttributor],
    [Node.ELEMENT_NODE, matchStyles],
    ['b', matchAlias.bind(matchAlias, 'bold')],
    ['i', matchAlias.bind(matchAlias, 'italic')]
  ]
};

function computeStyle(node) {
  if (node.nodeType !== Node.ELEMENT_NODE) return {};
  const DOM_KEY = '__ql-computed-style';
  return node[DOM_KEY] || (node[DOM_KEY] = window.getComputedStyle(node));
}

function deltaEndsWith(delta, text) {
  let endText = "";
  for (let i = delta.ops.length - 1; i >= 0 && endText.length < text.length; --i) {
    let op  = delta.ops[i];
    if (typeof op.insert !== 'string') break;
    endText = op.insert + endText;
  }
  return endText.slice(-1*text.length) === text;
}

function isLine(node) {
  if (node.childNodes.length === 0) return false;   // Exclude embed blocks
  let style = computeStyle(node);
  return ['block', 'list-item'].indexOf(style.display) > -1;
}

function matchAlias(format, node, delta) {
  return delta.compose(new Delta().retain(delta.length(), { [format]: true }));
}

function matchAttributor(node, delta) {
  let attributes = Parchment.Attributor.Attribute.keys(node);
  let classes = Parchment.Attributor.Class.keys(node);
  let styles = Parchment.Attributor.Style.keys(node);
  let formats = {};
  attributes.concat(classes).concat(styles).forEach((name) => {
    let attr = Parchment.query(name, Parchment.Scope.ATTRIBUTE) || STYLE_ATTRIBUTORS[name];
    if (attr != null) {
      formats[attr.attrName] = attr.value(node);
    }
  });
  if (Object.keys(formats).length > 0) {
    delta = delta.compose(new Delta().retain(delta.length(), formats));
  }
  return delta;
}

function matchBlot(node, delta) {
  let match = Parchment.query(node);
  if (match == null) return delta;
  if (match.prototype instanceof Parchment.Embed) {
    let embed = {};
    let value = match.value(node);
    if (value != null) {
      embed[match.blotName] = value;
      delta.insert(embed, match.formats(node));
      if (match.prototype instanceof BlockEmbed) {
        let newlineDelta = matchAttributor(node, new Delta().insert('\n'));
        delta = delta.concat(newlineDelta);
      }
    }
  } else if (typeof match.formats === 'function') {
    let formats = { [match.blotName]: match.formats(node) };
    delta = delta.compose(new Delta().retain(delta.length(), formats));
  }
  return delta;
}

function matchNewline(node, delta) {
  if (!isLine(node)) return delta;
  if (computeStyle(node).whiteSpace.startsWith('pre') || !deltaEndsWith(delta, '\n')) {
    delta.insert('\n');
  }
  return delta;
}

function matchSpacing(node, delta) {
  if (isLine(node) &&
      node.nextElementSibling != null &&
      node.nextElementSibling.offsetTop > node.offsetTop + node.offsetHeight*1.25 &&
      !deltaEndsWith(delta, '\n\n')) {
    delta.insert('\n');
  }
  return delta;
}

function matchStyles(node, delta) {
  let formats = {};
  if (node.style.fontWeight && computeStyle(node).fontWeight === 'bold') {
    formats.bold = true;
  }
  if (Object.keys(formats).length > 0) {
    delta = delta.compose(new Delta().retain(delta.length(), formats));
  }
  if (parseFloat(node.style.textIndent || 0) > 0) {  // Could be 0.5in
    delta = new Delta().insert('\t').concat(delta);
  }
  return delta;
}

function matchText(node, delta) {
  let text = node.data;
  // Word represents empty line with <o:p> </o:p>
  if (node.parentNode.tagName === 'O:P') {
    return delta.insert(text.trim());
  }
  if (!computeStyle(node.parentNode).whiteSpace.startsWith('pre')) {
    function replacer(collapse, match) {
      match = match.replace(/[^\u00a0]/g, '');    // \u00a0 is nbsp;
      return match.length < 1 && collapse ? ' ' : match;
    }
    text = text.replace(/\r\n/g, ' ').replace(/\n/g, ' ');
    text = text.replace(/\s\s+/g, replacer.bind(replacer, true));  // collapse whitespace
    if ((node.previousSibling == null && isLine(node.parentNode)) ||
        (node.previousSibling != null && isLine(node.previousSibling))) {
      text = text.replace(/^\s+/, replacer.bind(replacer, false));
    }
    if ((node.nextSibling == null && isLine(node.parentNode)) ||
        (node.nextSibling != null && isLine(node.nextSibling))) {
      text = text.replace(/\s+$/, replacer.bind(replacer, false));
    }
  }
  return delta.insert(text);
}

export { Clipboard as default, matchAttributor, matchBlot, matchNewline, matchSpacing, matchText };
<|endoftext|>


<commit_before>require('./_globalHooks');

var tcpConfig = require('./support/tcpConfig');
var eventstore = require('../index.js');
var assert = require('assert');
var uuid = require('uuid');
var _ = require('lodash');

describe('TCP Client - Check Stream Exist', function() {
    it('Should return true when a stream exist', function() {
        this.timeout(5000);
        var client = eventstore.tcp(tcpConfig);

        var testStream = 'TestStream-' + uuid.v4();
        return client.writeEvent(testStream, 'TestEventType', {
            something: '123'
        }).then(function() {
            return client.checkStreamExists(testStream).then(function(exists) {
                assert.equal(true, exists);
            });
        });
    });

    it('Should return false when a stream does not exist', function() {
        this.timeout(5000);
        var client = eventstore.tcp(tcpConfig);

        return client.checkStreamExists('Non_existentStream').then(function(exists) {
            assert.equal(false, exists);
        });
    });
});<commit_msg>[cleanup] remove unused lodash<commit_after>require('./_globalHooks');

var tcpConfig = require('./support/tcpConfig');
var eventstore = require('../index.js');
var assert = require('assert');
var uuid = require('uuid');

describe('TCP Client - Check Stream Exist', function() {
    it('Should return true when a stream exist', function() {
        this.timeout(5000);
        var client = eventstore.tcp(tcpConfig);

        var testStream = 'TestStream-' + uuid.v4();
        return client.writeEvent(testStream, 'TestEventType', {
            something: '123'
        }).then(function() {
            return client.checkStreamExists(testStream).then(function(exists) {
                assert.equal(true, exists);
            });
        });
    });

    it('Should return false when a stream does not exist', function() {
        this.timeout(5000);
        var client = eventstore.tcp(tcpConfig);

        return client.checkStreamExists('Non_existentStream').then(function(exists) {
            assert.equal(false, exists);
        });
    });
});<|endoftext|>


<commit_before>// Copyright (c) Visual Data Solutions, Inc. All rights reserved. This source code is distributed under the terms of the MIT license. See LICENSE file in the project root for complete license information.

var DynObject = require('dynel-core').DynObject;

module.exports = DynObject.extend({

    getTemplateArgs: function () {

        if (this.updateTemplateArgs) {
            this.updateTemplateArgs();
        }
        var a = this.get('templateArgs');

        var data = {};
        if (this.model) {

            var attr = this.model.getAttributes();
            attr.modelObject = this.model;

            for (var p in attr) {
                data[p] = attr[p];
            }
        }

        if (this.get('templateArgs')) {
            var args = this.get('templateArgs');
            for (var p in args) {
                if (args.hasOwnProperty(p))
                    data[p] = args[p];
            }
        }
        data.view = this;
        data.viewId = this.objectId;

        return data;
    },
    renderTemplate: function (tmplArgs) {

        if (this.template) {
            this.el().empty();

            var data = this.getTemplateArgs();

            if (tmplArgs) {
                for (var p in tmplArgs) {
                    if (tmplArgs.hasOwnProperty(p))
                        data[p] = tmplArgs[p];
                }
            }
            var html = this.template(data);
            this.el().append(html.trim());
		  }
        return this;
    },

    remove: function () {
        this.el().remove();
    },

    find: function (selector) {
        var val = this.el().find(selector);
        if (val.get(0))
            return val;

        return undefined;
    },

    prepend: function (element) {
        this.el().prepend(element);
    },

    append: function (element) {
        this.el().append(element);
    },

    render: function () {

        if (!this.visible)
            return null;

        if (this.preRender)
            this.preRender();

        var output = this.renderTemplate();

        if (this.postRender) {
            this.postRender();
        }

        return output;
    },

    el: function () {
        return this.get('$element');
    },
    init: function () {

        this._super();

        if (this.get('selector')) {
            this.set('$element', $(this.get('selector')));
        }
        else if (this.get('parentElement')) {
            this.set('$element', this.get('parentElement'));
        }
        else if (this.get('tagName')) {
            var elem = document.createElement(this.get('tagName'));
            this.set('$element', $(elem));
        }

        if (this.get('$element')) {
            this.set('element', this.get('$element').get(0));
        }

        if (this.get('tagAttributes')) {
            for (var p in this.get('tagAttributes')) {
                if (this.get('tagAttributes').hasOwnProperty(p)) {
                    this.get('$element').attr(p, this.get('tagAttributes')[p]);
                }
            }
        }

        this.visible = true;
    },

    addTemplateArgs: function (argsIn) {
        var args = this.get('templateArgs');
        if (!args) {
            args = {};
            this.set('templateArgs', args);
        }

        for (var p in argsIn) {
            if (argsIn.hasOwnProperty(p)) {
                args[p] = argsIn[p];
            }
        }
    },

    empty: function () {
        this.el().empty();
    },

    css: function (css) {

        this.el().css(css);
    },

    show: function () {
        this.visible = true;
        if (this.el())
            this.el().show();
    },
    hide: function () {
        this.visible = false;

        if (this.el()) {
            this.el().hide();
        }
    },
});
<commit_msg>publish<commit_after>// Copyright (c) Visual Data Solutions, Inc. All rights reserved. This source code is distributed under the terms of the MIT license. See LICENSE file in the project root for complete license information.

var DynObject = require('dynel-core').DynObject;

module.exports = DynObject.extend({

    getTemplateArgs: function () {

        if (this.updateTemplateArgs) {
            this.updateTemplateArgs();
        }
        var a = this.get('templateArgs');

        var data = {};
        if (this.model) {

            var attr = this.model.getAttributes();
            attr.modelObject = this.model;

            for (var p in attr) {
                data[p] = attr[p];
            }
        }

        if (this.get('templateArgs')) {
            var args = this.get('templateArgs');
            for (var p in args) {
                if (args.hasOwnProperty(p))
                    data[p] = args[p];
            }
        }
        data.view = this;
        data.viewId = this.objectId;

        return data;
    },
    renderTemplate: function (tmplArgs) {

        if (this.template) {
            this.el().empty();

            var data = this.getTemplateArgs();

            if (tmplArgs) {
                for (var p in tmplArgs) {
                    if (tmplArgs.hasOwnProperty(p))
                        data[p] = tmplArgs[p];
                }
            }
            var html = this.template(data);
            this.el().append(html.trim());
		  }
        return this;
    },

    remove: function () {
        this.el().remove();
    },

    find: function (selector) {
        var val = this.el().find(selector);
        if (val.get(0))
            return val;

        return undefined;
    },

    prepend: function (element) {
        this.el().prepend(element);
    },

    append: function (element) {
        this.el().append(element);
    },

    render: function () {

        if (!this.visible)
            return null;

        if (this.preRender)
            this.preRender();

        var output = this.renderTemplate();

        if (this.postRender) {
            this.postRender();
        }

        return output;
    },

    el: function () {
        return this.get('$element');
    },
    init: function () {

        this._super();

        if (this.get('selector')) {
            this.set('$element', $(this.get('selector')));
        }
        else if (this.get('parentElement')) {
            this.set('$element', this.get('parentElement'));
        }
        else if (this.get('tagName')) {
            var elem = document.createElement(this.get('tagName'));
            this.set('$element', $(elem));
        }
        else {
            //default to a div
            var elem = document.createElement('div');
            this.set('$element', $(elem));
        }

        if (this.get('$element')) {
            this.set('element', this.get('$element').get(0));
        }

        if (this.get('tagAttributes')) {
            for (var p in this.get('tagAttributes')) {
                if (this.get('tagAttributes').hasOwnProperty(p)) {
                    this.get('$element').attr(p, this.get('tagAttributes')[p]);
                }
            }
        }

        this.visible = true;
    },

    addTemplateArgs: function (argsIn) {
        var args = this.get('templateArgs');
        if (!args) {
            args = {};
            this.set('templateArgs', args);
        }

        for (var p in argsIn) {
            if (argsIn.hasOwnProperty(p)) {
                args[p] = argsIn[p];
            }
        }
    },

    empty: function () {
        this.el().empty();
    },

    css: function (css) {

        this.el().css(css);
    },

    show: function () {
        this.visible = true;
        if (this.el())
            this.el().show();
    },
    hide: function () {
        this.visible = false;

        if (this.el()) {
            this.el().hide();
        }
    },
});
<|endoftext|>