<commit_before>function alertDismissed() {}
function checkConnection() {
  var networkState = navigator.connection.type;
  var states = {};
  states[Connection.UNKNOWN] = 'Desconocida';
  states[Connection.ETHERNET] = 'Ethernet';
  states[Connection.WIFI] = 'WiFi';
  states[Connection.CELL_2G] = 'Teléfono 2G';
  states[Connection.CELL_3G] = 'Teléfono 3G';
  states[Connection.CELL_4G] = 'Teléfono 4G';
  states[Connection.NONE] = 'Sin conexión';
  alert('Conexión de red: ' + states[networkState]);
}
function cargaNoticias() {
  alert ("Estoy aquí");
  $.mobile.loading("show", {
    textVisible: true,
    textonly: true,
    theme:"a",
    html: "cargando datos"
  });
  $.getJSON('http://www.villarrobledo.com/app/listado_noticias.php', function(data) {
    $.each(data.items, function(i,item) {
      $('#noticias').empty().append('
' + item.publicacion + '...

' + item.titulo + '
').trigger("create");
    });
  });
}

/*
function cargaNoticias() {
  $('#noticias').load("http://www.villarrobledo.com/app/listado_noticias.php",function(){
    $(this).trigger('create');
  });
}
*/
function onDeviceReady() {
  //navigator.notification.alert("El dispositivo está listo", alertDismissed(), 'Aviso', 'Cerrar');
  // checkConnection();
  $('#consola').empty().append('
El dispositivo está listo
').trigger("create");
}
function init() {
  document.addEventListener("deviceready", onDeviceReady(), false);
}
<commit_msg>Cruza los dedos nuevamente<commit_after>// Generales
function alertDismissed() {}
function checkConnection() {
  var networkState = navigator.connection.type;
  var states = {};
  states[Connection.UNKNOWN] = 'Desconocida';
  states[Connection.ETHERNET] = 'Ethernet';
  states[Connection.WIFI] = 'WiFi';
  states[Connection.CELL_2G] = 'Teléfono 2G';
  states[Connection.CELL_3G] = 'Teléfono 3G';
  states[Connection.CELL_4G] = 'Teléfono 4G';
  states[Connection.NONE] = 'Sin conexión';
  alert('Conexión de red: ' + states[networkState]);
}

// Al cargar la página de noticias
$(document).on('pagebeforeshow', '#noticias', function() {
  $.ajax({
    url: 'http://www.villarrobledo.com/app/listado_noticias.php',
    type: 'GET',
    dataType: 'json',
    timeout: 25000,
    success: function(data, status) {
      $.each(data, function(i,item) {
        $('#listadonoticias').append('
' + item.publicacion + '
' + item.titulo + '
').trigger("create");
      });
    },
    error: function() {
      alert("Ocurrió un error");
    }
  });
});

// Al cargar Cordova PhoneGap
function onDeviceReady() {
  //navigator.notification.alert("El dispositivo está listo", alertDismissed(), 'Aviso', 'Cerrar');
  // checkConnection();
  $('#consola').empty().append('
El dispositivo está listo
').trigger("create");
}

// Al cargar la aplicación
function init() {
  document.addEventListener("deviceready", onDeviceReady(), false);
}
<|endoftext|>


<commit_before>'use strict';

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

/**
 * IncrementalFont - A namespace.
 */
function IncrementalFont() {
}

/**
 * The IndexedDB version.
 * Increment this number every time there is a change in the schema.
 */
IncrementalFont.version = 1;

/**
 * The the database name.
 */
IncrementalFont.DB_NAME = 'incrfonts';

/**
 * The time in milliseconds to wait before persisting the data.
 */
IncrementalFont.timeoutTime = 1000;

/**
 * The the base name.
 */
IncrementalFont.BASE = 'base';

/**
 * The the base dirty (needs to be persisted) key.
 */
IncrementalFont.BASE_DIRTY = 'base_dirty';

/**
 * The the char list name.
 */
IncrementalFont.CHARLIST = 'charList';

/**
 * The the char list dirty (needs to be persisted) key.
 */
IncrementalFont.CHARLIST_DIRTY = 'charList_dirty';

///**
// * The the persist timeout key.
// */
//IncrementalFont.TIMEOUT_ID = 'timeoutID';

/**
 * Get the incremental font object.
 * This class does the following:
 * 1. Create a class using the "@font-face" rule and with visibility=hidden
 * 2. Create an incremental font manager object.
 * 3. Open the IndexedDB.
 * 4. Start the operation to get the base.
 * 5. Start the operation to get the list of fetched/not-fetched chars.
 * 6. Create a "@font-face" rule (need the data to make the blob URL).
 * 7. When the base is available set the class visibility=visible
 *
 * @param {string} fontname The name of the font.
 * @return {Object} The incremental font object.
 */
IncrementalFont.createManager = function(fontname) {
  var incrFontMgr = new IncrementalFont.obj_(fontname);
  incrFontMgr.getIDB_ = incrFontMgr.openIndexedDB(fontname);

  //console.log('Create a class with visibility: hidden.');
  var style = document.createElement('style');
  //// WebKit hack
  //style.appendChild(document.createTextNode(''));
  document.head.appendChild(style);
  style.sheet.insertRule('.' + fontname +
    ' { font-family: nanum-brush; visibility: hidden; }', 0);

  console.log('Get the base.');
  // Get the base and charList in parallel.
  // Start the operation to get the base.
  incrFontMgr.getBase = incrFontMgr.getData_(IncrementalFont.BASE).
  then(function(data) {
    debugger;
    var base_font = data.base;
    return base_font;
  }).
  catch (function(e) {
    //console.log('Need to fetch the data');
    return IncrementalFontLoader.requestURL('/fonts/' + incrFontMgr.fontname +
      '/base', 'GET', null, {}, 'arraybuffer').
    then(function(xfer_bytes) {
      console.log('fetched the raw base: ' + xfer_bytes.byteLength + ' bytes');
      console.log('need to parseBaseHeader_');
      var base_font_rle = xfer_bytes;
      return base_font_rle;
    }).
    then(function(base_font_rle) {
      console.log('need to RLEDecoder.rleDecode');
      var base_font_pre_sanitize = base_font_rle;
      return base_font_pre_sanitize;
    }).
    then(function(base_font_pre_sanitize) {
      console.log('need to sanitize');
      var base_font = base_font_pre_sanitize;
      return base_font;
    }).
    then(function(base_font) {
      console.log('for debug: get some ttf font data so we can test saving' +
        '  data');
      return IncrementalFontLoader.requestURL(
        '../fonts/nanum-brush/NanumBrushScript-Regular.ttf',
        'GET', null, {}, 'arraybuffer').
      then(function(base_font) {
        console.log('fetched the ttf: ' + base_font.byteLength + ' bytes');
        return base_font;
      })
    }).
    then(function(base_font) {
//      debugger;
      console.log('persist the base: ' + base_font.byteLength + ' bytes');
      incrFontMgr.persistDelayed_(IncrementalFont.BASE);
      return base_font;
    }).
    then(function(base_font) {
      //console.log('Set the @font-face');
      IncrementalFont.obj_.setFont_(fontname, base_font,
        'application/x-font-ttf');
      //console.log('make the class visible');
      // style.sheet.rules.length
      style.sheet.deleteRule(0);
      style.sheet.insertRule('.' + fontname +
        ' { font-family: nanum-brush; visibility: visible; }', 0);
      return base_font;
    });
  });
// For debug just do one persist operation.
//  // Start the operation to get the list of already fetched chars.
//  //console.log('Get the list of already fetched chars.');
//  incrFontMgr.getCharList = incrFontMgr.getData_(IncrementalFont.CHARLIST).
//  then(function(data) {
//    debugger;
//    return data;
//  }).
//  catch (function(e) {
//    console.log('no charList');
//    return {};
//  }).
//  then(function(data) {
//    return data;
//  });

  // For Debug: add a button to clear the IndexedDB.
  IncrementalFont.addDropDbButton_(incrFontMgr, fontname);

  return incrFontMgr;
};

/**
 * Add a "drop DB" button.
 * @private
 */
IncrementalFont.addDropDbButton_ = function(incrFontMgr, fontname) {
  window.onload = function() {
    var span = document.createElement('span');
    span.style.position = 'absolute';
    span.style.top = '10px';
    span.style.right = '10px';
    var button = document.createElement('button');
    button.onclick = dropDB;
    var label = document.createTextNode('drop DB');
    button.appendChild(label);
    span.appendChild(button);
    var br = document.createElement('br');
    span.appendChild(br);
    var msg_span = document.createElement('span');
    msg_span.id = 'dropDB_msg';
    span.appendChild(msg_span);
    document.body.appendChild(span);
  };
  function dropDB() {
    var msg_span = document.getElementById('dropDB_msg');
    IncrementalFont.dropDB(incrFontMgr, fontname).
    then(function() {
      msg_span.innerHTML = 'dropped DB';
    }).
    catch (function(msg) {
      msg_span.innerHTML = msg;
    });
  }

};

/**
 * Drop the IndexedDB database.
 * @return {Promise} The Promise for when the DB is dropped.
 */
IncrementalFont.dropDB = function(incrFontMgr, fontname) {
  var db_name = IncrementalFont.DB_NAME + '/' + fontname;
  return incrFontMgr.getIDB_
  .then(function(db) {
    db.close();
    return new Promise(function(resolve, reject) {
      console.log('drop ' + db_name);
      var request = indexedDB.deleteDatabase(db_name);
      request.onsuccess = function(e) {
        resolve();
      };
      request.onblocked = function() {
        console.log("deleteDatbase got blocked event");
      };
      request.onerror = function(e) {
        debugger;
        reject(e);
      };
    })
  }).
  then(function() {
    return 'dropped ' + db_name;
  }).
  catch (function(e) {
    console.log('dropDB ' + db_name + ': ' + e.message);
    debugger;
    return 'dropDB ' + db_name + ': ' + e.message;
  });
};

/**
 * IncrFontIDB.obj_ - A class to handle interacting the IndexedDB.
 * @param {string} fontname The name of the font.
 * @constructor
 * @private
 */
IncrementalFont.obj_ = function(fontname) {
  this.fontname = fontname;
  this.charsURL = '/incremental_fonts/request';
  this.persistInfo = {};
  this.persistInfo[IncrementalFont.BASE_DIRTY] = false;
  this.persistInfo[IncrementalFont.CHARLIST_DIRTY] = false;

  // Promises
  this.getIDB_ = null;
  this.getBase = null;
  this.getCharList = null;
  this.finishPersistingData = Promise.resolve();
};

/**
 * Save data that needs to be persisted.
 * @param {string} name The name of the data item.
 * @private
 */
IncrementalFont.obj_.prototype.persistDelayed_ = function(name) {
  var that = this;
  //console.log('persist ' + name);

  // Note what needs to be persisted.
  if (name == IncrementalFont.BASE) {
    this.persistInfo[IncrementalFont.BASE_DIRTY] = true;
  } else if (name == IncrementalFont.CHARLIST) {
    this.persistInfo[IncrementalFont.CHARLIST_DIRTY] = true;
  }

  // Wait for any pending persist operation to finish.
  this.finishPersistingData.then(function() {
    // Previous persists may have already saved the data so see if there is
    // anything still to persist.
//    debugger;
    var base_dirty = that.persistInfo[IncrementalFont.BASE_DIRTY];
    var charList_dirty = that.persistInfo[IncrementalFont.CHARLIST_DIRTY];
    if (!base_dirty && !charList_dirty) {
      return;
    }

    // What ever got in upto this point will get saved.
    that.persistInfo[IncrementalFont.BASE_DIRTY] = false;
    that.persistInfo[IncrementalFont.CHARLIST_DIRTY] = false;

    // Wait a bit before persisting.
    that.finishPersistingData = new Promise(function(resolve, reject) {
      setTimeout(function() {
        //console.log('persist timeout');
        resolve();
      }, IncrementalFont.timeoutTime);
    }).
    then(function() {
//      debugger;
      if (base_dirty) {
        return that.getBase.
        then(function(base) {
//          debugger;
          return that.saveData_(IncrementalFont.BASE, base);
        });
      }
    }).
    then(function() {
      if (charList_dirty) {
        return that.getCharList().
        then(function(charList) {
          return that.saveData_(IncrementalFont.CHARLIST, charList);
        });
      }
    }).
    catch (function(e) {
      console.log('persistDelayed_: ' + e.message);
      debugger;
    }).
    then(function() {
      //console.log('persisted ' + name);
    });
  });
};

/**
 * Save a data item.
 * @param {string} name The name of the item.
 * @param {Array} data The data.
 * @return {Promise} Operation completion.
 * @private
 */
IncrementalFont.obj_.prototype.saveData_ = function(name, data) {
  var that = this;
  //console.log('save ' + name);
  return that.getIDB_.
  then(function(db) {
    // the initialization form x = { varname: value } handles the key is a literal
    // string. If a variable varname is used for the key then the string varname
    // will be used ... NOT the value of the varname.
    return new Promise(function(resolve, reject) {
      debugger;
      var value = {};
      value[name] = data;
//      value['id'] = 0;
      var trans = db.transaction([name], 'readwrite');
      var store = trans.objectStore(name);
      var request = store.put(value, 0);
      request.onsuccess = function(e) {
        debugger;
        resolve();
      };
      request.onerror = function(e) {
        debugger;
        reject();
      };
    }).
    catch (function(e) {
      console.log('saveData ' + name + ': ' + e.message);
      debugger;
    }).
    then(function() {
//      debugger;
    });
  });
};

/**
 * Add the "@font-face" rule
 * @param {string} fontname The CSS fontname
 * @param {Array} data The font data.
 * @param {string} mime_type The mime type of the font.
 * @private
 */
IncrementalFont.obj_.setFont_ = function(fontname, data, mime_type) {
  var blob = new Blob([data], { type: mime_type });
  var blobUrl = window.URL.createObjectURL(blob);
  //console.log('fontname = ' + fontname);
  var font = new FontFace(fontname, 'url(' + blobUrl + ')', {});
  document.fonts.add(font);
  font.load();
};

/**
 * Get the fontDB.
 * @param {string} fontname The name of the font.
 * @return {Promise} The font DB.
 */
IncrementalFont.obj_.prototype.openIndexedDB = function(fontname) {
  var that = this;

  var openIDB = new Promise(function(resolve, reject) {
    var db_name = IncrementalFont.DB_NAME + '/' + fontname;
    var dbOpen = indexedDB.open(db_name, IncrementalFont.version);

    dbOpen.onsuccess = function(e) {
      var db = e.target.result;
      console.log('open db "' + db_name + '"');
      resolve(db);
    };
    dbOpen.onerror = function(e) {
      console.log('!!! IncrFontIDB.obj_ "' + db_name + '": ' + e.value);
      debugger;
      reject(e);
    };

    // Will get called when the version changes.
    dbOpen.onupgradeneeded = function(e) {
      var db = e.target.result;
      //console.log('onupgradeneeded');
      e.target.transaction.onerror = function(e) {
        console.log('!!! onupgradeneeded: ' + e.value);
        debugger;
        reject(e);
      };
      //console.log('before deletes');
      if (db.objectStoreNames.contains(IncrementalFont.BASE)) {
        console.log('onupgradeneeded base');
        db.deleteObjectStore(IncrementalFont.BASE);
      }
      if (db.objectStoreNames.contains(IncrementalFont.CHARLIST)) {
        console.log('onupgradeneeded charList');
        db.deleteObjectStore(IncrementalFont.CHARLIST);
      }
      //console.log('before creates');
      var store = db.createObjectStore(IncrementalFont.BASE,
        { keypath: 'id' });
      var store = db.createObjectStore(IncrementalFont.CHARLIST,
        { keypath: 'id' });
      //console.log('after create');
    };
  }).then(function(db) {
    // TODO(bstell) timing call
    return db;
  });
  return openIDB;
};

/**
 * Get a part of the font.
 * @param {string} name The name of the font data to get.
 * @return {Promise} Promise to return the data.
 * @private
 */
IncrementalFont.obj_.prototype.getData_ = function(name) {
  var that = this;
  //console.log('getData_');
  var getData = new Promise(function(resolve, reject) {
    //console.log('create transaction');
    that.getIDB_.then(function(db) {
//      try {
        var trans = db.transaction([name], 'readwrite');
        var store = trans.objectStore(name);
        var request = store.get(0);
//      } catch (e) {
//        console.log('e = ' + e.message);
//        debugger;
//        throw e;
//      }

      request.onsuccess = function(e) {
        var result = e.target.result;
        console.log('cursor onsuccess: result = ' + result);
        if (result != undefined) {
          resolve(result);
        } else {
          reject(e);
        }
        return; // I think this is unnecessary.
      };

      console.log('define cursor onerror');
      request.onerror = function(e) {
        console.log('result = ' + result.value);
        debugger;
        reject(e);
      };
      console.log('after define cursor onerror');
    });
  });
  return getData;
};

<commit_msg>CHeckpoint: Call any preexisting window.onload function. Add timing calls. Minor cleanup.<commit_after>'use strict';

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

/**
 * IncrementalFont - A namespace.
 */
function IncrementalFont() {
}

/**
 * The IndexedDB version.
 * Increment this number every time there is a change in the schema.
 */
IncrementalFont.version = 1;

/**
 * The the database name.
 */
IncrementalFont.DB_NAME = 'incrfonts';

/**
 * The time in milliseconds to wait before persisting the data.
 */
IncrementalFont.timeoutTime = 1000;

/**
 * The the base name.
 */
IncrementalFont.BASE = 'base';

/**
 * The the base dirty (needs to be persisted) key.
 */
IncrementalFont.BASE_DIRTY = 'base_dirty';

/**
 * The the char list name.
 */
IncrementalFont.CHARLIST = 'charList';

/**
 * The the char list dirty (needs to be persisted) key.
 */
IncrementalFont.CHARLIST_DIRTY = 'charList_dirty';

///**
// * The the persist timeout key.
// */
//IncrementalFont.TIMEOUT_ID = 'timeoutID';

/**
 * Get the incremental font object.
 * This class does the following:
 * 1. Create a class using the "@font-face" rule and with visibility=hidden
 * 2. Create an incremental font manager object.
 * 3. Open the IndexedDB.
 * 4. Start the operation to get the base.
 * 5. Start the operation to get the list of fetched/not-fetched chars.
 * 6. Create a "@font-face" rule (need the data to make the blob URL).
 * 7. When the base is available set the class visibility=visible
 *
 * @param {string} fontname The name of the font.
 * @return {Object} The incremental font object.
 */
IncrementalFont.createManager = function(fontname) {
  var incrFontMgr = new IncrementalFont.obj_(fontname);
  timer.start('openIndexedDB.open ' + fontname);
  incrFontMgr.getIDB_ = incrFontMgr.openIndexedDB(fontname);
  timer.end('openIndexedDB.open ' + fontname);

  //console.log('Create a class with visibility: hidden.');
  var style = document.createElement('style');
  //// WebKit hack
  //style.appendChild(document.createTextNode(''));
  document.head.appendChild(style);
  style.sheet.insertRule('.' + fontname +
    ' { font-family: nanum-brush; visibility: hidden; }', 0);

  console.log('Get the base.');
  // Get the base and charList in parallel.
  // Start the operation to get the base.
  timer.start('get the base data ' + fontname);
  timer.start('did not get the base data ' + fontname);
  incrFontMgr.getBase = incrFontMgr.getData_(IncrementalFont.BASE).
  then(function(data) {
    timer.end('get the base data ' + fontname);
    var base_font = data.base;
    return base_font;
  }).
  catch (function(e) {
    timer.end('did not get the base data ' + fontname);
    //console.log('Need to fetch the data');
    return IncrementalFontLoader.requestURL('/fonts/' + incrFontMgr.fontname +
      '/base', 'GET', null, {}, 'arraybuffer').
    then(function(xfer_bytes) {
      console.log('fetched the raw base: ' + xfer_bytes.byteLength + ' bytes');
      console.log('need to parseBaseHeader_');
      var base_font_rle = xfer_bytes;
      return base_font_rle;
    }).
    then(function(base_font_rle) {
      console.log('need to RLEDecoder.rleDecode');
      var base_font_pre_sanitize = base_font_rle;
      return base_font_pre_sanitize;
    }).
    then(function(base_font_pre_sanitize) {
      console.log('need to sanitize');
      var base_font = base_font_pre_sanitize;
      return base_font;
    }).
    then(function(base_font) {
      console.log('for debug: get some ttf font data so we can test saving' +
        '  data');
      return IncrementalFontLoader.requestURL(
        '../fonts/nanum-brush/NanumBrushScript-Regular.ttf',
        'GET', null, {}, 'arraybuffer').
      then(function(base_font) {
        console.log('fetched the ttf: ' + base_font.byteLength + ' bytes');
        return base_font;
      })
    }).
    then(function(base_font) {
//      debugger;
      console.log('persist the base: ' + base_font.byteLength + ' bytes');
      incrFontMgr.persistDelayed_(IncrementalFont.BASE);
      return base_font;
    }).
    then(function(base_font) {
      //console.log('Set the @font-face');
      IncrementalFont.obj_.setFont_(fontname, base_font,
        'application/x-font-ttf');
      //console.log('make the class visible');
      // style.sheet.rules.length
      style.sheet.deleteRule(0);
      style.sheet.insertRule('.' + fontname +
        ' { font-family: nanum-brush; visibility: visible; }', 0);
      return base_font;
    });
  });
// For debug just do one persist operation.
//  // Start the operation to get the list of already fetched chars.
//  //console.log('Get the list of already fetched chars.');
//  incrFontMgr.getCharList = incrFontMgr.getData_(IncrementalFont.CHARLIST).
//  then(function(data) {
//    debugger;
//    return data;
//  }).
//  catch (function(e) {
//    console.log('no charList');
//    return {};
//  }).
//  then(function(data) {
//    return data;
//  });

  // For Debug: add a button to clear the IndexedDB.
  IncrementalFont.addDropDbButton_(incrFontMgr, fontname);

  return incrFontMgr;
};

/**
 * Add a "drop DB" button.
 * @private
 */
IncrementalFont.addDropDbButton_ = function(incrFontMgr, fontname) {
  var old_onload = window.onload;
  window.onload = function() {
    var span = document.createElement('span');
    span.style.position = 'absolute';
    span.style.top = '10px';
    span.style.right = '10px';
    var button = document.createElement('button');
    button.onclick = dropDB;
    var label = document.createTextNode('drop DB');
    button.appendChild(label);
    span.appendChild(button);
    var br = document.createElement('br');
    span.appendChild(br);
    var msg_span = document.createElement('span');
    msg_span.id = 'dropDB_msg';
    span.appendChild(msg_span);
    document.body.appendChild(span);
    if (old_onload) {
      old_onload(window);
    }
  };
  function dropDB() {
    var msg_span = document.getElementById('dropDB_msg');
    IncrementalFont.dropDB(incrFontMgr, fontname).
    then(function() {
      msg_span.innerHTML = 'dropped DB';
    }).
    catch (function(msg) {
      msg_span.innerHTML = msg;
    });
  }

};

/**
 * Drop the IndexedDB database.
 * @return {Promise} The Promise for when the DB is dropped.
 */
IncrementalFont.dropDB = function(incrFontMgr, fontname) {
  var db_name = IncrementalFont.DB_NAME + '/' + fontname;
  return incrFontMgr.getIDB_
  .then(function(db) {
    db.close();
    return new Promise(function(resolve, reject) {
      console.log('drop ' + db_name);
      var request = indexedDB.deleteDatabase(db_name);
      request.onsuccess = function(e) {
        resolve();
      };
      request.onblocked = function() {
        console.log("deleteDatbase got blocked event");
      };
      request.onerror = function(e) {
        debugger;
        reject(e);
      };
    })
  }).
  then(function() {
    return 'dropped ' + db_name;
  }).
  catch (function(e) {
    console.log('dropDB ' + db_name + ': ' + e.message);
    debugger;
    return 'dropDB ' + db_name + ': ' + e.message;
  });
};

/**
 * IncrFontIDB.obj_ - A class to handle interacting the IndexedDB.
 * @param {string} fontname The name of the font.
 * @constructor
 * @private
 */
IncrementalFont.obj_ = function(fontname) {
  this.fontname = fontname;
  this.charsURL = '/incremental_fonts/request';
  this.persistInfo = {};
  this.persistInfo[IncrementalFont.BASE_DIRTY] = false;
  this.persistInfo[IncrementalFont.CHARLIST_DIRTY] = false;

  // Promises
  this.getIDB_ = null;
  this.getBase = null;
  this.getCharList = null;
  this.finishPersistingData = Promise.resolve();
};

/**
 * Save data that needs to be persisted.
 * @param {string} name The name of the data item.
 * @private
 */
IncrementalFont.obj_.prototype.persistDelayed_ = function(name) {
  var that = this;
  //console.log('persist ' + name);

  // Note what needs to be persisted.
  if (name == IncrementalFont.BASE) {
    this.persistInfo[IncrementalFont.BASE_DIRTY] = true;
  } else if (name == IncrementalFont.CHARLIST) {
    this.persistInfo[IncrementalFont.CHARLIST_DIRTY] = true;
  }

  // Wait for any pending persist operation to finish.
  this.finishPersistingData.then(function() {
    // Previous persists may have already saved the data so see if there is
    // anything still to persist.
//    debugger;
    var base_dirty = that.persistInfo[IncrementalFont.BASE_DIRTY];
    var charList_dirty = that.persistInfo[IncrementalFont.CHARLIST_DIRTY];
    if (!base_dirty && !charList_dirty) {
      return;
    }

    // What ever got in upto this point will get saved.
    that.persistInfo[IncrementalFont.BASE_DIRTY] = false;
    that.persistInfo[IncrementalFont.CHARLIST_DIRTY] = false;

    // Wait a bit before persisting.
    that.finishPersistingData = new Promise(function(resolve, reject) {
      setTimeout(function() {
        //console.log('persist timeout');
        resolve();
      }, IncrementalFont.timeoutTime);
    }).
    then(function() {
//      debugger;
      if (base_dirty) {
        return that.getBase.
        then(function(base) {
//          debugger;
          return that.saveData_(IncrementalFont.BASE, base);
        });
      }
    }).
    then(function() {
      if (charList_dirty) {
        return that.getCharList().
        then(function(charList) {
          return that.saveData_(IncrementalFont.CHARLIST, charList);
        });
      }
    }).
    catch (function(e) {
      console.log('persistDelayed_: ' + e.message);
      debugger;
    }).
    then(function() {
      //console.log('persisted ' + name);
    });
  });
};

/**
 * Save a data item.
 * @param {string} name The name of the item.
 * @param {Array} data The data.
 * @return {Promise} Operation completion.
 * @private
 */
IncrementalFont.obj_.prototype.saveData_ = function(name, data) {
  var that = this;
  //console.log('save ' + name);
  return that.getIDB_.
  then(function(db) {
    // the initialization form x = { varname: value } handles the key is a literal
    // string. If a variable varname is used for the key then the string varname
    // will be used ... NOT the value of the varname.
    return new Promise(function(resolve, reject) {
      var value = {};
      value[name] = data;
      var trans = db.transaction([name], 'readwrite');
      var store = trans.objectStore(name);
      var request = store.put(value, 0);
      request.onsuccess = function(e) {
        resolve();
      };
      request.onerror = function(e) {
        debugger;
        reject();
      };
    }).
    catch (function(e) {
      console.log('saveData ' + name + ': ' + e.message);
      debugger;
    });
  });
};

/**
 * Add the "@font-face" rule
 * @param {string} fontname The CSS fontname
 * @param {Array} data The font data.
 * @param {string} mime_type The mime type of the font.
 * @private
 */
IncrementalFont.obj_.setFont_ = function(fontname, data, mime_type) {
  var blob = new Blob([data], { type: mime_type });
  var blobUrl = window.URL.createObjectURL(blob);
  //console.log('fontname = ' + fontname);
  var font = new FontFace(fontname, 'url(' + blobUrl + ')', {});
  document.fonts.add(font);
  font.load();
};

/**
 * Get the fontDB.
 * @param {string} fontname The name of the font.
 * @return {Promise} The font DB.
 */
IncrementalFont.obj_.prototype.openIndexedDB = function(fontname) {
  var that = this;

  var openIDB = new Promise(function(resolve, reject) {
    var db_name = IncrementalFont.DB_NAME + '/' + fontname;
    timer.start('indexedDB.open ' + db_name);
    var dbOpen = indexedDB.open(db_name, IncrementalFont.version);
    timer.end('indexedDB.open ' + db_name);

    dbOpen.onsuccess = function(e) {
      var db = e.target.result;
      console.log('open db "' + db_name + '"');
      resolve(db);
    };
    dbOpen.onerror = function(e) {
      console.log('!!! IncrFontIDB.obj_ "' + db_name + '": ' + e.value);
      debugger;
      reject(e);
    };

    // Will get called when the version changes.
    dbOpen.onupgradeneeded = function(e) {
      var db = e.target.result;
      //console.log('onupgradeneeded');
      e.target.transaction.onerror = function(e) {
        console.log('!!! onupgradeneeded: ' + e.value);
        debugger;
        reject(e);
      };
      //console.log('before deletes');
      if (db.objectStoreNames.contains(IncrementalFont.BASE)) {
        console.log('onupgradeneeded base');
        db.deleteObjectStore(IncrementalFont.BASE);
      }
      if (db.objectStoreNames.contains(IncrementalFont.CHARLIST)) {
        console.log('onupgradeneeded charList');
        db.deleteObjectStore(IncrementalFont.CHARLIST);
      }
      //console.log('before creates');
      var store = db.createObjectStore(IncrementalFont.BASE,
        { keypath: 'id' });
      var store = db.createObjectStore(IncrementalFont.CHARLIST,
        { keypath: 'id' });
      //console.log('after create');
    };
  }).then(function(db) {
    // TODO(bstell) timing call
    return db;
  });
  return openIDB;
};

/**
 * Get a part of the font.
 * @param {string} name The name of the font data to get.
 * @return {Promise} Promise to return the data.
 * @private
 */
IncrementalFont.obj_.prototype.getData_ = function(name) {
  var that = this;
  //console.log('getData_');
  var getData = new Promise(function(resolve, reject) {
    //console.log('create transaction');
    that.getIDB_.then(function(db) {
//      try {
        var trans = db.transaction([name], 'readwrite');
        var store = trans.objectStore(name);
        var request = store.get(0);
//      } catch (e) {
//        console.log('e = ' + e.message);
//        debugger;
//        throw e;
//      }

      request.onsuccess = function(e) {
        var result = e.target.result;
        console.log('cursor onsuccess: result = ' + result);
        if (result != undefined) {
          resolve(result);
        } else {
          reject(e);
        }
        return; // I think this is unnecessary.
      };

      console.log('define cursor onerror');
      request.onerror = function(e) {
        console.log('result = ' + result.value);
        debugger;
        reject(e);
      };
      console.log('after define cursor onerror');
    });
  });
  return getData;
};

<|endoftext|>


<commit_before>dc.ui.TimelineDialog = dc.ui.Dialog.extend({

  GRAPH_OPTIONS : {
    xaxis     : {mode : 'time', minTickSize: [1, "day"]},
    yaxis     : {ticks: [], min: -0.5},
    selection : {mode : 'x', color: '#09f'},
    legend    : {show : false},
    series    : {lines : {show : false}, points : {show : true}},
    grid      : {backgroundColor: '#222', borderColor: '#444', tickColor: '#282828', borderWidth: 1, hoverable : true, clickable : true}
  },

  ROW_HEIGHT : 50,
  MIN_HEIGHT : 100,

  DATE_FORMAT : "%b %d, %y",

  POINT_COLOR : '#777',

  id : 'timeline_dialog',

  callbacks : {
    '.zoom_out.click':              '_zoomOut',
    '.ok.click':                    'confirm',
    '.timeline_plot.plothover':     '_showTooltop',
    '.timeline_plot.plotselected':  '_zoomIn',
    '.timeline_plot.plotclick':     '_openPage'
  },

  constructor : function(documents) {
    this.documents = documents;
    this.base({
      mode        : 'custom',
      title       : this.displayTitle(),
      information : 'Drag a range of dates to zoom in.'
    });
    dc.ui.spinner.show();
    this._loadDates();
  },

  render : function() {
    this.base();
    $('.custom', this.el).html(JST['document/timeline']({docs : this.documents, minHeight : this.MIN_HEIGHT, rowHeight : this.ROW_HEIGHT}));
    this._zoomButton = $.el('div', {'class' : 'minibutton zoom_out dark not_enabled'}, 'Zoom Out');
    $('.controls_inner', this.el).prepend(this._zoomButton);
    this.setCallbacks();
    this.center();
    return this;
  },

  displayTitle : function() {
    if (this.documents.length == 1) return 'Timeline for "' + Inflector.truncate(this.documents[0].get('title'), 55) + '"';
    return "Timeline for " + this.documents.length + " Documents";
  },

  // Redraw the Flot Plot.
  drawPlot : function() {
    $.plot($('.timeline_plot', this.el), this._data, this._options);
  },

  _loadDates : function() {
    var dates = _.pluck(this.documents, 'id');
    $.getJSON('/documents/dates', {'ids[]' : dates}, _.bind(this._plotDates, this));
  },

  // Chart the dates for the selected documents.
  _plotDates : function(resp) {
    dc.ui.spinner.hide();
    if (resp.dates.length == 0) return this._noDates();
    this.render();
    var color = this.POINT_COLOR;
    var series = {}, styles = {}, ids = this._dateIds = {};
    _.each(this.documents, function(doc, i) {
      series[doc.id]   = [];
      styles[doc.id]   = {pos : i, color : color};
    });
    _.each(resp.dates, function(json) {
      var docId = json.document_id;
      var date  = json.date * 1000;
      ids[date] = json.id;
      series[docId].push([date, styles[docId].pos]);
    });
    this._data = _.map(series, function(val, key) {
      return {data : val, color : styles[key].color, docId : parseInt(key, 10)};
    });
    this._options = _.clone(this.GRAPH_OPTIONS);
    this._options.xaxis.min   = null;
    this._options.xaxis.max   = null;
    this._options.yaxis.max   = this.documents.length - 0.5;
    this._options.yaxis.ticks = _.map(this.documents, function(doc){
      return [styles[doc.id].pos, Inflector.truncate(doc.get('title'), 30)];
    });
    this.drawPlot();
  },

  // Create a tooltip to show a hovered date.
  _showTooltop : function(e, pos, item) {
    if (this._request) return;
    if (!item) return dc.ui.tooltip.hide();
    var docId = item.series.docId;
    var id    = this._dateIds[item.datapoint[0]];
    var model = EntityDates.get(id);
    if (model) return this._renderTooltip(model, pos);
    this._request = $.getJSON('/documents/dates', {id : id}, _.bind(function(resp) {
      delete this._request;
      if (!resp) return;
      var model   = new dc.model.Entity(resp.date);
      EntityDates.add(model);
      this._renderTooltip(model, pos);
    }, this));
  },

  _renderTooltip : function(date, pos) {
    var title   = Inflector.truncate(Documents.get(date.get('document_id')).get('title'), 50);
    var excerpt = date.get('excerpts')[0];
    dc.ui.tooltip.show({
      left  : pos.pageX,
      top   : pos.pageY,
      title : title,
      text  : 'p.' + excerpt.page_number + ' ' + Inflector.trimExcerpt(excerpt.excerpt)
    });
  },

  // Allow clicking on date ranges to jump to the page containing the date
  // in the document.
  _openPage : function(e, pos, item) {
    if (!item) return;
    var unixTime = item.datapoint[0] / 1000;
    var doc = Documents.get(item.series.docId);
    window.open(doc.url() + "?date=" + unixTime);
  },

  // Allow selection of date ranges to zoom in.
  _zoomIn : function(e, ranges) {
    $(this._zoomButton).setMode('is', 'enabled');
    this._options.xaxis.min = ranges.xaxis.from;
    this._options.xaxis.max = ranges.xaxis.to;
    this.drawPlot();
  },

  // Zoom back out to see the entire timeline.
  _zoomOut : function() {
    $(this._zoomButton).setMode('not', 'enabled');
    this._options.xaxis.min = null;
    this._options.xaxis.max = null;
    this.drawPlot();
  },

  // Close, with an error, when no dates are found.
  _noDates : function() {
    var count = this.documents.length;
    this.close();
    var message = "None of the " + count + " documents contained recognizable dates.";
    if (count <= 1) message = '"' + this.documents[0].get('title') + '" does not contain any recognizable dates.';
    dc.ui.Dialog.alert(message);
  }

});<commit_msg>discriminating dateIds based on documentId.<commit_after>dc.ui.TimelineDialog = dc.ui.Dialog.extend({

  GRAPH_OPTIONS : {
    xaxis     : {mode : 'time', minTickSize: [1, "day"]},
    yaxis     : {ticks: [], min: -0.5},
    selection : {mode : 'x', color: '#09f'},
    legend    : {show : false},
    series    : {lines : {show : false}, points : {show : true}},
    grid      : {backgroundColor: '#222', borderColor: '#444', tickColor: '#282828', borderWidth: 1, hoverable : true, clickable : true}
  },

  ROW_HEIGHT : 50,
  MIN_HEIGHT : 100,

  DATE_FORMAT : "%b %d, %y",

  POINT_COLOR : '#777',

  id : 'timeline_dialog',

  callbacks : {
    '.zoom_out.click':              '_zoomOut',
    '.ok.click':                    'confirm',
    '.timeline_plot.plothover':     '_showTooltop',
    '.timeline_plot.plotselected':  '_zoomIn',
    '.timeline_plot.plotclick':     '_openPage'
  },

  constructor : function(documents) {
    this.documents = documents;
    this.base({
      mode        : 'custom',
      title       : this.displayTitle(),
      information : 'Drag a range of dates to zoom in.'
    });
    dc.ui.spinner.show();
    this._loadDates();
  },

  render : function() {
    this.base();
    $('.custom', this.el).html(JST['document/timeline']({docs : this.documents, minHeight : this.MIN_HEIGHT, rowHeight : this.ROW_HEIGHT}));
    this._zoomButton = $.el('div', {'class' : 'minibutton zoom_out dark not_enabled'}, 'Zoom Out');
    $('.controls_inner', this.el).prepend(this._zoomButton);
    this.setCallbacks();
    this.center();
    return this;
  },

  displayTitle : function() {
    if (this.documents.length == 1) return 'Timeline for "' + Inflector.truncate(this.documents[0].get('title'), 55) + '"';
    return "Timeline for " + this.documents.length + " Documents";
  },

  // Redraw the Flot Plot.
  drawPlot : function() {
    $.plot($('.timeline_plot', this.el), this._data, this._options);
  },

  _loadDates : function() {
    var dates = _.pluck(this.documents, 'id');
    $.getJSON('/documents/dates', {'ids[]' : dates}, _.bind(this._plotDates, this));
  },

  // Chart the dates for the selected documents.
  _plotDates : function(resp) {
    dc.ui.spinner.hide();
    if (resp.dates.length == 0) return this._noDates();
    this.render();
    var color = this.POINT_COLOR;
    var series = {}, styles = {}, ids = this._dateIds = {};
    _.each(this.documents, function(doc, i) {
      ids[doc.id]      = {};
      series[doc.id]   = [];
      styles[doc.id]   = {pos : i, color : color};
    });
    _.each(resp.dates, function(json) {
      var docId         = json.document_id;
      var date          = json.date * 1000;
      ids[docId][date]  = json.id;
      series[docId].push([date, styles[docId].pos]);
    });
    this._data = _.map(series, function(val, key) {
      return {data : val, color : styles[key].color, docId : parseInt(key, 10)};
    });
    this._options = _.clone(this.GRAPH_OPTIONS);
    this._options.xaxis.min   = null;
    this._options.xaxis.max   = null;
    this._options.yaxis.max   = this.documents.length - 0.5;
    this._options.yaxis.ticks = _.map(this.documents, function(doc){
      return [styles[doc.id].pos, Inflector.truncate(doc.get('title'), 30)];
    });
    this.drawPlot();
  },

  // Create a tooltip to show a hovered date.
  _showTooltop : function(e, pos, item) {
    if (this._request) return;
    if (!item) return dc.ui.tooltip.hide();
    var docId = item.series.docId;
    var id    = this._dateIds[docId][item.datapoint[0]];
    var model = EntityDates.get(id);
    if (model) return this._renderTooltip(model, pos);
    this._request = $.getJSON('/documents/dates', {id : id}, _.bind(function(resp) {
      delete this._request;
      if (!resp) return;
      var model   = new dc.model.Entity(resp.date);
      EntityDates.add(model);
      this._renderTooltip(model, pos);
    }, this));
  },

  _renderTooltip : function(date, pos) {
    var title   = Inflector.truncate(Documents.get(date.get('document_id')).get('title'), 50);
    var excerpt = date.get('excerpts')[0];
    dc.ui.tooltip.show({
      left  : pos.pageX,
      top   : pos.pageY,
      title : title,
      text  : 'p.' + excerpt.page_number + ' ' + Inflector.trimExcerpt(excerpt.excerpt)
    });
  },

  // Allow clicking on date ranges to jump to the page containing the date
  // in the document.
  _openPage : function(e, pos, item) {
    if (!item) return;
    var unixTime = item.datapoint[0] / 1000;
    var doc = Documents.get(item.series.docId);
    window.open(doc.url() + "?date=" + unixTime);
  },

  // Allow selection of date ranges to zoom in.
  _zoomIn : function(e, ranges) {
    $(this._zoomButton).setMode('is', 'enabled');
    this._options.xaxis.min = ranges.xaxis.from;
    this._options.xaxis.max = ranges.xaxis.to;
    this.drawPlot();
  },

  // Zoom back out to see the entire timeline.
  _zoomOut : function() {
    $(this._zoomButton).setMode('not', 'enabled');
    this._options.xaxis.min = null;
    this._options.xaxis.max = null;
    this.drawPlot();
  },

  // Close, with an error, when no dates are found.
  _noDates : function() {
    var count = this.documents.length;
    this.close();
    var message = "None of the " + count + " documents contained recognizable dates.";
    if (count <= 1) message = '"' + this.documents[0].get('title') + '" does not contain any recognizable dates.';
    dc.ui.Dialog.alert(message);
  }

});<|endoftext|>


<commit_before>var app = require('app');
var BrowserWindow = require('browser-window');
var ipc = require('ipc');
var fs = require('fs');

require('crash-reporter').start();

var mainWindow = null;

app.on('window-all-closed', function() {
  //TODO: exit when computer restart, to see what node service should do when system down?
  //app.quit();
});

app.on('ready', function() {
  mainWindow = new BrowserWindow({
	width: 1366,
	height: 768,
	show: false,
	frame: false,
	'node-integration': false,
	preload: __dirname + '/preload.js'
  });

  mainWindow.loadUrl('file://' + __dirname + '/index.html');

  //mainWindow.openDevTools();

  mainWindow.on('closed', function() {
    mainWindow = null;
  });
});

ipc.on('WriteFile', function(event, args){
  console.log(args[0]);
  console.log(args[1].toDataUrl());
  /*fs.writeFile(, buf.toPng(), function(err) {
    console.log("write file finished: "+Date.now());
    if(err){
      console.log(err);
    }
  });*/
});<commit_msg>for ipc test<commit_after>var app = require('app');
var BrowserWindow = require('browser-window');
var ipc = require('ipc');
var fs = require('fs');

require('crash-reporter').start();

var mainWindow = null;

app.on('window-all-closed', function() {
  //TODO: exit when computer restart, to see what node service should do when system down?
  //app.quit();
});

app.on('ready', function() {
  mainWindow = new BrowserWindow({
	width: 1366,
	height: 768,
	show: false,
	frame: false,
	'node-integration': false,
	preload: __dirname + '/preload.js'
  });

  mainWindow.loadUrl('file://' + __dirname + '/index.html');

  //mainWindow.openDevTools();

  mainWindow.on('closed', function() {
    mainWindow = null;
  });
});

ipc.on('WriteFile', function(event, id, test, buf){
  console.log(id);
  console.log(test);
  /*fs.writeFile(, buf.toPng(), function(err) {
    console.log("write file finished: "+Date.now());
    if(err){
      console.log(err);
    }
  });*/
});<|endoftext|>


<commit_before>/*
 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
 *
 * Cache client wrapper.
 */

var assert = require('assert-plus');
var redis = require('redis');
var sprintf = require('util').format;

var common = require('./common');

var VM_KEY = 'vmapi:vms:%s';
var SERVER_KEY = 'vmapi:servers:%s:vms';
var STATUS_KEY = 'vmapi:vms:status';

function Cache(options) {
    assert.object(options, 'redis options');
    assert.object(options.log, 'redis options.log');

    this.options = options;
    this.log = options.log;

    attemptConnect.call(this);
}

function attemptConnect() {
    var self = this;
    var log = this.log;
    var timeout = null;

    var client = this.client = redis.createClient(
        this.options.port || 6379,   // redis default port
        this.options.host || '127.0.0.1',
        { max_attempts: 1 });

    function onReady() {
        clearTimeout(timeout);
        timeout = null;

        // VMAPI's DB Index
        client.select(4);
        log.info('Redis client connected');
    }

    function onError(err) {
        log.error(err, 'Cache client error');
    }

    function onEnd() {
        client.end();
        self.client = null;
        log.error('Cache client disconnected');
        log.info('Re-attempting connection to Redis');

        if (!timeout) {
            attemptConnect.call(self);
        }
    }

    function timeoutCallback() {
        attemptConnect.call(self);
    }

    client.once('ready', onReady);
    client.on('error', onError);
    client.once('end', onEnd);

    timeout = setTimeout(timeoutCallback, 10000);
}

Cache.prototype.connected = function () {
    return this.client && this.client.connected;
};

Cache.prototype.set = function (hash, object, callback) {
    return this.client.hmset(hash, object, callback);
};

Cache.prototype.get = function (hash, callback) {
    return this.client.hgetall(hash, callback);
};

Cache.prototype.del = function (key, callback) {
    return this.client.del(key, callback);
};

Cache.prototype.getKey = function (hash, key, callback) {
    return this.client.hget(hash, key, callback);
};

Cache.prototype.getKeys = function (hash, callback) {
    return this.client.hkeys(hash, callback);
};

Cache.prototype.setKey = function (hash, key, value, callback) {
    return this.client.hset(hash, key, value, callback);
};

Cache.prototype.delKey = function (hash, key, callback) {
    return this.client.hdel(hash, key, callback);
};

Cache.prototype.getHashes = function (hashes, callback) {
    var multi = this.client.multi();

    for (var i = 0; i < hashes.length; i++) {
        multi.hgetall(hashes[i]);
    }

    multi.exec(callback);
};

Cache.prototype.exists = function (key, callback) {
    this.client.exists(key, callback);
};

/**
 * VM helper functions
 */

/*
 * Gets a list of VMs from a list of uuids
 */
Cache.prototype.getVms = function (uuids, callback) {
    assert.arrayOfString(uuids, 'VM UUIDs');

    var vmKeys = [];

    for (var i = 0; i < uuids.length; i++) {
        vmKeys.push(sprintf(VM_KEY, uuids[i]));
    }

    return this.getHashes(vmKeys, callback);
};

Cache.prototype.setVm = function (uuid, vm, callback) {
    var vmKey = sprintf(VM_KEY, uuid);
    var hash = common.vmToHash(vm);

    return this.set(vmKey, hash, callback);
};

Cache.prototype.getVm = function (uuid, callback) {
    var vmKey = sprintf(VM_KEY, uuid);

    return this.get(vmKey, callback);
};

Cache.prototype.getVmsForServer = function (server, callback) {
    var serverKey = sprintf(SERVER_KEY, server);

    return this.getKeys(serverKey, callback);
};

Cache.prototype.setVmsForServer = function (server, hash, callback) {
    var self = this;
    var serverKey = sprintf(SERVER_KEY, server);

    this.del(serverKey, function (err) {
        if (err) {
            callback(err);
            return;
        }

        self.set(serverKey, hash, callback);
    });
};

Cache.prototype.getState = function (uuid, callback) {
    return this.getKey(STATUS_KEY, uuid, callback);
};

Cache.prototype.setState = function (uuid, state, callback) {
    return this.setKey(STATUS_KEY, uuid, state, callback);
};

Cache.prototype.delState = function (uuid, callback) {
    return this.delKey(STATUS_KEY, uuid, callback);
};

Cache.prototype.setVmState =
    function (uuid, zoneState, timestamp, server, persisted, cb) {

    var self = this;
    var stateStamp;

    if (persisted) {
        stateStamp = zoneState + ';' + timestamp;
    } else {
        stateStamp = zoneState + ';' + timestamp + ';false';
    }

    var machineState = (zoneState == 'running' || zoneState == 'shutting_down')
                     ? 'running'
                     : 'stopped';

    function onSaveState(stateErr) {
        if (stateErr) {
            cb(stateErr);
            return;
        }

        self.getVm(uuid, onGetVm);
    }

    function onGetVm(readErr, cached) {
        if (readErr) {
            cb(readErr);
            return;
        }

        if (!cached) {
            cached = { uuid: uuid };
        }

        // The first time we see a zone its server_uuid is null because it
        // probably was automatically allocated by DAPI
        if (!cached['server_uuid']) {
            cached['server_uuid'] = server;
        }

        cached.state = machineState;
        cached['zone_state'] = stateStamp;

        self.setVm(uuid, common.translateVm(cached, false),
        function (writeErr) {
            if (writeErr) {
                cb(writeErr);
                return;
            }

            cb();
        });
    }

    self.setState(uuid, stateStamp, onSaveState);
};

Cache.prototype.existsVm = function (uuid, callback) {
    var vmKey = sprintf(VM_KEY, uuid);

    this.exists(vmKey, callback);
};

module.exports = Cache;
<commit_msg>ZAPI-163: Add debug line<commit_after>/*
 * Copyright (c) 2012, Joyent, Inc. All rights reserved.
 *
 * Cache client wrapper.
 */

var assert = require('assert-plus');
var redis = require('redis');
var sprintf = require('util').format;

var common = require('./common');

var VM_KEY = 'vmapi:vms:%s';
var SERVER_KEY = 'vmapi:servers:%s:vms';
var STATUS_KEY = 'vmapi:vms:status';

function Cache(options) {
    assert.object(options, 'redis options');
    assert.object(options.log, 'redis options.log');

    this.options = options;
    this.log = options.log;

    attemptConnect.call(this);
}

function attemptConnect() {
    var self = this;
    var log = this.log;
    var timeout = null;

    var client = this.client = redis.createClient(
        this.options.port || 6379,   // redis default port
        this.options.host || '127.0.0.1',
        { max_attempts: 1 });

    function onReady() {
        clearTimeout(timeout);
        timeout = null;

        // VMAPI's DB Index
        client.select(4);
        log.info('Redis client connected');
    }

    function onError(err) {
        log.error(err, 'Cache client error');
    }

    function onEnd() {
        client.end();
        self.client = null;
        log.error('Cache client disconnected');
        log.info('Re-attempting connection to Redis');

        if (!timeout) {
            attemptConnect.call(self);
        }
    }

    function timeoutCallback() {
        attemptConnect.call(self);
    }

    client.once('ready', onReady);
    client.on('error', onError);
    client.once('end', onEnd);

    timeout = setTimeout(timeoutCallback, 10000);
}

Cache.prototype.connected = function () {
    return this.client && this.client.connected;
};

Cache.prototype.set = function (hash, object, callback) {
    // ZAPI-163
    this.log.debug('Calling hmset with', hash, object);
    return this.client.hmset(hash, object, callback);
};

Cache.prototype.get = function (hash, callback) {
    return this.client.hgetall(hash, callback);
};

Cache.prototype.del = function (key, callback) {
    return this.client.del(key, callback);
};

Cache.prototype.getKey = function (hash, key, callback) {
    return this.client.hget(hash, key, callback);
};

Cache.prototype.getKeys = function (hash, callback) {
    return this.client.hkeys(hash, callback);
};

Cache.prototype.setKey = function (hash, key, value, callback) {
    return this.client.hset(hash, key, value, callback);
};

Cache.prototype.delKey = function (hash, key, callback) {
    return this.client.hdel(hash, key, callback);
};

Cache.prototype.getHashes = function (hashes, callback) {
    var multi = this.client.multi();

    for (var i = 0; i < hashes.length; i++) {
        multi.hgetall(hashes[i]);
    }

    multi.exec(callback);
};

Cache.prototype.exists = function (key, callback) {
    this.client.exists(key, callback);
};

/**
 * VM helper functions
 */

/*
 * Gets a list of VMs from a list of uuids
 */
Cache.prototype.getVms = function (uuids, callback) {
    assert.arrayOfString(uuids, 'VM UUIDs');

    var vmKeys = [];

    for (var i = 0; i < uuids.length; i++) {
        vmKeys.push(sprintf(VM_KEY, uuids[i]));
    }

    return this.getHashes(vmKeys, callback);
};

Cache.prototype.setVm = function (uuid, vm, callback) {
    var vmKey = sprintf(VM_KEY, uuid);
    var hash = common.vmToHash(vm);

    return this.set(vmKey, hash, callback);
};

Cache.prototype.getVm = function (uuid, callback) {
    var vmKey = sprintf(VM_KEY, uuid);

    return this.get(vmKey, callback);
};

Cache.prototype.getVmsForServer = function (server, callback) {
    var serverKey = sprintf(SERVER_KEY, server);

    return this.getKeys(serverKey, callback);
};

Cache.prototype.setVmsForServer = function (server, hash, callback) {
    var self = this;
    var serverKey = sprintf(SERVER_KEY, server);

    this.del(serverKey, function (err) {
        if (err) {
            callback(err);
            return;
        }

        self.set(serverKey, hash, callback);
    });
};

Cache.prototype.getState = function (uuid, callback) {
    return this.getKey(STATUS_KEY, uuid, callback);
};

Cache.prototype.setState = function (uuid, state, callback) {
    return this.setKey(STATUS_KEY, uuid, state, callback);
};

Cache.prototype.delState = function (uuid, callback) {
    return this.delKey(STATUS_KEY, uuid, callback);
};

Cache.prototype.setVmState =
    function (uuid, zoneState, timestamp, server, persisted, cb) {

    var self = this;
    var stateStamp;

    if (persisted) {
        stateStamp = zoneState + ';' + timestamp;
    } else {
        stateStamp = zoneState + ';' + timestamp + ';false';
    }

    var machineState = (zoneState == 'running' || zoneState == 'shutting_down')
                     ? 'running'
                     : 'stopped';

    function onSaveState(stateErr) {
        if (stateErr) {
            cb(stateErr);
            return;
        }

        self.getVm(uuid, onGetVm);
    }

    function onGetVm(readErr, cached) {
        if (readErr) {
            cb(readErr);
            return;
        }

        if (!cached) {
            cached = { uuid: uuid };
        }

        // The first time we see a zone its server_uuid is null because it
        // probably was automatically allocated by DAPI
        if (!cached['server_uuid']) {
            cached['server_uuid'] = server;
        }

        cached.state = machineState;
        cached['zone_state'] = stateStamp;

        self.setVm(uuid, common.translateVm(cached, false),
        function (writeErr) {
            if (writeErr) {
                cb(writeErr);
                return;
            }

            cb();
        });
    }

    self.setState(uuid, stateStamp, onSaveState);
};

Cache.prototype.existsVm = function (uuid, callback) {
    var vmKey = sprintf(VM_KEY, uuid);

    this.exists(vmKey, callback);
};

module.exports = Cache;
<|endoftext|>


<commit_before>// Basic stuff we need
var exec   = require('child_process').exec,
    config = require('./barebones.json'),
    gulp   = require('gulp');

// Gulp plugins
var rename = require("gulp-rename"),
    rimraf = require('gulp-rimraf'),
    filter = require('gulp-filter'),

    cache    = require('gulp-cache'),
    imagemin = require('gulp-imagemin'),

    compass      = require('gulp-compass'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss    = require('gulp-minify-css'),

    useref = require('gulp-useref'),
    uglify = require('gulp-uglify');

/* Project directory structure
 *
 * barebones
 * |
 * |- bower_components          [vendor]  libraries (via Bower)
 * |- dist                      [project] compiled files, misc files (html, ico)
 * |  |- fonts                  [fonts]   compressed (eot, svg, ttf, woff)
 * |  |- images                 [images]  compressed (jpg, png) and sprites (png)
 * |  |- scripts                [scripts] combined and minified (min.js)
 * |  |  '- vendor              [scripts] vendor libraries (min.js)
 * |  '- styles                 [styles]  prefixed and minifed (min.css)
 * '- src                       [project] source files, misc files (html, ico)
 *    |- fonts                  [fonts]   source (eot, svg, ttf, woff)
 *    |- images                 [images]  source (jpg, png)
 *    |- scripts                [scripts] source (js)
 *    |- sprites                [images]  sprite components (png)
 *    |  '- icon                [example] [images] sprite components (png)
 *    '- styles                 [styles]  uncompiled source (scss)
 *
 */

// Gulp tasks

/* Bower task
 *
 * Installs all bower dependencies
 */
gulp.task('bower', function (cb) {
    // Install bower dependencies
    exec('bower install', function (err, stdout, stderr) {
        if (stdout) console.log(stdout);
        if (stderr) console.log(stderr);
        cb(err);
    });
});

/* Vendor task
 *
 * Copies all vendor dependencies into their respective locations
 */
gulp.task('vendor', [
    'vendor:normalize',
    'vendor:modernizr',
    'vendor:jquery',
    'vendor:bootstrap',
    'vendor:jquery-mousewheel',
    'vendor:jquery-touchswipe'
]);

/* Vendor:normalize subtask
 *
 * Copies normalize.scss to style vendor dir
 */
gulp.task('vendor:normalize', ['bower'], function () {
    gulp.src('bower_components/normalize-scss/_normalize.scss')
        .pipe(gulp.dest(config.path.style.vendor));
});

/* Vendor:modernizr subtask
 *
 * Copies modernizr to js vendor dir
 */
gulp.task('vendor:modernizr', ['bower'], function () {
    gulp.src('bower_components/modernizr/modernizr.js')
        .pipe(gulp.dest(config.path.script.vendor));
});

/* Vendor:jquery subtask
 *
 * Copies jquery to dest js vendor dir
 */
gulp.task('vendor:jquery', ['bower'], function () {
    gulp.src('bower_components/jquery/dist/jquery.min.js')
        .pipe(rename('jquery-2.1.1.min.js'))
        .pipe(gulp.dest(config.path.script.dest + '/vendor'));
});

/* Vendor:bootstrap task
 *
 * Copies bootstrap js files to js vendor dir
 */
gulp.task('vendor:bootstrap', ['bower'], function () {
    gulp.src('bower_components/bootstrap/js/*.js')
        .pipe(rename({prefix: 'bootstrap-'}))
        .pipe(gulp.dest(config.path.script.vendor));
});

/* Vendor:jquery-mousewheel task
 *
 * Copies jquery-mousewheel js file to js vendor dir
 */
gulp.task('vendor:jquery-mousewheel', ['bower'], function () {
    gulp.src('bower_components/jquery-mousewheel/jquery.mousewheel.js')
        .pipe(rename('jquery-mousewheel.js'))
        .pipe(gulp.dest(config.path.script.vendor));
});

/* Vendor:jquery-touchswipe task
 *
 * Copies jquery-touchswipe js file to js vendor dir
 */
gulp.task('vendor:jquery-touchswipe', ['bower'], function () {
    gulp.src('bower_components/jquery-touchswipe/jquery.touchSwipe.js')
        .pipe(rename('jquery-touchswipe.js'))
        .pipe(gulp.dest(config.path.script.vendor));
});

/* Font task
 *
 * Copies font files over to dest dir
 */
gulp.task('font', function () {
    gulp.src(config.path.font.src + '/**/*.{eot,otf,svg,ttf,woff}')
        .pipe(gulp.dest(config.path.font.dest));
});

/* Html task
 *
 * Copies html files over to dest dir
 */
gulp.task('html', function () {
    var assets  = useref.assets(),
        jsfiles = filter("**/*.js");

    gulp.src(config.path.html.src + '/*.html')
        .pipe(assets)

        // Concatenate and minify javascripts
        .pipe(jsfiles)
        .pipe(uglify())
        .pipe(jsfiles.restore())

        // Restore html stream and write concatenated js file names
        .pipe(assets.restore())
        .pipe(useref())
        .pipe(gulp.dest(config.path.html.dest));
});

/* Image task
 *
 * Copies compressed and optimized images over to dest dir
 */
gulp.task('image', function() {
  gulp.src(config.path.image.src + '/**/*.{jpg,png}')
      .pipe(cache(imagemin({
            optimizationLevel: 5,
            progressive: true,
            interlaced: true
      })))
      .pipe(gulp.dest(config.path.image.dest));
});

/* Script task
 *
 * Concatenates and uglifies scripts
 */
gulp.task('script', ['html']);

/* Style task
 *
 * Compiles scss files to css dest dir
 */
gulp.task('style', function () {
    gulp.src(config.path.style.src + '/*.scss')
        .pipe(compass({
            config_file: 'config.rb',
            css: config.path.style.dest,
            sass: config.path.style.src,
            style: 'expanded'
        }))
        .on('error', function (err) {}) // Error message is output by the plugin
        .pipe(autoprefixer("> 1%", "last 2 version"))
        .pipe(gulp.dest(config.path.style.dest))
        .pipe(rename({suffix: '.min'}))
        .pipe(minifycss())
        .pipe(gulp.dest(config.path.style.dest));
});

/* Misc task
 *
 * Copies misc files misc dest dir
 */
gulp.task('misc', function () {
    // Compile a list of all paths
    var files = config.path.misc.files || [],
        src   = config.path.misc.src,
        dest  = config.path.misc.dest,
        paths = [];

    // Compile a list of files
    for (var i = 0, l = files.length; i < l; i++) {
        paths.push(src + '/' + files[i]);
    }

    // Copy all files from the list
    gulp.src(paths)
        .pipe(gulp.dest(dest));
});

/* Watch task
 *
 * Enters watch mode, automatically recompiling assets on source changes
 */
gulp.task('watch', function () {
    gulp.watch(config.path.font.src + '/**/*.{eot,otf,svg,ttf,woff}', ['font']);
    gulp.watch(config.path.html.src + '/*.html', ['html']);
    gulp.watch(config.path.image.src + '/**/*.{jpg,png}', ['image']);
    gulp.watch(config.path.script.src + '/**/*.js', ['script']);
    gulp.watch([
        config.path.style.src + '/**/*.scss',
        config.path.sprite.src + '/**/*.png' // TODO: check if sprites support jpegs
    ], ['style']);
});

/* Clean:font task
 *
 * Removes font dest folder
 */
gulp.task('clean:font', function () {
    gulp.src(config.path.font.dest, {read: false})
        .pipe(rimraf());
});

/* Clean:html task
 *
 * Removes html files from dest folder
 */
gulp.task('clean:html', function () {
    gulp.src(config.path.html.dest + '/*.html', {read: false})
        .pipe(rimraf());
});

/* Clean:image task
 *
 * Removes image dest folder
 */
gulp.task('clean:image', function () {
    gulp.src(config.path.image.dest, {read: false})
        .pipe(rimraf())
        .pipe(cache.clear());
});

/* Clean:script
 *
 * Clears script dest folder, except vendor subfolder
 */
gulp.task('clean:script', function () {
    gulp.src([
        config.path.script.dest + '/**/*',
        '!' + config.path.script.dest + '/vendor',
        '!' + config.path.script.dest + '/vendor/**/*.js'
    ], {read: false})
        .pipe(rimraf());
});

/* Clean:style task
 *
 * Removes style dest folder
 */
gulp.task('clean:style', function () {
    gulp.src(config.path.style.dest, {read: false})
        .pipe(rimraf());
});

/* Clean:misc task
 *
 * Removes misc files from dest folder
 */
gulp.task('clean:misc', function () {
    // Compile a list of all paths
    var files = config.path.misc.files || [],
        dest  = config.path.misc.dest,
        paths = [];

    // Compile a list of files
    for (var i = 0, l = files.length; i < l; i++) {
        paths.push(dest + '/' + files[i]);
    }

    // Clean all files and folders from the list
    gulp.src(paths, {read: false})
        .pipe(clean());
});

/* Clean task
 *
 * Removes html dest folder
 */
gulp.task('clean', [
    'clean:font',
    'clean:html',
    'clean:image',
    'clean:script',
    'clean:style',
    'clean:misc'
]);

/* Default task
 *
 * Compiles all files
 */
gulp.task('default', [
    'font',
    'html',
    'image',
    'script',
    'style',
    'misc'
]);

/* Init task
 *
 * Loads and installs required vendor libraries via bower
 */
gulp.task('init', [
    'bower',
    'vendor'
]);

/* Connect task
 *
 * Creates a web server with an index of all html files within html dest dir
 */
gulp.task('connect', function() {
    var serveStatic = require('serve-static'),
        serveIndex  = require('serve-index');

    var app = require('connect')()
        .use(serveStatic(config.path.html.dest)) // serve files from within a given root directory
        .use(serveIndex(config.path.html.dest)); // returns middlware that serves an index of the directory in the given path

    require('http')
        .createServer(app)
        .listen(config.server.port)
        .on('listening', function() {
            console.log('Started connect web server on http://localhost:' + config.server.port);
        });
});

/* Server task
 *
 * Creates a web server and starts watching for any changes within src dir
 */
gulp.task('server', [
    'connect',
    'watch'
]);

// validation
<commit_msg>Fixed bug with using clean() instead of rimraf() in clean:misc<commit_after>// Basic stuff we need
var exec   = require('child_process').exec,
    config = require('./barebones.json'),
    gulp   = require('gulp');

// Gulp plugins
var rename = require("gulp-rename"),
    rimraf = require('gulp-rimraf'),
    filter = require('gulp-filter'),

    cache    = require('gulp-cache'),
    imagemin = require('gulp-imagemin'),

    compass      = require('gulp-compass'),
    autoprefixer = require('gulp-autoprefixer'),
    minifycss    = require('gulp-minify-css'),

    useref = require('gulp-useref'),
    uglify = require('gulp-uglify');

/* Project directory structure
 *
 * barebones
 * |
 * |- bower_components          [vendor]  libraries (via Bower)
 * |- dist                      [project] compiled files, misc files (html, ico)
 * |  |- fonts                  [fonts]   compressed (eot, svg, ttf, woff)
 * |  |- images                 [images]  compressed (jpg, png) and sprites (png)
 * |  |- scripts                [scripts] combined and minified (min.js)
 * |  |  '- vendor              [scripts] vendor libraries (min.js)
 * |  '- styles                 [styles]  prefixed and minifed (min.css)
 * '- src                       [project] source files, misc files (html, ico)
 *    |- fonts                  [fonts]   source (eot, svg, ttf, woff)
 *    |- images                 [images]  source (jpg, png)
 *    |- scripts                [scripts] source (js)
 *    |- sprites                [images]  sprite components (png)
 *    |  '- icon                [example] [images] sprite components (png)
 *    '- styles                 [styles]  uncompiled source (scss)
 *
 */

// Gulp tasks

/* Bower task
 *
 * Installs all bower dependencies
 */
gulp.task('bower', function (cb) {
    // Install bower dependencies
    exec('bower install', function (err, stdout, stderr) {
        if (stdout) console.log(stdout);
        if (stderr) console.log(stderr);
        cb(err);
    });
});

/* Vendor task
 *
 * Copies all vendor dependencies into their respective locations
 */
gulp.task('vendor', [
    'vendor:normalize',
    'vendor:modernizr',
    'vendor:jquery',
    'vendor:bootstrap',
    'vendor:jquery-mousewheel',
    'vendor:jquery-touchswipe'
]);

/* Vendor:normalize subtask
 *
 * Copies normalize.scss to style vendor dir
 */
gulp.task('vendor:normalize', ['bower'], function () {
    gulp.src('bower_components/normalize-scss/_normalize.scss')
        .pipe(gulp.dest(config.path.style.vendor));
});

/* Vendor:modernizr subtask
 *
 * Copies modernizr to js vendor dir
 */
gulp.task('vendor:modernizr', ['bower'], function () {
    gulp.src('bower_components/modernizr/modernizr.js')
        .pipe(gulp.dest(config.path.script.vendor));
});

/* Vendor:jquery subtask
 *
 * Copies jquery to dest js vendor dir
 */
gulp.task('vendor:jquery', ['bower'], function () {
    gulp.src('bower_components/jquery/dist/jquery.min.js')
        .pipe(rename('jquery-2.1.1.min.js'))
        .pipe(gulp.dest(config.path.script.dest + '/vendor'));
});

/* Vendor:bootstrap task
 *
 * Copies bootstrap js files to js vendor dir
 */
gulp.task('vendor:bootstrap', ['bower'], function () {
    gulp.src('bower_components/bootstrap/js/*.js')
        .pipe(rename({prefix: 'bootstrap-'}))
        .pipe(gulp.dest(config.path.script.vendor));
});

/* Vendor:jquery-mousewheel task
 *
 * Copies jquery-mousewheel js file to js vendor dir
 */
gulp.task('vendor:jquery-mousewheel', ['bower'], function () {
    gulp.src('bower_components/jquery-mousewheel/jquery.mousewheel.js')
        .pipe(rename('jquery-mousewheel.js'))
        .pipe(gulp.dest(config.path.script.vendor));
});

/* Vendor:jquery-touchswipe task
 *
 * Copies jquery-touchswipe js file to js vendor dir
 */
gulp.task('vendor:jquery-touchswipe', ['bower'], function () {
    gulp.src('bower_components/jquery-touchswipe/jquery.touchSwipe.js')
        .pipe(rename('jquery-touchswipe.js'))
        .pipe(gulp.dest(config.path.script.vendor));
});

/* Font task
 *
 * Copies font files over to dest dir
 */
gulp.task('font', function () {
    gulp.src(config.path.font.src + '/**/*.{eot,otf,svg,ttf,woff}')
        .pipe(gulp.dest(config.path.font.dest));
});

/* Html task
 *
 * Copies html files over to dest dir
 */
gulp.task('html', function () {
    var assets  = useref.assets(),
        jsfiles = filter("**/*.js");

    gulp.src(config.path.html.src + '/*.html')
        .pipe(assets)

        // Concatenate and minify javascripts
        .pipe(jsfiles)
        .pipe(uglify())
        .pipe(jsfiles.restore())

        // Restore html stream and write concatenated js file names
        .pipe(assets.restore())
        .pipe(useref())
        .pipe(gulp.dest(config.path.html.dest));
});

/* Image task
 *
 * Copies compressed and optimized images over to dest dir
 */
gulp.task('image', function() {
  gulp.src(config.path.image.src + '/**/*.{jpg,png}')
      .pipe(cache(imagemin({
            optimizationLevel: 5,
            progressive: true,
            interlaced: true
      })))
      .pipe(gulp.dest(config.path.image.dest));
});

/* Script task
 *
 * Concatenates and uglifies scripts
 */
gulp.task('script', ['html']);

/* Style task
 *
 * Compiles scss files to css dest dir
 */
gulp.task('style', function () {
    gulp.src(config.path.style.src + '/*.scss')
        .pipe(compass({
            config_file: 'config.rb',
            css: config.path.style.dest,
            sass: config.path.style.src,
            style: 'expanded'
        }))
        .on('error', function (err) {}) // Error message is output by the plugin
        .pipe(autoprefixer("> 1%", "last 2 version"))
        .pipe(gulp.dest(config.path.style.dest))
        .pipe(rename({suffix: '.min'}))
        .pipe(minifycss())
        .pipe(gulp.dest(config.path.style.dest));
});

/* Misc task
 *
 * Copies misc files misc dest dir
 */
gulp.task('misc', function () {
    // Compile a list of all paths
    var files = config.path.misc.files || [],
        src   = config.path.misc.src,
        dest  = config.path.misc.dest,
        paths = [];

    // Compile a list of files
    for (var i = 0, l = files.length; i < l; i++) {
        paths.push(src + '/' + files[i]);
    }

    // Copy all files from the list
    gulp.src(paths)
        .pipe(gulp.dest(dest));
});

/* Watch task
 *
 * Enters watch mode, automatically recompiling assets on source changes
 */
gulp.task('watch', function () {
    gulp.watch(config.path.font.src + '/**/*.{eot,otf,svg,ttf,woff}', ['font']);
    gulp.watch(config.path.html.src + '/*.html', ['html']);
    gulp.watch(config.path.image.src + '/**/*.{jpg,png}', ['image']);
    gulp.watch(config.path.script.src + '/**/*.js', ['script']);
    gulp.watch([
        config.path.style.src + '/**/*.scss',
        config.path.sprite.src + '/**/*.png' // TODO: check if sprites support jpegs
    ], ['style']);
});

/* Clean:font task
 *
 * Removes font dest folder
 */
gulp.task('clean:font', function () {
    gulp.src(config.path.font.dest, {read: false})
        .pipe(rimraf());
});

/* Clean:html task
 *
 * Removes html files from dest folder
 */
gulp.task('clean:html', function () {
    gulp.src(config.path.html.dest + '/*.html', {read: false})
        .pipe(rimraf());
});

/* Clean:image task
 *
 * Removes image dest folder
 */
gulp.task('clean:image', function () {
    gulp.src(config.path.image.dest, {read: false})
        .pipe(rimraf())
        .pipe(cache.clear());
});

/* Clean:script
 *
 * Clears script dest folder, except vendor subfolder
 */
gulp.task('clean:script', function () {
    gulp.src([
        config.path.script.dest + '/**/*',
        '!' + config.path.script.dest + '/vendor',
        '!' + config.path.script.dest + '/vendor/**/*.js'
    ], {read: false})
        .pipe(rimraf());
});

/* Clean:style task
 *
 * Removes style dest folder
 */
gulp.task('clean:style', function () {
    gulp.src(config.path.style.dest, {read: false})
        .pipe(rimraf());
});

/* Clean:misc task
 *
 * Removes misc files from dest folder
 */
gulp.task('clean:misc', function () {
    // Compile a list of all paths
    var files = config.path.misc.files || [],
        dest  = config.path.misc.dest,
        paths = [];

    // Compile a list of files
    for (var i = 0, l = files.length; i < l; i++) {
        paths.push(dest + '/' + files[i]);
    }

    // Clean all files and folders from the list
    gulp.src(paths, {read: false})
        .pipe(rimraf());
});

/* Clean task
 *
 * Removes html dest folder
 */
gulp.task('clean', [
    'clean:font',
    'clean:html',
    'clean:image',
    'clean:script',
    'clean:style',
    'clean:misc'
]);

/* Default task
 *
 * Compiles all files
 */
gulp.task('default', [
    'font',
    'html',
    'image',
    'script',
    'style',
    'misc'
]);

/* Init task
 *
 * Loads and installs required vendor libraries via bower
 */
gulp.task('init', [
    'bower',
    'vendor'
]);

/* Connect task
 *
 * Creates a web server with an index of all html files within html dest dir
 */
gulp.task('connect', function() {
    var serveStatic = require('serve-static'),
        serveIndex  = require('serve-index');

    var app = require('connect')()
        .use(serveStatic(config.path.html.dest)) // serve files from within a given root directory
        .use(serveIndex(config.path.html.dest)); // returns middlware that serves an index of the directory in the given path

    require('http')
        .createServer(app)
        .listen(config.server.port)
        .on('listening', function() {
            console.log('Started connect web server on http://localhost:' + config.server.port);
        });
});

/* Server task
 *
 * Creates a web server and starts watching for any changes within src dir
 */
gulp.task('server', [
    'connect',
    'watch'
]);

// validation
<|endoftext|>


<commit_before>// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.numberOfCompetencesToAdd = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.getProjectInfo = function() {
        console.log($("#projectHeader").data('value'));
        $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };
}

function addCompetence() {
    ++viewModel.numberOfCompetencesToAdd;

    var competencePanelWrapper = document.createElement('div');
    var competencePanel = document.createElement('div');
    var competencePanelHeading = document.createElement('div');
    var competencePanelBody = document.createElement('div');
    var competencePanelFooter = document.createElement('div');
    var competenceCode = document.createElement('input');
    var competenceName = document.createElement('input');
    var subcompetenceButton = document.createElement('button');

    $(competencePanelWrapper).addClass("col-md-9");
    $(competencePanel).addClass("panel panel-default");
    $(competencePanelHeading).addClass("panel-heading");
    $(competencePanelBody).addClass("panel-body");
    $(competencePanelFooter).addClass("panel-footer");

    competenceCode.type = 'text';
    competenceCode.placeholder = "Competence-Code";
    $(competenceCode).addClass("form-control");

    competenceName.type = 'text';
    competenceName.placeholder = "Name of the competence";
    $(competenceName).addClass("form-control");

    $(subcompetenceButton).addClass("btn");
    $(subcompetenceButton).text("Add a subcompetence");
    $(subcompetenceButton).val(viewModel.numberOfCompetencesToAdd);
    $(subcompetenceButton).on('click', addSubCompetence);

    $("#top-col").after(competencePanelWrapper);
    $(competencePanelWrapper).append(competencePanel);
    $(competencePanel).append(competencePanelHeading);
    $(competencePanelHeading).append(competenceName);
    $(competenceName).after(competenceCode);
    $(competencePanelHeading).after(competencePanelBody);
    $(competencePanelBody).after(competencePanelFooter);
    $(competencePanelFooter).append(subcompetenceButton);
}

function addSubCompetence() {
}

function addIndicator() {

}

function initPage() {
    viewModel.getProjectInfo();
    $("#addCompetenceBtn").click(function() {
        addCompetence();
    })
}<commit_msg>projectpage<commit_after>// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.numberOfCompetencesToAdd = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.getProjectInfo = function() {
        console.log($("#projectHeader").data('value'));
        $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };
}

function addCompetence() {
    ++viewModel.numberOfCompetencesToAdd;

    var competencePanelWrapper = document.createElement('div');
    var competencePanel = document.createElement('div');
    var competencePanelHeading = document.createElement('div');
    var competencePanelBody = document.createElement('div');
    var competencePanelFooter = document.createElement('div');
    var competenceCode = document.createElement('input');
    var competenceName = document.createElement('input');
    var subcompetenceButton = document.createElement('button');

    $(competencePanelWrapper).addClass("col-md-9");
    $(competencePanel).addClass("panel panel-default");
    $(competencePanelHeading).addClass("panel-heading");
    $(competencePanelBody).addClass("panel-body");
    $(competencePanelFooter).addClass("panel-footer");

    competenceCode.type = 'text';
    competenceCode.placeholder = "Competence-Code";
    $(competenceCode).addClass("form-control");

    competenceName.type = 'text';
    competenceName.placeholder = "Name of the competence";
    $(competenceName).addClass("form-control");

    $(subcompetenceButton).addClass("btn");
    $(subcompetenceButton).text("Add a subcompetence");
    $(subcompetenceButton).val(viewModel.numberOfCompetencesToAdd);
    $(subcompetenceButton).on('click', addSubCompetence($(subcompetenceButton).val()));

    $("#top-col").after(competencePanelWrapper);
    $(competencePanelWrapper).append(competencePanel);
    $(competencePanel).append(competencePanelHeading);
    $(competencePanelHeading).append(competenceName);
    $(competenceName).after(competenceCode);
    $(competencePanelHeading).after(competencePanelBody);
    $(competencePanelBody).after(competencePanelFooter);
    $(competencePanelFooter).append(subcompetenceButton);
}

function addSubCompetence() {
}

function addIndicator() {

}

function initPage() {
    viewModel.getProjectInfo();
    $("#addCompetenceBtn").click(function() {
        addCompetence();
    })
}<|endoftext|>


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

/**
 * @fileoverview Utilities for user creation, login and privileging when
 * carrying out end-to-end testing with protractor.
 *
 * @author Jacob Davis (jacobdavis11@gmail.com)
 */

var forms = require('./forms.js');
var general = require('./general.js');
var admin = require('./admin.js');

var login = function(email, isSuperAdmin) {
  // Use of element is not possible because the login page is non-angular.
  // The full url is also necessary.
  var driver = browser.driver;
  driver.get(general.SERVER_URL_PREFIX + general.LOGIN_URL_SUFFIX);

  driver.findElement(protractor.By.name('email')).clear();
  driver.findElement(protractor.By.name('email')).sendKeys(email);
  if (isSuperAdmin) {
    driver.findElement(protractor.By.name('admin')).click();
  }
  driver.findElement(protractor.By.id('submit-login')).click();
};

var logout = function() {
  var driver = browser.driver;
  driver.get(general.SERVER_URL_PREFIX + general.LOGIN_URL_SUFFIX);
  driver.findElement(protractor.By.id('submit-logout')).click();
};

// The user needs to log in immediately before this method is called. Note
// that this will fail if the user already has a username.
var _completeSignup = function(username) {
  browser.get('/signup?return_url=http%3A%2F%2Flocalhost%3A4445%2F');
  element(by.css('.protractor-test-username-input')).sendKeys(username);
  element(by.css('.protractor-test-agree-to-terms-checkbox')).click();
  element(by.css('.protractor-test-register-user')).click();
};

var createUser = function(email, username) {
  login(email);
  _completeSignup(username);
  general.waitForSystem();
  logout();
};

var createAndLoginUser = function(email, username) {
  login(email);
  _completeSignup(username);
};

var createModerator = function(email, username) {
  login(email, true);
  _completeSignup(username);
  admin.editConfigProperty(
      'Email addresses of moderators', 'List', function(listEditor) {
    listEditor.addItem('Unicode').setValue(email);
  });
  logout();
};

var createAdmin = function(email, username) {
  login(email, true);
  _completeSignup(username);
  admin.editConfigProperty(
      'Email addresses of admins', 'List', function(listEditor) {
    listEditor.addItem('Unicode').setValue(email);
  });
  logout();
};

exports.login = login;
exports.logout = logout;
exports.createUser = createUser;
exports.createAndLoginUser = createAndLoginUser;
exports.createModerator = createModerator;
exports.createAdmin = createAdmin;

<commit_msg>Fix e2e test failure due to config property change.<commit_after>// Copyright 2014 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Utilities for user creation, login and privileging when
 * carrying out end-to-end testing with protractor.
 *
 * @author Jacob Davis (jacobdavis11@gmail.com)
 */

var forms = require('./forms.js');
var general = require('./general.js');
var admin = require('./admin.js');

var login = function(email, isSuperAdmin) {
  // Use of element is not possible because the login page is non-angular.
  // The full url is also necessary.
  var driver = browser.driver;
  driver.get(general.SERVER_URL_PREFIX + general.LOGIN_URL_SUFFIX);

  driver.findElement(protractor.By.name('email')).clear();
  driver.findElement(protractor.By.name('email')).sendKeys(email);
  if (isSuperAdmin) {
    driver.findElement(protractor.By.name('admin')).click();
  }
  driver.findElement(protractor.By.id('submit-login')).click();
};

var logout = function() {
  var driver = browser.driver;
  driver.get(general.SERVER_URL_PREFIX + general.LOGIN_URL_SUFFIX);
  driver.findElement(protractor.By.id('submit-logout')).click();
};

// The user needs to log in immediately before this method is called. Note
// that this will fail if the user already has a username.
var _completeSignup = function(username) {
  browser.get('/signup?return_url=http%3A%2F%2Flocalhost%3A4445%2F');
  element(by.css('.protractor-test-username-input')).sendKeys(username);
  element(by.css('.protractor-test-agree-to-terms-checkbox')).click();
  element(by.css('.protractor-test-register-user')).click();
};

var createUser = function(email, username) {
  login(email);
  _completeSignup(username);
  general.waitForSystem();
  logout();
};

var createAndLoginUser = function(email, username) {
  login(email);
  _completeSignup(username);
};

var createModerator = function(email, username) {
  login(email, true);
  _completeSignup(username);
  admin.editConfigProperty(
      'Usernames of moderators', 'List', function(listEditor) {
    listEditor.addItem('Unicode').setValue(username);
  });
  logout();
};

var createAdmin = function(email, username) {
  login(email, true);
  _completeSignup(username);
  admin.editConfigProperty(
      'Usernames of admins', 'List', function(listEditor) {
    listEditor.addItem('Unicode').setValue(username);
  });
  logout();
};

exports.login = login;
exports.logout = logout;
exports.createUser = createUser;
exports.createAndLoginUser = createAndLoginUser;
exports.createModerator = createModerator;
exports.createAdmin = createAdmin;

<|endoftext|>


<commit_before>requirejs.config({
    paths: {
        jquery: "./3rdparty/jquery-1.8.2",
        jquery_anythingslider: "./3rdparty/jquery.anythingslider",
        jquery_autosuggest: "./3rdparty/jquery.autoSuggest",
        jquery_chosen: "./3rdparty/chosen.jquery",
        jquery_ext: "./jquery-ext",
        jquery_form: "./lib/jquery.form/jquery.form",
        jquery_fullcalendar: "./3rdparty/fullcalendar/fullcalendar",
        jquery_jcrop: "./3rdparty/jCrop/js/jquery.Jcrop",
        jquery_placeholder: "./3rdparty/jquery.placeholder",
        jquery_textchange: "./3rdparty/jquery.textchange/jquery.textchange",
        jquery_validate: "./3rdparty/jquery-validation/jquery.validate",
        jquery_validate_additional_methods: "./3rdparty/jquery-validation/additional-methods",
        logging: "./3rdparty/logging/src/logging",
        less: "./3rdparty/less-1.3.1",
        pagedown_converter: "./3rdparty/pagedown/Markdown.Converter",
        pagedown_extra: "./3rdparty/pagedown-extra/Markdown.Extra",
        pagedown_sanitizer: "./3rdparty/pagedown/Markdown.Sanitizer",
        modernizr: "./3rdparty/modernizr-2.0.6",
        prefixfree: "./3rdparty/prefixfree",
        tinymce: "./3rdparty/tiny_mce/tiny_mce_src"
    },
    shim: {
        jquery_anythingslider: {
            deps: ["jquery"]
        },
        jquery_autosuggest: {
            deps: ["jquery"]
        },
        jquery_chosen: {
            deps: ["jquery"]
        },
        jquery_form: {
            deps: ["jquery"]
        },
        jquery_fullcalendar: {
            deps: ["jquery"]
        },
        jquery_jcrop: {
            deps: ["jquery"]
        },
        jquery_placeholder: {
            deps: ["jquery"]
        },
        jquery_textchange: {
            deps: ["jquery"]
        },
        jquery_validate: {
            deps: ["jquery"]
        },
        jquery_validate_additional_methods: {
            deps: ["jquery_validate"]
        },
        pagedown_extra: {
            deps: ["pagedown_converter", 'pagedown_sanitizer']
        },
        pagedown_sanitizer: {
            deps: ["pagedown_converter"]
        }
    }
});

define([
    "modernizr",
    "less",
    "prefixfree",
    "./patterns/autofocus",
    "./patterns/autoscale",
    "./patterns/autosubmit",
    "./patterns/autosubmit2",
    "./patterns/autosuggest",
    "./patterns/breadcrumbs",
    "./patterns/bumper",
    "./patterns/carousel",
    "./patterns/checkedflag",
    "./patterns/checklist",
    "./patterns/chosen",
    "./patterns/collapsible",
    "./patterns/depends",
    "./patterns/edit-tinymce",
    "./patterns/expandable",
    "./patterns/focus",
    "./patterns/form-state",
    "./patterns/fullcalendar",
    "./patterns/image-crop",
    "./patterns/inject",
    "./patterns/markdown",
    "./patterns/menu",
    "./patterns/modal",
    "./patterns/navigation",
    "./patterns/placeholder",
    "./patterns/setclass",
    "./patterns/sortable",
    "./patterns/switch",
    "./patterns/transforms",
    "./patterns/toggle",
    "./patterns/tooltip",
    "./patterns/validate",
    "./patterns/zoom"
], function() { });
<commit_msg>Always load markdown before injectino.<commit_after>requirejs.config({
    paths: {
        jquery: "./3rdparty/jquery-1.8.2",
        jquery_anythingslider: "./3rdparty/jquery.anythingslider",
        jquery_autosuggest: "./3rdparty/jquery.autoSuggest",
        jquery_chosen: "./3rdparty/chosen.jquery",
        jquery_ext: "./jquery-ext",
        jquery_form: "./lib/jquery.form/jquery.form",
        jquery_fullcalendar: "./3rdparty/fullcalendar/fullcalendar",
        jquery_jcrop: "./3rdparty/jCrop/js/jquery.Jcrop",
        jquery_placeholder: "./3rdparty/jquery.placeholder",
        jquery_textchange: "./3rdparty/jquery.textchange/jquery.textchange",
        jquery_validate: "./3rdparty/jquery-validation/jquery.validate",
        jquery_validate_additional_methods: "./3rdparty/jquery-validation/additional-methods",
        logging: "./3rdparty/logging/src/logging",
        less: "./3rdparty/less-1.3.1",
        pagedown_converter: "./3rdparty/pagedown/Markdown.Converter",
        pagedown_extra: "./3rdparty/pagedown-extra/Markdown.Extra",
        pagedown_sanitizer: "./3rdparty/pagedown/Markdown.Sanitizer",
        modernizr: "./3rdparty/modernizr-2.0.6",
        prefixfree: "./3rdparty/prefixfree",
        tinymce: "./3rdparty/tiny_mce/tiny_mce_src"
    },
    shim: {
        jquery_anythingslider: {
            deps: ["jquery"]
        },
        jquery_autosuggest: {
            deps: ["jquery"]
        },
        jquery_chosen: {
            deps: ["jquery"]
        },
        jquery_form: {
            deps: ["jquery"]
        },
        jquery_fullcalendar: {
            deps: ["jquery"]
        },
        jquery_jcrop: {
            deps: ["jquery"]
        },
        jquery_placeholder: {
            deps: ["jquery"]
        },
        jquery_textchange: {
            deps: ["jquery"]
        },
        jquery_validate: {
            deps: ["jquery"]
        },
        jquery_validate_additional_methods: {
            deps: ["jquery_validate"]
        },
        pagedown_extra: {
            deps: ["pagedown_converter", 'pagedown_sanitizer']
        },
        pagedown_sanitizer: {
            deps: ["pagedown_converter"]
        }
    }
});

define([
    "modernizr",
    "less",
    "prefixfree",
    "./patterns/autofocus",
    "./patterns/autoscale",
    "./patterns/autosubmit",
    "./patterns/autosubmit2",
    "./patterns/autosuggest",
    "./patterns/breadcrumbs",
    "./patterns/bumper",
    "./patterns/carousel",
    "./patterns/checkedflag",
    "./patterns/checklist",
    "./patterns/chosen",
    "./patterns/collapsible",
    "./patterns/depends",
    "./patterns/edit-tinymce",
    "./patterns/expandable",
    "./patterns/focus",
    "./patterns/form-state",
    "./patterns/fullcalendar",
    "./patterns/image-crop",
    "./patterns/markdown",  // This must be loaded before injection
    "./patterns/inject",
    "./patterns/menu",
    "./patterns/modal",
    "./patterns/navigation",
    "./patterns/placeholder",
    "./patterns/setclass",
    "./patterns/sortable",
    "./patterns/switch",
    "./patterns/transforms",
    "./patterns/toggle",
    "./patterns/tooltip",
    "./patterns/validate",
    "./patterns/zoom"
], function() { });
<|endoftext|>


<commit_before>/**
 * Created by Ralph Varjabedian.
 * nodetastic is licensed under the [BSD-3 License] http://bitbucket.com/ralphv/nodetastic/raw/master/LICENSE.
 * do not remove this notice.
 */

'use strict';

var logger = require('../logger.js');
var lruCache = require("lru-cache");
var cacheMaxItems = require('../config.js').cacheMaxItems;
var cacheMaxPoolSize = require('../config.js').cacheMaxPoolSize;

//<editor-fold defaultstate="collapsed" desc="built in server side cache service">
function Cache(minutes) {
  this.cache = lruCache({max: cacheEngine.cacheMaxItems, maxAge: minutes * (1000 * 60)});
}
Cache.prototype = {
  getWrapper: function(seed) {
    return new CacheWrapper(this, seed);
  }
};
function CacheWrapper(cache, seed) {
  this.cache = cache.cache;
  this.getSeed = function() { return seed; }
}
CacheWrapper.prototype = {
  set: function(key, value) {
    return this.cache.set(this.key(key), value);
  },
  get: function(key) {
    return this.cache.get(this.key(key));
  },
  has: function(key) {
    return this.cache.has(this.key(key));
  },
  key: function(key) {
    if(Array.isArray(key)) {
      return this.getSeed() + "_" + key.join("&");
    } else {
      return this.getSeed() + key;
    }
  }
};
var cacheEngine = {
  cacheMaxItems: cacheMaxItems,
  poolSize: cacheMaxPoolSize,
  poolArray: [],
  poolHash: {},
  getInjectionFunction: function() {
    var self = this;
    return function(context, param) { return self.getCache(context.req, param, context.className); }
  },
  getCache: function(req, param, className) {
    var metaDataIndex = param.indexOf('$', 1);
    var metaData = param.substring(metaDataIndex + 1);
    return this.getCacheOf(parseInt(metaData)).getWrapper(className);
  },
  getCacheOf: function(minutes) {
    if(this.poolHash["_" + minutes]) {
      return this.poolHash["_" + minutes];
    } else {
      if(this.poolArray.length >= this.poolSize) {
        logger.error("DynamicHttpLayer Pool limit reached");
        return null;
      }
      var newCache = new Cache(minutes);
      this.poolHash["_" + minutes] = newCache;
      this.poolArray.push(newCache);
      return newCache;
    }
  }
};
//</editor-fold>

module.exports = cacheEngine;
<commit_msg>adding samples<commit_after>/**
 * Created by Ralph Varjabedian.
 * nodetastic is licensed under the [BSD-3 License] http://bitbucket.com/ralphv/nodetastic/raw/master/LICENSE.
 * do not remove this notice.
 */

'use strict';

var lruCache = require("lru-cache");
var logger = require('../logger.js');
var cacheMaxItems = require('../config.js').cacheMaxItems;
var cacheMaxPoolSize = require('../config.js').cacheMaxPoolSize;

//<editor-fold defaultstate="collapsed" desc="built in server side cache service">
function Cache(minutes) {
  this.cache = lruCache({max: cacheEngine.cacheMaxItems, maxAge: minutes * (1000 * 60)});
}
Cache.prototype = {
  getWrapper: function(seed) {
    return new CacheWrapper(this, seed);
  }
};
function CacheWrapper(cache, seed) {
  this.cache = cache.cache;
  this.getSeed = function() { return seed; }
}
CacheWrapper.prototype = {
  set: function(key, value) {
    return this.cache.set(this.key(key), value);
  },
  get: function(key) {
    return this.cache.get(this.key(key));
  },
  has: function(key) {
    return this.cache.has(this.key(key));
  },
  key: function(key) {
    if(Array.isArray(key)) {
      return this.getSeed() + "_" + key.join("&");
    } else {
      return this.getSeed() + key;
    }
  }
};
var cacheEngine = {
  cacheMaxItems: cacheMaxItems,
  poolSize: cacheMaxPoolSize,
  poolArray: [],
  poolHash: {},
  getInjectionFunction: function() {
    var self = this;
    return function(context, param) { return self.getCache(context.req, param, context.className); }
  },
  getCache: function(req, param, className) {
    var metaDataIndex = param.indexOf('$', 1);
    var metaData = param.substring(metaDataIndex + 1);
    if (metaDataIndex == -1) {
        metaData = 30; // default 30 minutes
    }
    return this.getCacheOf(parseInt(metaData)).getWrapper(className);
  },
  getCacheOf: function(minutes) {
    if(this.poolHash["_" + minutes]) {
      return this.poolHash["_" + minutes];
    } else {
      if(this.poolArray.length >= this.poolSize) {
        logger.error("DynamicHttpLayer Pool limit reached");
        return null;
      }
      var newCache = new Cache(minutes);
      this.poolHash["_" + minutes] = newCache;
      this.poolArray.push(newCache);
      return newCache;
    }
  }
};
//</editor-fold>

module.exports = cacheEngine;
<|endoftext|>


<commit_before>(function (angular) {
  'use strict'
  // https://github.com/johnpapa/angularjs-styleguide#controllers

  angular
    .module('$1')
    .controller('$2', $2)

  /* @ngInject */
  function $2 ($scope) {
    var vm = this

    activate()

    // -------

    function activate () {

    }

    // deregister event handlers
    $scope.$on('$destroy', function () {})
  }

}(window.angular))
<commit_msg>fix  in ngcontroller<commit_after>(function (angular) {
  'use strict'
  // https://github.com/johnpapa/angularjs-styleguide#controllers

  angular
    .module('$1')
    .controller('$2', $2)

  /* @ngInject */
  function $2 (\$scope) {
    var vm = this

    activate()

    // -------

    function activate () {

    }

    // deregister event handlers
    \$scope.\$on('\$destroy', function () {})
  }

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