<commit_before>'use strict';

  var fs = require('fs');

  var request = require('request');
  var memoryStream = require('memorystream');
  require('./utils');
  var FileInfo = require('./fileinfo');
  var Mime = require('mime');
  var toJSON = require('./tojson')
  var Path = require('path')

  var zipFile = {};
  zipFile.diskcache = null;

  var walk = require('walk');
  var rmdirSync = require('./rmdir')

  // request file from url, with otional jar,
  // then unzip, and then call cb with assetInfo
  zipFile.getAssetInfoUrl = function (handler, url, jar, cb) {

    var params = {};
    params.handler = handler;
    params.cb = cb;
    params.url = url;
    params.jar = jar;
    params.dryrun = true;

    uploadAndUnzip(params);
  }

  zipFile.unzipUrl = function (handler,collectionpath, assetpath,url,jar,target,cb){
    var params = {};
    params.handler = handler;
    params.collectionpath = collectionpath;
    params.assetpath = assetpath;
    params.url = url;
    params.target = target;
    params.dryrun = true;
    params.jar = jar;
    params.cb = cb;

    uploadAndUnzip(params);
  }

  zipFile.unzipFile = function (handler,collectionpath, assetpath,target,cb){

  }

  zipFile.getAssetInfoFile = function (handler, name, filename, jar, cb) {

    var params = {};
    params.handler = handler;
    params.cb = cb;
    params.url = name;
    params.jar = jar;
    params.dryrun = true;
    params.filename = filename;

    uploadAndUnzip(params);
  }

  zipFile.unzipUploadUrl = function (handler, collectionpath, assetpath, url, jar, cb) {

    var params = {};
    params.handler = handler;
    params.cb = cb;
    params.url = url;
    params.jar = jar;

    params.collectionpath = collectionpath;
    params.assetpath = assetpath;

    uploadAndUnzip(params);
  };

  zipFile.unzipUploadFile = function (handler, collectionpath, assetpath, name, filename, jar, cb) {

    var params = {};
    params.handler = handler;
    params.cb = cb;
    params.name = name;
    params.filename = filename;
    params.jar = jar;
    params.collectionpath = collectionpath;
    params.assetpath = assetpath;

    uploadAndUnzip(params);
  };

  // upload does not use handler at all

  zipFile.uploadUrl = function (url, jar, cb) {

    var params = {};

    params.cb = cb;
    params.url = url;
    params.jar = jar;

    params.uploadOnly = true;

    uploadAndUnzip(params);
  };

  zipFile.uploadFile = function (name, filename, jar, cb) {

    var params = {};

    params.cb = cb;
    params.name = name;
    params.filename = filename;
    params.jar = jar;

    params.uploadOnly = true;

    uploadAndUnzip(params);
  };

  var uploadAndUnzip = function (params) {
    if (params.url) {
      if (!zipFile.diskcache) return params.cb('diskcache not set in zipFile');
      zipFile.diskcache.hit(params.url, function (err, entry) {
        if (entry) {
          console.log('zip disk cache HIT!=' + entry.filename);
          getname(entry,params);
          params.donotmove=true;
          unzip(params);
        } else {
          var buffer = new memoryStream(null, {
            readable: false
          });
          buffer.on('error', function (error) {
            params.cb(error);
          });
          buffer.on('end', function () {
            params.req.response.body = this.toBuffer();
            zipFile.diskcache.store(params.url, params.req.response, function (err, entry) {
              if (err)
                return params.cb(err);

              getname(entry,params);
              params.donotmove=true;
              unzip(params);
            });
          });

          // for some reason, request(url, cb) returns an incmplete body
          // but pipe() provides the right body
          // but I need the response headers, so I split this in half
          // and I can get to the header in 'close'
          var options = {
            url: params.url
          };
          if (params.jar) options.jar = params.jar;
          try {
            params.req = request.get(options);
            params.req.pipe(buffer);
          } catch (e) {
            console.log('caught error in uploadAndUnzip for url='+params.url);
            return params.cb(e)
          }
        }
      });
    } else {
      // callers has to set params.name and params.filename
      params.donotmove=false;
      unzip(params);
    }
  };

  var getname = function(resp, params) {

    var name = params.name;
    if (name) return

    var headers = null;

    if (!name) {
      if (resp.headers && resp.headers['content-disposition'])
        headers = resp.headers['content-disposition'];
      if (params.req && params.req.response && params.req.response.headers)
        headers = params.req.response.headers['content-disposition'];
      if (headers) {
        var index = headers.indexOf('filename=');
        name = headers.substring(index + 9);
      }
      if (!name) {
        var contentType = null;
        if (resp.headers && resp.headers['content-type'])
          contentType = resp.headers['content-type'];
        if (!contentType && params.req && params.req.response && params.req.response.headers)
          contentType = params.req.response.headers['content-type'];
        if (contentType) {
          var extension = Mime.extension(contentType);
          name = params.url;
          if (name.contains('?')) name = name.stringBefore('?');
          while (name.contains('/')) name = name.stringAfter('/');
          if (name.contains('.')) name = name.stringBefore('.');
          name += '.' + extension;
        }
      }
      if (!name)
        console.log('cannot find header in unzip/getfilename');
      params.name = name;

      params.filename = resp.filename;
    }
  }

  // unzip a file
  // resp-> filename (input)
  // params.name -> output
  // if params does not have a filename, extract filename from headers
  var unzip = function (params) {

    var counter = 0;

    var there_was_an_error=false;

    var files = []; // retuns an array of fileInfos;

    if (!params.name) return params.cb(new Error('cannot find name in unzip'))

    if (params.uploadOnly) {
       var item = {
            name: params.name,
            path: params.filename
            // size and type will be created by new FileInfo()
        };
        var fileInfo = new FileInfo(item, params.collectionpath, params.assetpath);

        fileInfo.donotmove = params.donotmove;
        return params.cb(undefined, fileInfo);
    }

    var folder = params.handler.req.session.sid;

    var finish = function (err, rest3d_asset) {
      if (there_was_an_error) return;
      if (err) {
        console.log('ERROR IN ZIPFILE FINISH');

        if(folder.indexOf("tmp/")!==-1)rmdirSync(folder);
        params.cb(err);
        counter = -1;
        there_was_an_error=true;
        return;
      }
      if(folder.indexOf("tmp/")!==-1)rmdirSync(folder);
      params.cb(undefined, files);
    };

    if(params.target){
      var folder = params.target;
    }else{
      var folder = 'tmp/'+params.handler.req.session.sid;
    }
    var cmd = 'unzip '+params.filename+' -x Thumbs.db .DS_Store .Trashes __MACOSX/* -d '+folder;
    console.log('exec ['+cmd+']');
    exec(cmd, function(code, output){
      if (code === 9){
         console.log("error in unzip - assuming this is not a zip file");

        var item = {
            name: params.name,
            path: params.filename
            // size and type will be created by new FileInfo()
        };
        var fileInfo = new FileInfo(item, params.collectionpath, params.assetpath);
        //item.fileInfo = fileInfo;
        counter ++;
        //asset = {name:params.name, path:params.filename, type:fileInfo.type};

        fileInfo.donotmove = params.donotmove;
        files.push(fileInfo);

        if (!params.dryrun) {
           fileInfo.upload(params.handler, finish);
        } else
          finish(undefined);
      } else if (code) {
        console.log('Exit code:', code);
        console.log('Program output:', output);
        return finish('unzip exit code ='+code+' output='+output);
      } else {
      // now march the folder structure and upload files to database
        var options = {
          listeners: {
              names: function (root, nodeNamesArray) {
                /*
                nodeNamesArray.sort(function (a, b) {
                  if (a > b) return 1;
                  if (a < b) return -1;
                  return 0;
                });
                */
              }
            , directories: function (root, dirStatsArray, next) {
                // dirStatsArray is an array of `stat` objects with the additional attributes
                // * type
                // * error
                // * name

                next();
              }
            , file: function (root, fileStats, next) {

                  var item = {
                    name: fileStats.name,
                    path: Path.join(root,fileStats.name)
                  };
                  var currentpath = root.stringAfter(folder)+'/'+fileStats.name;
                  if (currentpath[0] ==='/') currentpath = currentpath.substring(1);
                  var fileInfo = new FileInfo(item, params.collectionpath, currentpath);

                  files.push(fileInfo);
                  counter++;
                  if (!params.dryrun) {
                     fileInfo.upload(params.handler, finish);
                  } else
                    //finish(undefined);

                  next();

              }
            , errors: function (root, nodeStatsArray, next) {
                next();
              }
            , end: function(){
              finish(undefined);
            }
          }
        };

        walk.walkSync(folder, options);
      }

    });
    // I could not make the following work with large ZIP files
/*
    var counter = 1; // event 'close' will sent last counter--
    var files=[];

    var there_was_an_error = false;

    var finish = function (err, rest3d_asset) {
      if (there_was_an_error) return;
      if (err) {
        console.log('ERROR IN ZIPFILE FINISH');
        //params.handler.handleError(err);
        params.cb(err);
        counter = -1;
        return;
      }
      counter -= 1;
      if (counter === 0)
        params.cb(undefined, asset);

    };

    var readStream = fs.createReadStream(params.filename);
    fs.createReadStream(params.filename)
     .pipe(zip.Parse({verbose:true}))
     .on('entry', function (entry) {
        console.log('entry ='+entry.path)

        if (entry.type === 'Directory') return; // 'Directory' or 'File'
        var filename = entry.path;
        // entry.size;
        if (filename === "I don't care for that file") {
          entry.autodrain();
        } else {

          var path = filename;
          var currentpath = Path.join(params.name,params.assetpath) || "";
          var index = path.indexOf('/'); // where to cut
          var file = path; // currenly considered item in the path
          var folder = asset; // were we are at in the {asset}

          while (index > 0) {
            file = path.substring(0, index);

            if (currentpath !== '')
              currentpath += '/' + file;
            else
              currentpath = file;

            if (!folder.children) folder.children = [];
            var test = null;
            for (var i = 0; i < folder.children.length; i++) {
              if (folder.children[i].name === file) {
                test = folder.children[i];
                break;
              }
            };
            if (!test) {
              test = {
                name: file,
                type: 'folder',
                path: currentpath
              };
              folder.children.push(test);
            }
            folder = test;
            path = path.substring(index + 1);
            index = path.indexOf('/');
          }
          if (path.length !== 0) {
            var fullpath = currentpath + '/' + path;
            if (currentpath === '') fullpath = path;
            var item = {
              name: path
              //size: entry._header.uncompressed_size,
              //type: Mime.looku
            };

            if (!folder.children) folder.children = [];
            folder.children.push(item);
            if (path.toLowerCase().endsWith('.dae'))
              asset.dae = filename;

            // file -> name, path, optional:size, type, not used: hash, lastModifiedDate)

            var fileInfo = new FileInfo(item, params.collectionpath, currentpath);
            //entry.pipe(fs.createWriteStream('output/path'));
            fileInfo.buffer = new Buffer(entry.size);
            //entry.pipe(fileInfo.buffer);

            var data=[];
            entry
            .on('data',function(chuck){
              data.push(chuck);
            })
            .on('error', function(err){
              var error=new Error('error in reading stream in zipFile')
              console.log(error);
              finish(error)
            })
            .on('finish', function(a){
                console.log('got finish event '+a)
            })
            .on('end',function(){

              fileInfo.buffer = Buffer.concat(data);

              files.push(fileInfo);
              counter++;
              if (!params.dryrun) {
                 fileInfo.upload(params.handler, function(err,rest_asset){
                  if (err) {
                    there_was_an_error=true;
                    params.cb(err);
                  } else {
                    item.fileInfo = fileInfo;
                    finish(undefined);
                  }
                });
              } else
                finish(undefined);
            })
          }
        }
     })
     .on('error', function(err){
        console.log("error in unzip - assuming this is not a zip file");

        var item = {
            name: params.name,
            path: params.filename
            // size and type will be created by new FileInfo()
        };
        var fileInfo = new FileInfo(item, params.collectionpath, params.assetpath);
        item.fileInfo = fileInfo;

        files.push(fileInfo);
        asset = {name:params.name, path:params.filename, type:fileInfo.type};

        fileInfo.donotmove = params.donotmove;

        if (!params.dryrun) {
           fileInfo.upload(params.handler, function(err,rest_asset){
             asset.fileInfo = fileInfo;
             finish(err,rest_asset);
           });
        } else
          finish(undefined);
     })
     .on('close', function(){
        finish(undefined);
     });
*/
  }

  module.exports = zipFile;
<commit_msg>Fix walker v2<commit_after>'use strict';

  var fs = require('fs');

  var request = require('request');
  var memoryStream = require('memorystream');
  require('./utils');
  var FileInfo = require('./fileinfo');
  var Mime = require('mime');
  var toJSON = require('./tojson')
  var Path = require('path')

  var zipFile = {};
  zipFile.diskcache = null;

  var walk = require('walk');
  var rmdirSync = require('./rmdir')

  // request file from url, with otional jar,
  // then unzip, and then call cb with assetInfo
  zipFile.getAssetInfoUrl = function (handler, url, jar, cb) {

    var params = {};
    params.handler = handler;
    params.cb = cb;
    params.url = url;
    params.jar = jar;
    params.dryrun = true;

    uploadAndUnzip(params);
  }

  zipFile.unzipUrl = function (handler,collectionpath, assetpath,url,jar,target,cb){
    var params = {};
    params.handler = handler;
    params.collectionpath = collectionpath;
    params.assetpath = assetpath;
    params.url = url;
    params.target = target;
    params.dryrun = true;
    params.jar = jar;
    params.cb = cb;

    uploadAndUnzip(params);
  }

  zipFile.unzipFile = function (handler,collectionpath, assetpath,target,cb){

  }

  zipFile.getAssetInfoFile = function (handler, name, filename, jar, cb) {

    var params = {};
    params.handler = handler;
    params.cb = cb;
    params.url = name;
    params.jar = jar;
    params.dryrun = true;
    params.filename = filename;

    uploadAndUnzip(params);
  }

  zipFile.unzipUploadUrl = function (handler, collectionpath, assetpath, url, jar, cb) {

    var params = {};
    params.handler = handler;
    params.cb = cb;
    params.url = url;
    params.jar = jar;

    params.collectionpath = collectionpath;
    params.assetpath = assetpath;

    uploadAndUnzip(params);
  };

  zipFile.unzipUploadFile = function (handler, collectionpath, assetpath, name, filename, jar, cb) {

    var params = {};
    params.handler = handler;
    params.cb = cb;
    params.name = name;
    params.filename = filename;
    params.jar = jar;
    params.collectionpath = collectionpath;
    params.assetpath = assetpath;

    uploadAndUnzip(params);
  };

  // upload does not use handler at all

  zipFile.uploadUrl = function (url, jar, cb) {

    var params = {};

    params.cb = cb;
    params.url = url;
    params.jar = jar;

    params.uploadOnly = true;

    uploadAndUnzip(params);
  };

  zipFile.uploadFile = function (name, filename, jar, cb) {

    var params = {};

    params.cb = cb;
    params.name = name;
    params.filename = filename;
    params.jar = jar;

    params.uploadOnly = true;

    uploadAndUnzip(params);
  };

  var uploadAndUnzip = function (params) {
    if (params.url) {
      if (!zipFile.diskcache) return params.cb('diskcache not set in zipFile');
      zipFile.diskcache.hit(params.url, function (err, entry) {
        if (entry) {
          console.log('zip disk cache HIT!=' + entry.filename);
          getname(entry,params);
          params.donotmove=true;
          unzip(params);
        } else {
          var buffer = new memoryStream(null, {
            readable: false
          });
          buffer.on('error', function (error) {
            params.cb(error);
          });
          buffer.on('end', function () {
            params.req.response.body = this.toBuffer();
            zipFile.diskcache.store(params.url, params.req.response, function (err, entry) {
              if (err)
                return params.cb(err);

              getname(entry,params);
              params.donotmove=true;
              unzip(params);
            });
          });

          // for some reason, request(url, cb) returns an incmplete body
          // but pipe() provides the right body
          // but I need the response headers, so I split this in half
          // and I can get to the header in 'close'
          var options = {
            url: params.url
          };
          if (params.jar) options.jar = params.jar;
          try {
            params.req = request.get(options);
            params.req.pipe(buffer);
          } catch (e) {
            console.log('caught error in uploadAndUnzip for url='+params.url);
            return params.cb(e)
          }
        }
      });
    } else {
      // callers has to set params.name and params.filename
      params.donotmove=false;
      unzip(params);
    }
  };

  var getname = function(resp, params) {

    var name = params.name;
    if (name) return

    var headers = null;

    if (!name) {
      if (resp.headers && resp.headers['content-disposition'])
        headers = resp.headers['content-disposition'];
      if (params.req && params.req.response && params.req.response.headers)
        headers = params.req.response.headers['content-disposition'];
      if (headers) {
        var index = headers.indexOf('filename=');
        name = headers.substring(index + 9);
      }
      if (!name) {
        var contentType = null;
        if (resp.headers && resp.headers['content-type'])
          contentType = resp.headers['content-type'];
        if (!contentType && params.req && params.req.response && params.req.response.headers)
          contentType = params.req.response.headers['content-type'];
        if (contentType) {
          var extension = Mime.extension(contentType);
          name = params.url;
          if (name.contains('?')) name = name.stringBefore('?');
          while (name.contains('/')) name = name.stringAfter('/');
          if (name.contains('.')) name = name.stringBefore('.');
          name += '.' + extension;
        }
      }
      if (!name)
        console.log('cannot find header in unzip/getfilename');
      params.name = name;

      params.filename = resp.filename;
    }
  }

  // unzip a file
  // resp-> filename (input)
  // params.name -> output
  // if params does not have a filename, extract filename from headers
  var unzip = function (params) {

    var counter = 0;

    var there_was_an_error=false;

    var files = []; // retuns an array of fileInfos;

    if (!params.name) return params.cb(new Error('cannot find name in unzip'))

    if (params.uploadOnly) {
       var item = {
            name: params.name,
            path: params.filename
            // size and type will be created by new FileInfo()
        };
        var fileInfo = new FileInfo(item, params.collectionpath, params.assetpath);

        fileInfo.donotmove = params.donotmove;
        return params.cb(undefined, fileInfo);
    }

    var folder = params.handler.req.session.sid;

    var finish = function (err, rest3d_asset) {
      if (there_was_an_error) return;
      if (err) {
        console.log('ERROR IN ZIPFILE FINISH');

        if(folder.indexOf("tmp/")!==-1)rmdirSync(folder);
        params.cb(err);
        counter = -1;
        there_was_an_error=true;
        return;
      }
      if(folder.indexOf("tmp/")!==-1)rmdirSync(folder);
      params.cb(undefined, files);
    };

    if(params.target){
      var folder = params.target;
    }else{
      var folder = 'tmp/'+params.handler.req.session.sid;
    }
    var cmd = 'unzip '+params.filename+' -x Thumbs.db .DS_Store .Trashes __MACOSX/* -d '+folder;
    console.log('exec ['+cmd+']');
    exec(cmd, function(code, output){
      if (code === 9){
         console.log("error in unzip - assuming this is not a zip file");

        var item = {
            name: params.name,
            path: params.filename
            // size and type will be created by new FileInfo()
        };
        var fileInfo = new FileInfo(item, params.collectionpath, params.assetpath);
        //item.fileInfo = fileInfo;
        counter ++;
        //asset = {name:params.name, path:params.filename, type:fileInfo.type};

        fileInfo.donotmove = params.donotmove;
        files.push(fileInfo);

        if (!params.dryrun) {
           fileInfo.upload(params.handler, finish);
        } else
          finish(undefined);
      } else if (code) {
        console.log('Exit code:', code);
        console.log('Program output:', output);
        return finish('unzip exit code ='+code+' output='+output);
      } else {
      // now march the folder structure and upload files to database
        var options = {
          listeners: {
              names: function (root, nodeNamesArray) {
                /*
                nodeNamesArray.sort(function (a, b) {
                  if (a > b) return 1;
                  if (a < b) return -1;
                  return 0;
                });
                */
              }
            , directories: function (root, dirStatsArray, next) {
                // dirStatsArray is an array of `stat` objects with the additional attributes
                // * type
                // * error
                // * name

                next();
              }
            , file: function (root, fileStats, next) {

                  var item = {
                    name: fileStats.name,
                    path: Path.join(root,fileStats.name)
                  };
                  var assetpath = root.split(folder).join("");
                  var fileInfo = new FileInfo(item, params.collectionpath,assetpath);

                  files.push(fileInfo);
                  counter++;
                  if (!params.dryrun) {
                     fileInfo.upload(params.handler, finish);
                  } else
                    //finish(undefined);

                  next();

              }
            , errors: function (root, nodeStatsArray, next) {
                next();
              }
            , end: function(){
              finish(undefined);
            }
          }
        };

        walk.walkSync(folder, options);
      }

    });
    // I could not make the following work with large ZIP files
/*
    var counter = 1; // event 'close' will sent last counter--
    var files=[];

    var there_was_an_error = false;

    var finish = function (err, rest3d_asset) {
      if (there_was_an_error) return;
      if (err) {
        console.log('ERROR IN ZIPFILE FINISH');
        //params.handler.handleError(err);
        params.cb(err);
        counter = -1;
        return;
      }
      counter -= 1;
      if (counter === 0)
        params.cb(undefined, asset);

    };

    var readStream = fs.createReadStream(params.filename);
    fs.createReadStream(params.filename)
     .pipe(zip.Parse({verbose:true}))
     .on('entry', function (entry) {
        console.log('entry ='+entry.path)

        if (entry.type === 'Directory') return; // 'Directory' or 'File'
        var filename = entry.path;
        // entry.size;
        if (filename === "I don't care for that file") {
          entry.autodrain();
        } else {

          var path = filename;
          var currentpath = Path.join(params.name,params.assetpath) || "";
          var index = path.indexOf('/'); // where to cut
          var file = path; // currenly considered item in the path
          var folder = asset; // were we are at in the {asset}

          while (index > 0) {
            file = path.substring(0, index);

            if (currentpath !== '')
              currentpath += '/' + file;
            else
              currentpath = file;

            if (!folder.children) folder.children = [];
            var test = null;
            for (var i = 0; i < folder.children.length; i++) {
              if (folder.children[i].name === file) {
                test = folder.children[i];
                break;
              }
            };
            if (!test) {
              test = {
                name: file,
                type: 'folder',
                path: currentpath
              };
              folder.children.push(test);
            }
            folder = test;
            path = path.substring(index + 1);
            index = path.indexOf('/');
          }
          if (path.length !== 0) {
            var fullpath = currentpath + '/' + path;
            if (currentpath === '') fullpath = path;
            var item = {
              name: path
              //size: entry._header.uncompressed_size,
              //type: Mime.looku
            };

            if (!folder.children) folder.children = [];
            folder.children.push(item);
            if (path.toLowerCase().endsWith('.dae'))
              asset.dae = filename;

            // file -> name, path, optional:size, type, not used: hash, lastModifiedDate)

            var fileInfo = new FileInfo(item, params.collectionpath, currentpath);
            //entry.pipe(fs.createWriteStream('output/path'));
            fileInfo.buffer = new Buffer(entry.size);
            //entry.pipe(fileInfo.buffer);

            var data=[];
            entry
            .on('data',function(chuck){
              data.push(chuck);
            })
            .on('error', function(err){
              var error=new Error('error in reading stream in zipFile')
              console.log(error);
              finish(error)
            })
            .on('finish', function(a){
                console.log('got finish event '+a)
            })
            .on('end',function(){

              fileInfo.buffer = Buffer.concat(data);

              files.push(fileInfo);
              counter++;
              if (!params.dryrun) {
                 fileInfo.upload(params.handler, function(err,rest_asset){
                  if (err) {
                    there_was_an_error=true;
                    params.cb(err);
                  } else {
                    item.fileInfo = fileInfo;
                    finish(undefined);
                  }
                });
              } else
                finish(undefined);
            })
          }
        }
     })
     .on('error', function(err){
        console.log("error in unzip - assuming this is not a zip file");

        var item = {
            name: params.name,
            path: params.filename
            // size and type will be created by new FileInfo()
        };
        var fileInfo = new FileInfo(item, params.collectionpath, params.assetpath);
        item.fileInfo = fileInfo;

        files.push(fileInfo);
        asset = {name:params.name, path:params.filename, type:fileInfo.type};

        fileInfo.donotmove = params.donotmove;

        if (!params.dryrun) {
           fileInfo.upload(params.handler, function(err,rest_asset){
             asset.fileInfo = fileInfo;
             finish(err,rest_asset);
           });
        } else
          finish(undefined);
     })
     .on('close', function(){
        finish(undefined);
     });
*/
  }

  module.exports = zipFile;
<|endoftext|>


<commit_before>import supertest from 'supertest';
import app from '../index';

const request = supertest(app);

describe('PostIt Tests', () => {
  describe('Authentication routes test', () => {
    it('ensures proper response for successful user sign in', () => {

    });
    it('ensures proper response for incorrect auth details', () => {

    });
    it('ensures proper response for successful user sign up', () => {

    });
    it('ensures proper response for sign up with incorrect data', () => {

    });
  });
  describe('Group CRUD operation routes', () => {
    it('ensure proper response when group is created successfully', () => {

    });
    it('ensures proper response when messages are posted successfully', () => {

    });
    it('ensures all messages for a particular group can be read successfully', () => {

    });
    it('ensures all members of a particular group can be read successfully', () => {

    });
  });
});
<commit_msg>[fix] Remove buggy code from test suite<commit_after>import supertest from 'supertest';
import app from '../index';

describe('PostIt Tests', () => {
  describe('Authentication routes test', () => {
    it('ensures proper response for successful user sign in', (done) => {

    });
    it('ensures proper response for incorrect auth details', (done) => {

    });
    it('ensures proper response for successful user sign up', (done) => {

    });
    it('ensures proper response for sign up with incorrect data', (done) => {

    });
  });
  describe('Group CRUD operation routes', () => {
    it('ensure proper response when group is created successfully', (done) => {

    });
    it('ensures proper response when messages are posted successfully', (done) => {

    });
    it('ensures all messages for a particular group can be read successfully', (done) => {

    });
    it('ensures all members of a particular group can be read successfully', (done) => {

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


<commit_before>define(function (require) {
  "use strict";

  var React = require('react'),
      Router = require('react-router'),
      stores = require('stores'),
      actions = require('actions'),
      ImageRequestActions = require('actions/ImageRequestActions');

  return React.createClass({

    mixins: [Router.State],

    getInitialState: function(){
      return{
        response: ""
      }
    },

    handleResponseChange: function (event) {
      var response = event.target.value;
      if (response) this.setState({response: response});
    },

    approve: function(){

      // request is guaranteed to exist in our store, since we needed it to render this component
      var request = stores.ImageRequestStore.get(this.getParams().imageRequestId),
      status = stores.StatusStore.findOne({name: "approved"});

      ImageRequestActions.update({
        request: request,
        response: this.state.response,
        status: status.id
      });

    },

    deny: function(){

      var request = stores.ImageRequestStore.get(this.getParams().imageRequestId),
      status = stores.StatusStore.findOne({name: "rejected"});

      ImageRequestActions.update({
        request: request,
        response: this.state.response,
        status: status.id
      });

    },

    resubmit: function(){

      var request = stores.ImageRequestStore.get(this.getParams().imageRequestId),
      status = stores.StatusStore.findOne({name: "pending"});

      ImageRequestActions.update({
        request: request,
        response: this.state.response,
        status: status.id
      });

    },

    render: function () {
      var requestId = (this.getParams().imageRequestId);

      var request = stores.ImageRequestStore.get(requestId);

      if(!request){
        return

      }

      // This is done to ensure boolean values are displayed as strings

      var allowImaging = "false";
      var forked = "false";

      if(request.get('new_version_forked')){
        forked = "true";
      }

      if(request.get('new_version_allow_imaging')){
        allowImaging = "true";
      }

      var instance = request.get('instance');

      return(

Image Request #{request.get('id')}

Installed software: {request.get('installed_software')}

Instance:

ID: {instance.id}

Name: {instance.name}

iPlant sys files: {request.get('iplant_sys_files')}

New application description: {request.get('new_application_description')}

New application name: {request.get('new_application_name')}

New machine owner: {request.get('new_machine_owner').username}

New provider: {request.get('new_machine_provider').name}

Allow imaging: {allowImaging}

Forked: {forked}

New version licenses: {request.get('new_version_licenses')}

New version memory min: {request.get('new_version_memory_min')}

New version storage min: {request.get('new_version_storage_min')}

New version name: {request.get('new_version_name')}

New version scripts: {request.get('new_version_scripts')}

New version tags: {request.get('new_version_tags')}

Request state: {request.get('old_status')}

Status: {request.get('status').name}

          <textarea type="text" form="admin" value={this.state.value} cols="60" rows="8"
                      onChange={this.handleResponseChange}/>
          <button onClick={this.approve} type="button" className="btn btn-default btn-sm">Approve</button>
          <button onClick={this.deny} type="button" className="btn btn-default btn-sm">Deny</button>
          <button onClick={this.resubmit} type="button" className="btn btn-default btn-sm">Re-Submit</button>

      );
    }
  });
});

<commit_msg>show cpu_min, not storage_min<commit_after>define(function (require) {
  "use strict";

  var React = require('react'),
      Router = require('react-router'),
      stores = require('stores'),
      actions = require('actions'),
      ImageRequestActions = require('actions/ImageRequestActions');

  return React.createClass({

    mixins: [Router.State],

    getInitialState: function(){
      return{
        response: ""
      }
    },

    handleResponseChange: function (event) {
      var response = event.target.value;
      if (response) this.setState({response: response});
    },

    approve: function(){

      // request is guaranteed to exist in our store, since we needed it to render this component
      var request = stores.ImageRequestStore.get(this.getParams().imageRequestId),
      status = stores.StatusStore.findOne({name: "approved"});

      ImageRequestActions.update({
        request: request,
        response: this.state.response,
        status: status.id
      });

    },

    deny: function(){

      var request = stores.ImageRequestStore.get(this.getParams().imageRequestId),
      status = stores.StatusStore.findOne({name: "rejected"});

      ImageRequestActions.update({
        request: request,
        response: this.state.response,
        status: status.id
      });

    },

    resubmit: function(){

      var request = stores.ImageRequestStore.get(this.getParams().imageRequestId),
      status = stores.StatusStore.findOne({name: "pending"});

      ImageRequestActions.update({
        request: request,
        response: this.state.response,
        status: status.id
      });

    },

    render: function () {
      var requestId = (this.getParams().imageRequestId);

      var request = stores.ImageRequestStore.get(requestId);

      if(!request){
        return

      }

      // This is done to ensure boolean values are displayed as strings

      var allowImaging = "false";
      var forked = "false";

      if(request.get('new_version_forked')){
        forked = "true";
      }

      if(request.get('new_version_allow_imaging')){
        allowImaging = "true";
      }

      var instance = request.get('instance');

      return(

Image Request #{request.get('id')}

Installed software: {request.get('installed_software')}

Instance:

ID: {instance.id}

Name: {instance.name}

iPlant sys files: {request.get('iplant_sys_files')}

New application description: {request.get('new_application_description')}

New application name: {request.get('new_application_name')}

New machine owner: {request.get('new_machine_owner').username}

New provider: {request.get('new_machine_provider').name}

Allow imaging: {allowImaging}

Forked: {forked}

New version licenses: {request.get('new_version_licenses')}

New version memory min: {request.get('new_version_memory_min')}

New version cpu min: {request.get('new_version_cpu_min')}

New version name: {request.get('new_version_name')}

New version scripts: {request.get('new_version_scripts')}

New version tags: {request.get('new_version_tags')}

Request state: {request.get('old_status')}

Status: {request.get('status').name}

          <textarea type="text" form="admin" value={this.state.value} cols="60" rows="8"
                      onChange={this.handleResponseChange}/>
          <button onClick={this.approve} type="button" className="btn btn-default btn-sm">Approve</button>
          <button onClick={this.deny} type="button" className="btn btn-default btn-sm">Deny</button>
          <button onClick={this.resubmit} type="button" className="btn btn-default btn-sm">Re-Submit</button>

      );
    }
  });
});

<|endoftext|>


<commit_before>// ==UserScript==
// @name        SubScene Filter
// @namespace   www.subscene.com
// @description Add filter to subscene searches
// @include     https://*subscene.com/subtitles/*
// @exclude     https://*subscene.com/subtitles/title?q*
// @exclude     https://*subscene.com/subtitles/*/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @version     1
// @grant       none
// ==/UserScript==

$("#flagWrapper").after(
  '<div>\
    <label>\
      <input type="checkbox" id="langCheckBox">\
      English Only\
    </label>\
    <input id="myFilterQuery" type="text">\
    <button id="filterButton" type="button">Filter</button>\
    <button id="clearButton" type="button">Clear</button>\
  </div>'
);
var rows = $("tr").filter(function(ix,el) {
  return $(this).find("span.l").text();
});
$("#filterButton").click(function() {
  // Get the regex to search for
  var isValid = true;
  try {
    var inputRegex = new RegExp($("#myFilterQuery").val());
  } catch(e) {
    isValid = false;
  }

  // Get the status of the checkbox
  filter_lang = $("#langCheckBox").prop('checked');

  rows.hide()
    .filter(function(ix,el) {
      if(!filter_lang) {
        return true;
      }
      return $(this).find("span.l").text().trim() == "English";
    })
    .filter(function(ix,el) {
      if(!isValid) {
        return true;
      }
      return $(this).find("td.a1 a span:nth-child(2)").text().trim().match(inputRegex);
    })
    .show();
});
$("#clearButton").click(function() {
  rows.show();
  // restore the filters to the empy state
  $("#langCheckBox").prop('checked',false);
  $("#myFilterQuery").val("");
});
<commit_msg>Add case insensitive option<commit_after>// ==UserScript==
// @name        SubScene Filter
// @namespace   www.subscene.com
// @description Add filter to subscene searches
// @include     https://*subscene.com/subtitles/*
// @exclude     https://*subscene.com/subtitles/title?q*
// @exclude     https://*subscene.com/subtitles/*/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @version     1
// @grant       none
// ==/UserScript==

$("#flagWrapper").after(
  '<div>\
    <label>\
      <input type="checkbox" id="langCheckBox">\
      English Only\
    </label>\
    <input id="myFilterQuery" type="text">\
    <label>\
      <input type="checkbox" id="caseInsensitiveBox">\
      Case Insensitive\
    </label>\
    <button id="filterButton" type="button">Filter</button>\
    <button id="clearButton" type="button">Clear</button>\
  </div>'
);
var rows = $("tr").filter(function(ix,el) {
  return $(this).find("span.l").text();
});
$("#filterButton").click(function() {
  // Get the regex to search for
  var isValid = true;
  try {
    if($("#caseInsensitiveBox").prop('checked')) {
      var inputRegex = new RegExp($("#myFilterQuery").val(),"i");
    } else {
      var inputRegex = new RegExp($("#myFilterQuery").val());
    }
  } catch(e) {
    isValid = false;
  }

  // Get the status of the checkbox
  filter_lang = $("#langCheckBox").prop('checked');

  rows.hide()
    .filter(function(ix,el) {
      if(!filter_lang) {
        return true;
      }
      return $(this).find("span.l").text().trim() == "English";
    })
    .filter(function(ix,el) {
      if(!isValid) {
        return true;
      }
      return $(this).find("td.a1 a span:nth-child(2)").text().trim().match(inputRegex);
    })
    .show();
});
$("#clearButton").click(function() {
  rows.show();
  // restore the filters to the empy state
  $("#langCheckBox").prop('checked',false);
  $("#caseInsensitiveBox").prop('checked',false);
  $("#myFilterQuery").val("");
});
<|endoftext|>


<commit_before>'use strict';

viewModel.TLPlots = new Object();
var tlp = viewModel.TLPlots;

vm.currentMenu('TrendLinePlots');
vm.currentTitle('TrendLinePlots');
vm.breadcrumb([ {
    title: 'Analysis Tool Box',
    href: '#'
}, {
    title: 'Trend Line Plots',
    href: "#"//viewModel.appName + 'page/analytictrendlineplots'
}]);

tlp.turbineList = ko.observableArray([]);

tlp.turbine = ko.observableArray([]);
tlp.compTemp = ko.observableArray([
    { "value": 2, "text": "Ambient Temp", "colname": "temp_outdoor" },
    { "value": 5, "text": "Temp_GearBox_IMS_NDE", "colname": "temp_gearbox_ims_nde" },
    { "value": 5, "text": "Temp_GearBox_HSS_NDE", "colname": "temp_gearbox_hss_nde"  },
    { "value": 5, "text": "Temp_G1L1", "colname": "temp_g1l1"  },
    { "value": 5, "text": "Temp_G1L2", "colname": "temp_g1l2"  },
    { "value": 5, "text": "Temp_G1L3", "colname": "temp_g1l3"  },
    { "value": 5, "text": "Temp_GearBox_HSS_DE", "colname": "temp_gearbox_hss_de"  },
    { "value": 5, "text": "Temp_GearOilSump", "colname": "temp_gearoilsump"  },
    { "value": 5, "text": "Temp_GeneratorBearing_DE", "colname": "temp_generatorbearing_de"  },
    { "value": 5, "text": "Temp_GeneratorBearing_NDE", "colname": "temp_generatorbearing_nde"  },
    { "value": 5, "text": "Temp_MainBearing", "colname": "temp_mainbearing"  },
    { "value": 5, "text": "Temp_GearBox_IMS_DE", "colname": "temp_gearbox_ims_de"  },
    { "value": 5, "text": "Converter-1,2 temp", "colname": ""  },
    { "value": 5, "text": "Nacelle Temp", "colname": "temp_nacelle"  },
]);

tlp.deviation= ko.observable(2);
tlp.deviationList = ko.observableArray([1,2,3,4,5]);
tlp.isDeviation = ko.observable(false);
tlp.compTempVal = ko.observable("2");

tlp.initChart = function() {
    app.loading(true);

    app.ajaxPost(viewModel.appName + "/trendlineplots/getscadaoemavaildate", {}, function(res) {
        if (!app.isFine(res)) {
            return;
        }

        //Scada Data
        if (res.data.ScadaOemAvailDate.length == 0) {
            res.data.ScadaOemAvailDate = [];
        } else {
            if (res.data.ScadaOemAvailDate.length > 0) {
                var minDatetemp = new Date(res.data.ScadaOemAvailDate[0]);
                var maxDatetemp = new Date(res.data.ScadaOemAvailDate[1]);
                $('#availabledatestarttlp').html(kendo.toString(moment.utc(minDatetemp).format('DD-MMMM-YYYY')));
                $('#availabledateendtlp').html(kendo.toString(moment.utc(maxDatetemp).format('DD-MMMM-YYYY')));
            }
        }
    });

    var compTemp =  $('#compTemp').data('kendoDropDownList').text()
    var ddldeviation = $('#ddldeviation').data('kendoDropDownList').value()
    var colnameTemp = _.find(tlp.compTemp(), function(num){ return num.text == compTemp; }).colname;
    var turb = $("#turbineList").data("kendoMultiSelect").value()[0] == "All Turbine" ? [] : $("#turbineList").data("kendoMultiSelect").value()
    var param = {
        period: fa.period,
        dateStart: fa.dateStart,
        dateEnd: fa.dateEnd,
        turbine: turb, // $("#turbineList").data("kendoMultiSelect").value(),
        project: fa.project,
        colname: colnameTemp,
        deviationstatus:tlp.isDeviation(), // Param from checkbox
        deviation: parseFloat(ddldeviation)// Param from Dropdown
    };

    var link = "trendlineplots/getlist"

    toolkit.ajaxPost(viewModel.appName + link, param, function(res) {
        if (!app.isFine(res)) {
            app.loading(false);
            return;
        }

        var datatlp = res.data.Data;
        var categories = res.data.Categories;
        var catTitle = res.data.CatTitle;
        var minValue = res.data.Min;
        var maxValue = res.data.Max;

        datatlp.forEach( function(data, idxTlp) {
            if(data.data != undefined && data.data != null) {
                data.data.forEach( function(element, idxData) {
                    if(element == -99999.99999) {
                        datatlp[idxTlp].data[idxData] = null;
                    }
                });
            }
        });

        localStorage.setItem("datatlp", JSON.stringify(datatlp));

        $('#charttlp').html("");

        $("#charttlp").kendoChart({
            pdf: {
                fileName: "DetailPowerCurve.pdf",
            },
            theme: "flat",
            // renderAs: "canvas",
            title: {
                text: "Trend Line Plots | Project : "+fa.project.substring(0,fa.project.indexOf("("))+""+$(".date-info").text(),
                visible: false,
                font: '12px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif'
            },
            legend: {
                position: "bottom",
                visible: false,
            },
            chartArea: {
                height: 400,
            },
            seriesDefaults: {
                type: "line",
                style: "smooth",
                dashType: "longDash",
                markers: {
                    visible: false,
                    size: 4,
                },
            },
            // seriesColors: colorField,
            series: datatlp,
            valueAxis: {
                name: compTemp,
                title: {
                    text: "Temperature",//compTemp,
                    visible: true,
                    font: '14px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif'
                },
                labels: {
                    font: '12px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif'
                },
                line: {
                    visible: false
                },
                axisCrossingValue: -10,
                majorGridLines: {
                    visible: true,
                    color: "#eee",
                    width: 0.8,
                },
                // majorUnit: 0.5,
                min: minValue,
                max: maxValue,
            },
            categoryAxis: {
                categories: categories,
                majorGridLines: {
                    visible: false
                },
                title: {
                    text: catTitle,//"Time",
                    font: '14px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif'
                },
                majorTickType: "none",
            },
            tooltip: {
                visible: true,
                format: "{0:n1}",
                background: "rgb(255,255,255, 0.9)",
                shared: true,
                color: "#58666e",
                font: 'Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
                border: {
                    color: "#eee",
                    width: "2px",
                },
            }
            // pannable: true,
            // zoomable: true
        });

        app.loading(false);
        $("#charttlp").data("kendoChart").refresh();

        tlp.InitRightTurbineList();

    });
}

tlp.InitRightTurbineList = function(){
    tlp.turbineList([]);

    var dtTurbines = JSON.parse(localStorage.getItem("datatlp"));

    if (dtTurbines.length > 1) {
        $("#showHideChk").html('' +
            '<input type="checkbox" id="showHideAll" checked onclick="tlp.showHideAllLegend(this)" >' +
            '' +
            'Select All' +
            '');
    } else {
        $("#showHideChk").html("");
    }

    $("#right-turbine-list").html("");
    $.each(dtTurbines, function(idx, val) {
        if(val.idxseries > 0){

            if(val.data == undefined || val.data == ""){
                $("#right-turbine-list").append('
' +
                '<button class="btn btn-default btn-sm turbine-chk" type="button" disabled="disabled" onclick="tlp.showHideLegend(' + val.idxseries + ')" style="border-color:#a0a0a0;background-color:#a0a0a0"></button>' +
                '<input class="chk-option" type="checkbox" name="' + val.name + '" checked id="disabled-' + val.idxseries + '" hidden disabled="disabled">' +
                '<button class="btn btn-default btn-sm turbine-btn wbtn" type="button" disabled="disabled" onclick="tlp.showHideLegend(' + val.idxseries  + ')">' + val.name + '</button>' +
                '
');
            }else{
                $("#right-turbine-list").append('
' +
                '<button class="btn btn-default btn-sm turbine-chk" type="button" onclick="tlp.showHideLegend(' + val.idxseries + ')" style="border-color:' + val.color + ';background-color:' + val.color + '"></button>' +
                '<input class="chk-option" type="checkbox" name="' + val.name + '" checked id="chk-' + val.idxseries + '" hidden>' +
                '<button class="btn btn-default btn-sm turbine-btn wbtn" type="button" onclick="tlp.showHideLegend(' + val.idxseries  + ')">' + val.name + '</button>' +
                '
');
            }
        }
    });
}

tlp.showHideAllLegend = function(e){
    var dtTurbines = JSON.parse(localStorage.getItem("datatlp"));

    if (e.checked == true) {
        $('.fa-check').css("visibility", 'visible');
        $.each(dtTurbines, function(i, val) {
            if(val.idxseries > 0){
                $("#charttlp").data("kendoChart").options.series[val.idxseries].visible = true;
            }
        });
        $('#labelShowHide b').text('Select All');
    } else {
        $.each(dtTurbines, function(i, val) {
            if(val.idxseries > 0){
                $("#charttlp").data("kendoChart").options.series[val.idxseries].visible = false;
            }
        });
        $('.fa-check').css("visibility", 'hidden');
        $('#labelShowHide b').text('Select All');
    }
    $('.chk-option').not(e).prop('checked', e.checked);
    $("#charttlp").data("kendoChart").redraw();
}
tlp.showHideLegend = function(idx){

    $('#chk-' + idx).trigger('click');
    var chart = $("#charttlp").data("kendoChart");

    if ($('input[id*=chk-][type=checkbox]:checked').length == $('input[id*=chk-][type=checkbox]').length) {
        $('#showHideAll').prop('checked', true);
    } else {
        $('#showHideAll').prop('checked', false);
    }

    // var idxHide = idx+1
    // console.log(idxHide)
    if ($('#chk-' + idx).is(':checked')) {
        $('#icon-' + idx).css("visibility", "visible");
    } else {
        $('#icon-' + idx).css("visibility", "hidden");
    }
    // if (idx == $('input[id*=chk-][type=checkbox]').length) {
    //     idx == 0
    // }

    chart._legendItemClick(idx);
}

$(document).ready(function() {
    setTimeout(function() {
        fa.LoadData();
        tlp.initChart();
    }, 300);

    $('#btnRefresh').on('click', function() {
        setTimeout(function() {
            tlp.initChart();
        }, 300);
    });

     $('#compTemp').on("change", function() {
        setTimeout(function() {
            tlp.initChart();
        }, 300);
    });

});<commit_msg>bug fixing for empty data<commit_after>'use strict';

viewModel.TLPlots = new Object();
var tlp = viewModel.TLPlots;

vm.currentMenu('TrendLinePlots');
vm.currentTitle('TrendLinePlots');
vm.breadcrumb([ {
    title: 'Analysis Tool Box',
    href: '#'
}, {
    title: 'Trend Line Plots',
    href: "#"//viewModel.appName + 'page/analytictrendlineplots'
}]);

tlp.turbineList = ko.observableArray([]);

tlp.turbine = ko.observableArray([]);
tlp.compTemp = ko.observableArray([
    { "value": 2, "text": "Ambient Temp", "colname": "temp_outdoor" },
    { "value": 5, "text": "Temp_GearBox_IMS_NDE", "colname": "temp_gearbox_ims_nde" },
    { "value": 5, "text": "Temp_GearBox_HSS_NDE", "colname": "temp_gearbox_hss_nde"  },
    { "value": 5, "text": "Temp_G1L1", "colname": "temp_g1l1"  },
    { "value": 5, "text": "Temp_G1L2", "colname": "temp_g1l2"  },
    { "value": 5, "text": "Temp_G1L3", "colname": "temp_g1l3"  },
    { "value": 5, "text": "Temp_GearBox_HSS_DE", "colname": "temp_gearbox_hss_de"  },
    { "value": 5, "text": "Temp_GearOilSump", "colname": "temp_gearoilsump"  },
    { "value": 5, "text": "Temp_GeneratorBearing_DE", "colname": "temp_generatorbearing_de"  },
    { "value": 5, "text": "Temp_GeneratorBearing_NDE", "colname": "temp_generatorbearing_nde"  },
    { "value": 5, "text": "Temp_MainBearing", "colname": "temp_mainbearing"  },
    { "value": 5, "text": "Temp_GearBox_IMS_DE", "colname": "temp_gearbox_ims_de"  },
    { "value": 5, "text": "Converter-1,2 temp", "colname": ""  },
    { "value": 5, "text": "Nacelle Temp", "colname": "temp_nacelle"  },
]);

tlp.deviation= ko.observable(2);
tlp.deviationList = ko.observableArray([1,2,3,4,5]);
tlp.isDeviation = ko.observable(false);
tlp.compTempVal = ko.observable("2");

tlp.initChart = function() {
    app.loading(true);

    app.ajaxPost(viewModel.appName + "/trendlineplots/getscadaoemavaildate", {}, function(res) {
        if (!app.isFine(res)) {
            return;
        }

        //Scada Data
        if (res.data.ScadaOemAvailDate.length == 0) {
            res.data.ScadaOemAvailDate = [];
        } else {
            if (res.data.ScadaOemAvailDate.length > 0) {
                var minDatetemp = new Date(res.data.ScadaOemAvailDate[0]);
                var maxDatetemp = new Date(res.data.ScadaOemAvailDate[1]);
                $('#availabledatestarttlp').html(kendo.toString(moment.utc(minDatetemp).format('DD-MMMM-YYYY')));
                $('#availabledateendtlp').html(kendo.toString(moment.utc(maxDatetemp).format('DD-MMMM-YYYY')));
            }
        }
    });

    var compTemp =  $('#compTemp').data('kendoDropDownList').text()
    var ddldeviation = $('#ddldeviation').data('kendoDropDownList').value()
    var colnameTemp = _.find(tlp.compTemp(), function(num){ return num.text == compTemp; }).colname;
    var turb = $("#turbineList").data("kendoMultiSelect").value()[0] == "All Turbine" ? [] : $("#turbineList").data("kendoMultiSelect").value()
    var param = {
        period: fa.period,
        dateStart: fa.dateStart,
        dateEnd: fa.dateEnd,
        turbine: turb, // $("#turbineList").data("kendoMultiSelect").value(),
        project: fa.project,
        colname: colnameTemp,
        deviationstatus:tlp.isDeviation(), // Param from checkbox
        deviation: parseFloat(ddldeviation)// Param from Dropdown
    };

    var link = "trendlineplots/getlist"

    toolkit.ajaxPost(viewModel.appName + link, param, function(res) {
        if (!app.isFine(res)) {
            app.loading(false);
            return;
        }

        var datatlp = res.data.Data;
        var categories = res.data.Categories;
        var catTitle = res.data.CatTitle;
        var minValue = res.data.Min;
        var maxValue = res.data.Max;
        var nullCount = 0
        datatlp.forEach( function(data, idxTlp) {
            if(data.data != undefined && data.data != null) {
                nullCount = 0
                data.data.forEach( function(element, idxData) {
                    if(element == -99999.99999) {
                        nullCount++
                        datatlp[idxTlp].data[idxData] = null;
                    }
                });
                if(data.data.length == nullCount) {
                    datatlp[idxTlp].data = undefined;
                }
            }
        });

        localStorage.setItem("datatlp", JSON.stringify(datatlp));

        $('#charttlp').html("");

        $("#charttlp").kendoChart({
            pdf: {
                fileName: "DetailPowerCurve.pdf",
            },
            theme: "flat",
            // renderAs: "canvas",
            title: {
                text: "Trend Line Plots | Project : "+fa.project.substring(0,fa.project.indexOf("("))+""+$(".date-info").text(),
                visible: false,
                font: '12px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif'
            },
            legend: {
                position: "bottom",
                visible: false,
            },
            chartArea: {
                height: 400,
            },
            seriesDefaults: {
                type: "line",
                style: "smooth",
                dashType: "longDash",
                markers: {
                    visible: false,
                    size: 4,
                },
            },
            // seriesColors: colorField,
            series: datatlp,
            valueAxis: {
                name: compTemp,
                title: {
                    text: "Temperature",//compTemp,
                    visible: true,
                    font: '14px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif'
                },
                labels: {
                    font: '12px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif'
                },
                line: {
                    visible: false
                },
                axisCrossingValue: -10,
                majorGridLines: {
                    visible: true,
                    color: "#eee",
                    width: 0.8,
                },
                // majorUnit: 0.5,
                min: minValue,
                max: maxValue,
            },
            categoryAxis: {
                categories: categories,
                majorGridLines: {
                    visible: false
                },
                title: {
                    text: catTitle,//"Time",
                    font: '14px Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif'
                },
                majorTickType: "none",
            },
            tooltip: {
                visible: true,
                format: "{0:n1}",
                background: "rgb(255,255,255, 0.9)",
                shared: true,
                color: "#58666e",
                font: 'Source Sans Pro, Lato , Open Sans , Helvetica Neue, Arial, sans-serif',
                border: {
                    color: "#eee",
                    width: "2px",
                },
            }
            // pannable: true,
            // zoomable: true
        });

        app.loading(false);
        $("#charttlp").data("kendoChart").refresh();

        tlp.InitRightTurbineList();

    });
}

tlp.InitRightTurbineList = function(){
    tlp.turbineList([]);

    var dtTurbines = JSON.parse(localStorage.getItem("datatlp"));

    if (dtTurbines.length > 1) {
        $("#showHideChk").html('' +
            '<input type="checkbox" id="showHideAll" checked onclick="tlp.showHideAllLegend(this)" >' +
            '' +
            'Select All' +
            '');
    } else {
        $("#showHideChk").html("");
    }

    $("#right-turbine-list").html("");
    $.each(dtTurbines, function(idx, val) {
        if(val.idxseries > 0){

            if(val.data == undefined || val.data == ""){
                $("#right-turbine-list").append('
' +
                '<button class="btn btn-default btn-sm turbine-chk" type="button" disabled="disabled" onclick="tlp.showHideLegend(' + val.idxseries + ')" style="border-color:#a0a0a0;background-color:#a0a0a0"></button>' +
                '<input class="chk-option" type="checkbox" name="' + val.name + '" checked id="disabled-' + val.idxseries + '" hidden disabled="disabled">' +
                '<button class="btn btn-default btn-sm turbine-btn wbtn" type="button" disabled="disabled" onclick="tlp.showHideLegend(' + val.idxseries  + ')">' + val.name + '</button>' +
                '
');
            }else{
                $("#right-turbine-list").append('
' +
                '<button class="btn btn-default btn-sm turbine-chk" type="button" onclick="tlp.showHideLegend(' + val.idxseries + ')" style="border-color:' + val.color + ';background-color:' + val.color + '"></button>' +
                '<input class="chk-option" type="checkbox" name="' + val.name + '" checked id="chk-' + val.idxseries + '" hidden>' +
                '<button class="btn btn-default btn-sm turbine-btn wbtn" type="button" onclick="tlp.showHideLegend(' + val.idxseries  + ')">' + val.name + '</button>' +
                '
');
            }
        }
    });
}

tlp.showHideAllLegend = function(e){
    var dtTurbines = JSON.parse(localStorage.getItem("datatlp"));

    if (e.checked == true) {
        $('.fa-check').css("visibility", 'visible');
        $.each(dtTurbines, function(i, val) {
            if(val.idxseries > 0){
                $("#charttlp").data("kendoChart").options.series[val.idxseries].visible = true;
            }
        });
        $('#labelShowHide b').text('Select All');
    } else {
        $.each(dtTurbines, function(i, val) {
            if(val.idxseries > 0){
                $("#charttlp").data("kendoChart").options.series[val.idxseries].visible = false;
            }
        });
        $('.fa-check').css("visibility", 'hidden');
        $('#labelShowHide b').text('Select All');
    }
    $('.chk-option').not(e).prop('checked', e.checked);
    $("#charttlp").data("kendoChart").redraw();
}
tlp.showHideLegend = function(idx){

    $('#chk-' + idx).trigger('click');
    var chart = $("#charttlp").data("kendoChart");

    if ($('input[id*=chk-][type=checkbox]:checked').length == $('input[id*=chk-][type=checkbox]').length) {
        $('#showHideAll').prop('checked', true);
    } else {
        $('#showHideAll').prop('checked', false);
    }

    // var idxHide = idx+1
    // console.log(idxHide)
    if ($('#chk-' + idx).is(':checked')) {
        $('#icon-' + idx).css("visibility", "visible");
    } else {
        $('#icon-' + idx).css("visibility", "hidden");
    }
    // if (idx == $('input[id*=chk-][type=checkbox]').length) {
    //     idx == 0
    // }

    chart._legendItemClick(idx);
}

$(document).ready(function() {
    setTimeout(function() {
        fa.LoadData();
        tlp.initChart();
    }, 300);

    $('#btnRefresh').on('click', function() {
        setTimeout(function() {
            tlp.initChart();
        }, 300);
    });

     $('#compTemp').on("change", function() {
        setTimeout(function() {
            tlp.initChart();
        }, 300);
    });

});<|endoftext|>


<commit_before>import Metalsmith from 'metalsmith';
import layouts from 'metalsmith-layouts';
import prism from 'metalsmith-prism';
import marked from 'marked';
import markdown from 'metalsmith-markdown';
import inPlace from 'metalsmith-in-place';
import mock from 'metalsmith-mock';
import permalinks from 'metalsmith-permalinks';
import nunjucks from 'nunjucks';
import nunjucksDate from 'nunjucks-date';
import path from 'path';
import collections from 'metalsmith-collections';
import dataMarkdown from './plugins/metalsmith-data-markdown';
import slug from './plugins/nunjucks-slug';
import tocify from './plugins/metalsmith-tocify';

import pkg from '../package.json';

const markedOptions = {
  langPrefix: 'language-',
  renderer: new marked.Renderer(),
  gfm: true,
  tables: true
};

nunjucks
  .configure('docs/layouts', {watch: false, noCache: true})
  .addFilter('year', nunjucksDate)
  .addFilter('slug', slug);

nunjucksDate
  .setDefaultFormat('YYYY');

export default function build(done) {

  const metalsmith = new Metalsmith(__dirname);

  metalsmith
    .metadata({
      site: {
        title: 'Availity UIKit'
      },
      pkg: pkg
    })
    .ignore('**/.DS_Store')
    .source(path.join(process.cwd(), 'docs', 'content'))
    .use(markdown(markedOptions))
    .use(dataMarkdown({
      selector: '[data-markdown]'
    }))
    .use(prism({
      decode: true
    }))
    .use(mock())
    .use(collections({
      pages: {
        pattern: 'pages/**/*.html',
        reverse: false
      },
      components: {
        pattern: 'components/**/*.html',
        sortBy: 'title',
        refer: false
      },
      examples: {
        pattern: 'examples/**/*.html',
        sortBy: 'title',
        reverse: true,
        refer: false
      },
      javascript: {
        pattern: 'javascript/**/*.html',
        sortBy: 'title',
        reverse: true,
        refer: false
      }
    }))
    .use(permalinks({
      relative: false
    }))
    .use(inPlace({
      engine: 'nunjucks',
      partials: 'layouts/partials'
    }))
    .use(tocify({selector: '.docs-section-header, .docs-subsection-title'}))
    .use(layouts({
      engine: 'nunjucks',
      directory: 'layouts'
    }))
    .destination(path.join(process.cwd(), 'build'));

  metalsmith.build( (err) => {

    if (err) {
      throw err;
    }

    if (done) {
      done();
    }
  });

}
<commit_msg>add date to metalsmith meta<commit_after>import Metalsmith from 'metalsmith';
import layouts from 'metalsmith-layouts';
import prism from 'metalsmith-prism';
import marked from 'marked';
import markdown from 'metalsmith-markdown';
import inPlace from 'metalsmith-in-place';
import mock from 'metalsmith-mock';
import permalinks from 'metalsmith-permalinks';
import nunjucks from 'nunjucks';
import nunjucksDate from 'nunjucks-date';
import path from 'path';
import collections from 'metalsmith-collections';
import dataMarkdown from './plugins/metalsmith-data-markdown';
import slug from './plugins/nunjucks-slug';
import tocify from './plugins/metalsmith-tocify';

import pkg from '../package.json';

const markedOptions = {
  langPrefix: 'language-',
  renderer: new marked.Renderer(),
  gfm: true,
  tables: true
};

nunjucksDate
  .setDefaultFormat('YYYY');

nunjucks
  .configure('docs/layouts', {watch: false, noCache: true})
  .addFilter('year', nunjucksDate)
  .addFilter('slug', slug);

export default function build(done) {

  const metalsmith = new Metalsmith(__dirname);

  metalsmith
    .metadata({
      site: {
        title: 'Availity UIKit'
      },
      today: new Date(),
      pkg: pkg
    })
    .ignore('**/.DS_Store')
    .source(path.join(process.cwd(), 'docs', 'content'))
    .use(markdown(markedOptions))
    .use(dataMarkdown({
      selector: '[data-markdown]'
    }))
    .use(prism({
      decode: true
    }))
    .use(mock())
    .use(collections({
      pages: {
        pattern: 'pages/**/*.html',
        reverse: false
      },
      components: {
        pattern: 'components/**/*.html',
        sortBy: 'title',
        refer: false
      },
      examples: {
        pattern: 'examples/**/*.html',
        sortBy: 'title',
        reverse: true,
        refer: false
      },
      javascript: {
        pattern: 'javascript/**/*.html',
        sortBy: 'title',
        reverse: true,
        refer: false
      }
    }))
    .use(permalinks({
      relative: false
    }))
    .use(inPlace({
      engine: 'nunjucks',
      partials: 'layouts/partials'
    }))
    .use(tocify({selector: '.docs-section-header, .docs-subsection-title'}))
    .use(layouts({
      engine: 'nunjucks',
      directory: 'layouts'
    }))
    .destination(path.join(process.cwd(), 'build'));

  metalsmith.build( (err) => {

    if (err) {
      throw err;
    }

    if (done) {
      done();
    }
  });

}
<|endoftext|>


<commit_before>angular.module('os.biospecimen.specimen.detail', [])
  .controller('SpecimenDetailCtrl', function(
    $scope, $state, $modal, $stateParams,
    cpr, visit, specimen, Specimen, SpecimenLabelPrinter, SpecimensHolder, DeleteUtil, Alerts) {

    function init() {
      $scope.cpr = cpr;
      $scope.visit = visit;
      $scope.specimen = specimen;
      $scope.childSpecimens = $scope.specimen.children;
      }

    $scope.reload = function() {
      var promise = null;
      if ($stateParams.specimenId) {
        promise = Specimen.getById($stateParams.specimenId);
      } else if ($stateParams.srId) {
        promise = Specimen.getAnticipatedSpecimen($stateParams.srId);
      }

      return promise.then(
        function(specimen) {
          $scope.childSpecimens = specimen.children;
        }
      );
    }

    $scope.reopen = function() {
      specimen.reopen();
    }

    $scope.deleteSpecimen = function() {
      var params = {cpId: cpr.cpId, cprId: cpr.id, visitId: visit.id};
      var parentId = $scope.specimen.parentId;

      DeleteUtil.delete(
        $scope.specimen,
        {
          onDeletion: function() {
            if (!parentId) {
              $state.go('visit-detail.overview', params);
            } else {
              $state.go('specimen-detail.overview', angular.extend({specimenId: parentId}, params));
            }
          }
        }
      );
    }

    $scope.closeSpecimen = function() {
      var modalInstance = $modal.open({
        templateUrl: 'modules/biospecimen/participant/specimen/close.html',
        controller: 'SpecimenCloseCtrl',
        resolve: {
          specimens: function() {
            return [specimen];
          }
        }
      });
    }

    $scope.printSpecimenLabels = function() {
      SpecimenLabelPrinter.printLabels({specimenIds: [specimen.id]});
    };

    $scope.addSpecimensToSpecimenList = function(list) {
      var selectedSpecimens = [{label: $scope.specimen.label}];

      if (!!list) {
        list.addSpecimens(selectedSpecimens).then(function(specimens) {
          Alerts.success('specimen_list.specimens_added', {name: list.name});
        })
      } else {
        SpecimensHolder.setSpecimens(selectedSpecimens);
        $state.go('specimen-list-addedit', {listId: ''});
      }
    }

    init();
  });
<commit_msg>Fixed indentation<commit_after>angular.module('os.biospecimen.specimen.detail', [])
  .controller('SpecimenDetailCtrl', function(
    $scope, $state, $modal, $stateParams,
    cpr, visit, specimen, Specimen, SpecimenLabelPrinter, SpecimensHolder, DeleteUtil, Alerts) {

    function init() {
      $scope.cpr = cpr;
      $scope.visit = visit;
      $scope.specimen = specimen;
      $scope.childSpecimens = $scope.specimen.children;
    }

    $scope.reload = function() {
      var promise = null;
      if ($stateParams.specimenId) {
        promise = Specimen.getById($stateParams.specimenId);
      } else if ($stateParams.srId) {
        promise = Specimen.getAnticipatedSpecimen($stateParams.srId);
      }

      return promise.then(
        function(specimen) {
          $scope.childSpecimens = specimen.children;
        }
      );
    }

    $scope.reopen = function() {
      specimen.reopen();
    }

    $scope.deleteSpecimen = function() {
      var params = {cpId: cpr.cpId, cprId: cpr.id, visitId: visit.id};
      var parentId = $scope.specimen.parentId;

      DeleteUtil.delete(
        $scope.specimen,
        {
          onDeletion: function() {
            if (!parentId) {
              $state.go('visit-detail.overview', params);
            } else {
              $state.go('specimen-detail.overview', angular.extend({specimenId: parentId}, params));
            }
          }
        }
      );
    }

    $scope.closeSpecimen = function() {
      var modalInstance = $modal.open({
        templateUrl: 'modules/biospecimen/participant/specimen/close.html',
        controller: 'SpecimenCloseCtrl',
        resolve: {
          specimens: function() {
            return [specimen];
          }
        }
      });
    }

    $scope.printSpecimenLabels = function() {
      SpecimenLabelPrinter.printLabels({specimenIds: [specimen.id]});
    };

    $scope.addSpecimensToSpecimenList = function(list) {
      var selectedSpecimens = [{label: $scope.specimen.label}];

      if (!!list) {
        list.addSpecimens(selectedSpecimens).then(function(specimens) {
          Alerts.success('specimen_list.specimens_added', {name: list.name});
        })
      } else {
        SpecimensHolder.setSpecimens(selectedSpecimens);
        $state.go('specimen-list-addedit', {listId: ''});
      }
    }

    init();
  });
<|endoftext|>


<commit_before><commit_msg>começando a falar sobre heranças<commit_after><|endoftext|>


<commit_before>var PORT = 9529;
var http = require('http');
var qs = require('qs');
var crypto =require('crypto');
var url=require('url');
var xml2js =require('xml2js');
var tmpl = require('tmpl');

var TOKEN = 'rinesnow';

function checkSignature(params,token){
	//1.将token、timestamp、nonce三个参数进行字典序排序
	//2.将三个参数字符串拼接成一个字符串进行sha1加密
	//3.开发者获得加密后的字符串可与signature对比，标识该请求来源于微信  return true/false

	var key = [token, params.timestamp,params.nonce].sort().join('');//拼接
	var sha1 = crypto.createHash('sha1');
	sha1.update(key);
	return sha1.digest('hex')==params.signature;

}

var server = http.createServer(function (request,response){
	//解析URL中的Query部分，用qs模块（npm install qs）将Query解析成json
	var query = url.parse(request.url).query;
	var params = qs.parse(query);

	console.log(params);
	console.log("token-->",TOKEN);

	if(!checkSignature(params,TOKEN)){
		// response.end(params.echostr);不能乱response.end！否则后面response 用不了了！
		response.end('signature fail');
		return;
	}else{
		console.log("chenggong");
	}
		console.log(request.method+'/////');

	//若请求时GET，返回echostr用于通过服务器有效检验
	if(request.method=='GET'){
		response.end(params.echostr);
	}else{
	//否则是微信给开发者服务器的POST请求
		var postdata = '';

		request.addListener('data',function (postchunk){
			postdata += postchunk;
		});
		// console.log(postdata+'dfsdf');

		request.addListener('end',function (){
			console.log(postdata);
			var parseString=xml2js.parseString;
			parseString(postdata,function (err, result){
				if(!err){
					console.log(result);
					// console.log(result.xml.MsgType[0]);

					var back = reply(result,'这是一条回复');
				    console.log(back);
					response.end(back);
				}
			});
		});
	}
});
function reply(result,replyText){
	var template = '<xml>'+
						'<ToUserName><![CDATA[toUser]]></ToUserName>'+
						'<FromUserName><![CDATA[fromUser]]></FromUserName>'+
						'<CreateTime><![CDATA[time]]/CreateTime>'+
						'<MsgType><![CDATA[text]]></MsgType>'+
						'<Content><![CDATA[content]]></Content>'+
					+'</xml>';

	if(result.xml.MsgType[0]==='text'){
		console.log("shi text");
		return tmpl(template, {
            toUser: result.xml.FromUserName[0],
            fromUser: result.xml.ToUserName[0],
            type: 'text',
            time: Date.now(),
            content: replyText
        });
	}else if (result.xml.MsgType[0] === 'image') {
        return tmpl(template, {
                			console.log("shi image");

            toUser: result.xml.FromUserName[0],
            fromUser: result.xml.ToUserName[0],
            type: 'image',
            time: Date.now(),
            content: replyText
        });
    } else if (result.xml.MsgType[0] === 'voice') {
        return tmpl(template, {
            toUser: result.xml.FromUserName[0],
            fromUser: result.xml.ToUserName[0],
            type: 'voice',
            time: Date.now(),
            content: replyText
        });
    } else if (result.xml.MsgType[0] === 'video') {
        return tmpl(template, {
            toUser: result.xml.FromUserName[0],
            fromUser: result.xml.ToUserName[0],
            type: 'video',
            time: Date.now(),
            content: replyText
        });
    } else if (result.xml.MsgType[0] === 'shortvideo') {
        return tmpl(template, {
            toUser: result.xml.FromUserName[0],
            fromUser: result.xml.ToUserName[0],
            type: 'shortvideo',
            time: Date.now(),
            content: replyText
        });
    } else if (result.xml.MsgType[0] === 'location') {
        return tmpl(template, {
            toUser: result.xml.FromUserName[0],
            fromUser: result.xml.ToUserName[0],
            type: 'location',
            time: Date.now(),
            content: replyText
        });
    } else if (result.xml.MsgType[0] === 'link') {
        return tmpl(template, {
            toUser: result.xml.FromUserName[0],
            fromUser: result.xml.ToUserName[0],
            type: 'link',
            time: Date.now(),
            content: replyText
        });
    } else {
        return '';
    }

}
server.listen(PORT);
console.log("Server running at port:"+PORT+".");<commit_msg>add message.js debug<commit_after>var PORT = 9529;
var http = require('http');
var qs = require('qs');
var crypto =require('crypto');
var url=require('url');
var xml2js =require('xml2js');
var tmpl = require('tmpl');

var TOKEN = 'rinesnow';

function checkSignature(params,token){
	//1.将token、timestamp、nonce三个参数进行字典序排序
	//2.将三个参数字符串拼接成一个字符串进行sha1加密
	//3.开发者获得加密后的字符串可与signature对比，标识该请求来源于微信  return true/false

	var key = [token, params.timestamp,params.nonce].sort().join('');//拼接
	var sha1 = crypto.createHash('sha1');
	sha1.update(key);
	return sha1.digest('hex')==params.signature;

}

var server = http.createServer(function (request,response){
	//解析URL中的Query部分，用qs模块（npm install qs）将Query解析成json
	var query = url.parse(request.url).query;
	var params = qs.parse(query);

	console.log(params);
	console.log("token-->",TOKEN);

	if(!checkSignature(params,TOKEN)){
		// response.end(params.echostr);不能乱response.end！否则后面response 用不了了！
		response.end('signature fail');
		return;
	}else{
		console.log("chenggong");
	}
		console.log(request.method+'/////');

	//若请求时GET，返回echostr用于通过服务器有效检验
	if(request.method=='GET'){
		response.end(params.echostr);
	}else{
	//否则是微信给开发者服务器的POST请求
		var postdata = '';

		request.addListener('data',function (postchunk){
			postdata += postchunk;
		});
		// console.log(postdata+'dfsdf');

		request.addListener('end',function (){
			console.log(postdata);
			var parseString=xml2js.parseString;
			parseString(postdata,function (err, result){
				if(!err){
					console.log(result);
					// console.log(result.xml.MsgType[0]);

					var back = reply(result,'这是一条回复');
				    console.log(back);
					response.end(back);
				}
			});
		});
	}
});
function reply(result,replyText){
	var template = '<xml>'+
						'<ToUserName><![CDATA[toUser]]></ToUserName>'+
						'<FromUserName><![CDATA[fromUser]]></FromUserName>'+
						'<CreateTime><![CDATA[time]]/CreateTime>'+
						'<MsgType><![CDATA[text]]></MsgType>'+
						'<Content><![CDATA[content]]></Content>'+
					+'</xml>';

	if(result.xml.MsgType[0]==='text'){
		console.log("shi text");
		return tmpl(template, {
            toUser: result.xml.FromUserName[0],
            fromUser: result.xml.ToUserName[0],
            type: 'text',
            time: Date.now(),
            content: replyText
        });
	}else if (result.xml.MsgType[0] === 'image') {
       		console.log("shi image");

        return tmpl(template, {
            toUser: result.xml.FromUserName[0],
            fromUser: result.xml.ToUserName[0],
            type: 'image',
            time: Date.now(),
            content: replyText
        });
    } else if (result.xml.MsgType[0] === 'voice') {
        return tmpl(template, {
            toUser: result.xml.FromUserName[0],
            fromUser: result.xml.ToUserName[0],
            type: 'voice',
            time: Date.now(),
            content: replyText
        });
    } else if (result.xml.MsgType[0] === 'video') {
        return tmpl(template, {
            toUser: result.xml.FromUserName[0],
            fromUser: result.xml.ToUserName[0],
            type: 'video',
            time: Date.now(),
            content: replyText
        });
    } else if (result.xml.MsgType[0] === 'shortvideo') {
        return tmpl(template, {
            toUser: result.xml.FromUserName[0],
            fromUser: result.xml.ToUserName[0],
            type: 'shortvideo',
            time: Date.now(),
            content: replyText
        });
    } else if (result.xml.MsgType[0] === 'location') {
        return tmpl(template, {
            toUser: result.xml.FromUserName[0],
            fromUser: result.xml.ToUserName[0],
            type: 'location',
            time: Date.now(),
            content: replyText
        });
    } else if (result.xml.MsgType[0] === 'link') {
        return tmpl(template, {
            toUser: result.xml.FromUserName[0],
            fromUser: result.xml.ToUserName[0],
            type: 'link',
            time: Date.now(),
            content: replyText
        });
    } else {
        return '';
    }

}
server.listen(PORT);
console.log("Server running at port:"+PORT+".");<|endoftext|>


<commit_before>if(!jsFrontend) { var jsFrontend = new Object(); }

jsFrontend = {
	// datamembers
	debug: false,

	// init, something like a constructor
	init: function() {
		jsFrontend.gravatar.init();
	},

	// end
	eof: true
}

jsFrontend.gravatar = {
	// init, something like a constructor
	init: function() {
		$('.replaceWithGravatar').each(function() {
			var element = $(this);
			var gravatarId = element.attr('rel');
			var size = element.attr('height');
			// valid gravatar id
			if(gravatarId != '') {
				// build url
				var url = 'http://www.gravatar.com/avatar/'+ gravatarId + '?r=g&d=404';
				// add size if set before
				if(size != '') url += '&s=' + size;
				// create new image
				var gravatar = new Image();
				gravatar.src = url;
				// reset src
				gravatar.onload = function() { element.attr('src', url).addClass('gravatarLoaded'); }
			}
		});
	},

	// end
	eof: true
}

$(document).ready(function() { jsFrontend.init(); });<commit_msg>Ajax Init<commit_after>if(!jsFrontend) { var jsFrontend = new Object(); }

jsFrontend = {
	// datamembers
	debug: false,

	// init, something like a constructor
	init: function() {
		jsFrontend.gravatar.init();

		// init stuff
		jsFrontend.initAjax();
	},

	initAjax: function() {
		// set defaults for AJAX
		$.ajaxSetup({ cache: false, type: 'POST', dataType: 'json', timeout: 10000 });
	},

	// end
	eof: true
}

jsFrontend.gravatar = {
	// init, something like a constructor
	init: function() {
		$('.replaceWithGravatar').each(function() {
			var element = $(this);
			var gravatarId = element.attr('rel');
			var size = element.attr('height');
			// valid gravatar id
			if(gravatarId != '') {
				// build url
				var url = 'http://www.gravatar.com/avatar/'+ gravatarId + '?r=g&d=404';
				// add size if set before
				if(size != '') url += '&s=' + size;
				// create new image
				var gravatar = new Image();
				gravatar.src = url;
				// reset src
				gravatar.onload = function() { element.attr('src', url).addClass('gravatarLoaded'); }
			}
		});
	},

	// end
	eof: true
}

$(document).ready(function() { jsFrontend.init(); });<|endoftext|>