<commit_before>var fs = require('fs');
var path = require('path');
var sax = require("sax");
var AdmZip = require('adm-zip');
var _ = require('lodash');

var argv = require('minimist')(process.argv.slice(2));

if (!argv['d'] && !argv['f']) {
    console.log("no file or dir, use -d or -f argument");
    process.exit(1);
}

var outDir = argv['o'] || 'target';
var imgDir = 'ressources/images';

var inDir = argv["d"];
var inFile = argv["f"];

if (inDir && (!fs.existsSync(inDir) || !fs.statSync(inDir).isDirectory())) {
    console.log("directory not found", inDir);
    process.exit(1);
}
if (!inDir && !fs.existsSync(inFile)) {
    console.log("file not found", inFile);
    process.exit(1);
}

function MDWriter() {
    this.text = "";
    this.inCodeBlock = false;
    this.inNotes = false;
    this.listLevel = 0;
    this.titreAdded = false;
    this.mainTitleAdded = false;
    this.firstPage = false;

    this.addPage = function () {
        this.text += "\n\n\n\n";
        this.titreAdded = false;
        this.firstPage = true;
    };

    this.addParagraph = function () {
        if (this.inCodeBlock || this.inNotes) {
            this.text += "\n";
        }
    };

    this.addText = function (text) {
        if(this.firstPage && !this.mainTitleAdded) {
            this.text = '#' + text + '\n\n<!-- .slide: class="page-title" -->\n\n\n\n';
            this.mainTitleAdded = true;
        }
        else if (!this.titreAdded) {
            this.text += "## " + text + "\n";
            this.titreAdded = true;
        }
        else {
            this.text += text;
        }
    };

    this.addImage = function (path) {
        this.text += "\n\n![](ressources/images/" + path.replace("Pictures/", "") + ")\n";
    };

    this.startList = function () {
        this.listLevel++;
    };

    this.endList = function () {
        this.listLevel--;
    };

    this.addBullet = function () {
        if (!this.listLevel) {
            console.warning("not in a list");
        }
        this.text += "\n" + new Array(this.listLevel).join("\t") + "- ";
    };

    this.addEnd = function () {
        this.text += "\n\n\n\n<!-- .slide: class=\"page-questions\" -->\n\n\n\n<!-- .slide: class=\"page-tp1\" -->";
    };

    this.startCodeBlock = function () {
        this.text += "\n```";
        this.inCodeBlock = true;
    };

    this.endCodeBlock = function () {
        this.text += "\n```\n";
        this.inCodeBlock = false;
    };

    this.startNotes = function () {
        this.text += "\nNotes :\n";
        this.inNotes = true;
    };

    this.endNotes = function () {
        this.inNotes = false;
    };

    this.startTable = function() {
        this.inTable = true;
        this.rowNumber = 0;
        this.colNumber = 0;
    }

    this.endTable = function() {
        this.inTable = false;
    }

    this.startRow = function() {
        this.text += "\n|";
        if (this.rowNumber == 1) {
            //If header was written we write separation line
            this.text += Array(this.colNumber + 1).join("---|") + "\n|";
        }
        this.rowNumber++;
    }

    this.closeCell = function() {
        if (this.rowNumber == 1) {
            this.colNumber++;
        }
        this.text += "|";
    }

}

function OdpConverter(filepath, outDir) {

    this.filePath = filepath;
    this.name = path.basename(this.filePath, '.odp').replace(/\s+/g, '_');
    this.contentName = path.join(outDir, this.name + '-content.xml');

    this.extract = function () {
        console.log('extract : ' + this.filePath);
        var zip = new AdmZip(this.filePath);
        var zipEntries = zip.getEntries();
        zipEntries.forEach(function (val) {
            if (val.entryName.indexOf("content.xml") >= 0) {
                //console.log(val.entryName);
                zip.extractEntryTo(val, outDir, true, true);
                fs.renameSync(path.join(outDir, val.entryName), this.contentName);
            }
            if (val.entryName.indexOf("Pictures") >= 0) {
                //console.log(val.entryName);
                zip.extractEntryTo(val, path.join(outDir, imgDir), false, true);
                var baseName = path.basename(val.entryName);
                fs.renameSync(path.join(outDir, imgDir, baseName), path.join(outDir, imgDir, this.name + '-' + baseName));
            }
        }.bind(this));
    };

    this.convert = function () {
        console.log('convert : ' + this.name);
        var mdWriter = new MDWriter();
        var outName = this.name;
        var saxStream = sax.createStream(true, {
            trim: true,
            normalize: true,
            xmlns: false,
            lowercase: true
        });

        saxStream.on("opentag", function (node) {

            if (node.name === "draw:page") {
                mdWriter.addPage();
            } else if (node.name === "draw:image") {
                mdWriter.addImage(outName + '-' + node.attributes["xlink:href"]);
            } else if (node.name === "text:list") {
                mdWriter.startList();
            } else if (node.name === "text:list-item") {
                mdWriter.addBullet();
            } else if (node.name === "draw:custom-shape" || node.name === "draw:rect") {
                mdWriter.startCodeBlock();
            } else if (node.name === "text:p") {
                mdWriter.addParagraph();
            } else if (node.name === "presentation:notes") {
                mdWriter.startNotes();
            } else if (node.name === "table:table") {
                mdWriter.startTable();
            } else if (node.name === "table:table-row") {
                mdWriter.startRow();
            }
        });

        saxStream.on("closetag", function (node) {

            if (node === "draw:custom-shape" || node === "draw:rect") {
                mdWriter.endCodeBlock();
            } else if (node === "text:list") {
                mdWriter.endList();
            } else if (node === "presentation:notes") {
                mdWriter.endNotes();
            } else if (node === "table:table") {
                mdWriter.endTable();
            } else if (node === "table:table-cell") {
                mdWriter.closeCell();
            }
        });

        saxStream.on("end", function () {
            mdWriter.addEnd();
            console.log('write to ' + path.join(outDir, outName + '.md'));
            fs.writeFile(path.join(outDir, outName + '.md'), mdWriter.text);
        });

        saxStream.on("text", function (t) {
            mdWriter.addText(t);
        });

        fs.createReadStream(this.contentName).pipe(saxStream);
    }
}

if(inDir) {
    var outSlidesJson = [];
    _.forEach(
        _.filter(
            fs.readdirSync(inDir),
            function (file) {
                return path.extname(file) === '.odp';
            }
        ),
        function (odp) {
            var conv = new OdpConverter(path.join(inDir, odp), outDir);
            outSlidesJson.push(conv.name + '.md');
            conv.extract();
            conv.convert();
        }
    );
    fs.writeFile(path.join(outDir, 'slides.json'), JSON.stringify(outSlidesJson, null, 2));
} else {
    var conv = new OdpConverter(inFile, outDir);
    conv.extract();
    conv.convert();
}
<commit_msg>Fix #19 ligne vide avant puce<commit_after>var fs = require('fs');
var path = require('path');
var sax = require("sax");
var AdmZip = require('adm-zip');
var _ = require('lodash');

var argv = require('minimist')(process.argv.slice(2));

if (!argv['d'] && !argv['f']) {
    console.log("no file or dir, use -d or -f argument");
    process.exit(1);
}

var outDir = argv['o'] || 'target';
var imgDir = 'ressources/images';

var inDir = argv["d"];
var inFile = argv["f"];

if (inDir && (!fs.existsSync(inDir) || !fs.statSync(inDir).isDirectory())) {
    console.log("directory not found", inDir);
    process.exit(1);
}
if (!inDir && !fs.existsSync(inFile)) {
    console.log("file not found", inFile);
    process.exit(1);
}

function MDWriter() {
    this.text = "";
    this.inCodeBlock = false;
    this.inNotes = false;
    this.listLevel = 0;
    this.titreAdded = false;
    this.mainTitleAdded = false;
    this.firstPage = false;

    this.addPage = function () {
        this.text += "\n\n\n\n";
        this.titreAdded = false;
        this.firstPage = true;
    };

    this.addParagraph = function () {
        if (this.inCodeBlock || this.inNotes) {
            this.text += "\n";
        }
    };

    this.addText = function (text) {
        if(this.firstPage && !this.mainTitleAdded) {
            this.text = '#' + text + '\n\n<!-- .slide: class="page-title" -->\n\n\n\n';
            this.mainTitleAdded = true;
        }
        else if (!this.titreAdded) {
            this.text += "## " + text + "\n";
            this.titreAdded = true;
        }
        else {
            this.text += text;
        }
    };

    this.addImage = function (path) {
        this.text += "\n\n![](ressources/images/" + path.replace("Pictures/", "") + ")\n";
    };

    this.startList = function () {
        this.listLevel++;
        if (this.listLevel == 1 && this.text[this.text.length-1] !== '\n') {
            this.text += '\n';
        }
    };

    this.endList = function () {
        this.listLevel--;
    };

    this.addBullet = function () {
        if (!this.listLevel) {
            console.warning("not in a list");
        }
        this.text += "\n" + new Array(this.listLevel).join("\t") + "- ";
    };

    this.addEnd = function () {
        this.text += "\n\n\n\n<!-- .slide: class=\"page-questions\" -->\n\n\n\n<!-- .slide: class=\"page-tp1\" -->";
    };

    this.startCodeBlock = function () {
        this.text += "\n```";
        this.inCodeBlock = true;
    };

    this.endCodeBlock = function () {
        this.text += "\n```\n";
        this.inCodeBlock = false;
    };

    this.startNotes = function () {
        this.text += "\nNotes :\n";
        this.inNotes = true;
    };

    this.endNotes = function () {
        this.inNotes = false;
    };

    this.startTable = function() {
        this.inTable = true;
        this.rowNumber = 0;
        this.colNumber = 0;
    }

    this.endTable = function() {
        this.inTable = false;
    }

    this.startRow = function() {
        this.text += "\n|";
        if (this.rowNumber == 1) {
            //If header was written we write separation line
            this.text += Array(this.colNumber + 1).join("---|") + "\n|";
        }
        this.rowNumber++;
    }

    this.closeCell = function() {
        if (this.rowNumber == 1) {
            this.colNumber++;
        }
        this.text += "|";
    }

}

function OdpConverter(filepath, outDir) {

    this.filePath = filepath;
    this.name = path.basename(this.filePath, '.odp').replace(/\s+/g, '_');
    this.contentName = path.join(outDir, this.name + '-content.xml');

    this.extract = function () {
        console.log('extract : ' + this.filePath);
        var zip = new AdmZip(this.filePath);
        var zipEntries = zip.getEntries();
        zipEntries.forEach(function (val) {
            if (val.entryName.indexOf("content.xml") >= 0) {
                //console.log(val.entryName);
                zip.extractEntryTo(val, outDir, true, true);
                fs.renameSync(path.join(outDir, val.entryName), this.contentName);
            }
            if (val.entryName.indexOf("Pictures") >= 0) {
                //console.log(val.entryName);
                zip.extractEntryTo(val, path.join(outDir, imgDir), false, true);
                var baseName = path.basename(val.entryName);
                fs.renameSync(path.join(outDir, imgDir, baseName), path.join(outDir, imgDir, this.name + '-' + baseName));
            }
        }.bind(this));
    };

    this.convert = function () {
        console.log('convert : ' + this.name);
        var mdWriter = new MDWriter();
        var outName = this.name;
        var saxStream = sax.createStream(true, {
            trim: true,
            normalize: true,
            xmlns: false,
            lowercase: true
        });

        saxStream.on("opentag", function (node) {

            if (node.name === "draw:page") {
                mdWriter.addPage();
            } else if (node.name === "draw:image") {
                mdWriter.addImage(outName + '-' + node.attributes["xlink:href"]);
            } else if (node.name === "text:list") {
                mdWriter.startList();
            } else if (node.name === "text:list-item") {
                mdWriter.addBullet();
            } else if (node.name === "draw:custom-shape" || node.name === "draw:rect") {
                mdWriter.startCodeBlock();
            } else if (node.name === "text:p") {
                mdWriter.addParagraph();
            } else if (node.name === "presentation:notes") {
                mdWriter.startNotes();
            } else if (node.name === "table:table") {
                mdWriter.startTable();
            } else if (node.name === "table:table-row") {
                mdWriter.startRow();
            }
        });

        saxStream.on("closetag", function (node) {

            if (node === "draw:custom-shape" || node === "draw:rect") {
                mdWriter.endCodeBlock();
            } else if (node === "text:list") {
                mdWriter.endList();
            } else if (node === "presentation:notes") {
                mdWriter.endNotes();
            } else if (node === "table:table") {
                mdWriter.endTable();
            } else if (node === "table:table-cell") {
                mdWriter.closeCell();
            }
        });

        saxStream.on("end", function () {
            mdWriter.addEnd();
            console.log('write to ' + path.join(outDir, outName + '.md'));
            fs.writeFile(path.join(outDir, outName + '.md'), mdWriter.text);
        });

        saxStream.on("text", function (t) {
            mdWriter.addText(t);
        });

        fs.createReadStream(this.contentName).pipe(saxStream);
    }
}

if(inDir) {
    var outSlidesJson = [];
    _.forEach(
        _.filter(
            fs.readdirSync(inDir),
            function (file) {
                return path.extname(file) === '.odp';
            }
        ),
        function (odp) {
            var conv = new OdpConverter(path.join(inDir, odp), outDir);
            outSlidesJson.push(conv.name + '.md');
            conv.extract();
            conv.convert();
        }
    );
    fs.writeFile(path.join(outDir, 'slides.json'), JSON.stringify(outSlidesJson, null, 2));
} else {
    var conv = new OdpConverter(inFile, outDir);
    conv.extract();
    conv.convert();
}
<|endoftext|>


<commit_before>// Load required modules
const http = require("http"); // http server core module
const path = require("path");
const express = require("express"); // web framework external module

// Set process name
process.title = "networked-aframe-server";

// Get port or default to 8080
const port = process.env.PORT || 8080;

// Setup and configure Express http server.
const app = express();
app.use(express.static(path.resolve(__dirname, "..", "examples")));

// Serve the example and build the bundle in development.
if (process.env.NODE_ENV === "development") {
  const webpackMiddleware = require("webpack-dev-middleware");
  const webpack = require("webpack");
  const config = require("../webpack.config");

  app.use(
    webpackMiddleware(webpack(config), {
      publicPath: "/"
    })
  );
}

// Start Express http server
const webServer = http.createServer(app);
const io = require("socket.io")(webServer);

const rooms = {};

io.on("connection", socket => {
  console.log("user connected", socket.id);

  let curRoom = null;

  socket.on("joinRoom", data => {
    const { room } = data;

    if (!rooms[room]) {
      rooms[room] = {
        name: room,
        occupants: {},
      };
    }

    const joinedTime = Date.now();
    rooms[room].occupants[socket.id] = joinedTime;
    curRoom = room;

    console.log(`${socket.id} joined room ${room}`);
    socket.join(room);

    socket.emit("connectSuccess", { joinedTime });
    const occupants = rooms[room].occupants;
    io.in(curRoom).emit("occupantsChanged", { occupants });
  });

  socket.on("send", data => {
    io.to(data.to).emit("send", data);
  });

  socket.on("broadcast", data => {
    socket.to(curRoom).broadcast.emit("broadcast", data);
  });

  socket.on("disconnect", () => {
    console.log('disconnected: ', socket.id, curRoom);
    if (rooms[curRoom]) {
      console.log("user disconnected", socket.id);

      delete rooms[curRoom].occupants[socket.id];
      const occupants = rooms[curRoom].occupants;
      socket.to(curRoom).broadcast.emit("occupantsChanged", { occupants });

      if (occupants == {}) {
        console.log("everybody left room");
        delete rooms[curRoom];
      }
    }
  });
});

webServer.listen(port, () => {
  console.log("listening on http://localhost:" + port);
});
<commit_msg>fix condition in socketio-server.js to remove the room if everybody left (refs #264)<commit_after>// Load required modules
const http = require("http"); // http server core module
const path = require("path");
const express = require("express"); // web framework external module

// Set process name
process.title = "networked-aframe-server";

// Get port or default to 8080
const port = process.env.PORT || 8080;

// Setup and configure Express http server.
const app = express();
app.use(express.static(path.resolve(__dirname, "..", "examples")));

// Serve the example and build the bundle in development.
if (process.env.NODE_ENV === "development") {
  const webpackMiddleware = require("webpack-dev-middleware");
  const webpack = require("webpack");
  const config = require("../webpack.config");

  app.use(
    webpackMiddleware(webpack(config), {
      publicPath: "/"
    })
  );
}

// Start Express http server
const webServer = http.createServer(app);
const io = require("socket.io")(webServer);

const rooms = {};

io.on("connection", socket => {
  console.log("user connected", socket.id);

  let curRoom = null;

  socket.on("joinRoom", data => {
    const { room } = data;

    if (!rooms[room]) {
      rooms[room] = {
        name: room,
        occupants: {},
      };
    }

    const joinedTime = Date.now();
    rooms[room].occupants[socket.id] = joinedTime;
    curRoom = room;

    console.log(`${socket.id} joined room ${room}`);
    socket.join(room);

    socket.emit("connectSuccess", { joinedTime });
    const occupants = rooms[room].occupants;
    io.in(curRoom).emit("occupantsChanged", { occupants });
  });

  socket.on("send", data => {
    io.to(data.to).emit("send", data);
  });

  socket.on("broadcast", data => {
    socket.to(curRoom).broadcast.emit("broadcast", data);
  });

  socket.on("disconnect", () => {
    console.log('disconnected: ', socket.id, curRoom);
    if (rooms[curRoom]) {
      console.log("user disconnected", socket.id);

      delete rooms[curRoom].occupants[socket.id];
      const occupants = rooms[curRoom].occupants;
      socket.to(curRoom).broadcast.emit("occupantsChanged", { occupants });

      if (Object.keys(occupants).length === 0) {
        console.log("everybody left room");
        delete rooms[curRoom];
      }
    }
  });
});

webServer.listen(port, () => {
  console.log("listening on http://localhost:" + port);
});
<|endoftext|>


<commit_before>var ldap = require('ldapjs');
var async = require('async');

module.exports = function CSHLDAP(username, password) {
  var USERS = 'ou=Users,dc=csh,dc=rit,dc=edu';
  var GROUPS = 'ou=Groups,dc=csh,dc=rit,dc=edu';
  var COMMITTEES = 'ou=Committees,dc=csh,dc=rit,dc=edu';
  var APPS = 'ou=Apps,dc=csh,dc=rit,dc=edu';

  var client = ldap.createClient({
    url: 'ldaps://ldap.csh.rit.edu:636'
  });

  function search(base, opts, callback) {
    client.search(base,opts,function(err,res) {
      if(err) callback(err);
      var users = [];
      res.on('searchEntry', function(entry) {
        users.push(entry.object);
      });
      res.on('searchReference', function(referral) {
        console.log('referral: ' + referral.uris.join());
      });
      res.on('error', function(err) {
        callback(err);
      });
      res.on('end', function(result) {
        callback(null,users);
      });
    });
  }

  function searchGroup(group, callback) {
    var groupName = group || '*';
    var opts = {
      filter: 'cn='+groupName,
      scope: 'sub',
      attributes: ['*','+']
    };
    search(GROUPS, opts, function(err, res) {
      if(err) return callback(res);
      else {
        if(res.length === 0) return callback(null,[]);
        var functions = [];
        var comm = [];
        var bases = res[0].member;
        var mOpts = {
          scope: 'sub',
          attributes: ['*','+']
        };
        for(var x=0; x < bases.length; x++) {
          functions.push(async.apply(search, bases[x],mOpts));
        }

        async.parallel(functions,function(err, results) {
          if(err) throw err;
          var users = [];
          for(var x=0; x < results.length; x++) {
            users.push(results[x][0]);
          }
          callback(null,users);
        });
      }
    });
  }

  return {
    getGroupMembers: function(group, callback) {
      searchGroup(group, callback);
    },
    drinkAdmins: function(callback) {
      searchGroup('drink',callback);
    },
    rtps: function(callback) {
      searchGroup('rtp',callback);
    },
    eboard: function(callback) {
      var opts = {
        scope: 'sub',
        attributes: ['*','+']
      };
      search(COMMITTEES,opts,function(err,res) {
        if(err) return callback(err);
        else {
          var functions = [];
          var comm = [];
          for(var x=1; x < res.length; x++) {
            if(res[x].head instanceof Array) {
              for(head in res[x].head) {
                functions.push(async.apply(search,res[x].head[head].toString(),opts));
                comm.push(res[x].cn);
              }
            } else {
              functions.push(async.apply(search,res[x].head.toString(),opts));
              comm.push(res[x].cn);
            }
          }
        }
          async.parallel(functions,function(err, results) {
            if(err) throw err;
            var users = [];
            for(var x=0; x < results.length; x++) {
              results[x][0].committee = comm[x];
              users.push(results[x][0]);
            }
            callback(null,users);
          });
        });
    },
    member: function(uid,callback) {
      var opts = {
        filter: 'uid='+uid,
        scope: 'sub',
        attributes: ['*','+']
      };
      search(USERS,opts,function(err,res) {
        if(err) callback(err);
        else callback(null,res);
      });
    },
    members: function(callback) {
      var opts = {
        filter: 'uid=*',
        scope: 'sub',
        attributes: ['*','+']
      };
      search(USERS,opts,function(err,res) {
        if(err) callback(err);
        else callback(null,res);
      });
    },
    getClient: function() {
      return client;
    }
  };
};

<commit_msg>Created a searchMember function<commit_after>var ldap = require('ldapjs');
var async = require('async');

module.exports = function CSHLDAP(username, password) {
  var USERS = 'ou=Users,dc=csh,dc=rit,dc=edu';
  var GROUPS = 'ou=Groups,dc=csh,dc=rit,dc=edu';
  var COMMITTEES = 'ou=Committees,dc=csh,dc=rit,dc=edu';
  var APPS = 'ou=Apps,dc=csh,dc=rit,dc=edu';

  var client = ldap.createClient({
    url: 'ldaps://ldap.csh.rit.edu:636'
  });

  function search(base, opts, callback) {
    client.search(base,opts,function(err,res) {
      if(err) callback(err);
      var users = [];
      res.on('searchEntry', function(entry) {
        users.push(entry.object);
      });
      res.on('searchReference', function(referral) {
        console.log('referral: ' + referral.uris.join());
      });
      res.on('error', function(err) {
        callback(err);
      });
      res.on('end', function(result) {
        callback(null,users);
      });
    });
  }

  function searchGroup(group, callback) {
    var groupName = group || '*';
    var opts = {
      filter: 'cn='+groupName,
      scope: 'sub',
      attributes: ['*','+']
    };
    search(GROUPS, opts, function(err, res) {
      if(err) return callback(res);
      else {
        if(res.length === 0) return callback(null,[]);
        var functions = [];
        var comm = [];
        var bases = res[0].member;
        var mOpts = {
          scope: 'sub',
          attributes: ['*','+']
        };
        for(var x=0; x < bases.length; x++) {
          functions.push(async.apply(search, bases[x],mOpts));
        }

        async.parallel(functions,function(err, results) {
          if(err) throw err;
          var users = [];
          for(var x=0; x < results.length; x++) {
            users.push(results[x][0]);
          }
          callback(null,users);
        });
      }
    });
  }

  function searchMember(uid, callback) {
    var id = uid || '*';
    var opts = {
      filter: 'uid='+id,
      scope: 'sub',
      attributes: ['*','+']
    };
    search(USERS,opts,function(err,res) {
      if(err) callback(err);
      else callback(null,res);
    });
  }

  return {
    getGroupMembers: function(group, callback) {
      searchGroup(group, callback);
    },
    drinkAdmins: function(callback) {
      searchGroup('drink',callback);
    },
    rtps: function(callback) {
      searchGroup('rtp',callback);
    },
    eboard: function(callback) {
      var opts = {
        scope: 'sub',
        attributes: ['*','+']
      };
      search(COMMITTEES,opts,function(err,res) {
        if(err) return callback(err);
        else {
          var functions = [];
          var comm = [];
          for(var x=1; x < res.length; x++) {
            if(res[x].head instanceof Array) {
              for(head in res[x].head) {
                functions.push(async.apply(search,res[x].head[head].toString(),opts));
                comm.push(res[x].cn);
              }
            } else {
              functions.push(async.apply(search,res[x].head.toString(),opts));
              comm.push(res[x].cn);
            }
          }
        }
          async.parallel(functions,function(err, results) {
            if(err) throw err;
            var users = [];
            for(var x=0; x < results.length; x++) {
              results[x][0].committee = comm[x];
              users.push(results[x][0]);
            }
            callback(null,users);
          });
        });
    },
    member: function(uid,callback) {
      searchMember(uid,callback);
    },
    members: function(callback) {
      searchMember('*',callback);
    },
    getClient: function() {
      return client;
    }
  };
};

<|endoftext|>


<commit_before>

$(function() {

    var menu_number;
    switch(window.location.pathname) {
        case '/posizione-generale.php':
            menu_number = 0;
            break;
        case '/posizione-contributiva.php':
            menu_number = 0;
            break;
        case '/consultazione-cedolini.php':
            menu_number = 0;
            break;
        case '/consultazione-cu-cud.php':
            menu_number = 0;
            break;

        default:
            cmenu_number = -1;
    }

    var menu_number;
    switch(window.location.pathname) {

        case '/richiesta-piccolo-prestito.php':
            menu_number = 0;
            break;
        case '/richiesta-anticipazione-ifr-tfr.php':
            menu_number = 0;
            break;
        case '/variazione-dati-utente.php':
            menu_number = 0;
            break;

        default:
            cmenu_number = -1;
    }

    var menu_number;
    switch(window.location.pathname) {

        case '/visualizzazione-tfr.php':
            menu_number = 0;
            break;
        case '/visualizzazione-ifr.php':
            menu_number = 0;
            break;

        default:
            cmenu_number = -1;
    }

    var menu_number;
    switch(window.location.pathname) {

        case '/tool-prestiti.php':
            menu_number = 0;
            break;

        default:
            cmenu_number = -1;
    }

    $($('.treeview-menu')[menu_number]).css({
        display: 'block'
    });
    $($('.treeview-menu')[menu_number]).parent().toggleClass('menu-open');
});
<commit_msg>Update main.js<commit_after>

$(function() {

    var menu_number;
    switch(window.location.pathname) {
        case '/posizione-generale.php':
            menu_number = 0;
            break;
        case '/posizione-contributiva.php':
            menu_number = 0;
            break;
        case '/consultazione-cedolini.php':
            menu_number = 0;
            break;
        case '/consultazione-cu-cud.php':
            menu_number = 0;
            break;

        default:
            cmenu_number = -1;
    }

    var menu_number 1;
    switch(window.location.pathname) {

        case '/richiesta-piccolo-prestito.php':
            menu_number = 1;
            break;
        case '/richiesta-anticipazione-ifr-tfr.php':
            menu_number = 1;
            break;
        case '/variazione-dati-utente.php':
            menu_number = 1;
            break;

        default:
            cmenu_number = -1;
    }

    var menu_number 2;
    switch(window.location.pathname) {

        case '/visualizzazione-tfr.php':
            menu_number = 2;
            break;
        case '/visualizzazione-ifr.php':
            menu_number = 2;
            break;

        default:
            cmenu_number = -1;
    }

    var menu_number 3;
    switch(window.location.pathname) {

        case '/tool-prestiti.php':
            menu_number = 3;
            break;

        default:
            cmenu_number = -1;
    }

    $($('.treeview-menu')[menu_number]).css({
        display: 'block'
    });
    $($('.treeview-menu')[menu_number]).parent().toggleClass('menu-open');
});
<|endoftext|>


<commit_before>// Copyright 2014, Renasar Technologies Inc.
/* jshint: node:true */
'use strict';

var di = require('di');

module.exports = factory;
di.annotate(factory, new di.Provide('Task.Task'));
    di.annotate(factory,
    new di.Inject(
        'Protocol.Task',
        'Logger',
        'Assert',
        'uuid',
        'Q',
        '_',
        di.Injector
    )
);

/**
 * Injectable wrapper for dependencies
 * @param logger
 */
function factory(taskProtocol, Logger, assert, uuid, Q, _, injector) {
    var logger = Logger.initialize(factory);

    /**
     *
     * @param taskGraph
     * @param optionOverrides
     * @returns {factory.Task}
     * @constructor
     */
    function Task(definition, taskOverrides) {
        if (!(this instanceof Task)) {
            return new Task(definition);
        }

        assert.object(definition, 'Task definition data');
        assert.string(definition.friendlyName, 'Task definition friendly name');
        assert.string(definition.implementsTask, 'Task definition implementsTask');
        assert.string(definition.runJob, 'Task definition job name');
        assert.object(definition.options, 'Task definition option');
        assert.object(definition.properties, 'Task definition properties');

        this.definition = Object.freeze(_.cloneDeep(definition));
        var optionDefaults = {};
        this.options = _.defaults(definition, optionDefaults);

        this.id = uuid.v4();

        // run state related properties
        this.cancelled = false;
        this.retriesAttempted = 0;
        taskOverrides = taskOverrides || {};
        this.retriesAllowed = taskOverrides.retriesAllowed || 5;

        this.instanceId = taskOverrides.instanceId || uuid();
        this.name = taskOverrides.name || this.options.injectableName;
        this.waitingOn = taskOverrides.waitingOn || [];
        this.status = 'waiting';
        this.tags = [];

        // this.work = task;
        this.dependents = [];
        this.outcome = 'pending';
        this.stats = {
            created: new Date(),
            started: null,
            completed: null
        };

        // tags for categorization and hinting functionality
        this.properties = definition.properties;

        this.context = {
            // starts as false, this is changed to true if the job is cancelled
            // or times out - this is the place to check inside a loop whether
            // to continue to do work.
            canceled: false,
            local: {
                stats: {}
            },
            parent: {}
        };

        // state of the current object
        this.state = 'pending';

        // hint to whatever is running the task when it is successful
        this.successStates = ['succeeded'];

        // hint to whatever is running the task when it has failed
        this.failedStates = ['failed', 'timeout', 'canceled'];

        return this;
    }

    Task.prototype.work = function () {

    };

    //when someone finsihes a http requests for a specific file from a specifc ip
    Task.prototype.changeState = function (state) {
        state;
    };

    Task.prototype.waitOn = function (waitObject) {
        assert.equal(this.status, 'waiting', 'only newly initialized or still ' +
        'waiting tasks can add additional tasks to wait on');
        this.waitingOn.push(waitObject);
        return this;
    };

    Task.prototype.run = function () {
        var self = this;
        assert.string(this.options.runJob, 'Task.options.runJob injector string');
        self.job = injector.get(this.options.runJob);
        self.state = 'started';
        return self.job.run().then(function() {
            if (!self.outcome) {
                self.outcome = 'succeeded';
            } else {
                logger.warning("Task job succeeded after task had already completed.", {
                    taskId: self.instanceId,
                    task: self
                });
            }
        }).catch(function(error) {
            if (!self.outcome) {
                self.outcome = 'failed';
                self.error = error;
            } else {
                logger.warning("Task job failed after task had already completed.", {
                    error: error,
                    taskId: self.instanceId,
                    task: self
                });
            }
        });
    };

    Task.prototype.cancel = function() {
        var self = this;
        return self.job.cancel().catch(function(error) {
            logger.error("Error canceling Task job.", {
                error: error,
                taskId: self.instanceId,
                job: self.options.runJob,
                task: self
            });
        });
    };

    // TODO: move this into renasar-taskgraph
    /*
    Task.prototype.validate = function() {
        var self = this;
        var taskInterface;
        var job;

        try {
            taskInterface = injector.get(this.definition.implementsTask);
        } catch (e) {
            logger.error("Caught error loading task: ", {
                error: e,
                taskId: this.id
            });
            throw new Error("Task implements " + this.definition.implementsTask +
                    " but it could not be loaded.");
        }

        _.forEach(taskInterface.requiredOptions, function(op) {
            if (!_.has(self.options, op)) {
                throw new Error("Missing required option: " + op);
            }
        });

        try {
            job = injector.get(taskInterface.runJob);
        } catch (e) {
            logger.error("Caught error loading task: ", {
                error: e,
                taskId: this.id
            });
            throw new Error("Task runs job " + taskInterface.runJob +
                    " but it could not be loaded.");
        }
    };
    */

    Task.start = function start() {
        var self = this;
        return Q.all([
            taskProtocol.subscribeRun(self.instanceId, self.run),
            taskProtocol.subscribeCancel(self.instanceId, self.cancel)
        ]).then(function() {
            logger.info("Starting task.", {
                taskId: self.instanceId,
                name: self.options.friendlyName
            });
        }).catch(function(error) {
            logger.error("Error starting Task subscriptions.", {
                error: error,
                taskId: self.instanceId,
                task: self
            });
        });
    };

    Task.create = function create(definition, taskOverrides) {
        var task = new Task(definition, taskOverrides);
        task.start();
        return task;
    };

    Task.createRegistryObject = function (definition) {
        var _definition = _.cloneDeep(definition);
        return {
            create: function(definitionOverrides, taskOverrides) {
                var _definition = _.cloneDeep(definition);
                var options = _.defaults(_definition, definitionOverrides);
                return Task.create(options, taskOverrides);
            },
            definition: Object.freeze(_definition)
        };
    };

    return Task;
}
<commit_msg>Task subscription fixes<commit_after>// Copyright 2014, Renasar Technologies Inc.
/* jshint: node:true */
'use strict';

var di = require('di');

module.exports = factory;
di.annotate(factory, new di.Provide('Task.Task'));
    di.annotate(factory,
    new di.Inject(
        'Protocol.Task',
        'Protocol.Events',
        'Logger',
        'Assert',
        'uuid',
        'Q',
        '_',
        di.Injector
    )
);

/**
 * Injectable wrapper for dependencies
 * @param logger
 */
function factory(taskProtocol, eventsProtocol, Logger, assert, uuid, Q, _, injector) {
    var logger = Logger.initialize(factory);

    /**
     *
     * @param taskGraph
     * @param optionOverrides
     * @returns {factory.Task}
     * @constructor
     */
    function Task(definition, taskOverrides) {
        if (!(this instanceof Task)) {
            return new Task(definition);
        }

        assert.object(definition, 'Task definition data');
        assert.string(definition.friendlyName, 'Task definition friendly name');
        assert.string(definition.implementsTask, 'Task definition implementsTask');
        assert.string(definition.runJob, 'Task definition job name');
        assert.object(definition.options, 'Task definition option');
        assert.object(definition.properties, 'Task definition properties');

        this.definition = Object.freeze(_.cloneDeep(definition));
        var optionDefaults = {};
        this.options = _.defaults(definition, optionDefaults);

        this.id = uuid.v4();

        // run state related properties
        this.cancelled = false;
        this.retriesAttempted = 0;
        taskOverrides = taskOverrides || {};
        this.retriesAllowed = taskOverrides.retriesAllowed || 5;

        this.instanceId = taskOverrides.instanceId || uuid();
        this.name = taskOverrides.name || this.options.injectableName;
        this.waitingOn = taskOverrides.waitingOn || [];
        this.status = 'waiting';
        this.tags = [];
        this.subscriptions = {};

        // this.work = task;
        this.dependents = [];
        this.outcome = 'pending';
        this.stats = {
            created: new Date(),
            started: null,
            completed: null
        };

        // tags for categorization and hinting functionality
        this.properties = definition.properties;

        this.context = {
            // starts as false, this is changed to true if the job is cancelled
            // or times out - this is the place to check inside a loop whether
            // to continue to do work.
            canceled: false,
            local: {
                stats: {}
            },
            parent: {}
        };

        // state of the current object
        this.state = 'pending';

        // hint to whatever is running the task when it is successful
        this.successStates = ['succeeded'];

        // hint to whatever is running the task when it has failed
        this.failedStates = ['failed', 'timeout', 'canceled'];

        return this;
    }

    Task.prototype.work = function () {

    };

    //when someone finsihes a http requests for a specific file from a specifc ip
    Task.prototype.changeState = function (state) {
        state;
    };

    Task.prototype.waitOn = function (waitObject) {
        assert.equal(this.status, 'waiting', 'only newly initialized or still ' +
        'waiting tasks can add additional tasks to wait on');
        this.waitingOn.push(waitObject);
        return this;
    };

    Task.prototype.run = function () {
        var self = this;
        self.state = 'running';
        assert.string(this.options.runJob, 'Task.options.runJob injector string');
        self.job = injector.get(this.options.runJob);
        logger.info("Running task job.", {
            taskId: self.instanceId,
            name: self.options.friendlyName,
            job: self.options.runJob
        });
        return self.job.run().then(function() {
            if (self.outcome !== 'running') {
                self.outcome = 'succeeded';
            } else {
                logger.warning("Task job succeeded after task had already completed.", {
                    taskId: self.instanceId,
                    task: self
                });
            }
            eventsProtocol.publishTaskFinished(self.instanceId);
        }).catch(function(error) {
            if (self.outcome !== 'running') {
                self.outcome = 'failed';
                self.error = error;
            } else {
                logger.warning("Task job failed after task had already completed.", {
                    error: error,
                    taskId: self.instanceId,
                    task: self
                });
            }
            eventsProtocol.publishTaskFinished(self.instanceId);
        });
    };

    Task.prototype.cancel = function() {
        var self = this;
        self.outcome = 'canceled';
        return Q.all(_.map(self.subscriptions, function(subscription) {
            return subscription.dispose();
        })).then(function() {
            return self.job.cancel();
        }).catch(function(error) {
            logger.error("Error canceling Task job.", {
                error: error,
                taskId: self.instanceId,
                job: self.options.runJob,
                task: self
            });
        });
    };

    // TODO: move this into renasar-taskgraph
    /*
    Task.prototype.validate = function() {
        var self = this;
        var taskInterface;
        var job;

        try {
            taskInterface = injector.get(this.definition.implementsTask);
        } catch (e) {
            logger.error("Caught error loading task: ", {
                error: e,
                taskId: this.id
            });
            throw new Error("Task implements " + this.definition.implementsTask +
                    " but it could not be loaded.");
        }

        _.forEach(taskInterface.requiredOptions, function(op) {
            if (!_.has(self.options, op)) {
                throw new Error("Missing required option: " + op);
            }
        });

        try {
            job = injector.get(taskInterface.runJob);
        } catch (e) {
            logger.error("Caught error loading task: ", {
                error: e,
                taskId: this.id
            });
            throw new Error("Task runs job " + taskInterface.runJob +
                    " but it could not be loaded.");
        }
    };
    */

    Task.prototype.start = function start() {
        var self = this;
        return Q.all([
            taskProtocol.subscribeRun(self.instanceId, self.run.bind(self)),
            taskProtocol.subscribeCancel(self.instanceId, self.cancel.bind(self))
        ]).spread(function(runSubscription, cancelSubscription) {
            self.subscriptions.run = runSubscription;
            self.subscriptions.cancel = cancelSubscription;
            logger.info("Starting task.", {
                taskId: self.instanceId,
                name: self.options.friendlyName
            });
            self.state = 'started';
        }).catch(function(error) {
            logger.error("Error starting Task subscriptions.", {
                error: error,
                taskId: self.instanceId,
                task: self
            });
        });
    };

    Task.create = function create(definition, taskOverrides) {
        var task = new Task(definition, taskOverrides);
        return task;
    };

    Task.createRegistryObject = function (definition) {
        var _definition = _.cloneDeep(definition);
        return {
            create: function(definitionOverrides, taskOverrides) {
                var _definition = _.cloneDeep(definition);
                var options = _.defaults(_definition, definitionOverrides);
                return Task.create(options, taskOverrides);
            },
            definition: Object.freeze(_definition)
        };
    };

    return Task;
}
<|endoftext|>


<commit_before>var uuid = require('node-uuid'),
    jsface = require('jsface'),
    url = require('url'),
    META_KEY = 'x-postman-meta',

    ConvertResult = function (status, message) {
        this.status = status;
        this.message = message;
    },

    Swagger2Postman = jsface.Class({
        constructor: function (options) {
            this.collectionJson = {
                'id': '',
                'name': '',
                'description': '',
                'order': [],
                'folders': [],
                'timestamp': 1413302258635,
                'synced': false,
                'requests': []
            };
            this.basePath = '';
            this.collectionId = '';
            this.folders = {};
            this.baseParams = {};
            this.logger = function () {
            };

            this.options = options || {};

            this.options.includeQueryParams = typeof (this.options.includeQueryParams) == 'undefined' ?
                                                        true : this.options.includeQueryParams;
        },

        setLogger: function (func) {
            this.logger = func;
        },

        validate: function (json) {
            if (!json.hasOwnProperty('swagger') || json.swagger !== '2.0') {
                return new ConvertResult('failed', 'Must contain a swagger field (2.0)');
            }

            if (!json.hasOwnProperty('info')) {
                return new ConvertResult('failed', 'Must contain an info object');
            }
            else {
                var info = json.info;
                if (!info || !info.title) {
                    return new ConvertResult('failed', 'Must contain info.title');
                }
            }

            return new ConvertResult('passed', '');
        },

        setBasePath: function (json) {
            this.basePath = '';
            if (json.host) {
                this.basePath = json.host;
            }
            if (json.basePath) {
                this.basePath += json.basePath;
            }

            if (json.schemes && json.schemes.indexOf('https') != -1) {
                this.basePath = 'https://' + this.basePath;
            }
            else {
                this.basePath = 'http://' + this.basePath;
            }

            if (!this.endsWith(this.basePath, '/')) {
                this.basePath += '/';
            }
        },

        getFolderNameForPath: function (pathUrl) {
            if (pathUrl == '/') {
                return null;
            }
            var segments = pathUrl.split('/'),
                numSegments = segments.length,
                folderName = null;
            this.logger('Getting folder name for path: ' + pathUrl);
            this.logger('Segments: ' + JSON.stringify(segments));
            if (numSegments > 1) {
                folderName = segments[1];

                // create a folder for this path url
                if (!this.folders[folderName]) {
                    this.folders[folderName] = this.createNewFolder(folderName);
                }
                this.logger('For path ' + pathUrl + ', returning folderName ' + this.folders[folderName].name);
                return this.folders[folderName].name;
            }
            else {
                this.logger('Error - path MUST begin with /');
                return null;
            }
        },

        createNewFolder: function (name) {
            var newFolder = {
                'id': uuid.v4(),
                'name': name,
                'description': 'Folder for ' + name,
                'order': [],
                'collection_name': this.collectionJson.name,
                'collection_id': this.collectionId,
                'collection': this.collectionId
            };
            this.logger('Created folder ' + newFolder.name);
            return newFolder;
        },

        handleInfo: function (json) {
            this.collectionJson.name = json.info.title;
            this.collectionJson.description = json.info.description;
        },

        getParamsForPathItem: function (oldParams, newParams) {
            var retVal = {},
                numOldParams,
                numNewParams,
                i,
                parts,
                lastPart,
                getBaseParam;

            oldParams = oldParams || [];
            newParams = newParams || [];

            numOldParams = oldParams.length;
            numNewParams = newParams.length;

            for (i = 0; i < numOldParams; i++) {
                if (oldParams[i].$ref) {
                    // this is a ref
                    if (oldParams[i].$ref.indexOf('#/parameters') === 0) {
                        parts = oldParams[i].$ref.split('/');
                        lastPart = parts[parts.length - 1];
                        getBaseParam = this.baseParams[lastPart];
                        retVal[lastPart] = getBaseParam;
                    }
                }
                else {
                    retVal[oldParams[i].name] = oldParams[i];
                }
            }

            for (i = 0; i < numNewParams; i++) {
                if (newParams[i].$ref) {
                    // this is a ref
                    if (newParams[i].$ref.indexOf('#/parameters') === 0) {
                        parts = newParams[i].$ref.split('/');
                        lastPart = parts[parts.length - 1];
                        getBaseParam = this.baseParams[lastPart];
                        retVal[lastPart] = getBaseParam;
                    }
                }
                else {
                    retVal[newParams[i].name] = newParams[i];
                }
            }

            return retVal;
        },

        addOperationToFolder: function (path, method, operation, folderName, params) {
            var root = this,
                request = {
                    'id': uuid.v4(),
                    'headers': '',
                    'url': '',
                    'pathVariables': {},
                    'preRequestScript': '',
                    'method': 'GET',
                    'data': [],
                    'dataMode': 'params',
                    'description': operation.description || '',
                    'descriptionFormat': 'html',
                    'time': '',
                    'version': 2,
                    'responses': [],
                    'tests': '',
                    'collectionId': root.collectionId,
                    'synced': false
                },
                thisParams = this.getParamsForPathItem(params, operation.parameters),
                hasQueryParams = false,
                param,
                requestAttr,
                thisConsumes = root.globalConsumes;

            if (path.length > 0 && path[0] === '/') {
                path = path.substring(1);
            }
            request.url = decodeURI(url.resolve(this.basePath, path));
            request.method = method;
            request.name = operation.summary;
            request.time = (new Date()).getTime();

            // Handle custom swagger attributes for postman aws integration
            if (operation[META_KEY]) {
                for (requestAttr in operation[META_KEY]) {
                    if (operation[META_KEY].hasOwnProperty(requestAttr)) {
                        request[requestAttr] = operation[META_KEY][requestAttr];
                    }
                }
            }

            if (operation.consumes) {
                thisConsumes = operation.consumes;
            }
            // set the default dataMode for this request, even if it doesn't have a body
            // eg. for GET requests
            if (thisConsumes.indexOf('application/x-www-form-urlencoded') > -1) {
                request.dataMode = 'urlencoded';
            }

            // set data and headers
            for (param in thisParams) {
                if (thisParams.hasOwnProperty(param) && thisParams[param]) {
                    this.logger('Processing param: ' + JSON.stringify(param));
                    if (thisParams[param].in === 'query' && this.options.includeQueryParams !== false) {
                        if (!hasQueryParams) {
                            hasQueryParams = true;
                            request.url += '?';
                        }
                        request.url += thisParams[param].name + '={{' + thisParams[param].name + '}}&';
                    }

                    else if (thisParams[param].in === 'header') {
                        request.headers += thisParams[param].name + ': {{' + thisParams[param].name + '}}\n';
                    }

                    else if (thisParams[param].in === 'body') {
                        request.dataMode = 'raw';
                        request.data = thisParams[param].description;
                    }

                    else if (thisParams[param].in === 'formData') {
                        if (thisConsumes.indexOf('application/x-www-form-urlencoded') > -1) {
                            request.dataMode = 'urlencoded';
                        }
                        else {
                            request.dataMode = 'params';
                        }
                        request.data.push({
                            'key': thisParams[param].name,
                            'value': '{{' + thisParams[param].name + '}}',
                            'type': 'text',
                            'enabled': true
                        });
                    } // (thisParams[param].in === 'path') case not handled
                }
            }

            if (hasQueryParams && this.endsWith(request.url, '&')) {
                request.url = request.url.slice(0, -1);
            }

            this.collectionJson.requests.push(request);
            if (folderName !== null) {
                this.folders[folderName].order.push(request.id);
            }
            else {
                this.collectionJson.order.push(request.id);
            }
        },

        addPathItemToFolder: function (path, pathItem, folderName) {
            if (pathItem.$ref) {
                this.logger('Error - cannot handle $ref attributes');
                return;
            }

            var paramsForPathItem = this.getParamsForPathItem(this.baseParams, pathItem.parameters),
                acceptedPostmanVerbs = [
                    'get', 'put', 'post', 'patch', 'delete', 'copy', 'head', 'options',
                    'link', 'unlink', 'purge', 'lock', 'unlock', 'propfind', 'view'],
                numVerbs = acceptedPostmanVerbs.length,
                i,
                verb;

            // replace path variables {petId} with {{..}}
            if (path) {
                path = path.replace('{', '{{').replace('}', '}}');
            }

            for (i = 0; i < numVerbs; i++) {
                verb = acceptedPostmanVerbs[i];
                if (pathItem[verb]) {
                    this.addOperationToFolder(
                        path,
                        verb.toUpperCase(),
                        pathItem[verb],
                        folderName,
                        paramsForPathItem
                    );
                }
            }
        },

        handlePaths: function (json) {
            var paths = json.paths,
                path,
                folderName;

            // Add a folder for each path
            for (path in paths) {
                if (paths.hasOwnProperty(path)) {
                    folderName = this.getFolderNameForPath(path);
                    this.logger('Adding path item. path = ' + path + '   folder = ' + folderName);
                    this.addPathItemToFolder(path, paths[path], folderName);
                }
            }
        },

        handleParams: function (params, level) {
            if (!params) {
                return;
            }
            if (level === 'collection') {
                // base params
                for (var param in params) {
                    if (params.hasOwnProperty(param)) {
                        this.logger('Adding collection param: ' + param);
                        this.baseParams[param] = params[param];
                    }
                }
            }
        },

        addFoldersToCollection: function () {
            var folderName;
            for (folderName in this.folders) {
                if (this.folders.hasOwnProperty(folderName)) {
                    this.collectionJson.folders.push(this.folders[folderName]);
                }
            }
        },

        convert: function (json) {
            var validationResult = this.validate(json);
            if (validationResult.status === 'failed') {
                // error
                return validationResult;
            }

            this.collectionId = uuid.v4();

            this.globalConsumes = json.consumes || [];

            this.handleParams(json.parameters, 'collection');

            this.handleInfo(json);

            this.setBasePath(json);

            this.handlePaths(json);

            this.addFoldersToCollection();

            this.collectionJson.id = this.collectionId;
            // this.logger(JSON.stringify(this.collectionJson));
            this.logger('Swagger converted successfully');

            validationResult.collection = this.collectionJson;

            return validationResult;
        },

        // since travis doesnt support es6
        endsWith: function (str, suffix) {
            return str.indexOf(suffix, str.length - suffix.length) !== -1;
        }
    });

module.exports = Swagger2Postman;
<commit_msg>GH#2048 - Temporary removal of {{ and }} so that url.resolve works correctly<commit_after>var uuid = require('node-uuid'),
    jsface = require('jsface'),
    url = require('url'),
    META_KEY = 'x-postman-meta',

    ConvertResult = function (status, message) {
        this.status = status;
        this.message = message;
    },

    Swagger2Postman = jsface.Class({
        constructor: function (options) {
            this.collectionJson = {
                'id': '',
                'name': '',
                'description': '',
                'order': [],
                'folders': [],
                'timestamp': 1413302258635,
                'synced': false,
                'requests': []
            };
            this.basePath = '';
            this.collectionId = '';
            this.folders = {};
            this.baseParams = {};
            this.logger = function () {
            };

            this.options = options || {};

            this.options.includeQueryParams = typeof (this.options.includeQueryParams) == 'undefined' ?
                                                        true : this.options.includeQueryParams;
        },

        setLogger: function (func) {
            this.logger = func;
        },

        validate: function (json) {
            if (!json.hasOwnProperty('swagger') || json.swagger !== '2.0') {
                return new ConvertResult('failed', 'Must contain a swagger field (2.0)');
            }

            if (!json.hasOwnProperty('info')) {
                return new ConvertResult('failed', 'Must contain an info object');
            }
            else {
                var info = json.info;
                if (!info || !info.title) {
                    return new ConvertResult('failed', 'Must contain info.title');
                }
            }

            return new ConvertResult('passed', '');
        },

        setBasePath: function (json) {
            this.basePath = '';
            if (json.host) {
                this.basePath = json.host;
            }
            if (json.basePath) {
                this.basePath += json.basePath;
            }

            if (json.schemes && json.schemes.indexOf('https') != -1) {
                this.basePath = 'https://' + this.basePath;
            }
            else {
                this.basePath = 'http://' + this.basePath;
            }

            if (!this.endsWith(this.basePath, '/')) {
                this.basePath += '/';
            }
        },

        getFolderNameForPath: function (pathUrl) {
            if (pathUrl == '/') {
                return null;
            }
            var segments = pathUrl.split('/'),
                numSegments = segments.length,
                folderName = null;
            this.logger('Getting folder name for path: ' + pathUrl);
            this.logger('Segments: ' + JSON.stringify(segments));
            if (numSegments > 1) {
                folderName = segments[1];

                // create a folder for this path url
                if (!this.folders[folderName]) {
                    this.folders[folderName] = this.createNewFolder(folderName);
                }
                this.logger('For path ' + pathUrl + ', returning folderName ' + this.folders[folderName].name);
                return this.folders[folderName].name;
            }
            else {
                this.logger('Error - path MUST begin with /');
                return null;
            }
        },

        createNewFolder: function (name) {
            var newFolder = {
                'id': uuid.v4(),
                'name': name,
                'description': 'Folder for ' + name,
                'order': [],
                'collection_name': this.collectionJson.name,
                'collection_id': this.collectionId,
                'collection': this.collectionId
            };
            this.logger('Created folder ' + newFolder.name);
            return newFolder;
        },

        handleInfo: function (json) {
            this.collectionJson.name = json.info.title;
            this.collectionJson.description = json.info.description;
        },

        getParamsForPathItem: function (oldParams, newParams) {
            var retVal = {},
                numOldParams,
                numNewParams,
                i,
                parts,
                lastPart,
                getBaseParam;

            oldParams = oldParams || [];
            newParams = newParams || [];

            numOldParams = oldParams.length;
            numNewParams = newParams.length;

            for (i = 0; i < numOldParams; i++) {
                if (oldParams[i].$ref) {
                    // this is a ref
                    if (oldParams[i].$ref.indexOf('#/parameters') === 0) {
                        parts = oldParams[i].$ref.split('/');
                        lastPart = parts[parts.length - 1];
                        getBaseParam = this.baseParams[lastPart];
                        retVal[lastPart] = getBaseParam;
                    }
                }
                else {
                    retVal[oldParams[i].name] = oldParams[i];
                }
            }

            for (i = 0; i < numNewParams; i++) {
                if (newParams[i].$ref) {
                    // this is a ref
                    if (newParams[i].$ref.indexOf('#/parameters') === 0) {
                        parts = newParams[i].$ref.split('/');
                        lastPart = parts[parts.length - 1];
                        getBaseParam = this.baseParams[lastPart];
                        retVal[lastPart] = getBaseParam;
                    }
                }
                else {
                    retVal[newParams[i].name] = newParams[i];
                }
            }

            return retVal;
        },

        addOperationToFolder: function (path, method, operation, folderName, params) {
            var root = this,
                request = {
                    'id': uuid.v4(),
                    'headers': '',
                    'url': '',
                    'pathVariables': {},
                    'preRequestScript': '',
                    'method': 'GET',
                    'data': [],
                    'dataMode': 'params',
                    'description': operation.description || '',
                    'descriptionFormat': 'html',
                    'time': '',
                    'version': 2,
                    'responses': [],
                    'tests': '',
                    'collectionId': root.collectionId,
                    'synced': false
                },
                thisParams = this.getParamsForPathItem(params, operation.parameters),
                hasQueryParams = false,
                param,
                requestAttr,
                thisConsumes = root.globalConsumes;

            if (path.length > 0 && path[0] === '/') {
                path = path.substring(1);
            }

            //Problem here
            //url.resolve("http://host.com/", "/api") returns "http://host.com/api"
            //but url.resolve("http://{{host}}.com/", "/api") returns "http:///%7B..host.com/api"
            //(note the extra slash after http:)
            //request.url = decodeURI(url.resolve(this.basePath, path));

            var tempBasePath = this.basePath
                .replace(/{{/g,"POSTMAN_VARIABLE_OPEN_DB")
                .replace(/}}/g,"POSTMAN_VARIABLE_CLOSE_DB");

            request.url = decodeURI(url.resolve(tempBasePath, path))
                .replace(/POSTMAN_VARIABLE_OPEN_DB/g,"{{")
                .replace(/POSTMAN_VARIABLE_CLOSE_DB/g,"}}");

            request.method = method;
            request.name = operation.summary;
            request.time = (new Date()).getTime();

            // Handle custom swagger attributes for postman aws integration
            if (operation[META_KEY]) {
                for (requestAttr in operation[META_KEY]) {
                    if (operation[META_KEY].hasOwnProperty(requestAttr)) {
                        request[requestAttr] = operation[META_KEY][requestAttr];
                    }
                }
            }

            if (operation.consumes) {
                thisConsumes = operation.consumes;
            }
            // set the default dataMode for this request, even if it doesn't have a body
            // eg. for GET requests
            if (thisConsumes.indexOf('application/x-www-form-urlencoded') > -1) {
                request.dataMode = 'urlencoded';
            }

            // set data and headers
            for (param in thisParams) {
                if (thisParams.hasOwnProperty(param) && thisParams[param]) {
                    this.logger('Processing param: ' + JSON.stringify(param));
                    if (thisParams[param].in === 'query' && this.options.includeQueryParams !== false) {
                        if (!hasQueryParams) {
                            hasQueryParams = true;
                            request.url += '?';
                        }
                        request.url += thisParams[param].name + '={{' + thisParams[param].name + '}}&';
                    }

                    else if (thisParams[param].in === 'header') {
                        request.headers += thisParams[param].name + ': {{' + thisParams[param].name + '}}\n';
                    }

                    else if (thisParams[param].in === 'body') {
                        request.dataMode = 'raw';
                        request.data = thisParams[param].description;
                    }

                    else if (thisParams[param].in === 'formData') {
                        if (thisConsumes.indexOf('application/x-www-form-urlencoded') > -1) {
                            request.dataMode = 'urlencoded';
                        }
                        else {
                            request.dataMode = 'params';
                        }
                        request.data.push({
                            'key': thisParams[param].name,
                            'value': '{{' + thisParams[param].name + '}}',
                            'type': 'text',
                            'enabled': true
                        });
                    } // (thisParams[param].in === 'path') case not handled
                }
            }

            if (hasQueryParams && this.endsWith(request.url, '&')) {
                request.url = request.url.slice(0, -1);
            }

            this.collectionJson.requests.push(request);
            if (folderName !== null) {
                this.folders[folderName].order.push(request.id);
            }
            else {
                this.collectionJson.order.push(request.id);
            }
        },

        addPathItemToFolder: function (path, pathItem, folderName) {
            if (pathItem.$ref) {
                this.logger('Error - cannot handle $ref attributes');
                return;
            }

            var paramsForPathItem = this.getParamsForPathItem(this.baseParams, pathItem.parameters),
                acceptedPostmanVerbs = [
                    'get', 'put', 'post', 'patch', 'delete', 'copy', 'head', 'options',
                    'link', 'unlink', 'purge', 'lock', 'unlock', 'propfind', 'view'],
                numVerbs = acceptedPostmanVerbs.length,
                i,
                verb;

            // replace path variables {petId} with {{..}}
            if (path) {
                path = path.replace('{', '{{').replace('}', '}}');
            }

            for (i = 0; i < numVerbs; i++) {
                verb = acceptedPostmanVerbs[i];
                if (pathItem[verb]) {
                    this.addOperationToFolder(
                        path,
                        verb.toUpperCase(),
                        pathItem[verb],
                        folderName,
                        paramsForPathItem
                    );
                }
            }
        },

        handlePaths: function (json) {
            var paths = json.paths,
                path,
                folderName;

            // Add a folder for each path
            for (path in paths) {
                if (paths.hasOwnProperty(path)) {
                    folderName = this.getFolderNameForPath(path);
                    this.logger('Adding path item. path = ' + path + '   folder = ' + folderName);
                    this.addPathItemToFolder(path, paths[path], folderName);
                }
            }
        },

        handleParams: function (params, level) {
            if (!params) {
                return;
            }
            if (level === 'collection') {
                // base params
                for (var param in params) {
                    if (params.hasOwnProperty(param)) {
                        this.logger('Adding collection param: ' + param);
                        this.baseParams[param] = params[param];
                    }
                }
            }
        },

        addFoldersToCollection: function () {
            var folderName;
            for (folderName in this.folders) {
                if (this.folders.hasOwnProperty(folderName)) {
                    this.collectionJson.folders.push(this.folders[folderName]);
                }
            }
        },

        convert: function (json) {
            var validationResult = this.validate(json);
            if (validationResult.status === 'failed') {
                // error
                return validationResult;
            }

            this.collectionId = uuid.v4();

            this.globalConsumes = json.consumes || [];

            this.handleParams(json.parameters, 'collection');

            this.handleInfo(json);

            this.setBasePath(json);

            this.handlePaths(json);

            this.addFoldersToCollection();

            this.collectionJson.id = this.collectionId;
            // this.logger(JSON.stringify(this.collectionJson));
            this.logger('Swagger converted successfully');

            validationResult.collection = this.collectionJson;

            return validationResult;
        },

        // since travis doesnt support es6
        endsWith: function (str, suffix) {
            return str.indexOf(suffix, str.length - suffix.length) !== -1;
        }
    });

module.exports = Swagger2Postman;
<|endoftext|>


<commit_before>import React from 'react';
import axios from 'axios';
import CreateTodo from './create-todo';
import TodoList from './todo-list';

// load foundation
require('style!css!foundation-sites/dist/foundation.min.css');
$(document).foundation();

const BASE_URL = 'http://localhost:3000';
var todos = [];

export default class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            todos
        };
        this.init();
    }

    init() {
        var self = this;
        axios.get(BASE_URL + '/todos/getAll').then(function(response) {
            self.setState({todos: response.data.result.Items});
        }).catch(function(error) {
            console.log(error);
        });
    }

    render() {
        return (

My Todo List

                <CreateTodo createTask={this.createTask.bind(this)}/>
                <TodoList todos={this.state.todos} toggleTask={this.toggleTask.bind(this)} saveTask={this.saveTask.bind(this)} deleteTask={this.deleteTask.bind(this)}/>

        );
    }

    createTask(task) {
        var self = this;
        self.state.todos.unshift(task);
        self.setState({todos: self.state.todos});
        axios.post(BASE_URL + '/todos', task).then(function(response) {})
        .catch(function(error) {
            console.log(error);
        });
    }

    toggleTask(task) {
        const foundTodo = _.find(this.state.todos, todo => todo.id === task.id);
        foundTodo.isCompleted = !foundTodo.isCompleted;
        this.setState({ todos: this.state.todos });
        axios.put(BASE_URL + '/todos/status', {
            id: task.id,
            isCompleted: foundTodo.isCompleted
        }).then(function(response) {
        }).catch(function(error) {
            console.log(error);
        });
    }

    saveTask(oldTask, newTask) {
        var self = this;
        const foundTodo = _.find(self.state.todos, todo => todo.id === oldTask.id);
        foundTodo.task = newTask;
        self.setState({todos: self.state.todos});
        axios.put(BASE_URL + '/todos/update', {
            id: oldTask.id,
            task: newTask
        }).then(function(response) {
        }).catch(function(error) {
            console.log(error);
        });
    }

    deleteTask(taskToDelete) {
        var self = this;
        _.remove(self.state.todos, todo => todo.id === taskToDelete.id);
            self.setState({todos: self.state.todos});
        axios.delete(BASE_URL + '/todos/delete/'+ taskToDelete.id).then(function(response) {
        }).catch(function(error) {
            console.log(error);
        });

    }
}
<commit_msg>gh-50: Moved the `todos` `init` method execution to `componentDidMount`<commit_after>import React from 'react';
import axios from 'axios';
import CreateTodo from './create-todo';
import TodoList from './todo-list';

// load foundation
require('style!css!foundation-sites/dist/foundation.min.css');
$(document).foundation();

const BASE_URL = 'http://localhost:3000';
var todos = [];

export default class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            todos
        };
        this.init = this.init.bind(this);
    }

    componentDidMount() {
      this.init();
    }

    init() {
        var self = this;
        axios.get(BASE_URL + '/todos/getAll').then(function(response) {
            self.setState({todos: response.data.result.Items});
        }).catch(function(error) {
            self.setState({todos: [{}, {}]});
            console.log(error);
        });
    }

    render() {
        return (

My Todo List

                <CreateTodo createTask={this.createTask.bind(this)}/>
                <TodoList todos={this.state.todos} toggleTask={this.toggleTask.bind(this)} saveTask={this.saveTask.bind(this)} deleteTask={this.deleteTask.bind(this)}/>

        );
    }

    createTask(task) {
        var self = this;
        self.state.todos.unshift(task);
        self.setState({todos: self.state.todos});
        axios.post(BASE_URL + '/todos', task).then(function(response) {})
        .catch(function(error) {
            console.log(error);
        });
    }

    toggleTask(task) {
        const foundTodo = _.find(this.state.todos, todo => todo.id === task.id);
        foundTodo.isCompleted = !foundTodo.isCompleted;
        this.setState({ todos: this.state.todos });
        axios.put(BASE_URL + '/todos/status', {
            id: task.id,
            isCompleted: foundTodo.isCompleted
        }).then(function(response) {
        }).catch(function(error) {
            console.log(error);
        });
    }

    saveTask(oldTask, newTask) {
        var self = this;
        const foundTodo = _.find(self.state.todos, todo => todo.id === oldTask.id);
        foundTodo.task = newTask;
        self.setState({todos: self.state.todos});
        axios.put(BASE_URL + '/todos/update', {
            id: oldTask.id,
            task: newTask
        }).then(function(response) {
        }).catch(function(error) {
            console.log(error);
        });
    }

    deleteTask(taskToDelete) {
        var self = this;
        _.remove(self.state.todos, todo => todo.id === taskToDelete.id);
            self.setState({todos: self.state.todos});
        axios.delete(BASE_URL + '/todos/delete/'+ taskToDelete.id).then(function(response) {
        }).catch(function(error) {
            console.log(error);
        });

    }
}
<|endoftext|>


<commit_before>var fs = require('fs');
var sax = require("sax");
var AdmZip = require('adm-zip');

var argv = require('minimist')(process.argv.slice(2));

if (!argv["f"]) {
    console.log("no file, use -f argument");
    process.exit(1);
}

var filePath = argv["f"];

if (!fs.existsSync(filePath)) {
    console.log("file not found", filePath);
    process.exit(1);
}

var zip = new AdmZip(filePath);
var zipEntries = zip.getEntries();
zipEntries.forEach(function(val) {
    if (val.entryName.indexOf("content.xml") >= 0) {
        console.log(val.entryName);
        zip.extractEntryTo(val, "target/", true, true);
    }
    if (val.entryName.indexOf("Pictures") >= 0) {
        console.log(val.entryName);
        zip.extractEntryTo(val, "target/ressources/images/", false, true);
    }
})

function MDWriter() {
    this.text = "# TITRE\n\n<!-- .slide: class=\"page-title\" -->";
    this.inCodeBlock = false;
    this.listLevel = 0;
    this.titreAdded = false;

    this.addPage = function() {
        this.text += "\n\n\n\n";
        this.titreAdded = false;
    }

    this.addParagraph = function() {
        if (this.inCodeBlock) {
            this.text += "\n";
        }
    }

    this.addText = function(text) {
    	if (!this.titreAdded) {
    		 this.text += "## " + text + "\n";
    		 this.titreAdded = true;
    	}
    	else {
			this.text += text;
    	}
    }

    this.addImage = function(path) {
        this.text += "\n\n![](ressources/images/" + path.replace("Pictures/", "") + ")\n";
    }

    this.startList = function() {
        this.listLevel++;
    }

    this.endList = function() {
        this.listLevel--;
    }

    this.addBullet = function() {
        if (!this.listLevel) {
            console.warning("not in a list");
        }
        this.text += "\n" + Array(this.listLevel).join("\t") + "- ";
    }

    this.addEnd = function() {
        this.text += "\n\n\n\n<!-- .slide: class=\"page-questions\" -->\n\n\n\n<!-- .slide: class=\"page-tp1\" -->";
    }

    this.startCodeBlock = function() {
        this.text += "\n```\n";
        this.inCodeBlock = true;
    }

    this.endCodeBlock = function() {
        this.text += "\n```\n";
        this.inCodeBlock = false;
    }

}

var mdWriter = new MDWriter();

var saxStream = sax.createStream(true, {
    trim: true,
    normalize: true,
    xmlns: false,
    lowercase: true
});

saxStream.on("opentag", function(node) {
    //console.log(node.name);

    if (node.name === "draw:page") {
        mdWriter.addPage();
    } else if (node.name === "draw:image") {
        mdWriter.addImage(node.attributes["xlink:href"]);
    } else if (node.name === "text:list") {
        mdWriter.startList();
    } else if (node.name === "text:list-item") {
        mdWriter.addBullet();
    } else if (node.name === "draw:custom-shape") {
        mdWriter.startCodeBlock();
    } else if (node.name === "text:p") {
        mdWriter.addParagraph();
    }
});

saxStream.on("closetag", function(node) {
    //console.log(node);

    if (node === "draw:custom-shape") {
        mdWriter.endCodeBlock();
    } else if (node === "text:list") {
        mdWriter.endList();
    }
});

saxStream.on("end", function() {
    //console.log(mdWriter.text);
    mdWriter.addEnd();
    fs.writeFile("target/content.md", mdWriter.text);
});

saxStream.on("text", function(t) {
    mdWriter.addText(t);
});

fs.createReadStream("target/content.xml").pipe(saxStream);<commit_msg>fix blocs de code<commit_after>var fs = require('fs');
var sax = require("sax");
var AdmZip = require('adm-zip');

var argv = require('minimist')(process.argv.slice(2));

if (!argv["f"]) {
    console.log("no file, use -f argument");
    process.exit(1);
}

var filePath = argv["f"];

if (!fs.existsSync(filePath)) {
    console.log("file not found", filePath);
    process.exit(1);
}

var zip = new AdmZip(filePath);
var zipEntries = zip.getEntries();
zipEntries.forEach(function(val) {
    if (val.entryName.indexOf("content.xml") >= 0) {
        console.log(val.entryName);
        zip.extractEntryTo(val, "target/", true, true);
    }
    if (val.entryName.indexOf("Pictures") >= 0) {
        console.log(val.entryName);
        zip.extractEntryTo(val, "target/ressources/images/", false, true);
    }
})

function MDWriter() {
    this.text = "# TITRE\n\n<!-- .slide: class=\"page-title\" -->";
    this.inCodeBlock = false;
    this.listLevel = 0;
    this.titreAdded = false;

    this.addPage = function() {
        this.text += "\n\n\n\n";
        this.titreAdded = false;
    }

    this.addParagraph = function() {
        if (this.inCodeBlock) {
            this.text += "\n";
        }
    }

    this.addText = function(text) {
    	if (!this.titreAdded) {
    		 this.text += "## " + text + "\n";
    		 this.titreAdded = true;
    	}
    	else {
			this.text += text;
    	}
    }

    this.addImage = function(path) {
        this.text += "\n\n![](ressources/images/" + path.replace("Pictures/", "") + ")\n";
    }

    this.startList = function() {
        this.listLevel++;
    }

    this.endList = function() {
        this.listLevel--;
    }

    this.addBullet = function() {
        if (!this.listLevel) {
            console.warning("not in a list");
        }
        this.text += "\n" + Array(this.listLevel).join("\t") + "- ";
    }

    this.addEnd = function() {
        this.text += "\n\n\n\n<!-- .slide: class=\"page-questions\" -->\n\n\n\n<!-- .slide: class=\"page-tp1\" -->";
    }

    this.startCodeBlock = function() {
        this.text += "\n```\n";
        this.inCodeBlock = true;
    }

    this.endCodeBlock = function() {
        this.text += "\n```\n";
        this.inCodeBlock = false;
    }

}

var mdWriter = new MDWriter();

var saxStream = sax.createStream(true, {
    trim: true,
    normalize: true,
    xmlns: false,
    lowercase: true
});

saxStream.on("opentag", function(node) {
    //console.log(node.name);

    if (node.name === "draw:page") {
        mdWriter.addPage();
    } else if (node.name === "draw:image") {
        mdWriter.addImage(node.attributes["xlink:href"]);
    } else if (node.name === "text:list") {
        mdWriter.startList();
    } else if (node.name === "text:list-item") {
        mdWriter.addBullet();
    } else if (node.name === "draw:custom-shape" || node.name === "draw:rect") {
        mdWriter.startCodeBlock();
    } else if (node.name === "text:p") {
        mdWriter.addParagraph();
    }
});

saxStream.on("closetag", function(node) {
    //console.log(node);

    if (node === "draw:custom-shape" || node === "draw:rect") {
        mdWriter.endCodeBlock();
    } else if (node === "text:list") {
        mdWriter.endList();
    }
});

saxStream.on("end", function() {
    //console.log(mdWriter.text);
    mdWriter.addEnd();
    fs.writeFile("target/content.md", mdWriter.text);
});

saxStream.on("text", function(t) {
    mdWriter.addText(t);
});

fs.createReadStream("target/content.xml").pipe(saxStream);<|endoftext|>


<commit_before>(function(){
    'use strict';

    var http        = require('http'),
        url         = require('url');

    module.exports = function(host, callback) {
        var options = url.parse(host);

        options.method = 'HEAD';

        http.request(options, function(res) {
            callback(null, res.statusCode);
        }).on('error', function(error) {
            callback(error);
        }).end();
    };
})();
<commit_msg>feature(taus) add https support<commit_after>(function(){
    'use strict';

    var http        = require('http'),
        https       = require('https'),
        url         = require('url');

    module.exports  = function(host, callback) {
        var secure  = /^https/.test(host),
            options = url.parse(host);

        options.method = 'HEAD';

        (secure ? https : http).request(options, function(res) {
            callback(null, res.statusCode);
        }).on('error', function(error) {
            callback(error);
        }).end();
    };
})();
<|endoftext|>


<commit_before>var cssnext = Npm.require('cssnext')

var state = (function () {
  cssNextCss = ''
  return {
    set: function (compileStep) {
      cssNextCss += extractFileFromStep(compileStep)
    },
    get: function () {
      return cssNextCss
    }
  }
})()

function compileNextCss (compileStep) {
  compileStep.addStylesheet(
    extractStylesheetObject(
      cssnext(
        state.get() + extractFileFromStep(compileStep), {
          from: compileStep.inputPath,
          sourcemap: true,
          map: { inline: false, annotation: false }
        }
      )
    )
  )
}

function extractFileFromStep (compileStep) {
  return '\n' + compileStep.read().toString('utf8')
}

function extractStylesheetObject (postcssObj) {
  return {
    path: postcssObj.result.opts.from,
    data: postcssObj.css,
    sourceMap: JSON.stringify(postcssObj.map)
  }
}

Plugin.registerSourceHandler('import.next.css', {archMatching: 'web'}, state.set)
Plugin.registerSourceHandler('next.css', {archMatching: 'web'}, compileNextCss)
<commit_msg>Add _next<commit_after>var cssnext = Npm.require('cssnext')

var state = (function () {
  cssNextCss = ''
  return {
    set: function (compileStep) {
      cssNextCss += extractFileFromStep(compileStep)
    },
    get: function () {
      return cssNextCss
    }
  }
})()

function compileNextCss (compileStep) {
  compileStep.addStylesheet(
    extractStylesheetObject(
      cssnext(
        state.get() + extractFileFromStep(compileStep), {
          from: compileStep.inputPath,
          sourcemap: true,
          map: { inline: false, annotation: false }
        }
      )
    )
  )
}

function extractFileFromStep (compileStep) {
  return '\n' + compileStep.read().toString('utf8')
}

function extractStylesheetObject (postcssObj) {
  return {
    path: postcssObj.result.opts.from,
    data: postcssObj.css,
    sourceMap: JSON.stringify(postcssObj.map)
  }
}

Plugin.registerSourceHandler('import.next.css', {archMatching: 'web'}, state.set)
Plugin.registerSourceHandler('_next.css', {archMatching: 'web'}, state.set)
Plugin.registerSourceHandler('next.css', {archMatching: 'web'}, compileNextCss)
<|endoftext|>


<commit_before>/*********************************************************************
* #### jQuery File Browser Awesome v0.0.2 ####
* Coded by Ican Bachors 2014.
* http://ibacor.com/labs/jquery-file-browser-awesome/
* Updates will be posted to this site.
*********************************************************************/

var fba = function(g) {

	/* Testing di localhost */
    var h = /\\/;

	/* atau jika tombol back bermasalah ketika sudah di hosting gunakan script dibawah ini:
	var h = /\//;
	*/

    var j = '

' + '
File
' + '<textarea id="fba_text"></textarea>',
        k = getParameterByName('dir');

    $("#fba").html(j);
    if (k != '') {
        if (k.indexOf('.') === -1) {
            fba_direktori(g, k, h)
        } else {
            var l = k.substring(k.lastIndexOf('/') + 1),
                gehu = k.replace('/' + l, "");
            fba_direktori(g, gehu, h);
            fba_file(g, k)
        }
    } else {
        fba_direktori(g, "", h)
    }

    var editor = CodeMirror.fromTextArea(document.getElementById("fba_text"),
    {
        mode: "text/html",
        lineNumbers: true
    });

    function fba_direktori(d, e, f) {
        $.ajax({
            type: "POST",
            url: d,
            data: 'sub=' + e,
            crossDomain: true,
            dataType: "json"
        }).done(function(c) {
            var r = "";
            r += '

Name

Size

Last Modified

';
            r += '
';
            if (c.back != "") {
                r += '
 ' + c.root + unescape( '%3C%61%20%68%72%65%66%3D%27%68%74%74%70%3A%2F%2F%69%62%61%63%6F%72%2E%63%6F%6D%2F%6C%61%62%73%2F%6A%71%75%65%72%79%2D%66%69%6C%65%2D%62%72%6F%77%73%65%72%2D%61%77%65%73%6F%6D%65%27%20%74%69%74%6C%65%3D%27%6A%51%75%65%72%79%20%46%69%6C%65%20%42%72%6F%77%73%65%72%20%41%77%65%73%6F%6D%65%27%20%73%74%79%6C%65%3D%27%66%6C%6F%61%74%3A%72%69%67%68%74%27%20%74%61%72%67%65%74%3D%27%5F%42%4C%41%4E%4B%27%3E%3C%69%20%63%6C%61%73%73%3D%27%66%61%20%66%61%2D%69%6E%66%6F%2D%63%69%72%63%6C%65%27%3E%3C%2F%69%3E%3C%2F%61%3E%3C%2F%64%69%76%3E' )
            }
            $.each(c.items, function(i, a) {
                var b = fba_size(c.items[i].size);
                if (c.items[i].type == "folder") {
                    r += '

 ' + c.items[i].name + '

' + c.items[i].items.length + ' item

' + c.items[i].modif + '

'
                } else {
                    var s = c.items[i].path.substr(c.items[i].path.lastIndexOf(".") + 1);
                    switch (s) {

						// List read file. Custom/add example case"asp":case"jsp" etc
                        case "html":
                        case "php":
                        case "js":
                        case "css":
                        case "txt":
                            r += '

 ' + c.items[i].name + '

' + b + '

' + c.items[i].modif + '

';
                            break;

						// List download file
                        default:
                            r += '

 ' + c.items[i].name + '

' + b + '

' + c.items[i].modif + '

'
                    }
                }
            });
            r += "
";
            $(".fba_direktori").html(r);
            $(".sub").click(function() {
                var t = $(this).data("sub");
                fba_direktori(d, t, f);
                window.history.pushState(null, null, "?dir=" + t);
                return false
            });
            $(".bsub").click(function() {
                var t = $(this).data("bsub");
                fba_direktori(d, t, f);
                window.history.pushState(null, null, "?dir=" + t);
                return false
            });
            $(".rfile").click(function() {
                var a = $(this).data("rfile");
                fba_file(d, a);
                window.history.pushState(null, null, "?dir=" + a);
                return false
            })
        })
    }

    function fba_file(b, c) {
        $.ajax({
            type: "POST",
            url: b,
            data: 'file=' + c,
            crossDomain: true,
            dataType: "json"
        }).done(function(a) {
            $(".fba_read_file").html(c);
            editor.setValue(a.text)
        })
    }

    function fba_size(e) {
        var t = ["Bytes", "KB", "MB", "GB", "TB"];
        if (e == 0) return "0 Bytes";
        var n = parseInt(Math.floor(Math.log(e) / Math.log(1024)));
        return Math.round(e / Math.pow(1024, n), 2) + " " + t[n]
    }

    function getParameterByName(a) {
        a = a.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var b = new RegExp("[\\?&]" + a + "=([^&#]*)"),
            results = b.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "))
    }

}
<commit_msg>v0.2.0<commit_after>/*********************************************************************
* #### jQuery File Browser Awesome v0.2.0 ####
* Coded by Ican Bachors 2014.
* http://ibacor.com/labs/jquery-file-browser-awesome/
* Updates will be posted to this site.
*********************************************************************/

var fba = function(g) {
    if (g.host != undefined && g.api != undefined && g.dir != undefined && g.host != '' && g.api != '' && g.dir != '') {
        var j = '

' + '

' + '<textarea id="fba_text"></textarea>',
            k = getParameterByName('path');
        $("#fba").html(j);
        if (k != '') {
            if (k.indexOf('.') === -1) {
                fba_direktori(k)
            } else {
                var l = k.substring(k.lastIndexOf('/') + 1),
                    gehu = k.replace('/' + l, "");
                fba_direktori(gehu);
                fba_file(k)
            }
        } else {
            fba_direktori("")
        }
        var h = CodeMirror.fromTextArea(document.getElementById("fba_text"), {
            mode: "text/html",
            lineNumbers: true
        })
    } else {
        alert('Options required.')
    }

    function fba_direktori(e) {
        $.ajax({
            type: "POST",
            url: g.host + g.api,
            data: 'path=' + e,
            crossDomain: true,
            dataType: "json"
        }).done(function(c) {
            if (c.status == 'success') {
                var r = "";
                r += '

Name

Size

Last Modified

';
                r += '
';
                if (e != "") {
                    var d = e.split('/'),
                        ee = [];
                    for (i = 0; i < d.length - 1; i++) {
                        ee.push(d[i])
                    }
                    var f = (d.length > 1 ? ee.join('/') : '');
                    r += '
 ' + e + unescape('%3C%61%20%68%72%65%66%3D%27%68%74%74%70%73%3A%2F%2F%62%61%63%68%6F%72%73%2E%67%69%74%68%75%62%2E%69%6F%2F%6A%71%75%65%72%79%2D%66%69%6C%65%2D%62%72%6F%77%73%65%72%2D%61%77%65%73%6F%6D%65%2F%27%20%74%69%74%6C%65%3D%27%6A%51%75%65%72%79%20%46%69%6C%65%20%42%72%6F%77%73%65%72%20%41%77%65%73%6F%6D%65%27%20%73%74%79%6C%65%3D%27%66%6C%6F%61%74%3A%72%69%67%68%74%27%20%74%61%72%67%65%74%3D%27%5F%42%4C%41%4E%4B%27%3E%3C%69%20%63%6C%61%73%73%3D%27%66%61%20%66%61%2D%69%6E%66%6F%2D%63%69%72%63%6C%65%27%3E%3C%2F%69%3E%3C%2F%61%3E%3C%2F%64%69%76%3E')
                }
                $.each(c.data, function(i, a) {
                    if (c.data[i].type == "dir") {
                        r += '

 ' + c.data[i].name + '

' + c.data[i].items + ' items

' + c.data[i].modif + '

'
                    } else {
                        var b = fba_size(c.data[i].size);
                        var s = c.data[i].path.substr(c.data[i].path.lastIndexOf(".") + 1);
                        switch (s) {
                            case "html":
                            case "php":
                            case "js":
                            case "css":
                            case "txt":
                            case "md":
                            case "asp":
                            case "aspx":
                            case "jsp":
                            case "py":
                                r += '

 ' + c.data[i].name + '

' + b + '

' + c.data[i].modif + '

';
                                break;
                            case "apk":
                                r += '

 ' + c.data[i].name + '

' + b + '

' + c.data[i].modif + '

'
                                break;
                            case "pdf":
                                r += '

 ' + c.data[i].name + '

' + b + '

' + c.data[i].modif + '

'
                                break;
                            default:
                                r += '

 ' + c.data[i].name + '

' + b + '

' + c.data[i].modif + '

'
                        }
                    }
                });
                r += "
";
                $(".fba_direktori").html(r);
                $(".sub").click(function() {
                    var t = $(this).data("sub");
                    fba_direktori(t);
                    window.history.pushState(null, null, "?path=" + t);
                    return false
                });
                $(".bsub").click(function() {
                    var t = $(this).data("bsub");
                    fba_direktori(t);
                    window.history.pushState(null, null, "?path=" + t);
                    return false
                });
                $(".rfile").click(function() {
                    var a = $(this).data("rfile");
                    fba_file(a);
                    window.history.pushState(null, null, "?path=" + a);
                    return false
                })
            }
        })
    }

    function fba_file(c) {
        $.ajax({
            type: "POST",
            url: g.host + g.api,
            data: 'file=' + c,
            crossDomain: true,
            dataType: "json"
        }).done(function(a) {
            if (a.status == 'success') {
                $("#rf").html(c);
                h.setValue(a.text)
            }
        })
    }

    function fba_size(e) {
        var t = ["Bytes", "KB", "MB", "GB", "TB"];
        if (e == 0) return "0 Bytes";
        var n = parseInt(Math.floor(Math.log(e) / Math.log(1024)));
        return Math.round(e / Math.pow(1024, n), 2) + " " + t[n]
    }

    function getParameterByName(a) {
        a = a.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var b = new RegExp("[\\?&]" + a + "=([^&#]*)"),
            results = b.exec(location.search);
        return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "))
    }
}
<|endoftext|>