Example #1
0
 renderScenario: function (scenario) {
   var generateTopic = false, rendered, template;
   var context = {
     title: scenario.name,
     body: ''
   };
   
   for (var i = scenario.breakdown.length - 1; i >= 0 ; i--) {
     var step = scenario.breakdown[i];
     
     if (generateTopic) {
       context.body = this.renderTopic(step, context.body);
     }
     else {
       context.body += this.renderStep(step);
     }
     
     // Need to record when we've passed the 'Then' step because 
     // that is where we should stop generating topics and start
     // generating assertions
     if (this.isThen(step)) {
       generateTopic = true;
     }
   }
   
   context.body = this.indent(context.body, 1);
   
   template = _.template(this.templates['scenario']);
   rendered = template(context);
   return rendered;
 },
Example #2
0
File: ui.js Project: detrixVR/vk
 .bind('showProcessInfo', '.widget', function (event, rowData) {
     var $target = $(event.target);
     if ($target.hasClass('freezedEventsHolder')) {
         rowData.getListGroupItemClass = getListGroupItemClass;
         $('.list-group', $target).html(_.template($('#eventsList').html())(rowData));
     }
 });
Example #3
0
File: ui.js Project: detrixVR/vk
        .bind('printTask', '.widget', function (event, task, clear) {

            var $target = $(event.target);

            if ($target.hasClass('tasksHolder')) {

                var tabContainer = $('#tab1 .row', $target);

                if (clear) {
                    tabContainer.empty();
                }

                var lastMsg = task.messages.pop();

                tabContainer.prepend(_.template($('#taskRowTemplate').html())({
                    listGroupStyle: getListGroupItemClass(lastMsg ? lastMsg.type : 0),
                    accountId: task.accountId,
                    taskUid: task.uid,
                    processTitle: getTitleById(task.uid) || task.settings.taskName.value,
                    avatarUrl: task.settings.accountInfo.value.photo_50,
                    lastMessageTime: lastMsg ? new Date(lastMsg.time).toLocaleString() : null,
                    lastMessage: lastMsg ? lastMsg.msg : null,
                    startPauseButtonGlyph: (task.state === 2 || task.state === 0 ? 'glyphicon-play' : 'glyphicon-pause'),
                    taskState: task.state
                }));


            }
        })
Example #4
0
File: ui.js Project: detrixVR/vk
        .bind('printProcess', '.widget', function (event, process, clear) {

            var $target = $(event.target);

            if ($target.hasClass('tasksHolder')) {
                var tabContainer = $('#tab1 .row', $target);

                if (clear) {
                    tabContainer.empty();
                }

                var lastMsg = task.messages.pop();

                tabContainer.append(_.template($('#taskRow').html())({
                    listGroupStyle: getListGroupItemClass(lastMsg ? lastMsg.type : 0),
                    accountId: process.accountId,
                    processId: process.processId,
                    processTitle: getTitleById(process.processId),
                    avatarUrl: process.settings.accountInfo.value.photo_50,
                    lastMessageTime: new Date(lastMsg.time).toLocaleString(),
                    lastMessage: lastMsg.msg,
                    startPauseButtonGlyph: (process.state === 2 ? 'glyphicon-play' : 'glyphicon-pause')
                }));


            }
        })
Example #5
0
Info.pack = function(info, mapping){
  var data = _.clone(info);
  var reply = data.reply;

  //log('packing reply: ', reply);

  // 具备图文消息的特征
  if (_.isObject(reply) && !_.isArray(reply) && !reply.type) {
    reply = data.reply = [reply];
  }
  if (_.isArray(reply)) {
    if (_.isFunction(mapping)) {
      reply = reply.map(function(item, i) {
        return mapping.call(reply, item, i, info);
      });
    } else if (mapping) {
      reply.forEach(function(item, index){
        item['title'] = item[ mapping['title'] || 'title'];
        item['description'] = item[ mapping['description'] || 'description'];
        item['pic'] = item[ mapping['picUrl'] || 'picUrl'] || item[ mapping['pic'] || 'pic'];
        item['url'] = item[ mapping['url'] || 'url'];
      });
    }
  }
  data.reply = reply;

  var xml = _.template(Info.TEMPLATE_REPLY)(data);

  return xml;
};
Example #6
0
  selectQuery: function (tableName, options) {
    options = options || {}
    options.table = helper.addTicks(tableName)
    options.attributes = options.attributes && options.attributes.map(function (attr) {return helper.addTicks(attr)}).join(",")
    options.attributes = options.attributes || '*'

    var query = "SELECT <%= attributes %> FROM <%= table %>"

    if(options.where) {
      options.where = QueryGenerator.getWhereConditions(options.where)
      query += " WHERE <%= where %>"
    }
    if(options.order) query += " ORDER BY <%= order %>"
    if(options.group) {
      options.group = helper.addTicks(options.group)
      query += " GROUP BY <%= group %>"
    }
    if(options.limit) {
      if(options.offset) query += " LIMIT <%= offset %>, <%= limit %>"
      else query += " LIMIT <%= limit %>"
    }

    query += ";"

    return _.template(query)(options)
  },
Example #7
0
var getXML = function(info){
  _.defaults(info, {
    sp: 'webot',
    user: '******'
  })

  var tpl= [
    '<xml>',
      '<ToUserName><![CDATA[<%=sp%>]]></ToUserName>',
      '<FromUserName><![CDATA[<%=user%>]]></FromUserName>',
      '<CreateTime><%=(new Date().getTime())%></CreateTime>',
      '<MsgType><![CDATA[<%=type%>]]></MsgType>',
      '<% if(type=="text"){ %>',
        '<Content><![CDATA[<%=text%>]]></Content>',
      '<% }else if(type=="location"){  %>',
        '<Location_X><%=xPos%></Location_X>',
        '<Location_Y><%=yPos%></Location_Y>',
        '<Scale><%=scale%></Scale>',
        '<Label><![CDATA[<%=label%>]]></Label>',
      '<% }else if(type=="image"){  %>',
        '<PicUrl><![CDATA[<%=pic%>]]></PicUrl>',
      '<% } %>',
    '</xml>'
  ].join('')

  return _.template(tpl)(info);
}
Example #8
0
  dropTableQuery: function (tableName, options) {
    options = options || {}

    var query = "DROP TABLE IF EXISTS <%= table %>;"

    return _.template(query)({table: helper.addTicks(tableName)})
  },
 .use(function(req, res, next)
 {
     switch(req.method)
     {
         case 'GET':
             if (req.body) console.log(req.body);
             model.query.cat  = NaN;
             model.query.prod = NaN;
             if (!IsEmptyObject(req.query))
             {
                 model.query.cat  = parseInt(req.query['cat'],  10);
                 model.query.prod = parseInt(req.query['prod'], 10);
             }
             console.log("Category: " + model.query.cat);
             console.log("Product:  " + model.query.prod);
             res.writeHead(200, {'Content-Type':'text/html'});
             res.end(underscore.template(view.Render(), model));
         break;
         case 'PUT':
             console.log(req.body);
         break;
         case 'POST':
             console.log(req.body);
         break;
         case 'DELETE':
             console.log(req.body);
         break;
         default:
         break;
     }
 });
Example #10
0
var compileTemplate = function (templates) {

    for (var templ in templates) {
        try {
            console.log("Compiling: " + templates[templ]);
            var data = fs.readFileSync("./www/js/tpl/" + templates[templ] + ".html", 'utf8');
            //var uTpl =  templates[templ] + ".prototype.template = ";
            var uTpl = "define(function(require) { ";
            //precompile template
            uTpl += "return " + _.template(data).source + ";";
            uTpl += "});";
            //console.log(uTpl);
        } catch (e) {
            console.error('Could not compile a template for: ' + templates[templ] + " -- " + e.message);
        }

        try {

            fs.writeFileSync("./www/js/tpl/" + templates[templ] + ".js", uTpl);
        } catch (e) {
            console.error('Could not save compile template for: ' + templates[templ] + " -- " + e.message);
        }
    }

}
Example #11
0
File: ui.js Project: detrixVR/vk
var renderAccountHolder = function (account) {
    console.log(account);
    $('#accountHolder').html(_.template($('#accountHolderTemplate').html())(account.accountInfo));

    $('#accountHolder').trigger('account', account.accountInfo);


};
Example #12
0
var compile = function(f, data, context) {
  try {
    return _.template(data)(context);
  } catch(e) {
    log("error", "could not parse template file", f);
    log("error", "original error:");
    throw(e);
  }
};
Example #13
0
File: ui.js Project: detrixVR/vk
 }).on('account', function (event, account) {
     var $this = $(this);
     var popup = $this.data('bs.popover');
     if (popup) {
         //popup.hide();
         // popup.options.content = $('#accountPopupTemplate').html();
         popup.options.content = _.template($('#accountPopupTemplate').html())(account);
         popup.setContent();
     }
 })
Example #14
0
var compileTemplate = function (contents) {
    try {
        var uTpl = "define(function(require) { ";
        //precompile template
        uTpl += "return " + _.template(contents).source + ";";
        uTpl += "});";
        return uTpl;
    } catch (e) {
        console.error('Could not compile a template for: ' + templates[templ] + " -- " + e.message);
    }
}
Example #15
0
        var resultFn = function(vals, to_path) {
            var template = _.template(to_path);

            var url = template(vals);

            var msg =  {
                found : true,
                url : url
            }
            throw msg;
        }
Example #16
0
  updateQuery: function (tableName, values, where) {
    var query = "UPDATE <%= table %> SET <%= values %> WHERE <%= where %>"
    var replacements = {
      table: helper.addTicks(tableName),
      values: _.map(values, function (value, key) {
        return helper.addTicks(key) + "=" + helper.escape((value instanceof Date) ? helper.toSqlDate(value) : value)
      }).join(","),
      where: QueryGenerator.getWhereConditions(where)
    }

    return _.template(query)(replacements)
  },
Example #17
0
 renderStep: function (step) {
   var rendered, template; 
   step = step[Object.keys(step)[0]];
   
   template = _.template(this.templates['step']);
   rendered = template({ 
     title: step.join(' '),
     operator: capitalize(step[0])
   });
   
   return this.doIndent ? this.indent(rendered) : rendered;
 },
Example #18
0
  insertQuery: function (tableName, attrValueHash) {
    var query = "INSERT INTO <%= table %> (<%= attributes %>) VALUES (<%= values %>);"

    var replacements  = {
      table: helper.addTicks(tableName),
      attributes: _.keys(attrValueHash).map(function (attr) {return helper.addTicks(attr)}).join(","),
      values: _.values(attrValueHash).map(function (value) {
        return helper.escape((value instanceof Date) ? helper.toSqlDate(value) : value)
      }).join(",")
    }

    return _.template(query)(replacements)
  },
  return function(info, cb){
    //默认值
    info = _.isString(info) ? {text: info} : info;
    
    _.defaults(info, {
      sp: 'webot',
      user: '******',
      type: 'text',
      text: 'help',
      pic: 'http://www.baidu.com/img/baidu_sylogo1.gif',
      xPos: '23.08',
      yPos: '113.24',
      scale: '20',
      label: 'this is a location'
    });

//    console.dir(WeBotShell.TEMPLATE);
    var content = _.template(WeBotShell.TEMPLATE)(info);
    
    //发送请求
    request.post({
      url: url,
      qs: WeBotShell.makeAuthQuery(token),
      body: content
    }, function(err, res, body){
      if(err || res.statusCode=='403' || !body){
        cb(err || res.statusCode, body);
      }else{
        xmlParser.parseString(body, function(err, result){
          if (err || !result || !result.xml){
            cb(err || 'result format incorrect', result);
          }else{
            var json = result.xml;
            json.ToUserName = json.ToUserName && String(json.ToUserName);
            json.FromUserName = json.FromUserName && String(json.FromUserName);
            json.CreateTime = json.CreateTime && Number(json.CreateTime);
            json.FuncFlag = json.FuncFlag && Number(json.FuncFlag);
            json.MsgType = json.MsgType && String(json.MsgType);
            json.Content = json.Content && String(json.Content);
            if(json.MsgType=='news'){
              json.ArticleCount = json.ArticleCount && Number(json.ArticleCount);
              json.Articles = json.Articles && json.Articles.length>=1 && json.Articles[0];
            }
            cb(err, json);
          }
        });
      }
    });
    return content;
  };
function generateHtml(graphData) {

  var template = fs.readFileSync(__dirname + '/html/template.html', 'utf8');
  var css = fs.readFileSync(__dirname + '/html/style.css', 'utf8');
  var js = '';
  // var js = fs.readFileSync(__dirname + '/html/d3-graph.js', 'utf8');

   var data = {
    css : css,
    js : js,
    title : 'Character Connection',//'dependo',
    graphData: JSON.stringify(graphData, null)
  };

  return _.template(template, data);
}
Example #21
0
  deleteQuery: function (tableName, where, options) {
    options = options || {}

    var query;
    if (options.limit) {
      query = "DELETE FROM <%= table %> WHERE <%= where %> LIMIT <%= limit %>;"
    } else {
      query = "DELETE FROM <%= table %> WHERE <%= where %>;"
    }
    var replacements = {
      table: helper.addTicks(tableName),
      where: QueryGenerator.getWhereConditions(where),
      limit: helper.escape(options.limit)
    }

    return _.template(query)(replacements)
  },
Example #22
0
Info.pack = function(info, mapping){
  var data = _.clone(info);
  var reply = data.reply;
  if(mapping && _.isArray(reply)){
    _.each(reply, function(item, index){
      if(_.isFunction(mapping)){
        item = mapping(item, index, info)
      }else{
        item['title'] = item[ mapping['title'] || 'title']
        item['description'] = item[ mapping['description'] || 'description']
        item['pic'] = item[ mapping['pic'] || 'pic']
        item['url'] = item[ mapping['url'] || 'url']
      }
    })
  }
  var xml = _.template(Info.TEMPLATE_REPLY)(data);
  return xml;
}
Example #23
0
  createTableQuery: function (tableName, attributes, options) {
    options = options || {}

    var query   = "CREATE TABLE IF NOT EXISTS <%= table %> (<%= attributes%>);"
      , primaryKeys = []
      , attrStr = _.map(attributes, function (dataType, attr) {
          var dt = dataType
          if (dt.indexOf('PRIMARY KEY') !== -1) {
            primaryKeys.push(attr)
            return helper.addTicks(attr) + " " + dt.replace(/PRIMARY KEY/, '')
          } else {
            return helper.addTicks(attr) + " " + dt
          }
        }).join(",")
      , values  = {table: helper.addTicks(tableName), attributes: attrStr}
      , pkString = primaryKeys.map(function (pk) {return helper.addTicks(pk)}).join(",")

    if (pkString.length > 0) values.attributes += ", PRIMARY KEY (" + pkString + ")"

    return  _.template(query)(values)
  },
Example #24
0
 renderFeature: function (feature) {
   var context = {
     title: feature.name,
     scenarios: ''
   }
   
   for (var i = 0; i < feature.scenarios.length; i++) {
     context.scenarios += this.renderScenario(feature.scenarios[i]);
   }
   
   template = _.template(this.templates['feature']);
   rendered = template(context);
   
   if (this.trim) {
     rendered = rendered.replace(/\t/g, '');
   }
   
   return {
     name: feature.name,
     text: rendered
   };
 },
Example #25
0
  remoteScript: function(options, done) {
    var string = options.file ? fs.readFileSync(options.file, 'utf-8') : options.string;
    var template = _.template(string);
    var result = template(options.data || {});
    var copy = ('copy' in options) ? options.copy : true;
    var path = options.path || '/tmp/remoteScript';
    fs.writeFileSync('/tmp/remoteScript', result, 'utf-8');
    fs.chmodSync('/tmp/remoteScript', '755');

    // Create SSH process
    // TODO: use this instead of all the piping for node 0.8.x:
    //var ssh = spawn('ssh', [options.remote, 'bash -s'], { stdio: 'inherit' });
    var ssh = spawn('ssh', ['-o', 'StrictHostKeyChecking=no', options.remote, 'bash -s']);

    // Create readable file stream from local script
    var tmpFile = fs.createReadStream('/tmp/remoteScript');

    // Pipe output from SSH to output from this process
    ssh.stdout.pipe(process.stdout, {end: false});
    ssh.stderr.pipe(process.stderr, {end: false});

    // Resume input on this process and pipe it to SSH
    process.stdin.resume();
    process.stdin.pipe(ssh.stdin, {end: false});
    process.stdin.on('end', function() {
      ssh.stdin.write('exit', 'utf-8');
    });

    // Pipe the local script as SSH input
    tmpFile.pipe(ssh.stdin);

    // Complete whenever SSH exits
    ssh.on('exit', function(err, result) {
      // TODO: unlink temp script file
      console.log("SSH exit");
      process.stdin.pause();
      return done(err);
    });
  },
Example #26
0
/*********************************************************************
* Create a new VM based on newly created config files,
* if not already created.
**********************************************************************/
function create_vm ( name ) {

    var v = {
        'name': name,
        'running': false,
        'script': null,     
    }
    
    // if name exists then just return, otherwise integrate templates and then
    // lxc-create.  Bear in mind that currently (and naffly) the IP address 
    // will be the vm number + 1 (as vm0 has ip 10.0.1.1 )

    // write config and fstab to ...    
    var folder = path.join(root_folder, name);
    
    num = parseInt( name.substring(2) );
    
    // TODO: Fix me
    var ctx = {'name': name, 'ip': '10.0.1.' + (num + 1).toString(), "scrapername": "__public__" }


    var compiled = _.template( config_tpl );
    var cfg = compiled( ctx );
    
    var fs_compiled = _.template( fstab_tpl );
    var fstab = fs_compiled( ctx );
    
    path.exists(root_folder, function (exists) {    
        if ( ! exists ) {
            fs.mkdirSync( root_folder, "0777" );
        }   
    });
    
    
    path.exists(folder, function (exists) {
        if ( ! exists ) {
            fs.mkdirSync( folder, "0777" );
        } else {
            return;
        }

        // Mount the code folder
        var cfolder = get_code_folder(v);
        path.exists(cfolder, function (exists) {
            if (!exists) {
                fs.mkdirSync( cfolder, "0757" );
	    }
        });

        var tgt = path.join(folder, 'config')
        fs.writeFile(tgt, cfg, function(err) {
            if(err) {
                util.log.fatal('Failed to write config file, err: ' + err);
            } else {
                // call lxc-create -n name -f folder/config
                e = spawn('/usr/bin/lxc-create', ['-n', name, '-f', tgt]);
		e.stderr.on('data', function(stuff) {
		    util.log.debug('stderr from lxc-create: ' + stuff);
	        });
                e.on('exit', function (code, signal) {
                    if ( code && code == 127 ) {
                        util.log.fatal('LXC-Create exited with code ' + code);
                    } else {
                        util.log.info('LXC-Create exited with code ' + code);
                    }
                });
            }
        });
                    
        tgt = path.join(folder, 'fstab');
        fs.writeFile(tgt, fstab, function(err) {
            if(err) {
                util.log.fatal('Failed to write fstab file, err: ' + err);
            }
        }); 
    });
    
    return v;
}
Example #27
0
exports.topbar = function(head, req) {
    var settingsDoc = {};
    var selectedThemeDoc = null;
    var row;
    var apps = [];
    start({'headers' : {'Content-Type' : 'text/html'}});
    while ((row = getRow())) {
        if (row.key[0] === 0) settingsDoc = row.value;

        if (row.key[0] === 1) {
            if (row.key[3] == 'install') {
                apps.push({
                    title : row.key[2],
                    db :row.value.db,
                    doc : row.doc
                })
            }
            if (row.key[3] == 'link') {
                apps.push({
                    title : row.key[2],
                    link :row.value.url,
                    doc  : row.doc,
                    external : true
                })
            }
        }
        if (row.key[0] === 2) selectedThemeDoc = row.doc;
    }
    var settings = _.defaults(settingsDoc, dashboard_settings.defaultSettings);
    var username, avatar, avatar_large = null;
    var isAdmin = false;
    var isUser  = utils.isUser(req);
    var isAdminParty = utils.isAdminParty(req);
    if (utils.isAdmin(req) || isAdminParty) {
        isAdmin = true;
    }
    if (isUser) {
        username = req.userCtx.name;
        avatar = gravatar.avatarURL({
            email : req.userCtx.name,
            size : 20,
            default_image : 'mm'
        });
        avatar_large = gravatar.avatarURL({
            email : req.userCtx.name,
            size : 96,
            default_image : 'mm'
        });

    }

    var dashboard_url = dashboard_links.dashboardURL(settings, 'dashboard', 'dashboard', req);
    var home_url = dashboard_url;
    if (settings.frontpage.use_link) {
        home_url = settings.frontpage.link_url;
    }
    var settings_url  = dashboard_url + "settings";
    var login_url = dashboard_url + 'login';
    var profile_url = null;

    if (settings.sessions.type == 'other') {
        login_url = settings.sessions.other.login_url;
        _.templateSettings = {
            interpolate: /\{(.+?)\}/g
        }
        var template = _.template(settings.sessions.other.profile_url);
        profile_url = template({username : username});

    }

    var hide_apps = (!isUser && settings.host_options.redirect_frontpage_on_anon);

    apps = _.map(apps, function(app) {
        if (app.db) {
            app.link = dashboard_links.appUrl(settingsDoc, app.doc, req);
        }
        return app;
    });

    var grouped_apps = _.groupBy(apps, function(app) {
        if (app.doc.onDropdownMenu) return "more_apps"
        else return "apps";
    });



    var usrCtxString = encodeURI(JSON.stringify(req.userCtx));
    var templateContext = {
        dashboard_url : dashboard_url,
        home_url : home_url,
        settings_url : settings_url,
        login_url : login_url,
        profile_url : profile_url,
        apps : grouped_apps,
        username : username,
        avatar : avatar,
        avatar_large : avatar_large,
        isAdmin: isAdmin,
        isAdminParty : isAdminParty,
        hide_apps : hide_apps,
        settings : settings,
        usrCtxString : usrCtxString,
        sessionType : settings.sessions.type,
        extraResources : []
    };


    if (selectedThemeDoc) {
        if (selectedThemeDoc._attachments) {
            _.each(selectedThemeDoc._attachments, function(value, name){
                if (name === 'modules.js') return ;
                if (value.content_type == "application/javascript") {
                    templateContext.extraResources.push({
                        doc : selectedThemeDoc._id,
                        attachment: name
                    });
                }
            });
        }
        log(templateContext.extraResources);
        var template = handlebars.compile(selectedThemeDoc['template.html']);
        send(template(templateContext));
    } else {
        send(templates['topbar.html'](templateContext));
    }
}
 function update_file(file_txt, next_step) {
     var template = _.template(file_txt);
     fs.writeFile(file_name, template(context), next_step);
 }
Example #29
0
File: ui.js Project: detrixVR/vk
 .bind('printNoProcesses', '.widget', function (event) {
     var $target = $(event.target);
     if ($target.hasClass('tasksHolder')) {
         $('#tab1', $target).html(_.template($('#noProcessesTemplate').html())({}))
     }
 })
Example #30
0
File: ui.js Project: detrixVR/vk
var drawMemoryUsage = function (data) {
    $('#memoryUsageHolder').html(_.template($('#memoryUsageTemplate').html())({data: data}));
};