<commit_before>var videoWidth = 400;
var videoHeight = 300;
var video;
var capturedImage;
var movingImage = false;
var status = "";
var easterEgg;
var currTimeout;

function preload() {
    easterEgg = loadImage("./mask.png");
}

function setup() {
    createCanvas(windowWidth, windowHeight);
    video = createCapture(VIDEO);
    video.size(videoWidth, videoHeight);
    video.hide();
    easterEgg.position = {};
    easterEgg.position.x = floor(random(0,windowWidth));
    easterEgg.position.y = floor(random(0,windowHeight));
}

function draw() {
    background(51);
    if (easterEgg.destination) {
        if (easterEgg.position.x < easterEgg.destination.x) {
            easterEgg.position.x += 1
        } else if (easterEgg.position.x > easterEgg.destination.x) {
            easterEgg.position.x -= 1
        } else if (easterEgg.position.y < easterEgg.destination.y) {
            easterEgg.position.y += 1
        } else if (easterEgg.position.y > easterEgg.destination.y) {
            easterEgg.position.y -= 1
        } else {
            easterEgg.destination = undefined;
        }
    } else {
        easterEgg.destination = {
            x: floor(random(windowWidth)),
            y: floor(random(windowHeight))
        }
    }
    image(easterEgg,easterEgg.position.x,easterEgg.position.y, 20, 20);
    text(status, windowWidth * 0.5 - 200, 400);
    image(video, windowWidth * 0.5 - videoWidth * 0.5, 50);
    textFont("Helvetica");
    fill(255).strokeWeight(2).textSize(25);
    text("Face Recognizer", windowWidth * 0.5 - 100, 30);
    fill(255).strokeWeight(0).textSize(17);
    if (capturedImage) {
        if (movingImage.active) {
            movingImage.y += 25;
            image(capturedImage, windowWidth * 0.5 - videoWidth * 0.5, movingImage.y);
            if (movingImage.y >= 430) {
                movingImage.active = false;
            }
        } else {
            image(capturedImage, windowWidth * 0.5 - videoWidth * 0.5, 430);
        }
    } else {
        status = "Press anywhere to take a photo for face recognition.";
    }
}

function windowResized() {
    resizeCanvas(windowWidth, windowHeight);
}

function mouseClicked() {
    if (status === "Loading..") {
        return;
    }
    status = "Loading..";
    capturedImage = video.loadPixels();
    movingImage = {
        active: true,
        x: windowWidth * 0.5 - videoWidth * 0.5,
        y: 50
    };
    video = createCapture(VIDEO);
    video.size(videoWidth, videoHeight);
    video.hide();
    // Sending and receiving data in JSON format using POST mothod
    //
    xhr = new XMLHttpRequest();
    var url = "localhost:8015";
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.onreadystatechange = function () {
        if (xhr.status == 200) {
            status = xhr.responseText;
        } else {
            status = "Status code: " + xhr.status;
        }
        clearTimeout(currTimeout);
        currTimeout = setTimeout('capturedImage = undefined;', 5000);
    }
    var data = capturedImage.pixels;
    xhr.send(data);
}<commit_msg>added test<commit_after>var videoWidth = 400;
var videoHeight = 300;
var video;
var capturedImage;
var movingImage = false;
var status = "";
var easterEgg;
var currTimeout;

function preload() {
    easterEgg = loadImage("./mask.png");
}

function setup() {
    createCanvas(windowWidth, windowHeight);
    video = createCapture(VIDEO);
    video.size(videoWidth, videoHeight);
    video.hide();
    easterEgg.position = {};
    easterEgg.position.x = floor(random(0,windowWidth));
    easterEgg.position.y = floor(random(0,windowHeight));
}

function draw() {
    background(51);
    if (easterEgg.destination) {
        if (easterEgg.position.x < easterEgg.destination.x) {
            easterEgg.position.x += 1
        } else if (easterEgg.position.x > easterEgg.destination.x) {
            easterEgg.position.x -= 1
        } else if (easterEgg.position.y < easterEgg.destination.y) {
            easterEgg.position.y += 1
        } else if (easterEgg.position.y > easterEgg.destination.y) {
            easterEgg.position.y -= 1
        } else {
            easterEgg.destination = undefined;
        }
    } else {
        easterEgg.destination = {
            x: floor(random(windowWidth)),
            y: floor(random(windowHeight))
        }
    }
    image(easterEgg,easterEgg.position.x,easterEgg.position.y, 20, 20);
    text(status, windowWidth * 0.5 - 200, 400);
    image(video, windowWidth * 0.5 - videoWidth * 0.5, 50);
    textFont("Helvetica");
    fill(255).strokeWeight(2).textSize(25);
    text("Face Recognizer", windowWidth * 0.5 - 100, 30);
    fill(255).strokeWeight(0).textSize(17);
    if (capturedImage) {
        if (movingImage.active) {
            movingImage.y += 25;
            image(capturedImage, windowWidth * 0.5 - videoWidth * 0.5, movingImage.y);
            if (movingImage.y >= 430) {
                movingImage.active = false;
            }
        } else {
            image(capturedImage, windowWidth * 0.5 - videoWidth * 0.5, 430);
        }
    } else {
        status = "Press anywhere to take a photo for face recognition.";
    }
}

function windowResized() {
    resizeCanvas(windowWidth, windowHeight);
}

function mouseClicked() {
    if (status === "Loading..") {
        return;
    }
    status = "Loading..";
    capturedImage = video.loadPixels();
    movingImage = {
        active: true,
        x: windowWidth * 0.5 - videoWidth * 0.5,
        y: 50
    };
    video = createCapture(VIDEO);
    video.size(videoWidth, videoHeight);
    video.hide();
    // Sending and receiving data in JSON format using POST mothod
    //
    xhr = new XMLHttpRequest();
    var url = "http://httpbin.org/post";
    xhr.open("POST", url, true);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.onreadystatechange = function () {
        if (xhr.status == 200) {
            // status = xhr.responseText
            status = "Great Success";
        } else {
            status = "Status code: " + xhr.status;
        }
        clearTimeout(currTimeout);
        currTimeout = setTimeout('capturedImage = undefined;', 5000);
    }
    var data = capturedImage.pixels;
    xhr.send(data);
}<|endoftext|>


<commit_before>var raindropNum; // max number of drops to be drawn on the screen
var rainDrops = []; // the array holding the RainDrop objects
var rainSplashes = []; // the array holding the RainSplash objects
var maxSpeed = 6; // max speed of the drops
var splashFrames = 8; // number of frames for the splash animation
var horizon; // the Y position of the screen in which splashes cease to appear
var colFG; // foreground color
var colBG; // background color
var isPressed = false; // bollean to check if mouse/screen was pressed

function setup() {
  // the canvas is defined as half the height and width of the window
  // it is rendered as fullscreen by using css
  createCanvas(windowWidth/2, windowHeight/2);
  horizon = height/2;
  colFG = color(255, 255, 255);
  colBG = color(237, 34, 93);
  // Populate the rainDrops array with RainDrop objects
  raindropNum = windowWidth/3;
  for(var i = 0; i < raindropNum; i++){
    rainDrops.push(new RainDrop(3));
  }

}

function draw() {
  //Chech to see is screen or mouse are pressed
  if(mouseIsPressed || touchIsDown){
    if(!isPressed){
      invertColor();
      isPressed = true;
    }
  } else{
    isPressed = false;
  }
  // use the background color RGB values to create an RGBA value for the background
  background('rgba(' + red(colBG) + ',' + green(colBG) + ',' + blue(colBG) + ',' + 0.5 + ')');
  // iterate thgough the rainDrops array to update and draw its objects
  for(var i = 0; i < rainDrops.length; i++){
    rainDrops[i].update();
    rainDrops[i].draw();
  }
  // iterate through rhe rainSplashes array to update and draw its objects
  for(var j = 0; j < rainSplashes.length; j++){
    // if the frame of a RainSplash is less that the max value of frames we update and draw it
    if(rainSplashes[j].change < splashFrames){
      rainSplashes[j].update();
      rainSplashes[j].draw();
    // else we update, draw it and then remove it from the array
    } else{
      rainSplashes[j].update();
      rainSplashes[j].draw();
      rainSplashes.splice(j, j+1);
    }
  }

}
//when the window is resized the canvas is resized accordingly
function windowResized(){
  resizeCanvas(windowWidth/2, windowHeight/2);
}
// this function switches the foreground and background colors
function invertColor(){
  var temp = colBG;
  colBG = colFG;
  colFG = temp;
}

class RainDrop{
  // the only input the object takes is size
  constructor(_size){
    this.size = _size;
    this.end = random(horizon, height);// the Y position in which the object will restart
    this.x = random(-80, width -10); // X position, has an offset to compensate for the noise
    this.y = random(height); // Y position
    // Z position, defined as a value from 0 to 1 mapped from the distance between horizon and canvas height
    this.z = map(this.end, horizon, height, 0, 1)
    // speed, if the distance to travel is less then the speed is lower
    this.speed = map(this.end, 0, height, 1, maxSpeed);
  }
  // function to update the RainDrop values
  update(){
    // if the Y position is less that the END position, then the drop keeps falling
    if(this.y < this.end){
      this.x += noise(millis()/1000)*3; //we add noise to the X position to emulate wind
      this.y += this.speed;
    } else{
    //else it creates a new RainSplash object on the END position
      rainSplashes.push(new RainSplash(this.x, this.y, this.z, (this.y / height) * 1));
      // values are reset
      this.end = random(horizon, height);
      this.x = random(-80, width -10);
      this.y = 0;
      this.z = map(this.end, horizon, height, 0, 1);
      this.speed = map(this.end, 0, height, 1, maxSpeed);
    }
  }
  // function to draw the object
  draw(){
    // we use the Z value to interpolate from the FG and BG colors to give a sense of depth
    stroke(lerpColor(colBG, colFG, this.z));
    strokeWeight((255-this.z)/100); // Z value also influences the width of the raindrop
    line(this.x, this.y, this.x, this.y + this.size);
  }

}
// the RainSplash object
class RainSplash{
  // it gets ist X, Y, Z, and SIZE values from the RainDrop object that creates it
  constructor(_x, _y, _z, _size){
    this.x = _x;
    this.y = _y;
    this.z = _z;
    this.size = _size;
    this.change = 1;// this value is the current frame for the animation
  }
  // each time update() is called it increases the current frame
  update(){
    this.change++;
  }
  // the draw() function is similar to that of the RainDrop object
  // but CHANGE influences the stroke color
  draw(){
    noFill();
    stroke(lerpColor(colBG, colFG, this.z/splashFrames * this.change));
    strokeWeight(this.size);
    ellipse(this.x, this.y, this.size * this.change * 3, this.size * this.change);
  }

}
<commit_msg>added a map function on to the Raindrop X pos<commit_after>var raindropNum; // max number of drops to be drawn on the screen
var rainDrops = []; // the array holding the RainDrop objects
var rainSplashes = []; // the array holding the RainSplash objects
var maxSpeed = 6; // max speed of the drops
var splashFrames = 8; // number of frames for the splash animation
var horizon; // the Y position of the screen in which splashes cease to appear
var colFG; // foreground color
var colBG; // background color
var isPressed = false; // bollean to check if mouse/screen was pressed

function setup() {
  // the canvas is defined as half the height and width of the window
  // it is rendered as fullscreen by using css
  createCanvas(windowWidth/2, windowHeight/2);
  horizon = height/2;
  colFG = color(255, 255, 255);
  colBG = color(237, 34, 93);
  // Populate the rainDrops array with RainDrop objects
  raindropNum = windowWidth/3;
  for(var i = 0; i < raindropNum; i++){
    rainDrops.push(new RainDrop(3));
  }

}

function draw() {
  //Chech to see is screen or mouse are pressed
  if(mouseIsPressed || touchIsDown){
    if(!isPressed){
      invertColor();
      isPressed = true;
    }
  } else{
    isPressed = false;
  }
  // use the background color RGB values to create an RGBA value for the background
  background('rgba(' + red(colBG) + ',' + green(colBG) + ',' + blue(colBG) + ',' + 0.5 + ')');
  // iterate thgough the rainDrops array to update and draw its objects
  for(var i = 0; i < rainDrops.length; i++){
    rainDrops[i].update();
    rainDrops[i].draw();
  }
  // iterate through rhe rainSplashes array to update and draw its objects
  for(var j = 0; j < rainSplashes.length; j++){
    // if the frame of a RainSplash is less that the max value of frames we update and draw it
    if(rainSplashes[j].change < splashFrames){
      rainSplashes[j].update();
      rainSplashes[j].draw();
    // else we update, draw it and then remove it from the array
    } else{
      rainSplashes[j].update();
      rainSplashes[j].draw();
      rainSplashes.splice(j, j+1);
    }
  }

}
//when the window is resized the canvas is resized accordingly
function windowResized(){
  resizeCanvas(windowWidth/2, windowHeight/2);
}
// this function switches the foreground and background colors
function invertColor(){
  var temp = colBG;
  colBG = colFG;
  colFG = temp;
}

class RainDrop{
  // the only input the object takes is size
  constructor(_size){
    this.size = _size;
    this.end = random(horizon, height);// the Y position in which the object will restart
    this.x = random(-80, width + 80); // X position, has an offset to compensate for the noise
    this.y = random(height); // Y position
    // Z position, defined as a value from 0 to 1 mapped from the distance between horizon and canvas height
    this.z = map(this.end, horizon, height, 0, 1)
    // speed, if the distance to travel is less then the speed is lower
    this.speed = map(this.end, 0, height, 1, maxSpeed);
  }
  // function to update the RainDrop values
  update(){
    // if the Y position is less that the END position, then the drop keeps falling
    if(this.y < this.end){
      this.x += map(noise(millis()/1000), 0, 1, -1, 1)*2; //we add noise to the X position to emulate wind
      this.y += this.speed;
    } else{
    //else it creates a new RainSplash object on the END position
      rainSplashes.push(new RainSplash(this.x, this.y, this.z, (this.y / height) * 1));
      // values are reset
      this.end = random(horizon, height);
      this.x = random(-80, width + 80);
      this.y = 0;
      this.z = map(this.end, horizon, height, 0, 1);
      this.speed = map(this.end, 0, height, 1, maxSpeed);
    }
  }
  // function to draw the object
  draw(){
    // we use the Z value to interpolate from the FG and BG colors to give a sense of depth
    stroke(lerpColor(colBG, colFG, this.z));
    strokeWeight((255-this.z)/100); // Z value also influences the width of the raindrop
    line(this.x, this.y, this.x, this.y + this.size);
  }

}
// the RainSplash object
class RainSplash{
  // it gets ist X, Y, Z, and SIZE values from the RainDrop object that creates it
  constructor(_x, _y, _z, _size){
    this.x = _x;
    this.y = _y;
    this.z = _z;
    this.size = _size;
    this.change = 1;// this value is the current frame for the animation
  }
  // each time update() is called it increases the current frame
  update(){
    this.change++;
  }
  // the draw() function is similar to that of the RainDrop object
  // but CHANGE influences the stroke color
  draw(){
    noFill();
    stroke(lerpColor(colBG, colFG, this.z/splashFrames * this.change));
    strokeWeight(this.size);
    ellipse(this.x, this.y, this.size * this.change * 3, this.size * this.change);
  }

}
<|endoftext|>


<commit_before>var TestCase = function(caseName, caseDefinition) {
  this.caseName = caseName;
  this.caseDefinition = caseDefinition;
  this.shouldDefinitions = {};
  this.testNonPasses = [];
  this.setups = [];
  this.teardowns = [];
  this.contexts = [];
};

TestCase.cases = [];

TestCase.define = function(caseName, caseDefinition, addToCases) {
  var tc = new TestCase(caseName, caseDefinition);
  tc.defineCase();
  if (addToCases != false) { TestCase.addCase(tc); }
  return tc;
};

TestCase.addCase = function(testCase) {
  TestCase.cases.push(testCase);
};

TestCase.prototype = {
  defineCase: function() {
    this.caseDefinition.call(this);
  },

  run: function(runner) {
    runner.caseStarted(this);
    this._runShoulds(runner);
    runner.caseFinalized(this);
    this._runContexts(runner);
  },

  shouldCount: function() {
    var shouldCount = 0;
    for (var def in this.shouldDefinitions) { shouldCount += 1; }
    return shouldCount;
  },

  should: function(shouldName, shouldDefinition) {
    this.shouldDefinitions["test: " + this.caseName + " should " + shouldName] = shouldDefinition;
  },

  setup: function(setupFunction) {
    this.setups.push(setupFunction);
  },

  teardown: function(teardownFunction) {
    this.teardowns.push(teardownFunction);
  },

  debug: function(string) {
    if (!TestCase.debug) { return(null); }
    this.outputter.info(string);
  },

  context: function(contextName, contextDefinition) {
    var newCase = TestCase.define(contextName, contextDefinition, false);
    newCase._inheritAsContext(this);
    this.contexts.push(newCase);
  },

// Protected
  _inheritAsContext: function(otherCase) {
    this.setups = otherCase.setups.concat(this.setups);
    this.teardowns = otherCase.teardowns.concat(this.teardowns);
    this.caseName = otherCase.caseName + ' ' + this.caseName;
  },

// Private
  _runContexts: function(runner) {
    for (var i=0; i < this.contexts.length; i++) { this.contexts[i].run(runner); }
  },

  _runShoulds: function(runner) {
    for (var shouldName in this.shouldDefinitions) {
      this._runShould(shouldName, runner);
    }
  },

  _runShould: function(shouldName, runner) {
    var runContext = new TestCase.ShouldRunContext(this.setups, this.teardowns, shouldName, this.shouldDefinitions[shouldName]);
    runContext.run(runner);
  },

  _addPass: function(shouldName) {
    // TODO - ASSERTION COUNT.
    this.outputter.showPass(shouldName);
  },

  _addFailure: function(shouldName, error) {
    // TODO - ASSERTION COUNT
    this.outputter.showFailure(shouldName, error);
    this.testNonPasses.push({type: 'Failure', should: shouldName, error: error});
  },

  _addError: function(shouldName, error) {
    // TODO - ASSERTION COUNT
    this.outputter.showError(shouldName, error);
    this.testNonPasses.push({type: 'Error', should: shouldName, error: error});
  }

}; // TestCase.prototype<commit_msg>Fixes another output bug<commit_after>var TestCase = function(caseName, caseDefinition) {
  this.caseName = caseName;
  this.caseDefinition = caseDefinition;
  this.shouldDefinitions = {};
  this.testNonPasses = [];
  this.setups = [];
  this.teardowns = [];
  this.contexts = [];
};

TestCase.cases = [];

TestCase.define = function(caseName, caseDefinition) {
  var tc = new TestCase(caseName, caseDefinition);
  tc.defineCase();
  TestCase.addCase(tc);
  return tc;
};

TestCase.addCase = function(testCase) {
  TestCase.cases.push(testCase);
};

TestCase.prototype = {
  defineCase: function() {
    this.caseDefinition.call(this);
  },

  run: function(runner) {
    runner.caseStarted(this);
    this._runShoulds(runner);
    runner.caseFinalized(this);
    this._runContexts(runner);
  },

  shouldCount: function() {
    var shouldCount = 0;
    for (var def in this.shouldDefinitions) { shouldCount += 1; }
    return shouldCount;
  },

  should: function(shouldName, shouldDefinition) {
    this.shouldDefinitions["test: " + this.caseName + " should " + shouldName] = shouldDefinition;
  },

  setup: function(setupFunction) {
    this.setups.push(setupFunction);
  },

  teardown: function(teardownFunction) {
    this.teardowns.push(teardownFunction);
  },

  context: function(contextName, contextDefinition) {
    var newCase = new TestCase(contextName, contextDefinition);
    newCase._inheritAsContext(this);
    newCase.defineCase();
    this.contexts.push(newCase);
  },

// Protected
  _inheritAsContext: function(otherCase) {
    this.setups = otherCase.setups.concat(this.setups);
    this.teardowns = otherCase.teardowns.concat(this.teardowns);
    this.caseName = otherCase.caseName + ' ' + this.caseName;
  },

// Private
  _runContexts: function(runner) {
    for (var i=0; i < this.contexts.length; i++) { this.contexts[i].run(runner); }
  },

  _runShoulds: function(runner) {
    for (var shouldName in this.shouldDefinitions) {
      this._runShould(shouldName, runner);
    }
  },

  _runShould: function(shouldName, runner) {
    var runContext = new TestCase.ShouldRunContext(this.setups, this.teardowns, shouldName, this.shouldDefinitions[shouldName]);
    runContext.run(runner);
  }

}; // TestCase.prototype<|endoftext|>


<commit_before>var debug = require('debug')('mdns:lib:networking');
var debuginbound = require('debug')('mdns:inbound');
var debugoutbound = require('debug')('mdns:outbound');

var util = require('util');
var EventEmitter = require('events').EventEmitter;
var os = require('os');
var dgram = require('dgram');
var semver = require('semver');

var dns = require('mdns-js-packet');
var DNSPacket = dns.DNSPacket;
//var DNSRecord = dns.DNSRecord;

var MDNS_MULTICAST = '224.0.0.251';

var Networking = module.exports = function (options) {
  options = options || {};
  this.created = 0;
  this.connections = [];
  // list of ips to add membership for
  this.ips = [];
  this.started = false;
  this.users = [];
  this.INADDR_ANY = typeof options.INADDR_ANY === 'undefined' ?
    false : options.INADDR_ANY;
};

util.inherits(Networking, EventEmitter);

Networking.prototype.start = function () {
  var interfaces = os.networkInterfaces();
  var index = 0;
  for (var key in interfaces) {
    if (interfaces.hasOwnProperty(key)) {
      for (var i = 0; i < interfaces[key].length; i++) {
        var iface = interfaces[key][i];
        //no localhost
        if (iface.internal) {
          continue;
        }
        //no IPv6 addresses
        if (iface.address.indexOf(':') !== -1) {
          continue;
        }
        debug('interface', key, iface.address);
        this.createSocket(index++, key,
          iface.address, 0, this.bindToAddress.bind(this));
        if (this.ips.indexOf(iface.address) === -1) {
          this.ips.push(iface.address);
        }
      }
    }
  }
  // apple-tv always replies back using multicast,
  // regardless of the source of the query, it is answering back.
  this.createSocket(index++, 'pseudo multicast',
    '0.0.0.0', 5353, this.bindToAddress.bind(this));
  if (this.ips.length > 1) {
    // There is no way ( at least in node.js ) to listen ( or send )
    // to multicast on an interface other than the one, kernel had chosen.
    // so on a multihommed device, despite all these efforts, we never find devices
    // on other interfaces.
    debug('***Warning This is a multihommed device.***');
  }
};

Networking.prototype.stop = function () {
  debug('stopping');

  this.connections.forEach(closeEach);
  this.connections = [];

  function closeEach(connection) {
    var socket = connection.socket;
    socket.close();
    socket.unref();
  }
};

Networking.prototype.createSocket = function (
  interfaceIndex, networkInterface, address, port, next) {
  var sock;
  if (semver.gte(process.versions.node, '0.11.13')) {
    sock = dgram.createSocket({type:'udp4', reuseAddr:true});
  } else {
    sock = dgram.createSocket('udp4');
  }
  debug('creating socket for', networkInterface);
  this.created++;

  sock.bind(port, address, function () {
    if (address === '0.0.0.0' && port === 5353) {
      sock.addMembership(MDNS_MULTICAST);

      sock.setMulticastTTL(255);
      sock.setMulticastLoopback(true);
    }
    next(null, interfaceIndex, networkInterface, sock);
  });

};

Networking.prototype.bindToAddress = function (
  err, interfaceIndex, networkInterface, sock) {
  if (err) {
    debug('there was an error binding %s', err);
    return;
  }
  debug('bindToAddress', networkInterface);
  var info = sock.address();

  var connection = {
    socket:sock,
    interfaceIndex: interfaceIndex,
    networkInterface: networkInterface,
    counters: {
      sent: 0,
      received: 0
    }
  };

  this.connections.push(connection);
  var self = this;

  sock.on('message', function (message, remote) {
    var packets;
    connection.counters.received++;
    debuginbound('incomming message', message.toString('hex'));
    try {
      packets = dns.DNSPacket.parse(message);
      if (!(packets instanceof Array)) {
        packets = [packets];
      }

      self.emit('packets', packets, remote, connection);
    }
    catch (err) {
      //partial, skip it
      debug('packet parsing error', err);
    }
  });

  sock.on('error', self.onError.bind(self));

  sock.on('close', function () {
    debug('socket closed', info);
  });

  if (this.created === this.connections.length) {
    this.emit('ready', this.connections.length);
  }
};//--bindToAddress

Networking.prototype.onError = function (err) {
  this.emit('error', err);
};

Networking.prototype.send = function (packet) {
  var buf = DNSPacket.toBuffer(packet);
  this.connections.forEach(onEach);
  debug('created buffer with length', buf.length);
  debugoutbound('message', buf.toString('hex'));
  function onEach(connection) {
    var sock = connection.socket;
    // if the user did not specially asked for the pseudo interface
    // skip sending message on that interface.
    if (sock.address().address === '0.0.0.0' && !this.INADDR_ANY) {
      debug('skip send on pseudo interface.');
    } else {
      debug('sending to', sock.address());

      sock.send(buf, 0, buf.length, 5353, '224.0.0.251', function (err, bytes) {
        connection.counters.sent++;
        debug('%s sent %d bytes with err:%s', sock.address().address, bytes,
            err);
      });
    }
  }
};

Networking.prototype.startRequest = function (callback) {
  if (this.started) {
    return process.nextTick(callback());
  }
  this.start();
  this.once('ready', function () {
    if (typeof callback === 'function') {
      callback();
    }
  });
};

Networking.prototype.stopRequest = function () {
  if (this.users.length === 0) {
    this.stop();
  }
};

Networking.prototype.addUsage = function (browser, next) {
  this.users.push(browser);
  this.startRequest(next);
};

Networking.prototype.removeUsage = function (browser) {
  var index = this.users.indexOf(browser);
  if (index > -1) {
    this.users.splice(index, 1);
  }
  this.stopRequest();
};

<commit_msg>removed unnecessary code.<commit_after>var debug = require('debug')('mdns:lib:networking');
var debuginbound = require('debug')('mdns:inbound');
var debugoutbound = require('debug')('mdns:outbound');

var util = require('util');
var EventEmitter = require('events').EventEmitter;
var os = require('os');
var dgram = require('dgram');
var semver = require('semver');

var dns = require('mdns-js-packet');
var DNSPacket = dns.DNSPacket;
//var DNSRecord = dns.DNSRecord;

var MDNS_MULTICAST = '224.0.0.251';

var Networking = module.exports = function (options) {
  options = options || {};
  this.created = 0;
  this.connections = [];
  this.started = false;
  this.users = [];
  this.INADDR_ANY = typeof options.INADDR_ANY === 'undefined' ?
    false : options.INADDR_ANY;
};

util.inherits(Networking, EventEmitter);

Networking.prototype.start = function () {
  var interfaces = os.networkInterfaces();
  var index = 0;
  for (var key in interfaces) {
    if (interfaces.hasOwnProperty(key)) {
      for (var i = 0; i < interfaces[key].length; i++) {
        var iface = interfaces[key][i];
        //no localhost
        if (iface.internal) {
          continue;
        }
        //no IPv6 addresses
        if (iface.address.indexOf(':') !== -1) {
          continue;
        }
        debug('interface', key, iface.address);
        this.createSocket(index++, key,
          iface.address, 0, this.bindToAddress.bind(this));
      }
    }
  }
  // apple-tv always replies back using multicast,
  // regardless of the source of the query, it is answering back.
  this.createSocket(index++, 'pseudo multicast',
    '0.0.0.0', 5353, this.bindToAddress.bind(this));
};

Networking.prototype.stop = function () {
  debug('stopping');

  this.connections.forEach(closeEach);
  this.connections = [];

  function closeEach(connection) {
    var socket = connection.socket;
    socket.close();
    socket.unref();
  }
};

Networking.prototype.createSocket = function (
  interfaceIndex, networkInterface, address, port, next) {
  var sock;
  if (semver.gte(process.versions.node, '0.11.13')) {
    sock = dgram.createSocket({type:'udp4', reuseAddr:true});
  } else {
    sock = dgram.createSocket('udp4');
  }
  debug('creating socket for', networkInterface);
  this.created++;

  sock.bind(port, address, function () {
    if (address === '0.0.0.0' && port === 5353) {
      sock.addMembership(MDNS_MULTICAST);

      sock.setMulticastTTL(255);
      sock.setMulticastLoopback(true);
    }
    next(null, interfaceIndex, networkInterface, sock);
  });

};

Networking.prototype.bindToAddress = function (
  err, interfaceIndex, networkInterface, sock) {
  if (err) {
    debug('there was an error binding %s', err);
    return;
  }
  debug('bindToAddress', networkInterface);
  var info = sock.address();

  var connection = {
    socket:sock,
    interfaceIndex: interfaceIndex,
    networkInterface: networkInterface,
    counters: {
      sent: 0,
      received: 0
    }
  };

  this.connections.push(connection);
  var self = this;

  sock.on('message', function (message, remote) {
    var packets;
    connection.counters.received++;
    debuginbound('incomming message', message.toString('hex'));
    try {
      packets = dns.DNSPacket.parse(message);
      if (!(packets instanceof Array)) {
        packets = [packets];
      }

      self.emit('packets', packets, remote, connection);
    }
    catch (err) {
      //partial, skip it
      debug('packet parsing error', err);
    }
  });

  sock.on('error', self.onError.bind(self));

  sock.on('close', function () {
    debug('socket closed', info);
  });

  if (this.created === this.connections.length) {
    this.emit('ready', this.connections.length);
  }
};//--bindToAddress

Networking.prototype.onError = function (err) {
  this.emit('error', err);
};

Networking.prototype.send = function (packet) {
  var buf = DNSPacket.toBuffer(packet);
  this.connections.forEach(onEach);
  debug('created buffer with length', buf.length);
  debugoutbound('message', buf.toString('hex'));
  function onEach(connection) {
    var sock = connection.socket;
    // if the user did not specially asked for the pseudo interface
    // skip sending message on that interface.
    if (sock.address().address === '0.0.0.0' && !this.INADDR_ANY) {
      debug('skip send on pseudo interface.');
    } else {
      debug('sending to', sock.address());

      sock.send(buf, 0, buf.length, 5353, '224.0.0.251', function (err, bytes) {
        connection.counters.sent++;
        debug('%s sent %d bytes with err:%s', sock.address().address, bytes,
            err);
      });
    }
  }
};

Networking.prototype.startRequest = function (callback) {
  if (this.started) {
    return process.nextTick(callback());
  }
  this.start();
  this.once('ready', function () {
    if (typeof callback === 'function') {
      callback();
    }
  });
};

Networking.prototype.stopRequest = function () {
  if (this.users.length === 0) {
    this.stop();
  }
};

Networking.prototype.addUsage = function (browser, next) {
  this.users.push(browser);
  this.startRequest(next);
};

Networking.prototype.removeUsage = function (browser) {
  var index = this.users.indexOf(browser);
  if (index > -1) {
    this.users.splice(index, 1);
  }
  this.stopRequest();
};

<|endoftext|>


<commit_before>'use babel';
import {Disposable, CompositeDisposable} from 'atom';

export var config = {
  fixTreeView: {
    description: 'Make single clicks in the tree view open a file.',
    type: 'boolean',
    default: true,
  },
  fixSearchResultsView: {
    description: 'Make single click in the project search results view open a file.',
    type: 'boolean',
    default: true,
  },
  focusEditorOnOpen: {
    description: 'Focus the editor immediately when a file is opened.',
    type: 'boolean',
    default: true,
  }
};

var disposables;

export function activate() {
  disposables = new CompositeDisposable();

  if (atom.config.get('single-click-open.fixTreeView'))
    disposables.add(disablePendingItems());

  if (atom.config.get('single-click-open.fixSearchResultsView'))
    disposables.add(disableSearchResultDoubleClick());
}

export function deactivate() {
  disposable.dispose();
  disposable = null;
}

// No more pending pane items!
function disablePendingItems() {
  // Fix doesn't work without this setting enabled.
  atom.config.set('core.allowPendingPaneItems', true);
  disposables.add(
    atom.workspace.onDidAddPaneItem(({item, pane}) => {
      pane.setPendingItem(null);

      if (atom.config.get('single-click-open.focusEditorOnOpen')) {
        process.nextTick(() => atom.views.getView(item).focus());
      }
    })
  );

  if (atom.config.get('single-click-open.focusEditorOnOpen')) {
    disposables.add(
      atom.workspace.onDidChangeActivePaneItem(item => {
        var view = atom.views.getView(item);

        if (view && typeof view.focus == 'function')
          atom.views.getView(item).focus();
      })
    );
  }
}

// No more double click to open files!
function disableSearchResultDoubleClick() {
  document.body.addEventListener('mousedown', onSearchResultClick, true);
  return new Disposable(() => {
    document.body.removeEventListener('mousedown', onSearchResultClick)
  });
}

// Trigger a 2nd mousedown on the search result
// on a single mousedown.
function onSearchResultClick(event) {
  var el;
  // Ignore double-clicks or other mouse buttons.
  // Do nothing if it isn't a file that was clicked.
  if (event.detail == 2 || event.button != 0 ||
    !(el = event.target.closest('.pane-item > .results-view .search-result'))) return;
  // Without nextTick() two copies would open,
  // one in pending mode and one in normal mode.
  process.nextTick(() => {
    // Dispatch a double-click event on the file
    // that was clicked.
    el.dispatchEvent(new CustomEvent('mousedown', {
      bubbles: true,
      detail: 2,
    }));
  });
  // Cancel this event.
  event.stopImmediatePropagation();
}
<commit_msg>Simply call the functions<commit_after>'use babel';
import {Disposable, CompositeDisposable} from 'atom';

export var config = {
  fixTreeView: {
    description: 'Make single clicks in the tree view open a file.',
    type: 'boolean',
    default: true,
  },
  fixSearchResultsView: {
    description: 'Make single click in the project search results view open a file.',
    type: 'boolean',
    default: true,
  },
  focusEditorOnOpen: {
    description: 'Focus the editor immediately when a file is opened.',
    type: 'boolean',
    default: true,
  }
};

var disposables;

export function activate() {
  disposables = new CompositeDisposable();

  if (atom.config.get('single-click-open.fixTreeView'))
    disablePendingItems();

  if (atom.config.get('single-click-open.fixSearchResultsView'))
    disableSearchResultDoubleClick();
}

export function deactivate() {
  disposable.dispose();
  disposable = null;
}

// No more pending pane items!
function disablePendingItems() {
  // Fix doesn't work without this setting enabled.
  atom.config.set('core.allowPendingPaneItems', true);
  disposables.add(
    atom.workspace.onDidAddPaneItem(({item, pane}) => {
      pane.setPendingItem(null);

      if (atom.config.get('single-click-open.focusEditorOnOpen')) {
        process.nextTick(() => atom.views.getView(item).focus());
      }
    })
  );

  if (atom.config.get('single-click-open.focusEditorOnOpen')) {
    disposables.add(
      atom.workspace.onDidChangeActivePaneItem(item => {
        var view = atom.views.getView(item);

        if (view && typeof view.focus == 'function')
          atom.views.getView(item).focus();
      })
    );
  }
}

// No more double click to open files!
function disableSearchResultDoubleClick() {
  document.body.addEventListener('mousedown', onSearchResultClick, true);
  return new Disposable(() => {
    document.body.removeEventListener('mousedown', onSearchResultClick)
  });
}

// Trigger a 2nd mousedown on the search result
// on a single mousedown.
function onSearchResultClick(event) {
  var el;
  // Ignore double-clicks or other mouse buttons.
  // Do nothing if it isn't a file that was clicked.
  if (event.detail == 2 || event.button != 0 ||
    !(el = event.target.closest('.pane-item > .results-view .search-result'))) return;
  // Without nextTick() two copies would open,
  // one in pending mode and one in normal mode.
  process.nextTick(() => {
    // Dispatch a double-click event on the file
    // that was clicked.
    el.dispatchEvent(new CustomEvent('mousedown', {
      bubbles: true,
      detail: 2,
    }));
  });
  // Cancel this event.
  event.stopImmediatePropagation();
}
<|endoftext|>


<commit_before>var exec = require('child_process').exec,
    spawn = require('child_process').spawn;
module.exports.player = function(path, options) {
    var settings = options || {};
    var args = [];
    var command = 'omxplayer';
    args.push(path);

    if (['hdmi', 'local', 'both'].indexOf(settings.audioOutput) != -1)
        args.push('-o', settings.audioOutput);
    if (settings.blackBackground !== false)
        args.push('-b');
    if (settings.disableKeys === true)
        args.push('--no-keys');
    if (settings.disableOnScreenDisplay === true)
        args.push('--no-osd');
    if (settings.disableGhostbox === true)
        args.push('--no-ghost-box');
    if (settings.subtitlePath && settings.subtitlePath !== '')
        args.push('--subtitles', '"' + settings.subtitlePath + '"');
    if (settings.startAt)
        args.push('--pos', '' + settings.startAt + '');
    if (typeof settings.startVolume !== 'undefined') {
        if (settings.startVolume >= 0.0 && settings.startVolume <= 1.0) {
            args.push('--vol');
            var db = settings.startVolume > 0 ? Math.round(100 * 20 * (Math.log(settings.startVolume) / Math.log(10))) / 1 : -12000000;
            args.push(db);
        }
    }
    //omxplayer /home/pi/test.mp4 -o hdmi --no-keys --no-osd --loop --win "0 0 100 100"

    args.push('--dbus_name');
    args.push('org.mpris.MediaPlayer2.omxplayer');
    args.push('< omxpipe');
    //exec(command + ' ' + args.join(' ') + ' < omxpipe', function() {});
    spawn(command, args);
    //Check this out to see if you can make this work!!!!
    //https://github.com/nodejs/node-v0.x-archive/issues/4374#issuecomment-11065865

    exec(' . > omxpipe');
};
<commit_msg>Minnor fix<commit_after>var exec = require('child_process').exec,
    spawn = require('child_process').spawn,
    events = require('events'),
    eventEmitter = new events.EventEmitter();
module.exports = eventEmitter;
module.exports.player = function(path, options) {
    var settings = options || {};
    var args = [];
    var command = 'omxplayer';
    args.push(path);

    if (['hdmi', 'local', 'both'].indexOf(settings.audioOutput) != -1)
        args.push('-o', settings.audioOutput);
    if (settings.blackBackground !== false)
        args.push('-b');
    if (settings.disableKeys === true)
        args.push('--no-keys');
    if (settings.disableOnScreenDisplay === true)
        args.push('--no-osd');
    if (settings.disableGhostbox === true)
        args.push('--no-ghost-box');
    if (settings.subtitlePath && settings.subtitlePath !== '')
        args.push('--subtitles', '"' + settings.subtitlePath + '"');
    if (settings.startAt)
        args.push('--pos', '' + settings.startAt + '');
    if (typeof settings.startVolume !== 'undefined') {
        if (settings.startVolume >= 0.0 && settings.startVolume <= 1.0) {
            args.push('--vol');
            var db = settings.startVolume > 0 ? Math.round(100 * 20 * (Math.log(settings.startVolume) / Math.log(10))) / 1 : -12000000;
            args.push(db);
        }
    }

    args.push('--dbus_name');
    args.push('org.mpris.MediaPlayer2.omxplayer');
    args.push('< omxpipe');
    var omxspawn = spawn(command, args);
    omxspawn.on('exit', function(code) {
        eventEmitter.emit('exit', code);
    });
    //Check this out to see if you can make this work!!!!
    //https://github.com/nodejs/node-v0.x-archive/issues/4374#issuecomment-11065865

    exec(' . > omxpipe');
};
<|endoftext|>


<commit_before>var database = require('./database');
var utils = require('./utils');
var config = require('config');
var _ = require('lodash');

const allowed_operations = ['ADD', 'SEARCH', 'DELETE'];

function add(server, verbose) {
  if (verbose) {
    console.log(server);
  }
  var db_server = search({hostname: server.hostname});
  if (verbose) {
    console.log(db_server);
  }
  if (db_server && db_server.length>0) {
    db_server=db_server[0];
    console.log("Server already present into DB. Updating information if needed...");
    var dataToUpdate = {
      "ip": server.ip!==undefined ? server.ip : db_server.ip,
      "admin_server": server.admin_server!==undefined ? server.admin_server : db_server.admin_server,
      "username": server.username!==undefined ? server.username : db_server.username,
      "tags": server.tags!==undefined ? _.uniq(_.concat(server.tags, db_server.tags)) : db_server.tags
    };
    if (verbose) {
      console.log("Data to update: ");
      console.log(dataToUpdate);
    }
    database[config.server_collection].update({hostname: server.hostname}, dataToUpdate);
  } else {
    console.log("Saving...");
    database[config.server_collection].save(server);
  }
  if (verbose) {
    console.log("Checking tags: " + server.tags);
  }
  if (server.tags && server.tags.length > 0) {
      for (var i = 0; i < server.tags.length; i++) {
        var db_tag = database[config.tag_collection].find({tag: server.tags[i]});
        if (db_tag && db_tag.length>0) {
          if (verbose) {
            console.log("Tag " + server.tags[i] + " already present. Updating it.");
          }
          //supposing tag unique into collection
          db_tag[0].hostnames.push(server.hostname);
          database[config.tag_collection].update({tag: server.tags[i]}, {hostnames: _.uniq(db_tag[0].hostnames)});
        } else {
          if (verbose) {
            console.log("Saving new TAG " + server.tags[i]);
          }
          database[config.tag_collection].save({tag: server.tags[i], hostnames: [server.hostname]});
        }
      }
  }
}

function search(query, verbose) {
  if (query.hostname) {
    if (verbose) {
      console.log("Searching only using the Hostname 'cause it is unique into the database'");
    }
    return database[config.server_collection].find({"hostname": query.hostname});
  } else {
    //Searching using tags
    var hosts_list = [];
    if (query.tags && query.tags.length > 0) {
      if (verbose) {
        console.log("Searching with " + query.tags.length + " tags" );
      }
      for (var i=0; i<query.tags.length; i++) {
        var hosts = database[config.tag_collection].find({"tag": query.tags[i]});
        //Supposing only 1 tag
        var hostnames = hosts[0] ? hosts[0].hostnames : [];
        if (i > 0) {
          hosts_list = _.intersection(hosts_list, hostnames);
        } else {
          hosts_list = hostnames;
        }
      }
    }
    if (config.show_ssh_command) {
      return utils.convertHostToSSHCommand(hosts_list, verbose);
    } else {
      return hosts_list;
    }
  }
}

module.exports.allowed_operations = allowed_operations;
module.exports.database = database;
module.exports.add = add;
module.exports.search = search;
<commit_msg>Propagated Verbose between add and search function<commit_after>var database = require('./database');
var utils = require('./utils');
var config = require('config');
var _ = require('lodash');

const allowed_operations = ['ADD', 'SEARCH', 'DELETE'];

function add(server, verbose) {
  if (verbose) {
    console.log(server);
  }
  var db_server = search({hostname: server.hostname}, verbose);
  if (verbose) {
    console.log(db_server);
  }
  if (db_server && db_server.length>0) {
    db_server=db_server[0];
    console.log("Server already present into DB. Updating information if needed...");
    var dataToUpdate = {
      "ip": server.ip!==undefined ? server.ip : db_server.ip,
      "admin_server": server.admin_server!==undefined ? server.admin_server : db_server.admin_server,
      "username": server.username!==undefined ? server.username : db_server.username,
      "tags": server.tags!==undefined ? _.uniq(_.concat(server.tags, db_server.tags)) : db_server.tags
    };
    if (verbose) {
      console.log("Data to update: ");
      console.log(dataToUpdate);
    }
    database[config.server_collection].update({hostname: server.hostname}, dataToUpdate);
  } else {
    console.log("Saving...");
    database[config.server_collection].save(server);
  }
  if (verbose) {
    console.log("Checking tags: " + server.tags);
  }
  if (server.tags && server.tags.length > 0) {
      for (var i = 0; i < server.tags.length; i++) {
        var db_tag = database[config.tag_collection].find({tag: server.tags[i]});
        if (db_tag && db_tag.length>0) {
          if (verbose) {
            console.log("Tag " + server.tags[i] + " already present. Updating it.");
          }
          //supposing tag unique into collection
          db_tag[0].hostnames.push(server.hostname);
          database[config.tag_collection].update({tag: server.tags[i]}, {hostnames: _.uniq(db_tag[0].hostnames)});
        } else {
          if (verbose) {
            console.log("Saving new TAG " + server.tags[i]);
          }
          database[config.tag_collection].save({tag: server.tags[i], hostnames: [server.hostname]});
        }
      }
  }
}

function search(query, verbose) {
  if (query.hostname) {
    if (verbose) {
      console.log("Searching only using the Hostname 'cause it is unique into the database'");
    }
    return database[config.server_collection].find({"hostname": query.hostname});
  } else {
    //Searching using tags
    var hosts_list = [];
    if (query.tags && query.tags.length > 0) {
      if (verbose) {
        console.log("Searching with " + query.tags.length + " tags" );
      }
      for (var i=0; i<query.tags.length; i++) {
        var hosts = database[config.tag_collection].find({"tag": query.tags[i]});
        //Supposing only 1 tag
        var hostnames = hosts[0] ? hosts[0].hostnames : [];
        if (i > 0) {
          hosts_list = _.intersection(hosts_list, hostnames);
        } else {
          hosts_list = hostnames;
        }
      }
    }
    if (config.show_ssh_command) {
      return utils.convertHostToSSHCommand(hosts_list, verbose);
    } else {
      return hosts_list;
    }
  }
}

module.exports.allowed_operations = allowed_operations;
module.exports.database = database;
module.exports.add = add;
module.exports.search = search;
<|endoftext|>


<commit_before>// clone - For creating deep copies of data structures
// lodash - For various common data wrangling functions

var _ = require('lodash');
var clone = require('clone');
var fs = require('fs');
var path = require('path');
var working_dir;

var config_path = null;
var logger = null;

function set_logging(log_file) {
    var log4js = require('log4js');

    log4js.clearAppenders();
    log4js.loadAppender('file');
    log4js.loadAppender('console');
    log4js.addAppender(log4js.appenders.file(log_file), 'main');
    log4js.addAppender(log4js.appenders.console(log4js.messagePassThroughLayout), 'console');

    // Set the logger
    logger = log4js.getLogger('main');
}

exports.set_log_file = function(log_file_path) {
    set_logging(log_file_path);
};

exports.get_logger = function() {
    if (logger === null || logger === undefined) {
        log_file_path = path.resolve(exports.get_osdf_root(), 'logs/osdf.log');
        set_logging(log_file_path);
    }
    return logger;
};

exports.get_config = function() {
    if (config_path === null || config_path === undefined) {
        config_path = path.resolve(exports.get_osdf_root(), 'conf/config.ini');
    }
    return config_path;
};

exports.set_config = function(config_file_path) {
    config_path = config_file_path;
};

exports.set_working_dir = function(directory, cb) {
    fs.stat(directory, function(err, stats) {
        if (err) {
            throw err;
        }
        if (stats.isDirectory()) {
            working_dir = directory;
            cb();
        } else {
            throw "Configured path to working area is not a directory: " + directory;
        }
    });
};

exports.get_working_dir = function() {
    // If the working directory hasn't been set, then we use the default,
    // which is a directory called 'working' under the OSDF root.
    if (working_dir === null || typeof working_dir === 'undefined') {
        working_dir = path.resolve(exports.get_osdf_root(), 'working');
    }

    return working_dir;
};

exports.get_osdf_root = function() {
    return path.resolve(__dirname, '..');
};

exports.random_string = function(length) {
    var valid_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
    var chars = valid_chars.split('');
    var str = '';
    var i;

    if (! length) {
        length = Math.floor(Math.random() * chars.length);
    }

    for (i = 0; i < length; i++) {
        str += chars[Math.floor(Math.random() * chars.length)];
    }
    return str;
};

// Used to retrieve the namespace names known to this OSDF instance.
// The function takes a callback that is called when the namespace scan
// is complete. The callback will be passed an array of namespace names
// as its first argument.
exports.get_namespace_names = function(callback) {
    if (! callback) {
        throw "No callback provided.";
    }

    var namespaces = [];
    var namespace_dir = path.join(exports.get_working_dir(), 'namespaces');

    // Scan the directory containing the namespace descriptors for JSON
    // files. Do it ASYNCHRONOUSLY, so we DO NOT use the "sync" version
    // of readdir(), readDirSync().
    fs.readdir(namespace_dir, function(err, files) {
        if (err) {
            throw err;
        }

        // Reject any hidden files/directories, such as .svn directories
        files = _.reject(files, function(file) {
            return file.substr(0,1) === '.';
        });

        exports.async_for_each(files, function(entry, cb) {
            var full_path = path.join(namespace_dir, entry);

            fs.stat(full_path, function(err, stats) {
                if (err) {
                    throw err;
                }

                if (stats.isDirectory()) {
                    namespaces.push(entry);
                } else {
                    logger.debug(entry + " is not a directory!");
                }
                cb();
            });
        }, function() { callback(namespaces); });
    });
};

exports.async_for_each = function(array, iterator, then) {
    function loop(i) {
        if (i < array.length) {
            iterator(array[i], function() {
                loop(i + 1);
            });
        } else {
            if (typeof then !== 'undefined' && then !== null) { then(); }
        }
    }
    loop(0);
};

// Check for white space
exports.has_white_space = function(string) {
    return (/\s/).test(string);
};

exports.fix_keys = function(data) {
    // Should need to clone the data, but stumbled upon an apparent bug with V8.
    var new_data = null;

    if (data !== null) {
        new_data = clone(data);

        new_data['id'] = data._id;
        new_data['ver'] = parseInt(data._rev.split("-")[0], 10);

        delete new_data._id;
        delete new_data._rev;
    }
    return new_data;
};

exports.send_error = function(response, error_message, http_code) {
    response.set('X-OSDF-Error', error_message);
    response.status(http_code).send('');
};
<commit_msg>Using async and removed async_for_each().<commit_after>// clone - For creating deep copies of data structures
// lodash - For various common data wrangling functions

var _ = require('lodash');
var async = require('async');
var clone = require('clone');
var fs = require('fs');
var path = require('path');
var working_dir;

var config_path = null;
var logger = null;

function set_logging(log_file) {
    var log4js = require('log4js');

    log4js.clearAppenders();
    log4js.loadAppender('file');
    log4js.loadAppender('console');
    log4js.addAppender(log4js.appenders.file(log_file), 'main');
    log4js.addAppender(log4js.appenders.console(log4js.messagePassThroughLayout), 'console');

    // Set the logger
    logger = log4js.getLogger('main');
}

exports.set_log_file = function(log_file_path) {
    set_logging(log_file_path);
};

exports.get_logger = function() {
    if (logger === null || logger === undefined) {
        log_file_path = path.resolve(exports.get_osdf_root(), 'logs/osdf.log');
        set_logging(log_file_path);
    }
    return logger;
};

exports.get_config = function() {
    if (config_path === null || config_path === undefined) {
        config_path = path.resolve(exports.get_osdf_root(), 'conf/config.ini');
    }
    return config_path;
};

exports.set_config = function(config_file_path) {
    config_path = config_file_path;
};

exports.set_working_dir = function(directory, cb) {
    fs.stat(directory, function(err, stats) {
        if (err) {
            throw err;
        }
        if (stats.isDirectory()) {
            working_dir = directory;
            cb();
        } else {
            throw "Configured path to working area is not a directory: " +
                  directory;
        }
    });
};

exports.get_working_dir = function() {
    // If the working directory hasn't been set, then we use the default,
    // which is a directory called 'working' under the OSDF root.
    if (working_dir === null || typeof working_dir === 'undefined') {
        working_dir = path.resolve(exports.get_osdf_root(), 'working');
    }

    return working_dir;
};

exports.get_osdf_root = function() {
    return path.resolve(__dirname, '..');
};

exports.random_string = function(length) {
    var valid_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ' +
                      'abcdefghiklmnopqrstuvwxyz';
    var chars = valid_chars.split('');
    var str = '';
    var i;

    if (! length) {
        length = Math.floor(Math.random() * chars.length);
    }

    for (i = 0; i < length; i++) {
        str += chars[Math.floor(Math.random() * chars.length)];
    }
    return str;
};

// Used to retrieve the namespace names known to this OSDF instance.
// The function takes a callback that is called when the namespace scan
// is complete. The callback will be passed an array of namespace names
// as its first argument.
exports.get_namespace_names = function(callback) {
    if (! callback) {
        throw "No callback provided.";
    }

    var namespaces = [];
    var namespace_dir = path.join(exports.get_working_dir(), 'namespaces');

    // Scan the directory containing the namespace descriptors for JSON
    // files. Do it ASYNCHRONOUSLY, so we DO NOT use the "sync" version
    // of readdir(), readDirSync().
    fs.readdir(namespace_dir, function(err, files) {
        if (err) {
            throw err;
        }

        // Reject any hidden files/directories, such as .svn directories
        files = _.reject(files, function(file) {
            return file.substr(0,1) === '.';
        });

        async.each(files, function(entry, cb) {
            var full_path = path.join(namespace_dir, entry);

            fs.stat(full_path, function(err, stats) {
                if (err) {
                    cb(err);
                } else {
                    if (stats.isDirectory()) {
                        namespaces.push(entry);
                    } else {
                        logger.warn(entry + " is not a directory!");
                    }
                    cb();
                }
            });
        }, function(err) {
            if (err) {
                logger.error("Unable to get namespace names: " + err);
                callback(err, null);
            } else {
                 callback(null, namespaces);
            }
        });
    });
};

// Check for white space
exports.has_white_space = function(string) {
    return (/\s/).test(string);
};

exports.fix_keys = function(data) {
    // Should need to clone the data, but stumbled upon an apparent bug with V8.
    var new_data = null;

    if (data !== null) {
        new_data = clone(data);

        new_data['id'] = data._id;
        new_data['ver'] = parseInt(data._rev.split("-")[0], 10);

        delete new_data._id;
        delete new_data._rev;
    }
    return new_data;
};

exports.send_error = function(response, error_message, http_code) {
    response.set('X-OSDF-Error', error_message);
    response.status(http_code).send('');
};
<|endoftext|>


<commit_before>// clone - For creating deep copies of data structures

var _ = require('underscore');
var clone = require('clone');
var fs = require('fs');
var path = require('path');
var log4js = require('log4js');

var root = path.resolve(path.resolve(__dirname, '..'));
var log_file = path.join(root, '/logs/osdf.log');
log4js.clearAppenders();
log4js.loadAppender('file');
log4js.loadAppender('console');
log4js.addAppender(log4js.appenders.file(log_file), 'main');
log4js.addAppender(log4js.appenders.console(log4js.messagePassThroughLayout), 'console');

var logger = log4js.getLogger('main');

exports.get_logger = function() {
    return logger;
}

exports.get_config = function() {
    return path.resolve(exports.get_osdf_root(), 'conf/conf.ini');
}

exports.get_osdf_root = function() {
    return path.resolve(__dirname, '..');
}

exports.random_string = function (length) {
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');

    if (! length) {
        length = Math.floor(Math.random() * chars.length);
    }

    var str = '';
    for (var i = 0; i < length; i++) {
        str += chars[Math.floor(Math.random() * chars.length)];
    }
    return str;
}

// Used to retrieve the namespace names known to this OSDF instance.
// The function takes a callback that is called when the namespace scan
// is complete. The callback will be passed an array of namespace names
// as its first argument.
exports.get_namespace_names = function (callback) {
    if (! callback) {
        throw "No callback provided.";
    }

    var namespaces = [];
    var namespace_dir = path.join(exports.get_osdf_root(), 'working/namespaces');

    // Scan the directory containing the namespace descriptors for JSON
    // files. Do it ASYNCHRONOUSLY, so we DO NOT use the "sync" version
    // of readdir(), readDirSync().
    fs.readdir(namespace_dir, function(err, files) {
        if (err) throw err;

        // Reject any hidden files/directories, such as .svn directories
        files = _.reject(files, function(file) { return file.substr(0,1) == '.' });

        exports.async_for_each(files, function(entry, cb) {
            var full_path = path.join(namespace_dir, entry);

            fs.stat(full_path, function(err, stats) {
                if (err) throw err;

                if (stats.isDirectory()) {
                    namespaces.push(entry);
                } else {
                    logger.debug(entry + " is not a directory!");
                }
                cb();
            });
        }, function() { callback(namespaces)});
    });
}

// A quick way to check if an array contains a value
// The first argument is the value to check for, and the
// second argument is the array to check in.
exports.contains = function (value, array_to_check ) {
    var present = false;
    if (array_to_check != null) {
        var len = array_to_check.length;
        while (len--) {
            if (array_to_check[len] === value) {
                present = true;
            }
        }
    }
    return present;
}

exports.async_for_each = function (array, iterator, then) {
    function loop(i) {
        if (i < array.length) {
            iterator(array[i], function() {
                loop(i + 1);
            });
        } else {
            if (then != null) { then(); }
        }
    }
    loop(0);
}

// Check for white space
exports.has_white_space = function(string) {
    return /\s/.test(string);
}

exports.fix_keys = function(data) {
    // Should need to clone the data, but stumbled upon an apparent bug with V8.
    var new_data = null;

    if (data !== null) {
        new_data = clone(data);

        new_data['id'] = data._id;
        new_data['ver'] = parseInt(data._rev.split("-")[0], 10);

        delete new_data._id;
        delete new_data._rev;
    }
    return new_data;
}

<commit_msg>Updates to comply with nodelint.<commit_after>// clone - For creating deep copies of data structures

var _ = require('underscore');
var clone = require('clone');
var fs = require('fs');
var path = require('path');
var log4js = require('log4js');

var root = path.resolve(path.resolve(__dirname, '..'));
var log_file = path.join(root, '/logs/osdf.log');
log4js.clearAppenders();
log4js.loadAppender('file');
log4js.loadAppender('console');
log4js.addAppender(log4js.appenders.file(log_file), 'main');
log4js.addAppender(log4js.appenders.console(log4js.messagePassThroughLayout), 'console');

var logger = log4js.getLogger('main');

exports.get_logger = function() {
    return logger;
};

exports.get_config = function() {
    return path.resolve(exports.get_osdf_root(), 'conf/conf.ini');
};

exports.get_osdf_root = function() {
    return path.resolve(__dirname, '..');
};

exports.random_string = function (length) {
    var valid_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
    var chars = valid_chars.split('');
    var str = '';
    var i;

    if (! length) {
        length = Math.floor(Math.random() * chars.length);
    }

    for (i = 0; i < length; i++) {
        str += chars[Math.floor(Math.random() * chars.length)];
    }
    return str;
};

// Used to retrieve the namespace names known to this OSDF instance.
// The function takes a callback that is called when the namespace scan
// is complete. The callback will be passed an array of namespace names
// as its first argument.
exports.get_namespace_names = function (callback) {
    if (! callback) {
        throw "No callback provided.";
    }

    var namespaces = [];
    var namespace_dir = path.join(exports.get_osdf_root(), 'working/namespaces');

    // Scan the directory containing the namespace descriptors for JSON
    // files. Do it ASYNCHRONOUSLY, so we DO NOT use the "sync" version
    // of readdir(), readDirSync().
    fs.readdir(namespace_dir, function(err, files) {
        if (err) {
            throw err;
        }

        // Reject any hidden files/directories, such as .svn directories
        files = _.reject(files, function(file) { return file.substr(0,1) === '.'; });

        exports.async_for_each(files, function(entry, cb) {
            var full_path = path.join(namespace_dir, entry);

            fs.stat(full_path, function(err, stats) {
                if (err) {
                    throw err;
                }

                if (stats.isDirectory()) {
                    namespaces.push(entry);
                } else {
                    logger.debug(entry + " is not a directory!");
                }
                cb();
            });
        }, function() { callback(namespaces); });
    });
};

// A quick way to check if an array contains a value
// The first argument is the value to check for, and the
// second argument is the array to check in.
exports.contains = function (value, array_to_check ) {
    var present = false;
    if (array_to_check !== null) {
        var len = array_to_check.length;
        while (len--) {
            if (array_to_check[len] === value) {
                present = true;
            }
        }
    }
    return present;
};

exports.async_for_each = function (array, iterator, then) {
    function loop(i) {
        if (i < array.length) {
            iterator(array[i], function() {
                loop(i + 1);
            });
        } else {
            if (then !== null) { then(); }
        }
    }
    loop(0);
};

// Check for white space
exports.has_white_space = function(string) {
    return (/\s/).test(string);
};

exports.fix_keys = function(data) {
    // Should need to clone the data, but stumbled upon an apparent bug with V8.
    var new_data = null;

    if (data !== null) {
        new_data = clone(data);

        new_data['id'] = data._id;
        new_data['ver'] = parseInt(data._rev.split("-")[0], 10);

        delete new_data._id;
        delete new_data._rev;
    }
    return new_data;
};
<|endoftext|>


<commit_before>/**
* Template helpers
*/

Template.adminLocation.onRendered(function () {
  $('body').addClass('admin');
});

// Helpers for adminLocation template
Template.adminLocation.helpers({

  imageEntries: function () {

    return Images.find({}, { sort:{ isoDate: 1 } });

  },

  tableSettings: function () {
    return {
      collection: Images.find({}, { sort:{ isoDate: 1 } }),

      showNavigation: 'auto',
      showNavigationRowsPerPage: true,
      class: 'table table-striped col-sm-12 reactive-table',
      filters: ['myFilter'],
      showFilter: false,
      rowsPerPage: 100,
      fields: [
        { key: 'dsNumber', label: 'DS Number' },
        { key: 'isoDate', label: 'Date' },
        { key: 'title', label: 'Title' },
        { key: 'creationPlace', label: 'Creation place' },
        { key: 'creditLine', label: 'Credit line' },

        {
          key:'active',
          label: 'Active',
          headerClass: 'something-else',
          cellClass: 'something-else',
          fn: function (value) {
            if (value === true) {
              return new Spacebars.SafeString('
' +
                '
');
            } else {
              return new Spacebars.SafeString('');
            }
          },
        },

        {
          key:'_id',
          label: 'Thumbnail',
          sortable: false,
          fn: function (value) {
            var thumbPath = '/images/thumbnails/' + value + '.jpg';
            var previewPath = thumbPath;
            var imgDoc = Images.findOne({ _id: value });
            if (imgDoc) {
              if (imgDoc.imageFilePaths) {
                thumbPath = imgDoc.imageFilePaths[1].src;
                previewPath = imgDoc.imageFilePaths[0].src;
              }
            }

            return new Spacebars.SafeString(
              ''
            );
          },
        },

        /* Edit */
        {
          key:'_id',
          label: 'Actions',
          sortable: false,
          fn: function (value) {
            var htmlString = '
' +
              '
Edit
';
            return new Spacebars.SafeString(htmlString);
          },
        },

        /* Delete */
        {
          key:'_id',
          label: '',
          sortable: false,
          fn: function (value) {
            var htmlstring = '
' +
              '
Delete
';
            return new Spacebars.SafeString(htmlstring);
          },
        },

        /* Preview */
        {
          key:'_id',
          label: '',
          sortable: false,
          fn: function (value) {
            var htmlString = '';
            if (Images.findOne(value).active === true) htmlString += (
              '
' +
              '
Preview
'
            );
            return new Spacebars.SafeString(htmlString);
          },
        },

      ],
    };
  },

});

// Helpers for adminEditModal template
Template.adminEditModal.helpers({

  editImage: function () {

    return Images.findOne({ _id: Session.get('adminCurrentImageId') });

  },

  updateOrInsertMode: function () {

    if (Session.get('adminCurrentImageId') && Session.get('adminCurrentImageId') !== '') {
      return 'update';
    } else {
      return 'insert';
    }

  },

  modalHeader: function () {

    if (Session.get('adminCurrentImageId') && Session.get('adminCurrentImageId') !== '') {
      return 'EDIT IMAGE';
    } else {
      return 'ADD NEW IMAGE';
    }

  },

});

Template.adminLocation.events({
  /**
  * Entry click
  */
  'click a.edit, click .btn.add':function (e) {

    var clickedId = $(e.currentTarget).attr('id');

    if (clickedId === 'addBtn') {

      Session.set('adminCurrentImageId', '');
      $('#editModal').modal('show');

    } else {

      Session.set('adminCurrentImageId', clickedId);
      $('#editModal').modal('show');

    }

  },

  'click a.delete':function (e) {

    var imgToDeleteId = $(e.currentTarget).attr('id');

    console.log('delete clicked:', imgToDeleteId);

    var response = confirm('Are you sure you want to delete Image ' + imgToDeleteId + '?');

    if (response == true) {
      Images.remove(imgToDeleteId);
    } else {
      console.log('Deletion canceled.');
    }

  },

  'click a.preview':function (e) {

    var imgToPreviewId = $(e.currentTarget).attr('id');

    // Example link to image...
    // /riverside?image=ds20001

    var currentLink = Locations.findOne().link;
    var previewURL = 'http://' + window.location.host + '/location/' + currentLink + '';
    if (imgToPreviewId) {
      previewURL += '?image=' + imgToPreviewId;
    }

    Session.set('adminCurrentPreviewURL', previewURL);
    Session.set('adminCurrentReturnURL', '/admin/locations/' + currentLink);
    Session.set('adminCurrentReturnName', Locations.findOne().title);
    console.log('teete');

    // Router.go('/admin/preview');

  },

  'mouseenter table img.tableThumb':function (e) {

    var expandSrc = $(e.currentTarget).attr('data-preview-src');
    var $preview = $('#tableThumbPreview');
    $('#tableThumbPreview img').attr('src', expandSrc);
    $preview.css('top', e.clientY - $preview.outerHeight() / 2);
    $preview.css('right', $(document).width() - e.clientX + 17);
    $preview.delay(150).stop().fadeIn(70);

  },

  'mousemove table img.tableThumb':function (e) {
    var $preview = $('#tableThumbPreview');
    $preview.css('top', e.clientY - $preview.outerHeight() / 2);
    $preview.css('right', $(document).width() - e.clientX + 17);
  },

  'mouseleave table img.tableThumb':function (e) {
    $('#tableThumbPreview').stop().hide();
  },

  'show.bs.modal':function (e) {

    // Hack to fix autoform bug.
    // Clears image upload form when
    // no imageFilePaths are found. -tn
    setTimeout(function () {
      var imgDoc = Images.findOne({ _id: Session.get('adminCurrentImageId') });
      if (imgDoc) {
        if (imgDoc.imageFilePaths) {
          // Already has image. Allow to display.
          return;
        }
      }

      $('#editModal .file-upload-clear').trigger('click');
    }, 20);

  },

  'shown.bs.modal':function (e) {

  },

});

// ImageUtil
function loadImgDimensions(doc, isUpdate, callback) {

  var editDoc;
  if (isUpdate) {
    editDoc = doc.$set;
  } else {
    editDoc = doc;
  }

  if (
    editDoc.imageFilePaths == undefined ||
    editDoc.imageFilePaths == 'undefined' ||
    !editDoc.imageFilePaths
  ) {
    callback(doc);
    return false;
  }

  var expandedSrc = editDoc.imageFilePaths[0].src;
  var thumbSrc = editDoc.imageFilePaths[1].src;
  var myImage = new Image();
  var myThumbImage = new Image();

  var expandedLoaded = false;
  var thumbLoaded = false;

  myImage.onload = function () {

    console.log('\' Expanded is ' + this.width + ' by ' + this.height + ' pixels in size.');

    editDoc.expandedWidth = this.width;
    editDoc.expandedHeight = this.height;
    editDoc.expandedAspectRatio = (this.width / this.height).toFixed(4);

    expandedLoaded = true;
    if (thumbLoaded && expandedLoaded) {
      if (isUpdate) {
        callback({ $set:editDoc });
        return true;
      } else {
        callback(editDoc);
        return true;
      }
    }

  };

  myThumbImage.onload = function () {

    console.log('\' Thumb is ' + this.width + ' by ' + this.height + ' pixels in size.');

    editDoc.thumbWidth = this.width;
    editDoc.thumbHeight = this.height;
    editDoc.thumbAspectRatio = (this.width / this.height).toFixed(4);

    thumbLoaded = true;
    if (thumbLoaded && expandedLoaded) {
      if (isUpdate) {
        callback({ $set:editDoc });
        return true;
      } else {
        callback(editDoc);
        return true;
      }
    }

  };

  myImage.onerror = function () {

    console.log('\'' + this.name + '\' (expanded) failed to load.');
    callback(doc);
    return false;

  };

  myThumbImage.onerror = function () {

    console.log('\'' + this.name + '\' (thumb) failed to load.');
    callback(doc);
    return false;

  };

  myImage.src = expandedSrc;
  myThumbImage.src = thumbSrc;

}

/**
* Hooks for autoform. Manipulate data before/after submission.
*/
AutoForm.hooks({

  formImageEntry: {

    before: {

      insert: function (doc) {

        // Add location Id to create link to current location
        doc.dsLocId = Locations.findOne().dsLocId;
        doc.generalLocationDs = Locations.findOne().title;

        // Add image meta data
        loadImgDimensions(doc, false, this.result);

      },

      update: function (doc) {

        // Add image meta data
        loadImgDimensions(doc, true, this.result);

      },

    },

    docToForm: function (doc, ss) {

      // TODO - Remove unneccessary iso prepend (cleaning old data)
      if (doc.isoDate && doc.isoDate.indexOf('iso-') != -1) {
        doc.isoDate = doc.isoDate.replace('iso-', '');
      }

      return doc;

    },

    // Called when any submit operation succeeds
    onSuccess: function (formType, result) {

      if (formType === 'insert') {
        Session.set('adminCurrentImageId', result);
      }

      console.log('New doc:');
      console.log(Images.findOne(Session.get('adminCurrentImageId')));

      // Hide modal
      $('#editModal').modal('hide');
      $('#editModal form')[0].reset();

    },

    // Called when any submit operation fails
    onError: function (formType, error) {

      console.log('Autoform error:', formType, error);

    },

  },

});
<commit_msg>Cleanup<commit_after>/**
* Template helpers
*/

Template.adminLocation.onRendered(function () {
  $('body').addClass('admin');
});

// Helpers for adminLocation template
Template.adminLocation.helpers({

  imageEntries: function () {

    return Images.find({}, { sort:{ isoDate: 1 } });

  },

  tableSettings: function () {
    return {
      collection: Images.find({}, { sort:{ isoDate: 1 } }),

      showNavigation: 'auto',
      showNavigationRowsPerPage: true,
      class: 'table table-striped col-sm-12 reactive-table',
      filters: ['myFilter'],
      showFilter: false,
      rowsPerPage: 100,
      fields: [
        { key: 'dsNumber', label: 'DS Number' },
        { key: 'isoDate', label: 'Date' },
        { key: 'title', label: 'Title' },
        { key: 'creationPlace', label: 'Creation place' },
        { key: 'creditLine', label: 'Credit line' },

        {
          key:'active',
          label: 'Active',
          headerClass: 'something-else',
          cellClass: 'something-else',
          fn: function (value) {
            if (value === true) {
              return new Spacebars.SafeString('
' +
                '
');
            } else {
              return new Spacebars.SafeString('');
            }
          },
        },

        {
          key:'_id',
          label: 'Thumbnail',
          sortable: false,
          fn: function (value) {
            var thumbPath = '/images/thumbnails/' + value + '.jpg';
            var previewPath = thumbPath;
            var imgDoc = Images.findOne({ _id: value });
            if (imgDoc) {
              if (imgDoc.imageFilePaths) {
                thumbPath = imgDoc.imageFilePaths[1].src;
                previewPath = imgDoc.imageFilePaths[0].src;
              }
            }

            return new Spacebars.SafeString(
              ''
            );
          },
        },

        /* Edit */
        {
          key:'_id',
          label: 'Actions',
          sortable: false,
          fn: function (value) {
            var htmlString = '
' +
              '
Edit
';
            return new Spacebars.SafeString(htmlString);
          },
        },

        /* Delete */
        {
          key:'_id',
          label: '',
          sortable: false,
          fn: function (value) {
            var htmlstring = '
' +
              '
Delete
';
            return new Spacebars.SafeString(htmlstring);
          },
        },

        /* Preview */
        {
          key:'_id',
          label: '',
          sortable: false,
          fn: function (value) {
            var htmlString = '';
            if (Images.findOne(value).active === true) htmlString += (
              '
' +
              '
Preview
'
            );
            return new Spacebars.SafeString(htmlString);
          },
        },

      ],
    };
  },

});

// Helpers for adminEditModal template
Template.adminEditModal.helpers({

  editImage: function () {

    return Images.findOne({ _id: Session.get('adminCurrentImageId') });

  },

  updateOrInsertMode: function () {

    if (Session.get('adminCurrentImageId') && Session.get('adminCurrentImageId') !== '') {
      return 'update';
    } else {
      return 'insert';
    }

  },

  modalHeader: function () {

    if (Session.get('adminCurrentImageId') && Session.get('adminCurrentImageId') !== '') {
      return 'EDIT IMAGE';
    } else {
      return 'ADD NEW IMAGE';
    }

  },

});

Template.adminLocation.events({
  /**
  * Entry click
  */
  'click a.edit, click .btn.add':function (e) {

    var clickedId = $(e.currentTarget).attr('id');

    if (clickedId === 'addBtn') {

      Session.set('adminCurrentImageId', '');
      $('#editModal').modal('show');

    } else {

      Session.set('adminCurrentImageId', clickedId);
      $('#editModal').modal('show');

    }

  },

  'click a.delete':function (e) {

    var imgToDeleteId = $(e.currentTarget).attr('id');

    console.log('delete clicked:', imgToDeleteId);

    var response = confirm('Are you sure you want to delete Image ' + imgToDeleteId + '?');

    if (response == true) {
      Images.remove(imgToDeleteId);
    } else {
      console.log('Deletion canceled.');
    }

  },

  'click a.preview':function (e) {

    var imgToPreviewId = $(e.currentTarget).attr('id');

    // Example link to image...
    // /riverside?image=ds20001

    var currentLink = Locations.findOne().link;
    var previewURL = 'http://' + window.location.host + '/location/' + currentLink + '';
    if (imgToPreviewId) {
      previewURL += '?image=' + imgToPreviewId;
    }

    Session.set('adminCurrentPreviewURL', previewURL);
    Session.set('adminCurrentReturnURL', '/admin/locations/' + currentLink);
    Session.set('adminCurrentReturnName', Locations.findOne().title);
    console.log('teete');

    // Router.go('/admin/preview');

  },

  'mouseenter table img.tableThumb':function (e) {

    var expandSrc = $(e.currentTarget).attr('data-preview-src');
    var $preview = $('#tableThumbPreview');
    $('#tableThumbPreview img').attr('src', expandSrc);
    $preview.css('top', e.clientY - $preview.outerHeight() / 2);
    $preview.css('right', $(document).width() - e.clientX + 17);
    $preview.delay(150).stop().fadeIn(70);

  },

  'mousemove table img.tableThumb':function (e) {
    var $preview = $('#tableThumbPreview');
    $preview.css('top', e.clientY - $preview.outerHeight() / 2);
    $preview.css('right', $(document).width() - e.clientX + 17);
  },

  'mouseleave table img.tableThumb':function (e) {
    $('#tableThumbPreview').stop().hide();
  },

  'show.bs.modal':function (e) {

    // Hack to fix autoform bug.
    // Clears image upload form when
    // no imageFilePaths are found. -tn
    setTimeout(function () {
      var imgDoc = Images.findOne({ _id: Session.get('adminCurrentImageId') });
      if (imgDoc) {
        if (imgDoc.imageFilePaths) {
          // Already has image. Allow to display.
          return;
        }
      }

      $('#editModal .file-upload-clear').trigger('click');
    }, 20);

  },

  'shown.bs.modal':function (e) {

  },

});

// ImageUtil
function loadImgDimensions(doc, isUpdate, callback) {

  var editDoc;
  if (isUpdate) {
    editDoc = doc.$set;
  } else {
    editDoc = doc;
  }

  if (
    editDoc.imageFilePaths == undefined ||
    editDoc.imageFilePaths == 'undefined' ||
    !editDoc.imageFilePaths
  ) {
    callback(doc);
    return false;
  }

  var expandedSrc = editDoc.imageFilePaths[0].src;
  var thumbSrc = editDoc.imageFilePaths[1].src;
  var myImage = new Image();
  var myThumbImage = new Image();

  var expandedLoaded = false;
  var thumbLoaded = false;

  myImage.onload = function () {

    console.log('\' Expanded is ' + this.width + ' by ' + this.height + ' pixels in size.');

    editDoc.expandedWidth = this.width;
    editDoc.expandedHeight = this.height;
    editDoc.expandedAspectRatio = (this.width / this.height).toFixed(4);

    expandedLoaded = true;
    if (thumbLoaded && expandedLoaded) {
      if (isUpdate) {
        callback({ $set:editDoc });
        return true;
      } else {
        callback(editDoc);
        return true;
      }
    }

  };

  myThumbImage.onload = function () {

    console.log('\' Thumb is ' + this.width + ' by ' + this.height + ' pixels in size.');

    editDoc.thumbWidth = this.width;
    editDoc.thumbHeight = this.height;
    editDoc.thumbAspectRatio = (this.width / this.height).toFixed(4);

    thumbLoaded = true;
    if (thumbLoaded && expandedLoaded) {
      if (isUpdate) {
        callback({ $set:editDoc });
        return true;
      } else {
        callback(editDoc);
        return true;
      }
    }

  };

  myImage.onerror = function () {

    console.log('\'' + this.name + '\' (expanded) failed to load.');
    callback(doc);
    return false;

  };

  myThumbImage.onerror = function () {

    console.log('\'' + this.name + '\' (thumb) failed to load.');
    callback(doc);
    return false;

  };

  myImage.src = expandedSrc;
  myThumbImage.src = thumbSrc;

}

/**
* Hooks for autoform. Manipulate data before/after submission.
*/
AutoForm.hooks({

  formImageEntry: {

    before: {

      insert: function (doc) {

        // Add location Id to create link to current location
        doc.dsLocId = Locations.findOne().dsLocId;
        doc.generalLocationDs = Locations.findOne().title;

        // Add image meta data
        loadImgDimensions(doc, false, this.result);

      },

      update: function (doc) {

        // Add image meta data
        loadImgDimensions(doc, true, this.result);

      },

    },

    docToForm: function (doc, ss) {

      return doc;

    },

    // Called when any submit operation succeeds
    onSuccess: function (formType, result) {

      if (formType === 'insert') {
        Session.set('adminCurrentImageId', result);
      }

      console.log('New doc:');
      console.log(Images.findOne(Session.get('adminCurrentImageId')));

      // Hide modal
      $('#editModal').modal('hide');
      $('#editModal form')[0].reset();

    },

    // Called when any submit operation fails
    onError: function (formType, error) {

      console.log('Autoform error:', formType, error);

    },

  },

});
<|endoftext|>


<commit_before>(function (window, angular, undefined) {
    'use strict';

    angular
        .module('MainPage')
        .controller('GoodsPage', GoodsPage);

    GoodsPage.$inject = ['auxData', 'goodsSvc'];
    function GoodsPage(auxData, goodsSvc) {
        var vm = this;

        vm.getImgUrl = getImgUrl;

        initController();

        // IMPLEMENTATION

        function initController() {
            vm.list = [];
            vm.currentPage = 1;
            vm.currentItemsPerPage = 24;

            goodsSvc.load()
                .then((goods)=> {
                    vm.list = goods.data;
                });
        }

        function getImgUrl(good) {
            return '/uploads/' + good.urlDir + '/' + good.urlGifLoRes;
        }

    }

})(window, window.angular);
<commit_msg>fix img path<commit_after>(function (window, angular, undefined) {
    'use strict';

    angular
        .module('MainPage')
        .controller('GoodsPage', GoodsPage);

    GoodsPage.$inject = ['auxData', 'goodsSvc'];
    function GoodsPage(auxData, goodsSvc) {
        var vm = this;

        vm.getImgUrl = getImgUrl;

        initController();

        // IMPLEMENTATION

        function initController() {
            vm.list = [];
            vm.currentPage = 1;
            vm.currentItemsPerPage = 24;

            goodsSvc.load()
                .then((goods)=> {
                    vm.list = goods.data;
                });
        }

        function getImgUrl(good) {
            return '/uploads/ready/' + good.urlDir + '/' + good.urlGifLoRes;
        }

    }

})(window, window.angular);
<|endoftext|>


<commit_before>// Includes file dependencies
/* global _ */
define([
    "jquery",
    "backbone",
    "parse",
    "backform",
    "marionette",
    "../helpers/PromiseFailReport",
    "text!../templates/character-long-text-parent.html",
], function (
    $,
    Backbone,
    Parse,
    Backform,
    Marionette,
    PromiseFailReport,
    character_long_text_parent_html
) {

    var EditForm = Marionette.ItemView.extend({
        tagName: 'form',
        template: _.template(""),
        initialize: function (options) {
            var view = this;
            view.character = options.character;

            this.form = new Backform.Form({
                el: this.$el,
                model: view.model,
                fields: [
                    {
                        name: "text",
                        label: options.pretty,
                        control: "textarea",
                        helpMessage: options.description
                    },{
                        name: "preview",
                        label: "Live Preview Changes",
                        control: "checkbox",
                    },{
                        name: "submit",
                        label: "Update",
                        control: "button",
                        id: "submit"
                    }
                ],
                events: {
                    "change": function(e) {
                        e.preventDefault();
                        this.model.errorModel.clear();
                        this.fields.get("submit").set({status: "", message: "", disabled: false});
                        this.$el.enhanceWithin();
                    },
                    "submit": function (e) {
                        var self = this;
                        e.preventDefault();
                        $.mobile.loading("show");
                        self.undelegateEvents();
                        self.model.errorModel.clear();

                        view.character.update_long_text(options.category, self.model.get("text")).then(function () {
                            self.fields.get("submit").set({status: "success", message: "Successfully Updated"});
                            self.$el.enhanceWithin();
                        }, function (error) {
                            self.fields.get("submit").set({status: "error", message: _.escape(error.message)});
                            self.$el.enhanceWithin();
                        }).always(function () {
                            $.mobile.loading("hide");
                            self.delegateEvents();
                        });

                        return false;
                    }
                }
            });
        },

        onRender: function() {
            this.form.render();

            this.$el.enhanceWithin();
            return this;
        }
    });

    var Preview = Marionette.ItemView.extend({
        tagName: 'div',
        template: _.template("
Preview

<%= inputtext %>"),
        templateHelpers: function () {
            var self = this;
            if (self.model.get("preview")) {
                return {
                    inputtext: self.model.get("text")
                };
            } else {
                var lt = self.options.character.get_fetched_long_text(self.options.category)
                if (lt && lt.has("text")) {
                    return {
                        inputtext: lt.get("text")
                    };
                }
                return {
                    inputtext: "",
                }
            }
        },
        initialize: function(options) {
            var self = this;
            self.options = options;
            // Listen to the character and always render when that changes
            self.listenTo(
                self.options.character,
                "change:longtext" + self.options.category,
                self.render);
            // Listen to the option object but only render if live preview is on
            self.listenTo(
                self.model,
                "change:text",
                self.renderIfLive);

            _.bindAll(
                self,
                "renderIfLive",
                "templateHelpers");
        },
        renderIfLive: function() {
            var self = this;
            if (self.model.get("preview")) {
                return self.render();
            }
        },
        onRender: function() {
            this.$el.enhanceWithin();
        }
    });

    var LayoutView = Marionette.LayoutView.extend({
        template: _.template(character_long_text_parent_html),
        regions: {
            top: "#top",
            edit: "#edit",
            preview: "#preview"
        },
        setup_regions: function() {
            var self = this;
            var options = {};

            self.showChildView('edit', new EditForm({
                character: self.character,
                category: self.options.category,
                pretty: self.options.pretty,
                model: self.editingoptions
            }), options);
            self.showChildView('preview', new Preview({
                character: self.character,
                category: self.options.category,
                model: self.editingoptions
            }), options);
        },
        onRender: function() {
            this.setup_regions();
        },
        initialize: function(options) {
            _.bindAll(this, "setup_regions");
        },
        setup: function(character, options) {
            var self = this;
            var options = self.options || {};
            self.character = character;
            self.editingoptions = new Backbone.Model({
                preview: true
            });
            var lt = self.character.get_fetched_long_text(options.category);
            if (lt && lt.has("text")) {
                self.editingoptions.set("text", lt.get("text"));
            }
            self.render();
            return self;
        }
    });

    // Returns the View class
    return LayoutView;

});
<commit_msg>Fix update button to not be available when editing<commit_after>// Includes file dependencies
/* global _ */
define([
    "jquery",
    "backbone",
    "parse",
    "backform",
    "marionette",
    "../helpers/PromiseFailReport",
    "text!../templates/character-long-text-parent.html",
], function (
    $,
    Backbone,
    Parse,
    Backform,
    Marionette,
    PromiseFailReport,
    character_long_text_parent_html
) {

    var EditForm = Marionette.ItemView.extend({
        tagName: 'form',
        template: _.template(""),
        initialize: function (options) {
            var view = this;
            view.character = options.character;

            this.form = new Backform.Form({
                el: this.$el,
                model: view.model,
                fields: [
                    {
                        name: "text",
                        label: options.pretty,
                        control: "textarea",
                        helpMessage: options.description
                    },{
                        name: "preview",
                        label: "Live Preview Changes",
                        control: "checkbox",
                    },{
                        name: "submit",
                        label: "Update",
                        control: "button",
                        disabled: true,
                        id: "submit"
                    }
                ],
                events: {
                    "change": function(e) {
                        e.preventDefault();
                        this.model.errorModel.clear();
                        this.fields.get("submit").set({status: "", message: "", disabled: false});
                        this.$el.enhanceWithin();
                    },
                    "submit": function (e) {
                        var self = this;
                        e.preventDefault();
                        $.mobile.loading("show");
                        self.undelegateEvents();
                        self.model.errorModel.clear();

                        view.character.update_long_text(options.category, self.model.get("text")).then(function () {
                            self.fields.get("submit").set({status: "success", message: "Successfully Updated", disabled: true});
                            self.$el.enhanceWithin();
                        }, function (error) {
                            self.fields.get("submit").set({status: "error", message: _.escape(error.message), disabled: false});
                            self.$el.enhanceWithin();
                        }).always(function () {
                            $.mobile.loading("hide");
                            self.delegateEvents();
                        });

                        return false;
                    }
                }
            });
        },

        onRender: function() {
            this.form.render();

            this.$el.enhanceWithin();
            return this;
        }
    });

    var Preview = Marionette.ItemView.extend({
        tagName: 'div',
        template: _.template("
Preview

<%= inputtext %>"),
        templateHelpers: function () {
            var self = this;
            if (self.model.get("preview")) {
                return {
                    inputtext: self.model.get("text")
                };
            } else {
                var lt = self.options.character.get_fetched_long_text(self.options.category)
                if (lt && lt.has("text")) {
                    return {
                        inputtext: lt.get("text")
                    };
                }
                return {
                    inputtext: "",
                }
            }
        },
        initialize: function(options) {
            var self = this;
            self.options = options;
            // Listen to the character and always render when that changes
            self.listenTo(
                self.options.character,
                "change:longtext" + self.options.category,
                self.render);
            // Listen to the option object but only render if live preview is on
            self.listenTo(
                self.model,
                "change:text",
                self.renderIfLive);

            _.bindAll(
                self,
                "renderIfLive",
                "templateHelpers");
        },
        renderIfLive: function() {
            var self = this;
            if (self.model.get("preview")) {
                return self.render();
            }
        },
        onRender: function() {
            this.$el.enhanceWithin();
        }
    });

    var LayoutView = Marionette.LayoutView.extend({
        template: _.template(character_long_text_parent_html),
        regions: {
            top: "#top",
            edit: "#edit",
            preview: "#preview"
        },
        setup_regions: function() {
            var self = this;
            var options = {};

            self.showChildView('edit', new EditForm({
                character: self.character,
                category: self.options.category,
                pretty: self.options.pretty,
                model: self.editingoptions
            }), options);
            self.showChildView('preview', new Preview({
                character: self.character,
                category: self.options.category,
                model: self.editingoptions
            }), options);
        },
        onRender: function() {
            this.setup_regions();
        },
        initialize: function(options) {
            _.bindAll(this, "setup_regions");
        },
        setup: function(character, options) {
            var self = this;
            var options = self.options || {};
            self.character = character;
            self.editingoptions = new Backbone.Model({
                preview: true
            });
            var lt = self.character.get_fetched_long_text(options.category);
            if (lt && lt.has("text")) {
                self.editingoptions.set("text", lt.get("text"));
            }
            self.render();
            return self;
        }
    });

    // Returns the View class
    return LayoutView;

});
<|endoftext|>