<commit_before>'use strict';

var fs = require('fs');
var ffs = require('final-fs');
var path = require('path');
var cli = require('commander');
require('colors');

var XQLint = require('../xqlint').XQLint;
var JSONiqLexer = require('../lexers/jsoniq_lexer').JSONiqLexer;
var XQueryLexer = require('../lexers/xquery_lexer').XQueryLexer;
var ANSIOutput = require('./outputs/ansi').ANSIOutput;
var CodeFormatter = require('../formatter/formatter').CodeFormatter;

var pkg = require('../../package.json');

var getFiles = function(p){
    p = path.resolve(path.normalize(p));
    var files = [];
    if(fs.statSync(p).isFile()){
        files.push(p);
    } else {
        var list = ffs.readdirRecursiveSync(p, true, p);
        list.forEach(function(file){
            if(['jq', 'xq'].indexOf(file.substring(file.length - 2)) !== -1) {
                files.push(file);
            }
        });
    }
    return files;
};

var formatCmd = cli.command('format <path>');
formatCmd.description('Format queries')
.action(function(p){
    var files = getFiles(p);
    files.forEach(function(file){
        var source = fs.readFileSync(file, 'utf-8');
        var linter = new XQLint(file, source, undefined, { styleCheck: false });
        var formatter = new CodeFormatter(linter.getAST());
        var formatted = formatter.format();
        console.log(formatted.trim());
    });
});

var highlightCmd = cli.command('highlight <path>');
/*
highlightCmd.option(
    '-o, --output <html, ansi>',
    function(value){
        return value.toLowerCase();
    }
)
*/
highlightCmd
.description('Highlight queries')
.action(function(p){
    var files = getFiles(p);
    files.forEach(function(file){
        var source = fs.readFileSync(file, 'utf-8');
        var lines = source.split('\n');
        var isJSONiq = ((file.substring(file.length - '.jq'.length).indexOf('.jq') !== -1) && source.indexOf('xquery version') !== 0) || source.indexOf('jsoniq version') === 0;
        var lexer = isJSONiq ? new JSONiqLexer() : new XQueryLexer();
        var result = [], tokens, state;
        lines.forEach(function(line){
            tokens = lexer.getLineTokens(line, state);
            state = tokens.state;
            result.push(tokens);
        });
        ANSIOutput(result);

    });
});

var astCmd = cli.command('ast <path>');
astCmd
.description('Print AST')
.action(function(p){
    var files = getFiles(p);
    files.forEach(function(file){
        var source = fs.readFileSync(file, 'utf-8');
        var linter = new XQLint(source, { fileName: file, styleCheck: false });
        console.log(linter.printAST());
    });
});

var xqdocCmd = cli.command('xqdoc <path>');
xqdocCmd
.description('Print Module XQDoc')
.action(function(p){
    var files = getFiles(p);
    files.forEach(function(file){
        var source = fs.readFileSync(file, 'utf-8');
        var linter = new XQLint(source, { fileName: file, styleCheck: false });
        var xqdoc = linter.getXQDoc();
        console.log(JSON.stringify(xqdoc, null, 2));
    });
});

var lintCmd = cli.command('lint <path>');
lintCmd.option(
    '-e, --emacs',
    'Format for Gnu/Emacs flymake.'
)
.option(
    '-s, --style-check <yes, no>',
    'Check for code formatting.',
    function(value){
        return value === 'yes';
    }
)
.description('Check queries')
.action(function(p) {
    var files = getFiles(p);
    var errors = 0;
    var warnings = 0;
    var spaces = function(count){
        var result = '';
        for(var i = 1; i <= count; i++){
            result += ' ';
        }
        return result;
    };
    files.forEach(function(file){
        var source = fs.readFileSync(file, 'utf-8').replace(/^\uFEFF/, '');
        var linter = new XQLint(source, { fileName: file, styleCheck: lintCmd.styleCheck });
        var markers = linter.getMarkers().sort(function(a, b){ return a.sl - b.sl; });
        var lines = source.split('\n');
        if(markers.length !== 0) {
	    if (!lintCmd.emacs) {
		console.log(('\n' + file).bold);
		linter.getErrors().forEach(function(error){
                    errors++;
                    console.log('\t' + (error.pos.sl + 1) + ' |' + (lines[error.pos.sl].grey));
                    console.log('\t' + spaces((error.pos.sl + 1 + '').length + 1) + spaces(error.pos.sc + 1) + ('^ ' + error.message).red);
		});
		linter.getWarnings().forEach(function(error){
                    warnings++;
                    console.log('\t' + (error.pos.sl + 1) + ' |' + (lines[error.pos.sl].grey));
                    console.log('\t' + spaces((error.pos.sl + 1 + '').length + 1) + spaces(error.pos.sc + 1) + ('^ ' + error.message).yellow);
		});
            } else { // --emacs
		markers.forEach(function(marker){
                    console.log(marker.type.toUpperCase() + ": " + file + ":" + (marker.pos.sl + 1) + ":" + (marker.pos.sc) + ":" + marker.type + " " + marker.message);
		});
            }
	}
    });
    if (!lintCmd.emacs) {
	if(errors === 0 && warnings === 0) {
            console.log(('Linted ' + files.length + ' files').green);
	} else if(errors > 0) {
            throw new Error(('Linted ' + files.length + ' files. Found ' + errors + ' errors and ' + warnings + ' warnings.').red);
	} else if(warnings > 0) {
            throw new Error(('Linted ' + files.length + ' files. Found ' + errors + ' errors and ' + warnings + ' warnings.').yellow);
	}
    }
});

cli.version(pkg.version);
module.exports = cli;
<commit_msg>Fixes 'Strings must use single quote.' for the reintroduced --emacs linting flag.<commit_after>'use strict';

var fs = require('fs');
var ffs = require('final-fs');
var path = require('path');
var cli = require('commander');
require('colors');

var XQLint = require('../xqlint').XQLint;
var JSONiqLexer = require('../lexers/jsoniq_lexer').JSONiqLexer;
var XQueryLexer = require('../lexers/xquery_lexer').XQueryLexer;
var ANSIOutput = require('./outputs/ansi').ANSIOutput;
var CodeFormatter = require('../formatter/formatter').CodeFormatter;

var pkg = require('../../package.json');

var getFiles = function(p){
    p = path.resolve(path.normalize(p));
    var files = [];
    if(fs.statSync(p).isFile()){
        files.push(p);
    } else {
        var list = ffs.readdirRecursiveSync(p, true, p);
        list.forEach(function(file){
            if(['jq', 'xq'].indexOf(file.substring(file.length - 2)) !== -1) {
                files.push(file);
            }
        });
    }
    return files;
};

var formatCmd = cli.command('format <path>');
formatCmd.description('Format queries')
.action(function(p){
    var files = getFiles(p);
    files.forEach(function(file){
        var source = fs.readFileSync(file, 'utf-8');
        var linter = new XQLint(file, source, undefined, { styleCheck: false });
        var formatter = new CodeFormatter(linter.getAST());
        var formatted = formatter.format();
        console.log(formatted.trim());
    });
});

var highlightCmd = cli.command('highlight <path>');
/*
highlightCmd.option(
    '-o, --output <html, ansi>',
    function(value){
        return value.toLowerCase();
    }
)
*/
highlightCmd
.description('Highlight queries')
.action(function(p){
    var files = getFiles(p);
    files.forEach(function(file){
        var source = fs.readFileSync(file, 'utf-8');
        var lines = source.split('\n');
        var isJSONiq = ((file.substring(file.length - '.jq'.length).indexOf('.jq') !== -1) && source.indexOf('xquery version') !== 0) || source.indexOf('jsoniq version') === 0;
        var lexer = isJSONiq ? new JSONiqLexer() : new XQueryLexer();
        var result = [], tokens, state;
        lines.forEach(function(line){
            tokens = lexer.getLineTokens(line, state);
            state = tokens.state;
            result.push(tokens);
        });
        ANSIOutput(result);

    });
});

var astCmd = cli.command('ast <path>');
astCmd
.description('Print AST')
.action(function(p){
    var files = getFiles(p);
    files.forEach(function(file){
        var source = fs.readFileSync(file, 'utf-8');
        var linter = new XQLint(source, { fileName: file, styleCheck: false });
        console.log(linter.printAST());
    });
});

var xqdocCmd = cli.command('xqdoc <path>');
xqdocCmd
.description('Print Module XQDoc')
.action(function(p){
    var files = getFiles(p);
    files.forEach(function(file){
        var source = fs.readFileSync(file, 'utf-8');
        var linter = new XQLint(source, { fileName: file, styleCheck: false });
        var xqdoc = linter.getXQDoc();
        console.log(JSON.stringify(xqdoc, null, 2));
    });
});

var lintCmd = cli.command('lint <path>');
lintCmd.option(
    '-e, --emacs',
    'Format for Gnu/Emacs flymake.'
)
.option(
    '-s, --style-check <yes, no>',
    'Check for code formatting.',
    function(value){
        return value === 'yes';
    }
)
.description('Check queries')
.action(function(p) {
    var files = getFiles(p);
    var errors = 0;
    var warnings = 0;
    var spaces = function(count){
        var result = '';
        for(var i = 1; i <= count; i++){
            result += ' ';
        }
        return result;
    };
    files.forEach(function(file){
        var source = fs.readFileSync(file, 'utf-8').replace(/^\uFEFF/, '');
        var linter = new XQLint(source, { fileName: file, styleCheck: lintCmd.styleCheck });
        var markers = linter.getMarkers().sort(function(a, b){ return a.sl - b.sl; });
        var lines = source.split('\n');
        if(markers.length !== 0) {
	    if (!lintCmd.emacs) {
		console.log(('\n' + file).bold);
		linter.getErrors().forEach(function(error){
                    errors++;
                    console.log('\t' + (error.pos.sl + 1) + ' |' + (lines[error.pos.sl].grey));
                    console.log('\t' + spaces((error.pos.sl + 1 + '').length + 1) + spaces(error.pos.sc + 1) + ('^ ' + error.message).red);
		});
		linter.getWarnings().forEach(function(error){
                    warnings++;
                    console.log('\t' + (error.pos.sl + 1) + ' |' + (lines[error.pos.sl].grey));
                    console.log('\t' + spaces((error.pos.sl + 1 + '').length + 1) + spaces(error.pos.sc + 1) + ('^ ' + error.message).yellow);
		});
            } else { // --emacs
		markers.forEach(function(marker){
                    console.log(marker.type.toUpperCase() + ': ' + file + ':' + (marker.pos.sl + 1) + ':' + (marker.pos.sc) + ':' + marker.type + ' ' + marker.message);
		});
            }
	}
    });
    if (!lintCmd.emacs) {
	if(errors === 0 && warnings === 0) {
            console.log(('Linted ' + files.length + ' files').green);
	} else if(errors > 0) {
            throw new Error(('Linted ' + files.length + ' files. Found ' + errors + ' errors and ' + warnings + ' warnings.').red);
	} else if(warnings > 0) {
            throw new Error(('Linted ' + files.length + ' files. Found ' + errors + ' errors and ' + warnings + ' warnings.').yellow);
	}
    }
});

cli.version(pkg.version);
module.exports = cli;
<|endoftext|>


<commit_before>"use strict";
const fs = require('fs');
const glob = require("glob");
const account = require('./account');
const handlerTypes = ['update', 'insert', 'delete', 'validate'];
const path = require('path');
const readline = require('readline');

module.exports = function(args) {
  if (!args.app && !args.host) {
    return false;
  } else {
    return account.login({app: args.app, host: args.host}).then((db) => {
      if (!args.code && !args.files || args.code && args.files) {
        return Promise.all([
          deployFiles(db, args.fileDir, args.fileGlob),
          deployCode(db, args.codeDir)
        ]);
      } else if (args.code) {
        return deployCode(db, args.codeDir);
      } else if (args.files) {
        return deployFiles(db, args.fileDir, args.fileGlob);
      }
    });
  }
};

function deployFiles(db, cwd, pattern) {
  return new Promise((resolve, reject) => {
    glob(pattern, {nodir: true, cwd}, (er, files) => {
      if (er)
        reject(er);
      else
        resolve(uploadFiles(db, files, cwd));
    });
  }).then((result) => {
    if (result && result.length > 0) {
      console.log('File deployment completed.');
    } else {
      console.warn('No files where uploaded.');
    }
  })
}

function deployCode(db, codePath) {
  return readDirectory(codePath).then((fileNames) => {
    return Promise.all(fileNames.map((fileName) => {
      return readStat(path.join(codePath, fileName)).then((stat) => {
        if (stat.isDirectory()) {
          return uploadHandler(db, fileName, codePath);
        } else {
          return uploadCode(db, fileName, codePath);
        }
      });
    })).then(() => {
      console.log('Code deployment completed.');
    }).catch((e) => {
      console.error(`Failed to deploy code: ${e.message}`);
    });
  }).catch(() => {
    console.warn(`Code deployment skipped, the code folder ${codePath} does not exists.`);
  });
}

function readStat(filePath) {
  return new Promise((resolve, reject) => {
    fs.stat(filePath, (err, stat) => {
      err ? reject(err) : resolve(stat);
    })
  });
}

function readDirectory(filePath) {
  return new Promise((resolve, reject) => {
    fs.readdir(filePath, (err, fileNames) => {
      err ? reject(err) : resolve(fileNames);
    })
  })
}

function readFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf-8', (err, file) => {
      err ? reject(err) : resolve(file);
    })
  });
}

function uploadHandler(db, directoryName, codePath) {
  let bucket = directoryName;

  if (!db[bucket])
    return;

  return readDirectory(path.join(codePath,directoryName)).then((fileNames) => {
    return Promise.all(fileNames.map((fileName) => {
      let handlerType = fileName.replace(/.js$/, '');

      if (handlerTypes.indexOf(handlerType) == -1)
        return;

      return readFile(path.join(codePath, directoryName, fileName))
          .then((file) => db.code.saveCode(bucket, handlerType, file))
          .then(() => console.log(`${handlerType} handler for ${bucket} deployed.`));
    }));
  });
}

function uploadCode(db, name, codePath) {
  let moduleName = name.replace(/.js$/, '');
  return readFile(path.join(codePath, name)).then((file) => {
    return db.code.saveCode(moduleName, 'module', file);
  }).then(() => {
    console.log(`Module ${moduleName} deployed.`);
  });
}

function uploadFiles(db, files, cwd) {
  let isTty = process.stdout.isTTY;
  let index = 0;

  let uploads = [];
  for (let i = 0; i < 10 && i < files.length-1; ++i) {
    uploads.push(upload());
  }

  if (!isTty) {
    console.log(`Uploading ${files.length} files.`)
  }

  return Promise.all(uploads);

  function upload() {
    if (index < files.length) {
      if (isTty) {
        if (index > 0) {
          readline.clearLine(process.stdout, 0);
          readline.cursorTo(process.stdout, 0);
        }
        process.stdout.write(`Uploading file ${(index + 1)} of ${files.length}`);
      }

      var file = files[index++];

      if (isTty && index == files.length) {
        console.log(''); //add a final linebreak
      }

      return uploadFile(db, file, cwd).then(upload);
    }
  }
}

function uploadFile(db, filePath, cwd) {
  let fullFilePath = path.join(cwd, filePath);

  let stat = fs.statSync(fullFilePath);

  let file = new db.File({path: `/www/${filePath}`, data: fs.createReadStream(fullFilePath), size: stat.size, type: 'stream'});
  return file.upload({ force: true }).catch(function(e) {
    console.error(`Failed to upload file ${filePath}: ${e.message}`);
  });
}

<commit_msg>fixed upload of only one file<commit_after>"use strict";
const fs = require('fs');
const glob = require("glob");
const account = require('./account');
const handlerTypes = ['update', 'insert', 'delete', 'validate'];
const path = require('path');
const readline = require('readline');

module.exports = function(args) {
  if (!args.app && !args.host) {
    return false;
  } else {
    return account.login({app: args.app, host: args.host}).then((db) => {
      if (!args.code && !args.files || args.code && args.files) {
        return Promise.all([
          deployFiles(db, args.fileDir, args.fileGlob),
          deployCode(db, args.codeDir)
        ]);
      } else if (args.code) {
        return deployCode(db, args.codeDir);
      } else if (args.files) {
        return deployFiles(db, args.fileDir, args.fileGlob);
      }
    });
  }
};

function deployFiles(db, cwd, pattern) {
  return new Promise((resolve, reject) => {
    glob(pattern, {nodir: true, cwd}, (er, files) => {
      if (er)
        reject(er);
      else
        resolve(uploadFiles(db, files, cwd));
    });
  }).then((result) => {
    if (result && result.length > 0) {
      console.log('File deployment completed.');
    } else {
      console.warn('No files where uploaded.');
    }
  })
}

function deployCode(db, codePath) {
  return readDirectory(codePath).then((fileNames) => {
    return Promise.all(fileNames.map((fileName) => {
      return readStat(path.join(codePath, fileName)).then((stat) => {
        if (stat.isDirectory()) {
          return uploadHandler(db, fileName, codePath);
        } else {
          return uploadCode(db, fileName, codePath);
        }
      });
    })).then(() => {
      console.log('Code deployment completed.');
    }).catch((e) => {
      console.error(`Failed to deploy code: ${e.message}`);
    });
  }).catch(() => {
    console.warn(`Code deployment skipped, the code folder ${codePath} does not exists.`);
  });
}

function readStat(filePath) {
  return new Promise((resolve, reject) => {
    fs.stat(filePath, (err, stat) => {
      err ? reject(err) : resolve(stat);
    })
  });
}

function readDirectory(filePath) {
  return new Promise((resolve, reject) => {
    fs.readdir(filePath, (err, fileNames) => {
      err ? reject(err) : resolve(fileNames);
    })
  })
}

function readFile(filePath) {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf-8', (err, file) => {
      err ? reject(err) : resolve(file);
    })
  });
}

function uploadHandler(db, directoryName, codePath) {
  let bucket = directoryName;

  if (!db[bucket])
    return;

  return readDirectory(path.join(codePath,directoryName)).then((fileNames) => {
    return Promise.all(fileNames.map((fileName) => {
      let handlerType = fileName.replace(/.js$/, '');

      if (handlerTypes.indexOf(handlerType) == -1)
        return;

      return readFile(path.join(codePath, directoryName, fileName))
          .then((file) => db.code.saveCode(bucket, handlerType, file))
          .then(() => console.log(`${handlerType} handler for ${bucket} deployed.`));
    }));
  });
}

function uploadCode(db, name, codePath) {
  let moduleName = name.replace(/.js$/, '');
  return readFile(path.join(codePath, name)).then((file) => {
    return db.code.saveCode(moduleName, 'module', file);
  }).then(() => {
    console.log(`Module ${moduleName} deployed.`);
  });
}

function uploadFiles(db, files, cwd) {
  let isTty = process.stdout.isTTY;
  let index = 0;

  let uploads = [];
  for (let i = 0; i < 10 && i < files.length; ++i) {
    uploads.push(upload());
  }

  if (!isTty) {
    console.log(`Uploading ${files.length} files.`)
  }

  return Promise.all(uploads);

  function upload() {
    if (index < files.length) {
      if (isTty) {
        if (index > 0) {
          readline.clearLine(process.stdout, 0);
          readline.cursorTo(process.stdout, 0);
        }
        process.stdout.write(`Uploading file ${(index + 1)} of ${files.length}`);
      }

      var file = files[index++];

      if (isTty && index == files.length) {
        console.log(''); //add a final linebreak
      }

      return uploadFile(db, file, cwd).then(upload);
    }
  }
}

function uploadFile(db, filePath, cwd) {
  let fullFilePath = path.join(cwd, filePath);

  let stat = fs.statSync(fullFilePath);

  let file = new db.File({path: `/www/${filePath}`, data: fs.createReadStream(fullFilePath), size: stat.size, type: 'stream'});
  return file.upload({ force: true }).catch(function(e) {
    console.error(`Failed to upload file ${filePath}: ${e.message}`);
  });
}

<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import {
  renderIntoDocument
} from 'react-addons-test-utils';
import Timeline from '../src/Timeline.jsx';

describe('Timeline', function() {
  var sandbox,
    timeline,
    timelineNode,
    onSelect,
    onSelectMock;

  beforeEach(function() {
    sandbox = sinon.sandbox.create();

    onSelect = {
      fn: function() {
      }
    };
    onSelectMock = sandbox.mock(onSelect).expects('fn');

    timeline = renderIntoDocument(
      <Timeline height={ 300 } onSelect={ onSelect.fn } progress={ 50 } />
    ),
    timelineNode = ReactDOM.findDOMNode(timeline);
  });

  afterEach(function() {
    sandbox.restore();
  });

  it('should render the component', function() {
    expect(timeline).to.be.defined;
    expect(timelineNode).to.be.defined;
    expect(timelineNode.className).to.equal('timeline-block');
    expect(timelineNode.children[0].className).to.equal('timeline-line');
    expect(timelineNode.children[1].className).to.equal('timeline-progress');
  });
});<commit_msg>moar tests<commit_after>/*global sinon:true*/
import React from 'react';
import ReactDOM from 'react-dom';
import {
  renderIntoDocument,
  findRenderedDOMComponentWithClass,
  Simulate
} from 'react-addons-test-utils';
import Timeline from '../src/Timeline.jsx';

describe('Timeline', function() {
  var sandbox,
    timeline,
    timelineNode,
    onSelect,
    onSelectMock;

  beforeEach(function() {
    sandbox = sinon.sandbox.create();

    onSelect = {
      fn: function() {
      }
    };
    onSelectMock = sandbox.mock(onSelect).expects('fn');

    timeline = renderIntoDocument(
      <Timeline height={ 300 } onSelect={ onSelect.fn } progress={ 50 } />
    ),
    timelineNode = ReactDOM.findDOMNode(timeline);
  });

  afterEach(function() {
    sandbox.restore();
  });

  it('should render the component', function() {
    expect(timeline).to.be.defined;
    expect(timelineNode).to.be.defined;
    expect(timelineNode.className).to.equal('timeline-block');
    expect(timelineNode.children[0].className).to.equal('timeline-line');
    expect(timelineNode.children[1].className).to.equal('timeline-progress');
  });

  it('should call onSelect when the timeline is clicked after progress', function() {
    onSelectMock.once();
    Simulate.click(findRenderedDOMComponentWithClass(timeline, 'timeline-line'));
    onSelectMock.verify();
  });

  it('should call onSelect when the timeline is clicked in elapsed progress', function() {
    onSelectMock.once();
    Simulate.click(findRenderedDOMComponentWithClass(timeline, 'timeline-progress'));
    onSelectMock.verify();
  });
});<|endoftext|>


<commit_before>#!/usr/bin/env node

/*
TODO:
- provide option to just show available projects
- get rid of -c option as customerId it is available in a project. get project first then add hours

*/

'use strict';

var program = require('commander')
  , request = require('request')
  , js2xmlparser = require('js2xmlparser')
  , async = require('async')
  , parseXmlString = require('xml2js').parseString
  , colors = require('colors')
  , fs = require('fs')
  , path = require('path')
  , crypto = require('crypto')
  , prompt = require('prompt')
  , home = getUserHome()
  , config = path.join(home, '.fastbiller')
  , passphrase = 'bbebdde04a05a29bab7d25ba5ee89ef997f3230f63627b5b0725e42817a2f0d0';

colors.setTheme({
  success: 'green',
  help: 'cyan',
  warn: 'yellow',
  debug: 'blue',
  error: 'red'
});

program
  .version('0.1.0')
  .option('-p, --project <n>', 'Fastbill project id', parseInt)
  .option('-c, --customer <n>', 'Fastbill customer id', parseInt)
  .option('-f, --file <s>', 'clocker data file (json)')
  .parse(process.argv);

initialize();

function initialize() {
  fs.open(config, 'r', function (err) {
    if (err) { // config file does not exist
      if (process.stdin.isTTY) {
        askForCredentials(function (creds) {
          saveCredentials(creds);
        });
      } else {
        out.fatal('Please run fastbiller one time without piping data into it.');
      }
    } else {
      readCredentials(workflow);
    }
  });
}

function askForCredentials(cb) {
  prompt.message = '';
  prompt.delimiter = '';
  prompt.start();
  prompt.get([
    { name: 'email', description: 'E-Mail Address used for fastbill: ' },
    { name: 'apiKey', description: 'Fastbill API-key: ' }
  ], function (err, result) {
    cb(result);
  });
}

function saveCredentials(creds) {
  creds.email = encrypt(creds.email);
  creds.apiKey = encrypt(creds.apiKey);

  fs.writeFile(config, JSON.stringify(creds), { mode: 436 }, function (err) {
    if (err) return out.fatal('Could not write config file');
    out.success('Credentials saved successfully');
  });
}

function readCredentials(cb) {
  fs.readFile(config, function (err, data){
    if (err) return out.fatal('Could not read config file');
    try {
      data = JSON.parse(data);
    } catch (e) {
      out.fatal('Could not parse config file');
    }
    data.email = decrypt(data.email);
    data.apiKey = decrypt(data.apiKey);
    cb(data);
  });
}

function workflow(creds) {
  if (typeof program.project !== 'number') {
    out.fatal('Please provide a valid customer id in number format');
  }

  if (typeof program.customer !== 'number') {
    out.fatal('Please provide a valid customer id in number format');
  }

  if (typeof program.file === 'string') {
    fs.readFile(program.file, function (err, data) {
      if (err) return out.fatal('Could not read hours file.');
      execute(data, creds);
    });
  } else {
    withStdin(function (data) {
      execute(data, creds);
    });
  }

}

function execute(data, creds) {
  var parsedData;
  try {
    parsedData = JSON.parse(data);
  } catch (e) {
    out.fatal('Could not parse input. No valid JSON.');
  }

  if ('object' !== typeof parsedData || !parsedData[0] || !parsedData[0].hours) {
    return out.fatal('Incorrect input data. Please provide json data generated by clocker.');
  }

  var hours = parsedData[0].hours;

  async.map(hours, createTime, function (err, results) {
    if (err) {
      return out.fatal('Argh! Could not send hours. Here\'s why: ' + err);
    }
    out.success('Hours successfully transferred to fastbill!');
    out.info('HOUR-IDs: '.help + results.join(', '));
  });
}

var out = {
  fatal: function (errstr) {
    console.log('ERROR: '.error + errstr);
    process.exit(1);
  },
  error: function (errstr) {
    console.log('ERROR: '.error + errstr);
  },
  success: function (okstr) {
    console.log('SUCCESS: '.success + okstr);
  },
  info: function (infostr) {
    console.log(infostr);
  }
};

function withStdin(cb) {
  var str = '';
  process.stdin.setEncoding('utf8');
  process.stdin.on('data', function (chunk) { str += chunk; });
  process.stdin.on('end', function () { cb(str); }).resume();
}

function createTime(creds) {
  return function (data, callback) {
    var req = {
      service: 'time.create',
      data: decamelize({
        customerId: program.customerId,
        projectId: program.projectId,
        date: data.date,
        startTime: '00:00:00',
        minutes: data.hours*60
      })
    };

    request.post('https://my.fastbill.com/api/1.0/api.php', {
      auth: {
        user: creds.email,
        pass: creds.apiKey,
        sendImmediately: true
      },
      body: js2xmlparser('fbapi', req)
    }, function (err, res, body) {
      if (err) return callback(err);
      parseXmlString(body, function (err, result) {
        if (err) return callback(err);
        out.info('.'); // progress
        callback(null, result.FBAPI.RESPONSE[0]['TIME_ID']);
      });
    });
  };
}

function encrypt (str) {
  var cipher = crypto.createCipher('aes-256-cbc', passphrase);
  var encrypted = cipher.update(str, 'utf8', 'base64');
  return encrypted + cipher.final('base64');
}

function decrypt (str) {
  var decipher = crypto.createDecipher('aes-256-cbc', passphrase);
  var decrypted = decipher.update(str, 'base64', 'utf8');
  return decrypted + decipher.final('utf8');
}

/* Decamelize object keys to use underscores */
function decamelize(obj) {
  var out = {};
  Object.keys(obj).forEach(function (elm) {
    var newKey = elm.replace(/[A-Z]/g, function (match) {
      return '_' + match.toLowerCase();
    });
    if (obj[elm]) out[newKey] = obj[elm];
  });
  return out;
}

function getUserHome() {
  return process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
}<commit_msg>error handling<commit_after>#!/usr/bin/env node

/*
TODO:
- provide option to just show available projects
- get rid of -c option as customerId it is available in a project. get project first then add hours

*/

'use strict';

var program = require('commander')
  , request = require('request')
  , js2xmlparser = require('js2xmlparser')
  , async = require('async')
  , parseXmlString = require('xml2js').parseString
  , colors = require('colors')
  , fs = require('fs')
  , path = require('path')
  , crypto = require('crypto')
  , prompt = require('prompt')
  , home = getUserHome()
  , config = path.join(home, '.fastbiller')
  , passphrase = 'bbebdde04a05a29bab7d25ba5ee89ef997f3230f63627b5b0725e42817a2f0d0';

colors.setTheme({
  success: 'green',
  help: 'cyan',
  warn: 'yellow',
  debug: 'blue',
  error: 'red'
});

program
  .version('0.1.0')
  .option('-p, --project <n>', 'Fastbill project id', parseInt)
  .option('-c, --customer <n>', 'Fastbill customer id', parseInt)
  .option('-f, --file <s>', 'clocker data file (json)')
  .parse(process.argv);

initialize();

function initialize() {
  fs.open(config, 'r', function (err) {
    if (err) { // config file does not exist
      if (process.stdin.isTTY) {
        askForCredentials(function (creds) {
          saveCredentials(creds);
        });
      } else {
        out.fatal('Please run fastbiller one time without piping data into it.');
      }
    } else {
      readCredentials(workflow);
    }
  });
}

function askForCredentials(cb) {
  prompt.message = '';
  prompt.delimiter = '';
  prompt.start();
  prompt.get([
    { name: 'email', description: 'E-Mail Address used for fastbill: ' },
    { name: 'apiKey', description: 'Fastbill API-key: ' }
  ], function (err, result) {
    cb(result);
  });
}

function saveCredentials(creds) {
  creds.email = encrypt(creds.email);
  creds.apiKey = encrypt(creds.apiKey);

  fs.writeFile(config, JSON.stringify(creds), { mode: 436 }, function (err) {
    if (err) return out.fatal('Could not write config file');
    out.success('Credentials saved successfully');
  });
}

function readCredentials(cb) {
  fs.readFile(config, function (err, data){
    if (err) return out.fatal('Could not read config file');
    try {
      data = JSON.parse(data);
    } catch (e) {
      out.fatal('Could not parse config file');
    }
    data.email = decrypt(data.email);
    data.apiKey = decrypt(data.apiKey);
    cb(data);
  });
}

function workflow(creds) {
  if (typeof program.project !== 'number') {
    out.fatal('Please provide a valid customer id in number format');
  }

  if (typeof program.customer !== 'number') {
    out.fatal('Please provide a valid customer id in number format');
  }

  if (typeof program.file === 'string') {
    fs.readFile(program.file, { encoding: 'utf8' }, function (err, data) {
      if (err) return out.fatal('Could not read hours file.');
      execute(data, creds);
    });
  } else {
    withStdin(function (data) {
      execute(data, creds);
    });
  }

}

function execute(data, creds) {
  var parsedData;
  try {
    parsedData = JSON.parse(data);
  } catch (e) {
    out.fatal('Could not parse input. No valid JSON.');
  }

  if ('object' !== typeof parsedData || !parsedData[0] || !parsedData[0].hours) {
    return out.fatal('Incorrect input data. Please provide json data generated by clocker.');
  }

  var hours = parsedData[0].hours;

  async.map(hours, createTime(creds), function (err, results) {
    if (err) {
      return out.fatal('Argh! Could not send hours. Here\'s why: ' + err);
    }
    out.success('Hours successfully transferred to fastbill!');
    out.info('HOUR-IDs: '.help + results.join(', '));
  });
}

var out = {
  fatal: function (errstr) {
    console.log('ERROR: '.error + errstr);
    process.exit(1);
  },
  error: function (errstr) {
    console.log('ERROR: '.error + errstr);
  },
  success: function (okstr) {
    console.log('SUCCESS: '.success + okstr);
  },
  info: function (infostr) {
    console.log(infostr);
  }
};

function withStdin(cb) {
  var str = '';
  process.stdin.setEncoding('utf8');
  process.stdin.on('data', function (chunk) { str += chunk; });
  process.stdin.on('end', function () { cb(str); }).resume();
}

function createTime(creds) {
  return function (data, callback) {
    var req = {
      service: 'time.create',
      data: decamelize({
        customerId: program.customer,
        projectId: program.project,
        date: data.date,
        startTime: '00:00:00',
        minutes: data.hours*60
      })
    };

    request.post('https://my.fastbill.com/api/1.0/api.php', {
      auth: {
        user: creds.email,
        pass: creds.apiKey,
        sendImmediately: true
      },
      body: js2xmlparser('fbapi', req)
    }, function (err, res, body) {
      if (err) return callback(err);
      parseXmlString(body, function (err, result) {
        if (err) return callback(err);
        out.info('.'); // progress
        var error;
        try {
          error = result.FBAPI.RESPONSE[0].ERRORS[0].ERROR[0];
        } catch (e){}
        finally {
          callback(error, result.FBAPI.RESPONSE[0]['TIME_ID']);
        }
      });
    });
  };
}

function encrypt (str) {
  var cipher = crypto.createCipher('aes-256-cbc', passphrase);
  var encrypted = cipher.update(str, 'utf8', 'base64');
  return encrypted + cipher.final('base64');
}

function decrypt (str) {
  var decipher = crypto.createDecipher('aes-256-cbc', passphrase);
  var decrypted = decipher.update(str, 'base64', 'utf8');
  return decrypted + decipher.final('utf8');
}

/* Decamelize object keys to use underscores */
function decamelize(obj) {
  var out = {};
  Object.keys(obj).forEach(function (elm) {
    var newKey = elm.replace(/[A-Z]/g, function (match) {
      return '_' + match.toLowerCase();
    });
    if (obj[elm]) out[newKey] = obj[elm];
  });
  return out;
}

function getUserHome() {
  return process.env[(process.platform === 'win32') ? 'USERPROFILE' : 'HOME'];
}<|endoftext|>


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

    angular
        .module('cogeoApp')
        .controller('AppCtrl', AppCtrl);

    AppCtrl.$inject = [
        'CONFIG',
        'userFactory',
        '$scope',
        'localStorageService',
        'cogeoWebRtc',
        'usersFactory',
        'groupsFactory',
        'cozenEnhancedLogs',
        '$rootScope',
        '$state',
        '$stateParams',
        'cozenLanguage',
        '$timeout'
    ];

    function AppCtrl(CONFIG, userFactory, $scope, localStorageService, cogeoWebRtc, usersFactory, groupsFactory,
                     cozenEnhancedLogs, $rootScope, $state, $stateParams, cozenLanguage, $timeout) {
        var app = this;

        // Common data
        app.CONFIG  = CONFIG;
        app.isReady = false;

        // Methods
        app.methods = {
            onInit: onInit
        };

        // When the window is ready
        // Note: removed the window.onLoad because it is sometimes not trigger
        // If it is not trigger, the app will just not works so it's a huge problem ;)
        $timeout(function () {
            $timeout(function () {
                app.methods.onInit();
            });
        });

        // Update the configuration of the language when the url lang param was changed
        $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
            if (toParams.lang != fromParams.lang) {
                cozenLanguage.updateCurrentLanguage(toParams.lang);
            }
        });

        // Just to log the error when one occurred
        $rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams) {
            console.trace();
            console.log(arguments);
        });

        function onInit() {
            cozenEnhancedLogs.wrap.end('windowOnLoad');
            cozenEnhancedLogs.wrap.starting('cogeoInit');
            var requestQuantity = 3;

            // Get the stuff about the current connected user (to avoid manual login)
            var user = localStorageService.get('currentUser');
            if (user != null && user.username != null && user.token != null) {
                user.updateLastLogin = true;

                // Login with the app (how each load, to make sure that the token is still valid)
                // May be a potential performance leak nevertheless the security is enhanced
                userFactory.httpRequest.login(user, function (response) {
                    if (response.data.data.settings.language != cozenLanguage.getCurrentLanguage()) {
                        cozenLanguage.updateCurrentLanguage(response.data.data.settings.language);

                        // Refresh the state with new lang param
                        var params  = angular.copy($stateParams);
                        params.lang = cozenLanguage.getCurrentLanguage();
                        $state.transitionTo($state.current, params, {
                            reload : false,
                            inherit: false,
                            notify : false
                        });
                    }
                    isDone();
                }, function () {
                    isDone();
                });
                usersFactory.httpRequest.getAll(function () {
                    isDone();
                }, function () {
                    isDone();
                });

                // Get all the groups
                groupsFactory.httpRequest.getAllGroups(function () {
                    isDone();
                }, function () {
                    isDone();
                });
            }
            else {
                userFactory.setUser(null);

                // Get some data only if mod dev
                if (CONFIG.dev) {
                    usersFactory.httpRequest.getAll(function () {
                        isDone();
                    }, function () {
                        isDone();
                    });
                    groupsFactory.httpRequest.getAllGroups(function () {
                        isDone();
                    }, function () {
                        isDone();
                    });
                    isDone();
                }
                else {
                    isDone(3);
                }
            }

            function isDone(quantity) {
                if (Methods.isNullOrEmpty(quantity)) {
                    quantity = 1;
                }
                requestQuantity = requestQuantity - quantity;
                if (requestQuantity <= 0) {
                    app.isReady = true;
                    cozenEnhancedLogs.wrap.end('cogeoInit');
                    Methods.safeApply($scope);
                }
            }
        }
    }

})(window.angular);

<commit_msg>On refresh, if the current language in the url is different from the lang in the settings of the user, we change the lang in the url by the user one.<commit_after>(function (angular) {
    'use strict';

    angular
        .module('cogeoApp')
        .controller('AppCtrl', AppCtrl);

    AppCtrl.$inject = [
        'CONFIG',
        'userFactory',
        '$scope',
        'localStorageService',
        'cogeoWebRtc',
        'usersFactory',
        'groupsFactory',
        'cozenEnhancedLogs',
        '$rootScope',
        '$state',
        '$stateParams',
        'cozenLanguage',
        '$timeout'
    ];

    function AppCtrl(CONFIG, userFactory, $scope, localStorageService, cogeoWebRtc, usersFactory, groupsFactory,
                     cozenEnhancedLogs, $rootScope, $state, $stateParams, cozenLanguage, $timeout) {
        var app = this;

        // Common data
        app.CONFIG  = CONFIG;
        app.isReady = false;

        // Methods
        app.methods = {
            onInit: onInit
        };

        // When the window is ready
        // Note: removed the window.onLoad because it is sometimes not trigger
        // If it is not trigger, the app will just not works so it's a huge problem ;)
        $timeout(function () {
            $timeout(function () {
                app.methods.onInit();
            });
        });

        // Update the configuration of the language when the url lang param was changed
        $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
            if (toParams.lang != fromParams.lang) {
                cozenLanguage.updateCurrentLanguage(toParams.lang);
            }
        });

        // Just to log the error when one occurred
        $rootScope.$on('$stateChangeError', function (event, toState, toParams, fromState, fromParams) {
            console.trace();
            console.log(arguments);
        });

        function onInit() {
            cozenEnhancedLogs.wrap.end('windowOnLoad');
            cozenEnhancedLogs.wrap.starting('cogeoInit');
            var requestQuantity = 3;

            // Get the stuff about the current connected user (to avoid manual login)
            var user = localStorageService.get('currentUser');
            if (user != null && user.username != null && user.token != null) {
                user.updateLastLogin = true;

                // Login with the app (how each load, to make sure that the token is still valid)
                // May be a potential performance leak nevertheless the security is enhanced
                userFactory.httpRequest.login(user, function (response) {
                    if (response.data.data.settings.language != cozenLanguage.getCurrentLanguage() ||
                        cozenLanguage.getCurrentLanguage() != $stateParams.lang) {
                        cozenLanguage.updateCurrentLanguage(response.data.data.settings.language);

                        // Refresh the state with new lang param
                        var params  = angular.copy($stateParams);
                        params.lang = cozenLanguage.getCurrentLanguage();
                        $state.transitionTo($state.current, params, {
                            reload : false,
                            inherit: false,
                            notify : false
                        });
                    }
                    isDone();
                }, function () {
                    isDone();
                });
                usersFactory.httpRequest.getAll(function () {
                    isDone();
                }, function () {
                    isDone();
                });

                // Get all the groups
                groupsFactory.httpRequest.getAllGroups(function () {
                    isDone();
                }, function () {
                    isDone();
                });
            }
            else {
                userFactory.setUser(null);

                // Get some data only if mod dev
                if (CONFIG.dev) {
                    usersFactory.httpRequest.getAll(function () {
                        isDone();
                    }, function () {
                        isDone();
                    });
                    groupsFactory.httpRequest.getAllGroups(function () {
                        isDone();
                    }, function () {
                        isDone();
                    });
                    isDone();
                }
                else {
                    isDone(3);
                }
            }

            function isDone(quantity) {
                if (Methods.isNullOrEmpty(quantity)) {
                    quantity = 1;
                }
                requestQuantity = requestQuantity - quantity;
                if (requestQuantity <= 0) {
                    app.isReady = true;
                    cozenEnhancedLogs.wrap.end('cogeoInit');
                    Methods.safeApply($scope);
                }
            }
        }
    }

})(window.angular);

<|endoftext|>


<commit_before>import React from 'react'
import Views from '../../views'
import compileContext from './utils/compileContext'
import express from 'express'
import path from 'path'
import {Exceptions} from 'frontful-resolver'

const app = express()

app.use(express.static(path.resolve(process.cwd(), 'assets/root'), {maxAge: '7d'}))

app.use((req, res, next) => {
  compileContext(<Views/>, {req, res}).then((context) => {
    const assets = global.frontful.environment.assets
    res.send(`
      <!DOCTYPE html>

          <title>Frontful TodoMVC</title>
          <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=no" />
          ${context.style}

${context.view}

          ${context.state}

    `)
  }).catch((error) => {
    if (error instanceof Exceptions.Cancel) next()
    else next(error)
  })
})

export default app
<commit_msg>no message<commit_after>import React from 'react'
import Views from '../../views'
import compileContext from './utils/compileContext'
import express from 'express'
import path from 'path'
import {Exceptions} from 'frontful-resolver'

const app = express()

app.use(express.static(path.resolve(process.cwd(), 'assets/root'), {maxAge: '7d'}))

app.use((req, res, next) => {
  compileContext(<Views/>, {req, res}).then((context) => {
    const assets = global.frontful.environment.assets
    res.send(`
      <!DOCTYPE html>

          <title>Frontful TodoMVC</title>
          <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=no" />
          ${context.style}

${context.view}

          ${context.state}

    `)
  }).catch((error) => {
    if (error instanceof Exceptions.Cancel) next()
    else next(error)
  })
})

export default app
<|endoftext|>


<commit_before>/* global describe, it */
var assert = require("assert"),
	state = require("../lib/state.com.js");

var model = new state.StateMachine( "model" );

var initial = new state.PseudoState("initial", model, state.PseudoStateKind.Initial);
var ortho = new state.State("ortho", model);
var simple = new state.State("simple", model);
var final = new state.FinalState("final", model);

var r1 = new state.Region("r1", ortho);
var r2 = new state.Region("r2", ortho);

var i1 = new state.PseudoState("initial", r1, state.PseudoStateKind.ShallowHistory);
var i2 = new state.PseudoState("initial", r2, state.PseudoStateKind.ShallowHistory);

var s1 = new state.State("s1", r1);
var s2 = new state.State("s2", r2);

var f1 = new state.FinalState("f1", r1);
var f2 = new state.FinalState("f2", r2);

initial.to(ortho);

i1.to(s1);
i2.to(s2);

ortho.to(final); // This should happen once all regions in ortho are complete?

s1.to(f1).when(function(c) {
    return c === "complete1";
});

s2.to(f2).when(function(c) {
    return c === "complete2";
});

ortho.to(simple).when(function(c) {
    return c === "jump";
});

simple.to(ortho).when(function(c) {
    return c === "back";
});

var instance = new state.StateMachineInstance("instance");
state.initialise(model, instance);

describe("test/muximise.js", function () {
	describe("State type tests", function () {
		it("State.isSimple", function () {
			assert(true, simple.isSimple());
		});

		it("State.isComposite", function () {
			assert(true, ortho.isComposite());
		});

		it("State.isOrthogonal", function () {
			assert(true, ortho.isOrthogonal());
		});
	});

	describe("Orthogonal state completion", function () {
		it("Completion transition fires once all regions of an orthogonal state are complete", function(){
			state.evaluate(model, instance, "complete1");
			state.evaluate(model, instance, "complete2");

			assert.equal(true, state.isComplete(model, instance));
		});
	});
});<commit_msg>More complete tests for isSimple, isComposite and isOrthogonal<commit_after>/* global describe, it */
var assert = require("assert"),
	state = require("../lib/state.com.js");

var model = new state.StateMachine( "model" );

var initial = new state.PseudoState("initial", model, state.PseudoStateKind.Initial);
var ortho = new state.State("ortho", model);
var simple = new state.State("simple", model);
var final = new state.FinalState("final", model);

var r1 = new state.Region("r1", ortho);
var r2 = new state.Region("r2", ortho);

var i1 = new state.PseudoState("initial", r1, state.PseudoStateKind.ShallowHistory);
var i2 = new state.PseudoState("initial", r2, state.PseudoStateKind.ShallowHistory);

var s1 = new state.State("s1", r1);
var s2 = new state.State("s2", r2);

var f1 = new state.FinalState("f1", r1);
var f2 = new state.FinalState("f2", r2);

initial.to(ortho);

i1.to(s1);
i2.to(s2);

ortho.to(final); // This should happen once all regions in ortho are complete?

s1.to(f1).when(function(c) {
    return c === "complete1";
});

s2.to(f2).when(function(c) {
    return c === "complete2";
});

ortho.to(simple).when(function(c) {
    return c === "jump";
});

simple.to(ortho).when(function(c) {
    return c === "back";
});

var instance = new state.StateMachineInstance("instance");
state.initialise(model, instance);

console.log("simple.isSimple = " + simple.isSimple());
console.log("simple.isComposite = " + simple.isComposite());
console.log("simple.isOrthogonal = " + simple.isOrthogonal());

console.log("model.isSimple = " + model.isSimple());
console.log("model.isComposite = " + model.isComposite());
console.log("model.isOrthogonal = " + model.isOrthogonal());

console.log("ortho.isSimple = " + ortho.isSimple());
console.log("ortho.isComposite = " + ortho.isComposite());
console.log("ortho.isOrthogonal = " + ortho.isOrthogonal());

describe("test/muximise.js", function () {
	describe("State type tests", function () {
		it("simple state isSimple", function () {
			assert(simple.isSimple());
			assert(!model.isSimple());
			assert(!ortho.isSimple());
		});

		it("State.isComposite", function () {
			assert(!simple.isComposite());
			assert(model.isComposite());
			assert(ortho.isComposite());
		});

		it("State.isOrthogonal", function () {
			assert(!simple.isOrthogonal());
			assert(!model.isOrthogonal());
			assert(ortho.isOrthogonal());
		});
	});

	describe("Orthogonal state completion", function () {
		it("Completion transition fires once all regions of an orthogonal state are complete", function(){
			state.evaluate(model, instance, "complete1");
			state.evaluate(model, instance, "complete2");

			assert.equal(true, state.isComplete(model, instance));
		});
	});
});<|endoftext|>


<commit_before>//= require leaflet/map
//= require leaflet/awesome-markers
//= require map/sidebar
//= require leaflet/easy-button
//= require map/routes
//= require map/search
//= require leaflet/indoor-map

//Buildings

//Method called when click on one building
function onEachFeature(feature, layer) {
  layer.on('click', function() {
    //The key references to that building clicked
    var buildingKey = this.feature.geometry.coordinates[0].key;

    if (sidebar.isVisible()) {
      sidebar.hide();
    } else {
      //selects the building clicked and shows sidebar
      var numberToBuilding = '/map/data/building/' + buildingKey;
      $("#sidebar").load(numberToBuilding, function() {
        sidebar.toggle();
      });

      $.get('/map/data/roomsByBuilding/'+ buildingKey, function(data) { //getting the json data

        let rooms = {
          'type': 'FeatureCollection',
          'features': [],
        };

        data.forEach((room)=>{
          try {
            let geo_json = JSON.parse(room.geo_data);
            geo_json.features[0].properties.level = room.level;
            rooms.features.push(geo_json.features[0]);
          } catch (err) {
            console.log(err);
          }
        })

        let indoorLayer = new L.Indoor(rooms);
        indoorLayer.setLevel("0");
        indoorLayer.addTo(map);

        var levelControl = new L.Control.Level({
          level: "0",
          levels: indoorLayer.getLevels(),
        });
        levelControl.addTo(map);

      });

    }
  });
}

var buildingLayer = L.geoJSON('', {
  onEachFeature: onEachFeature
});

//adds layer of building on map
map.addLayer(buildingLayer);

//Insert each building on the layer of building
$.getJSON("/map/data/buildings", function(data) { //getting the json data
  var items = [];
  $.each(data, function(key, val) {

    try {
      var geo_json = JSON.parse(val.geo_data);
      geo_json.features[0].geometry.coordinates[0].key = val.id;
      buildingLayer.addData(geo_json); //adding the json data to the building layer
    } catch (err) {
      //console.log(err);
    }
  });

});

//Rooms

// $.getJSON("/map/data/rooms", function(data) { //getting the json data
//   var items = [];
//   $.each(data, function(key, val) {
//     try {
//       console.log(key, val);
//     } catch (err) {
//       //console.log(err);
//     }
//   });
// });

//Bikes

//Layer with bikes icon personalized
var bikesLayer = L.geoJSON('', {
  pointToLayer: function(feature, latlng) {
    var smallIcon = new L.Icon({
      iconUrl: 'http://icons.iconarchive.com/icons/elegantthemes/beautiful-flat/24/bike-icon.png',
    });
    return L.marker(latlng, {
      icon: smallIcon
    });
  }
});

//adds layer to bikes on map
map.addLayer(bikesLayer);

//Insert each bicycle rack on the layer of bikes
$.getJSON("/map/data/bikes", function(data) { //getting the json data
  var items = [];
  $.each(data, function(key, val) {
    try {
      var geo_json = JSON.parse(val.geo_data);
      bikesLayer.addData(geo_json); //adding the json data to the building layer
    } catch (err) {
      console.log(err);
    }
  });
});

//Bathrooms

//Layer with bathroom icon personalized
var bathroomLayer = L.geoJSON('', {
  pointToLayer: function(feature, latlng) {
    var smallIcon = new L.Icon({
      iconUrl: 'http://icons.iconarchive.com/icons/rokey/smooth/32/toilet-paper-icon.png',
      iconSize: [24, 24],
    });
    return L.marker(latlng, {
      icon: smallIcon
    });
  }
});

//adds layer to bathroom on map
map.addLayer(bathroomLayer);

//Insert each bathroom on the layer of bathrooms
$.getJSON("/map/data/bathrooms", function(data) { //getting the json data
  var items = [];
  $.each(data, function(key, val) {
    try {
      var geo_json = JSON.parse(val.geo_data);
      bathroomLayer.addData(geo_json); //adding the json data to the building layer
    } catch (err) {
      console.log(err);
    }
  });
});

//Snackbar

var snackbarLayer = L.geoJSON('', {
  pointToLayer: function(feature, latlng) {
    var smallIcon = new L.Icon({
      iconUrl: 'http://icons.iconarchive.com/icons/graphicloads/colorful-long-shadow/24/Restaurant-icon.png',
      iconSize: [24, 24],
    });
    return L.marker(latlng, {
      icon: smallIcon
    });
  }
});

map.addLayer(snackbarLayer);

$.getJSON("/map/data/snackbars", function(data) { //getting the json data
  var items = [];
  $.each(data, function(key, val) {
    try {
      var geo_json = JSON.parse(val.geo_data);
      snackbarLayer.addData(geo_json); //adding the json data to the building layer
    } catch (err) {
      console.log(err);
    }
  });
});

//Bus Stops

var busstopLayer = L.geoJSON('', {
  pointToLayer: function(feature, latlng) {
    var smallIcon = new L.Icon({
      iconUrl: 'http://icons.iconarchive.com/icons/elegantthemes/beautiful-flat/32/school-bus-icon.png',
      iconSize: [24, 24],
    });
    return L.marker(latlng, {
      icon: smallIcon
    });
  }
});

map.addLayer(busstopLayer);

$.getJSON("/map/data/busstops", function(data) { //getting the json data
  var items = [];
  $.each(data, function(key, val) {
    try {
      var geo_json = JSON.parse(val.geo_data);
      busstopLayer.addData(geo_json); //adding the json data to the building layer
    } catch (err) {
      console.log(err);
    }
  });
});

//Entrances

var entranceLayer = L.geoJSON('', {
  pointToLayer: function(feature, latlng) {
    var smallIcon = new L.Icon({
      iconUrl: 'http://icons.iconarchive.com/icons/elegantthemes/beautiful-flat-one-color/24/door-icon.png',
      iconSize: [24, 24],
    });
    return L.marker(latlng, {
      icon: smallIcon
    });
  }
});

map.addLayer(entranceLayer);

$.getJSON("/map/data/entrances", function(data) { //getting the json data
  var items = [];
  $.each(data, function(key, val) {
    try {
      var geo_json = JSON.parse(val.geo_data);
      entranceLayer.addData(geo_json); //adding the json data to the building layer
    } catch (err) {
      console.log(err);
    }
  });
});

//Indoor map

// Indoor Map

//Indoor Map

// $.getJSON("#", function(geoJSON) {
var data = [];
var indoorLayer = new L.Indoor(data, {
  getLevel: function(feature) {
    if (feature.properties.relations.length === 0)
      return null;

    return feature.properties.relations[0].reltags.level;
  },
  onEachFeature: function(feature, layer) {
    layer.bindPopup(JSON.stringify(feature.properties, null, 4));
  },
  style: function(feature) {
    var fill = 'white';

    if (feature.properties.tags.buildingpart === 'corridor') {
      fill = '#169EC6';
    } else if (feature.properties.tags.buildingpart === 'verticalpassage') {
      fill = '#0A485B';
    }

    return {
      fillColor: fill,
      weight: 1,
      color: '#666',
      fillOpacity: 1
    };
  }
});

indoorLayer.setLevel("0");

indoorLayer.addTo(map);

var levelControl = new L.Control.Level({
  level: "0",
  levels: indoorLayer.getLevels()
});

// Connect the level control to the indoor layer
levelControl.addEventListener("levelchange", indoorLayer.setLevel, indoorLayer);

levelControl.addTo(map);
// });
<commit_msg>rooms<commit_after>//= require leaflet/map
//= require leaflet/awesome-markers
//= require map/sidebar
//= require leaflet/easy-button
//= require map/routes
//= require map/search
//= require leaflet/indoor-map

//Buildings

//Method called when click on one building
function onEachFeature(feature, layer) {
  layer.on('click', function() {
    //The key references to that building clicked
    var buildingKey = this.feature.geometry.coordinates[0].key;

    if (sidebar.isVisible()) {
      sidebar.hide();
    } else {
      //selects the building clicked and shows sidebar
      var numberToBuilding = '/map/data/building/' + buildingKey;
      $("#sidebar").load(numberToBuilding, function() {
        sidebar.toggle();

      });

      $.get('/map/data/roomsByBuilding/'+ buildingKey, function(data) { //getting the json data

        let rooms = {
          'type': 'FeatureCollection',
          'features': [],
        };

        data.forEach((room)=>{
          try {
            let geo_json = JSON.parse(room.geo_data);
            geo_json.features[0].properties.level = room.level;
            rooms.features.push(geo_json.features[0]);
          } catch (err) {
            console.log(err);
          }
        })

        let indoorLayer = new L.Indoor(rooms);
        indoorLayer.setLevel("0");
        indoorLayer.addTo(map);

        var levelControl = new L.Control.Level({
          level: "0",
          levels: indoorLayer.getLevels(),
        });
        levelControl.addEventListener("levelchange", indoorLayer.setLevel, indoorLayer);
        levelControl.addTo(map);

      });

    }
  });
}

var buildingLayer = L.geoJSON('', {
  onEachFeature: onEachFeature
});

//adds layer of building on map
map.addLayer(buildingLayer);

//Insert each building on the layer of building
$.getJSON("/map/data/buildings", function(data) { //getting the json data
  var items = [];
  $.each(data, function(key, val) {

    try {
      var geo_json = JSON.parse(val.geo_data);
      geo_json.features[0].geometry.coordinates[0].key = val.id;
      buildingLayer.addData(geo_json); //adding the json data to the building layer
    } catch (err) {
      //console.log(err);
    }
  });

});

//Rooms

// $.getJSON("/map/data/rooms", function(data) { //getting the json data
//   var items = [];
//   $.each(data, function(key, val) {
//     try {
//       console.log(key, val);
//     } catch (err) {
//       //console.log(err);
//     }
//   });
// });

//Bikes

//Layer with bikes icon personalized
var bikesLayer = L.geoJSON('', {
  pointToLayer: function(feature, latlng) {
    var smallIcon = new L.Icon({
      iconUrl: 'http://icons.iconarchive.com/icons/elegantthemes/beautiful-flat/24/bike-icon.png',
    });
    return L.marker(latlng, {
      icon: smallIcon
    });
  }
});

//adds layer to bikes on map
map.addLayer(bikesLayer);

//Insert each bicycle rack on the layer of bikes
$.getJSON("/map/data/bikes", function(data) { //getting the json data
  var items = [];
  $.each(data, function(key, val) {
    try {
      var geo_json = JSON.parse(val.geo_data);
      bikesLayer.addData(geo_json); //adding the json data to the building layer
    } catch (err) {
      console.log(err);
    }
  });
});

//Bathrooms

//Layer with bathroom icon personalized
var bathroomLayer = L.geoJSON('', {
  pointToLayer: function(feature, latlng) {
    var smallIcon = new L.Icon({
      iconUrl: 'http://icons.iconarchive.com/icons/rokey/smooth/32/toilet-paper-icon.png',
      iconSize: [24, 24],
    });
    return L.marker(latlng, {
      icon: smallIcon
    });
  }
});

//adds layer to bathroom on map
map.addLayer(bathroomLayer);

//Insert each bathroom on the layer of bathrooms
$.getJSON("/map/data/bathrooms", function(data) { //getting the json data
  var items = [];
  $.each(data, function(key, val) {
    try {
      var geo_json = JSON.parse(val.geo_data);
      bathroomLayer.addData(geo_json); //adding the json data to the building layer
    } catch (err) {
      console.log(err);
    }
  });
});

//Snackbar

var snackbarLayer = L.geoJSON('', {
  pointToLayer: function(feature, latlng) {
    var smallIcon = new L.Icon({
      iconUrl: 'http://icons.iconarchive.com/icons/graphicloads/colorful-long-shadow/24/Restaurant-icon.png',
      iconSize: [24, 24],
    });
    return L.marker(latlng, {
      icon: smallIcon
    });
  }
});

map.addLayer(snackbarLayer);

$.getJSON("/map/data/snackbars", function(data) { //getting the json data
  var items = [];
  $.each(data, function(key, val) {
    try {
      var geo_json = JSON.parse(val.geo_data);
      snackbarLayer.addData(geo_json); //adding the json data to the building layer
    } catch (err) {
      console.log(err);
    }
  });
});

//Bus Stops

var busstopLayer = L.geoJSON('', {
  pointToLayer: function(feature, latlng) {
    var smallIcon = new L.Icon({
      iconUrl: 'http://icons.iconarchive.com/icons/elegantthemes/beautiful-flat/32/school-bus-icon.png',
      iconSize: [24, 24],
    });
    return L.marker(latlng, {
      icon: smallIcon
    });
  }
});

map.addLayer(busstopLayer);

$.getJSON("/map/data/busstops", function(data) { //getting the json data
  var items = [];
  $.each(data, function(key, val) {
    try {
      var geo_json = JSON.parse(val.geo_data);
      busstopLayer.addData(geo_json); //adding the json data to the building layer
    } catch (err) {
      console.log(err);
    }
  });
});

//Entrances

var entranceLayer = L.geoJSON('', {
  pointToLayer: function(feature, latlng) {
    var smallIcon = new L.Icon({
      iconUrl: 'http://icons.iconarchive.com/icons/elegantthemes/beautiful-flat-one-color/24/door-icon.png',
      iconSize: [24, 24],
    });
    return L.marker(latlng, {
      icon: smallIcon
    });
  }
});

map.addLayer(entranceLayer);

$.getJSON("/map/data/entrances", function(data) { //getting the json data
  var items = [];
  $.each(data, function(key, val) {
    try {
      var geo_json = JSON.parse(val.geo_data);
      entranceLayer.addData(geo_json); //adding the json data to the building layer
    } catch (err) {
      console.log(err);
    }
  });
});

//Indoor map

// Indoor Map

//Indoor Map

// $.getJSON("#", function(geoJSON) {
var data = [];
var indoorLayer = new L.Indoor(data, {
  getLevel: function(feature) {
    if (feature.properties.relations.length === 0)
      return null;

    return feature.properties.relations[0].reltags.level;
  },
  onEachFeature: function(feature, layer) {
    layer.bindPopup(JSON.stringify(feature.properties, null, 4));
  },
  style: function(feature) {
    var fill = 'white';

    if (feature.properties.tags.buildingpart === 'corridor') {
      fill = '#169EC6';
    } else if (feature.properties.tags.buildingpart === 'verticalpassage') {
      fill = '#0A485B';
    }

    return {
      fillColor: fill,
      weight: 1,
      color: '#666',
      fillOpacity: 1
    };
  }
});

indoorLayer.setLevel("0");

indoorLayer.addTo(map);

var levelControl = new L.Control.Level({
  level: "0",
  levels: indoorLayer.getLevels()
});

// Connect the level control to the indoor layer
levelControl.addEventListener("levelchange", indoorLayer.setLevel, indoorLayer);

levelControl.addTo(map);
// });
<|endoftext|>


<commit_before>/**
 * Created by toly on 12.04.14.
 */

angular.module('gtdTreeApp')
    .controller('ProjectsCtrl', function($scope, $rootScope, Projects, Trees){

        // projects operations

        $scope.new_project = {};

        $scope.add_project = function(){
            Projects.create($scope.new_project);
            $scope.new_project = {};
            $scope.new_project_show = false;
        };

        $scope.remove_project = function(project_id) {
            if ($rootScope.current_project && $rootScope.current_project.id == project_id) {
                $rootScope.current_project = {};
            }
            Projects.remove(project_id);
            Trees.remove_project_tree(project_id);
        };

        $scope.select_project = function(project_id) {
            $rootScope.current_project = Projects.get_project(project_id);
        };

        // tree operations

    });<commit_msg>confirm project deletion<commit_after>/**
 * Created by toly on 12.04.14.
 */

angular.module('gtdTreeApp')
    .controller('ProjectsCtrl', function($scope, $rootScope, Projects, Trees){

        // projects operations

        $scope.new_project = {};

        $scope.add_project = function(){
            Projects.create($scope.new_project);
            $scope.new_project = {};
            $scope.new_project_show = false;
        };

        $scope.remove_project = function(project_id) {

            var project = Projects.get_project(project_id);
            var confirm_delete = confirm('Are you sure you want to delete a project "' + project.title +'"?');

            if (!confirm_delete) return;

            if ($rootScope.current_project && $rootScope.current_project.id == project_id) {
                $rootScope.current_project = {};
            }
            Projects.remove(project_id);
            Trees.remove_project_tree(project_id);
        };

        $scope.select_project = function(project_id) {
            $rootScope.current_project = Projects.get_project(project_id);
        };

        // tree operations

    });<|endoftext|>


<commit_before>import express from 'express';
import passport from 'passport';
import User from '../models/user';
const router = express.Router();

//need to explicity log this user out
router.get('/logout',  function(req,res){

	var User = require('./models/user')(req.config.mongo.URL);

	if (req.user){
		User.findOne({ username: req.user.username}).remove().exec();
	}

	req.logout();

	req.session.destroy(function(err){
		res.redirect("/");
	});
});

router.get('/github', passport.authenticate('github', { scope: 'public_repo' }));

router.get('/github/callback', passport.authenticate('github', { failureRedirect: '/auth/github' }), function(req, res) {
    console.log("callback success");
    res.redirect('/');
});

module.exports = router;

<commit_msg>added in config support for dockerised version of sdk - fixed typo<commit_after>import express from 'express';
import passport from 'passport';
const router = express.Router();

//need to explicity log this user out
router.get('/logout',  function(req,res){

	var User = require('../models/user')(req.config.mongo.URL);

	if (req.user){
		User.findOne({ username: req.user.username}).remove().exec();
	}

	req.logout();

	req.session.destroy(function(err){
		res.redirect("/");
	});
});

router.get('/github', passport.authenticate('github', { scope: 'public_repo' }));

router.get('/github/callback', passport.authenticate('github', { failureRedirect: '/auth/github' }), function(req, res) {
    console.log("callback success");
    res.redirect('/');
});

module.exports = router;

<|endoftext|>


<commit_before>var optimize = require('../').optimize;

suite('optimize', function() {
  test('optimize twice', function() {
    optimize('test/fixtures/b.js');
    optimize('test/fixtures/b.js');
  });
});
<commit_msg>Update failing tests<commit_after>var optimize = require('../').optimize;

suite('optimize', function() {
  test('optimize `require` call', function() {
    optimize('test/fixtures/a.js');
    optimize('test/fixtures/b.js');
  });

  test('optimize `define` call twice', function() {
    optimize('test/fixtures/b.js');
    optimize('test/fixtures/b.js');
  });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

var Liftoff = require('liftoff');
var argv = require('minimist')(process.argv.slice(2));
var logger = require('../lib/log.js');
var path = require('path');
var nodeVersion = process.versions.node;
var parts = nodeVersion.split(".");

var cli = new Liftoff({
  name: 'fis',
  processTitle: 'fis',
  moduleName: 'fis3',
  configName: 'fis-conf',

  // only js supported!
  extensions: {
    '.js': null
  }
});

cli.launch({
  cwd: argv.r || argv.root,
  configPath: argv.f || argv.file
}, function(env) {
  var fis;

  if (!env.modulePath) {
    logger.warning('Local `fis3` not found, use global version instead.');
    fis = require('../');
  } else {
    fis = require(env.modulePath);
  }

  process.env.NODE_ENV = process.env.NODE_ENV || argv.env || 'dev';

  // default settings
  fis.config.merge({
    modules: {
      packager: 'map',
      deploy: 'default'
    },
    project: {
      files: ['*.html', '!output/**', '!node_modules/**'],
      watch: {
        exclude: /^\/(?:output|node_modules).*$/i,
      }
    }
  });

  fis.match('*.{js|css|html}', {
    preprocessor: fis.plugin('components')
  });

  fis.match('*.js', {
    postprocessor: fis.plugin('jswrapper'),
  });

  fis.env('production')
    .match('*.js', {
      optimizer: fis.plugin('uglify-js')
    })
    .match('*.css', {
      optimizer: fis.plugin('clean-css')
    })
    .match('*.png', {
      optimizer: fis.plugin('png-compressor')
    });

  //exports cli object
  fis.cli = {};

  fis.cli.name = 'fis';

  //colors
  fis.cli.colors = require('colors');

  //commander object
  fis.cli.commander = null;

  //package.json
  fis.cli.info = fis.util.readJSON(path.dirname(__dirname) + '/package.json');

  //output help info
  fis.cli.help = function() {
    var content = [
      '',
      '  Usage: ' + fis.cli.name + ' <command>',
      '',
      '  Commands:',
      ''
    ];

    fis.cli.help.commands.forEach(function(name) {
      var cmd = fis.require('command', name);
      name = cmd.name || name;
      name = fis.util.pad(name, 12);
      content.push('    ' + name + (cmd.desc || ''));
    });

    content = content.concat([
      '',
      '  Options:',
      '',
      '    -h, --help     output usage information',
      '    -v, --version  output the version number',
      '    --no-color     disable colored output',
      '    --env          set env, default value is `dev`.',
      ''
    ]);

    console.log(content.join('\n'));
  };

  fis.cli.help.commands = ['init', 'release', 'install', 'server'];

  //output version info
  fis.cli.version = function() {
    var content = ['',
      '  v' + fis.cli.info.version,
      ''
    ].join('\n');

    var logo = [
      ' __/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\__/\\\\\\\\\\\\\\\\\\\\\\_____/\\\\\\\\\\\\\\\\\\\\\\___',
      '  _\\/\\\\\\///////////__\\/////\\\\\\///____/\\\\\\/////////\\\\\\_       ',
      '   _\\/\\\\\\_________________\\/\\\\\\______\\//\\\\\\______\\///__',
      '    _\\/\\\\\\\\\\\\\\\\\\\\\\_________\\/\\\\\\_______\\////\\\\\\_________     ',
      '     _\\/\\\\\\///////__________\\/\\\\\\__________\\////\\\\\\______    ',
      '      _\\/\\\\\\_________________\\/\\\\\\_____________\\////\\\\\\___   ',
      '       _\\/\\\\\\_________________\\/\\\\\\______/\\\\\\______\\//\\\\\\__',
      '        _\\/\\\\\\______________/\\\\\\\\\\\\\\\\\\\\\\_\\///\\\\\\\\\\\\\\\\\\\\\\/___',
      '         _\\///______________\\///////////____\\///////////_____',
      ''
    ].join('\n');

    if (fis.get('cli.options.color') !== false) {
      logo = fis.lolcat(logo);
    }
    console.log(content + '\n' + logo);
  };

  //run cli tools
  fis.cli.run = function(argv) {

    if (fis.get('cli.options.color') === false) {
      fis.cli.colors.mode = 'none';
    }

    var first = argv[2];
    if (argv.length < 3 || first === '-h' || first === '--help') {
      fis.cli.help();
    } else if (first === '-v' || first === '--version') {
      fis.cli.version();
    } else if (first[0] === '-') {
      fis.cli.help();
    } else {
      //register command
      var commander = fis.cli.commander = require('commander');
      var cmd = fis.require('command', argv[2]);
      cmd.register(
        commander
        .command(cmd.name || first)
        .usage(cmd.usage)
        .description(cmd.desc)
      );
      commander.parse(argv);
    }
  };

  fis.set('cli.options', argv);
  fis.cli.run(process.argv);
});
<commit_msg>update<commit_after>#!/usr/bin/env node

var Liftoff = require('liftoff');
var argv = require('minimist')(process.argv.slice(2));
var logger = require('../lib/log.js');
var path = require('path');
var nodeVersion = process.versions.node;
var parts = nodeVersion.split(".");

var cli = new Liftoff({
  name: 'fis',
  processTitle: 'fis',
  moduleName: 'fis3',
  configName: 'fis-conf',

  // only js supported!
  extensions: {
    '.js': null
  }
});

cli.launch({
  cwd: argv.r || argv.root,
  configPath: argv.f || argv.file
}, function(env) {
  var fis;

  if (!env.modulePath) {
    logger.warning('Local `fis3` not found, use global version instead.');
    fis = require('../');
  } else {
    fis = require(env.modulePath);
  }

  process.env.NODE_ENV = process.env.NODE_ENV || argv.env || 'dev';

  // default settings
  fis.config.merge({
    modules: {
      packager: 'map',
      deploy: 'default'
    },
    project: {
      files: ['*.html', '!output/**', '!node_modules/**'],
      watch: {
        exclude: /^\/(?:output|node_modules).*$/i,
      }
    }
  });

  fis.match('*.{js|css|html}', {
    preprocessor: fis.plugin('components')
  });

  fis.match('*.js', {
    postprocessor: fis.plugin('jswrapper'),
  });

  fis.env('production')
    .match('*.js', {
      optimizer: fis.plugin('uglify-js')
    })
    .match('*.css', {
      optimizer: fis.plugin('clean-css')
    })
    .match('*.png', {
      optimizer: fis.plugin('png-compressor')
    });

  //exports cli object
  fis.cli = {};

  fis.cli.name = 'fis';

  //colors
  fis.cli.colors = require('colors');

  //commander object
  fis.cli.commander = null;

  //package.json
  fis.cli.info = fis.util.readJSON(path.dirname(__dirname) + '/package.json');

  //output help info
  fis.cli.help = function() {
    var content = [
      '',
      '  Usage: ' + fis.cli.name + ' <command>',
      '',
      '  Commands:',
      ''
    ];

    fis.cli.help.commands.forEach(function(name) {
      var cmd = fis.require('command', name);
      name = cmd.name || name;
      name = fis.util.pad(name, 12);
      content.push('    ' + name + (cmd.desc || ''));
    });

    content = content.concat([
      '',
      '  Options:',
      '',
      '    -h, --help     output usage information',
      '    -v, --version  output the version number',
      '    --no-color     disable colored output',
      '    --env          set env, default value is `dev`.',
      ''
    ]);

    console.log(content.join('\n'));
  };

  fis.cli.help.commands = ['init', 'release', 'install', 'server'];

  //output version info
  fis.cli.version = function() {
    var content = ['',
      '  v' + fis.cli.info.version,
      ''
    ].join('\n');

    var logo = [
      ' __/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\__/\\\\\\\\\\\\\\\\\\\\\\_____/\\\\\\\\\\\\\\\\\\\\\\___',
      '  _\\/\\\\\\///////////__\\/////\\\\\\///____/\\\\\\/////////\\\\\\_       ',
      '   _\\/\\\\\\_________________\\/\\\\\\______\\//\\\\\\______\\///__',
      '    _\\/\\\\\\\\\\\\\\\\\\\\\\_________\\/\\\\\\_______\\////\\\\\\_________     ',
      '     _\\/\\\\\\///////__________\\/\\\\\\__________\\////\\\\\\______    ',
      '      _\\/\\\\\\_________________\\/\\\\\\_____________\\////\\\\\\___   ',
      '       _\\/\\\\\\_________________\\/\\\\\\______/\\\\\\______\\//\\\\\\__',
      '        _\\/\\\\\\______________/\\\\\\\\\\\\\\\\\\\\\\_\\///\\\\\\\\\\\\\\\\\\\\\\/___',
      '         _\\///______________\\///////////____\\///////////_____',
      ''
    ].join('\n');

    if (fis.get('cli.options.color') !== false) {
      logo = fis.lolcat(logo);
    }
    console.log(content + '\n' + logo);
  };

  //run cli tools
  fis.cli.run = function(argv) {

    if (fis.get('cli.options.color') === false) {
      fis.cli.colors.mode = 'none';
    }

    var first = argv[2];
    if (argv.length < 3 || first === '-h' || first === '--help') {
      fis.cli.help();
    } else if (first === '-v' || first === '--version') {
      fis.cli.version();
    } else if (first[0] === '-') {
      fis.cli.help();
    } else {

      //fix args
      var p = argv.indexOf('--no-color');
      if (~p) argv.splice(p, 1);

      //register command
      var commander = fis.cli.commander = require('commander');
      var cmd = fis.require('command', argv[2]);
      cmd.register(
        commander
        .command(cmd.name || first)
        .usage(cmd.usage)
        .description(cmd.desc)
      );
      commander.parse(argv);
    }
  };

  fis.set('cli.options', argv);
  fis.cli.run(process.argv);
});
<|endoftext|>


<commit_before>(function () {
if (typeof(window) === 'undefined') {
    var nearley = require('../lib/nearley.js');
} else {
    var nearley = window.nearley;
}

function Compile(structure, opts) {
    var unique = uniquer();

    var outputRules = [];
    var body = []; // @directives list

    function buildProcessedRule(ruleName, rule) {
        var tokenList = [];

        rule.tokens.forEach(function(token) {
            if (token.literal) {
                var str = token.literal;
                if (str.length > 1) {
                    var rules = str.split("").map(function(d) {
                        return {
                            literal: d
                        };
                    });

                    var newname = unique(ruleName + "$string");
                    buildProcessedRule(newname, {
                        tokens: rules,
                        postprocess: joiner
                    });
                    tokenList.push(newname);
                } else if (str.length === 1) {
                    tokenList.push({
                        literal: str
                    });
                }
            } else if (token.subexpression) {
                var data = token.subexpression;
                var name = unique(ruleName + "$subexpression");
                structure.push({"name": name, "rules": data});
                tokenList.push(name);
            } else if (token.ebnf) {
                var data = token.ebnf;
                var modifier = token.modifier;
                var name = unique(ruleName + "$ebnf");

                switch (modifier) {
                    case ":+":
                        structure.push({
                            "name": name,
                            "rules": [{
                                "tokens": [data],
                            }, {
                                "tokens": [data, name],
                                "postprocess": arrconcat
                            }]
                        });
                        tokenList.push(name);
                        break;
                    case ":*":
                        structure.push({
                            "name": name,
                            "rules": [{
                                "tokens": [],
                            }, {
                                "tokens": [data, name],
                                "postprocess": arrconcat
                            }]
                        });
                        tokenList.push(name);
                        break;
                    case ":?":
                        structure.push({
                            "name": name,
                            "rules": [{
                                "tokens": [data],
                                "postprocess": "id"
                            }, {
                                "tokens": [],
                                "postprocess": "function(d) {return null;}"
                            }]
                        });
                        tokenList.push(name);
                        break;
                }
            } else if (typeof(token) === 'string') {
                if (token !== 'null') tokenList.push(token);
            } else if (token instanceof RegExp) {
                tokenList.push(token);
            } else {
                throw new Error("Should never get here");
            }
        });

        var out = new nearley.Rule(
            ruleName,
            tokenList,
            (opts.nojs ? null : rule.postprocess)
        );

        outputRules.push(out);
    }

    var firstName;

    for (var i = 0; i < structure.length; i++) {
        var productionRule = structure[i];
        if (productionRule.body) {
            // This isn't a rule, it's an @directive.
            if (!opts.nojs) body.push(productionRule.body);
        } else {
            var rules = productionRule.rules;
            if (!firstName) firstName = productionRule.name;
            rules.forEach(function(rule) {
                buildProcessedRule(productionRule.name, rule);
            });
        }
    }

    return {
        rules: outputRules,
        body: body,
        start: firstName
    };
}

function uniquer() {
    var uns = {};
    return unique;
    function unique(name) {
        var un = uns[name] = (uns[name] || 0) + 1;
        return name + '$' + un;
    }
}

function arrconcat(d) {
    return [d[0]].concat(d[1]);
}

function joiner(d) {
    return d.join('');
}

if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = Compile;
} else {
    window.Compile = Compile;
}
})();
<commit_msg>lib/compile: trivial cleanup<commit_after>(function () {
if (typeof(window) === 'undefined') {
    var nearley = require('../lib/nearley.js');
} else {
    var nearley = window.nearley;
}

function Compile(structure, opts) {
    var unique = uniquer();

    var outputRules = [];
    var body = []; // @directives list

    function buildProcessedRule(ruleName, rule) {
        var tokens = [];

        rule.tokens.forEach(function(token) {
            if (token.literal) {
                var str = token.literal;
                if (str.length > 1) {
                    var rules = str.split("").map(function(d) {
                        return {
                            literal: d
                        };
                    });

                    var newname = unique(ruleName + "$string");
                    buildProcessedRule(newname, {
                        tokens: rules,
                        postprocess: joiner
                    });
                    tokens.push(newname);
                } else if (str.length === 1) {
                    tokens.push({
                        literal: str
                    });
                }
            } else if (token.subexpression) {
                var data = token.subexpression;
                var name = unique(ruleName + "$subexpression");
                structure.push({"name": name, "rules": data});
                tokens.push(name);
            } else if (token.ebnf) {
                var data = token.ebnf;
                var modifier = token.modifier;
                var name = unique(ruleName + "$ebnf");

                switch (modifier) {
                    case ":+":
                        structure.push({
                            name: name,
                            rules: [{
                                tokens: [data],
                            }, {
                                tokens: [data, name],
                                postprocess: arrconcat
                            }]
                        });
                        tokens.push(name);
                        break;
                    case ":*":
                        structure.push({
                            name: name,
                            rules: [{
                                tokens: [],
                            }, {
                                tokens: [data, name],
                                postprocess: arrconcat
                            }]
                        });
                        tokens.push(name);
                        break;
                    case ":?":
                        structure.push({
                            name: name,
                            rules: [{
                                tokens: [data],
                                postprocess: "id"
                            }, {
                                tokens: [],
                                postprocess: "function(d) {return null;}"
                            }]
                        });
                        tokens.push(name);
                        break;
                }
            } else if (typeof token === 'string') {
                if (token !== 'null') tokens.push(token);
            } else if (token instanceof RegExp) {
                tokens.push(token);
            } else {
                throw new Error("Should never get here");
            }
        });

        var out = new nearley.Rule(
            ruleName,
            tokens,
            (opts.nojs ? null : rule.postprocess)
        );

        outputRules.push(out);
    }

    var firstName;

    for (var i = 0; i < structure.length; i++) {
        var productionRule = structure[i];
        if (productionRule.body) {
            // This isn't a rule, it's an @directive.
            if (!opts.nojs) body.push(productionRule.body);
        } else {
            var rules = productionRule.rules;
            if (!firstName) firstName = productionRule.name;
            rules.forEach(function(rule) {
                buildProcessedRule(productionRule.name, rule);
            });
        }
    }

    return {
        rules: outputRules,
        body: body,
        start: firstName
    };
}

function uniquer() {
    var uns = {};
    return unique;
    function unique(name) {
        var un = uns[name] = (uns[name] || 0) + 1;
        return name + '$' + un;
    }
}

function arrconcat(d) {
    return [d[0]].concat(d[1]);
}

function joiner(d) {
    return d.join('');
}

if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = Compile;
} else {
    window.Compile = Compile;
}
})();
<|endoftext|>


<commit_before>import Express from 'express'
import Delogger from 'delogger'
import compression from 'compression'
import cookieParser from 'cookie-parser'
import bodyParser from 'body-parser'
import https from 'https'
import http from 'http'
import fs from 'fs'
import Path from 'path'

import EnforceHttps from './module/enforceHttps'
import ResolveUser from './module/resolveUser'
import Config from '../model/config'
var config = new Config({sync: true})

export default class Server {
  constructor () {
    this.app = Express()
    this.app.disable('x-powered-by')
    this.app.use(compression())
    this.app.use(cookieParser())
    this.app.use(bodyParser.json())
    this.app.use(bodyParser.urlencoded({
      extended: true
    }))

    if (config.server.https) {
      this.app.use(EnforceHttps({
        port: config.server.https
      }))

      let options = {}

      Object.assign(options, {
        hostname: config.server.hostname,
        key: fs.readFileSync(config.server.certs.privatekey),
        cert: fs.readFileSync(config.server.certs.certificate),
        ca: fs.readFileSync(config.server.certs.chain)
      })

      this.serverSSL = https.createServer(options, this.app)
    }

    this.server = http.createServer(this.app)

    this.app.use(ResolveUser())
    require('./log')(this.app)
    require('./socket')(this.app, this)
    require('./auth')(this.app)
    this.baseFolder = require('./folder')(this.app)
    require('./file')(this.app, this.baseFolder)
    require('./torrent')(this.app, this.baseFolder)
    require('./app')(this.app, this.baseFolder)

    this.app.use(Express.static(Path.join(__dirname, '/public')))

    this.log = new Delogger('Server')
  }

  listen () {
    let host = '0.0.0.0'

    if (config.server.https) {
      // ssl server
      this.serverSSL.listen(config.server.https, host, () => this.log.info(`Server listening on ${host}:${config.server.https}`))
      this.app.socketSSL = this.app.ioSSL.listen(this.serverSSL, host)
    }

    // http server
    this.server.listen(config.server.port, host, () => this.log.info(`Server listening on ${host}:${config.server.port}`))
    this.app.socket = this.app.io.listen(this.server, host)
  }
}
<commit_msg>remove useless listen<commit_after>import Express from 'express'
import Delogger from 'delogger'
import compression from 'compression'
import cookieParser from 'cookie-parser'
import bodyParser from 'body-parser'
import https from 'https'
import http from 'http'
import fs from 'fs'
import Path from 'path'

import EnforceHttps from './module/enforceHttps'
import ResolveUser from './module/resolveUser'
import Config from '../model/config'
var config = new Config({sync: true})

export default class Server {
  constructor () {
    this.app = Express()
    this.app.disable('x-powered-by')
    this.app.use(compression())
    this.app.use(cookieParser())
    this.app.use(bodyParser.json())
    this.app.use(bodyParser.urlencoded({
      extended: true
    }))

    if (config.server.https) {
      this.app.use(EnforceHttps({
        port: config.server.https
      }))

      let options = {}

      Object.assign(options, {
        hostname: config.server.hostname,
        key: fs.readFileSync(config.server.certs.privatekey),
        cert: fs.readFileSync(config.server.certs.certificate),
        ca: fs.readFileSync(config.server.certs.chain)
      })

      this.serverSSL = https.createServer(options, this.app)
    }

    this.server = http.createServer(this.app)

    this.app.use(ResolveUser())
    require('./log')(this.app)
    require('./socket')(this.app, this)
    require('./auth')(this.app)
    this.baseFolder = require('./folder')(this.app)
    require('./file')(this.app, this.baseFolder)
    require('./torrent')(this.app, this.baseFolder)
    require('./app')(this.app, this.baseFolder)

    this.app.use(Express.static(Path.join(__dirname, '/public')))

    this.log = new Delogger('Server')
  }

  listen () {
    let host = '0.0.0.0'

    if (config.server.https) {
      // ssl server
      this.serverSSL.listen(config.server.https, host, () => this.log.info(`Server listening on ${host}:${config.server.https}`))
      //this.app.socketSSL = this.app.ioSSL.listen(this.serverSSL, host)
    }

    // http server
    this.server.listen(config.server.port, host, () => this.log.info(`Server listening on ${host}:${config.server.port}`))
    //this.app.socket = this.app.io.listen(this.server, host)
  }
}
<|endoftext|>