<commit_before>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var SiteGenerator = module.exports = function SiteGenerator(args, options, config) {
    yeoman.generators.Base.apply(this, arguments);
    this.on('end', function () {
        this.installDependencies({
            skipInstall: options['skip-install'],
            callback: function () {
                var fs = require('fs-extra');
                var projectDir = process.cwd();

                fs.copy(projectDir + '/bower_components/wordpress', projectDir + '/app', function (err) {
                    if (err) {
                        return console.error(err);
                    } else {
                        console.log('WordPress copied successfully');
                    }
                });

            }.bind(this)
        });
    });

    this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(SiteGenerator, yeoman.generators.Base);

SiteGenerator.prototype.askFor = function askFor() {
    var cb = this.async();

    // have Yeoman greet the user.
    console.log(this.yeoman);

    var prompts = [
        {
            name: 'siteName',
            message: 'What would you like to call your site?'
        }, /*{
            type: 'confirm',
            name: 'wordpress',
            message: 'Is this site going to be running on WordPress?',
            default: false
        }, */
        {
            type: 'list',
            name: 'cssFramework',
            message: 'Which CSS framework / grid system would you like to use?',
            choices: [{
                name: 'Compass/Susy',
                value: 'compassSusy'
            }, {
                name: 'Bourbon/Neat',
                value: 'bourbonNeat'
            }, {
                name: 'No framework',
                value: 'noFramework'
            }]
        }
    ];

    this.prompt(prompts, function (props) {
        this.siteName = props.siteName;
        this.cssFramework = props.cssFramework;
        this.wordpress = props.wordpress;

        cb();
    }.bind(this));
};

function convertToSlug(text) {
    return text
        .toLowerCase()
        .replace(/ä+/g, 'a')
        .replace(/ö+/g, 'o')
        .replace(/[^\w ]+/g, '')
        .replace(/ +/g, '-')
        ;
}

SiteGenerator.prototype.app = function app() {
    var appUrl = 'app';

    if (this.wordpress) {
        this.slugSiteName = convertToSlug(this.siteName);

        /*this.directory('wordpress', appUrl);*/
        this.directory('_s', '');
        appUrl = '_s';
    }

    this.mkdir(appUrl + '/assets/scss/lib');
    this.mkdir(appUrl + '/assets/scss/fonts');
    this.mkdir(appUrl + '/assets/js/lib');
    this.mkdir(appUrl + '/assets/php');

    this.template('Gruntfile.js', 'Gruntfile.js');
    this.template('index.html', appUrl + '/index.html');

    this.template('_bower.json', 'bower.json');
    this.template('_config.json', 'config.json');
    this.template('_package.json', 'package.json');
    this.copy('.htaccess', appUrl + '/.htaccess');

    this.copy('assets/img/sprite-assets/trans.png', appUrl + '/assets/img/sprite-assets/trans.png');
    this.copy('assets/scss/style.scss', appUrl + '/assets/scss/style.scss');
    this.copy('assets/scss/lteie8.scss', appUrl + '/assets/scss/lteie8.scss');

    this.copy('assets/scss/lib/_normalize.scss', appUrl + '/assets/scss/lib/_normalize.scss');

    this.copy('assets/scss/global/_fonts.scss', appUrl + '/assets/scss/global/_fonts.scss');
    this.copy('assets/scss/global/_variables.scss', appUrl + '/assets/scss/global/_variables.scss');
    this.copy('assets/scss/global/_functions.scss', appUrl + '/assets/scss/global/_functions.scss');
    this.copy('assets/scss/global/_mixins.scss', appUrl + '/assets/scss/global/_mixins.scss');
    this.copy('assets/scss/global/_framework_media.scss', appUrl + '/assets/scss/global/_framework_media.scss');
    this.copy('assets/scss/global/_framework_nav.scss', appUrl + '/assets/scss/global/_framework_nav.scss');

    this.copy('assets/scss/local/_typography.scss', appUrl + '/assets/scss/local/_typography.scss');
    this.copy('assets/scss/local/_helpers.scss', appUrl + '/assets/scss/local/_helpers.scss');
    this.copy('assets/scss/local/_images.scss', appUrl + '/assets/scss/local/_images.scss');
    this.copy('assets/scss/local/_forms.scss', appUrl + '/assets/scss/local/_forms.scss');
    this.copy('assets/scss/local/_lists.scss', appUrl + '/assets/scss/local/_lists.scss');
    this.copy('assets/scss/local/_local.scss', appUrl + '/assets/scss/local/_local.scss');

    this.copy('assets/js/script.js', appUrl + '/assets/js/script.js');

    if (this.wordpress) {
        this.directory('assets/scss/wordpress', appUrl + '/assets/scss/object');
    } else {
        this.directory('assets/scss/object', appUrl + '/assets/scss/object');
    }
};

SiteGenerator.prototype.runtime = function runtime() {
    this.copy('bowerrc', '.bowerrc');
    this.copy('gitignore', '.gitignore');
};

SiteGenerator.prototype.projectfiles = function projectfiles() {
    this.copy('editorconfig', '.editorconfig');
    this.copy('jshintrc', '.jshintrc');
};
<commit_msg>Conditionally copies wp dir<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var SiteGenerator = module.exports = function SiteGenerator(args, options, config) {
    yeoman.generators.Base.apply(this, arguments);
    this.on('end', function () {
        this.installDependencies({
            skipInstall: options['skip-install'],
            callback: function () {
                if (this.wordpress) {
                    var fs = require('fs-extra');
                    var projectDir = process.cwd();

                    fs.copy(projectDir + '/bower_components/wordpress', projectDir + '/app', function (err) {
                        if (err) {
                            return console.error(err);
                        } else {
                            console.log('WordPress copied successfully');
                        }
                    });
                }

            }.bind(this)
        });
    });

    this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(SiteGenerator, yeoman.generators.Base);

SiteGenerator.prototype.askFor = function askFor() {
    var cb = this.async();

    // have Yeoman greet the user.
    console.log(this.yeoman);

    var prompts = [
        {
            name: 'siteName',
            message: 'What would you like to call your site?'
        }, {
            type: 'confirm',
            name: 'wordpress',
            message: 'Is this site going to be running on WordPress?',
            default: false
        },
        {
            type: 'list',
            name: 'cssFramework',
            message: 'Which CSS framework / grid system would you like to use?',
            choices: [{
                name: 'Compass/Susy',
                value: 'compassSusy'
            }, {
                name: 'Bourbon/Neat',
                value: 'bourbonNeat'
            }, {
                name: 'No framework',
                value: 'noFramework'
            }]
        }
    ];

    this.prompt(prompts, function (props) {
        this.siteName = props.siteName;
        this.cssFramework = props.cssFramework;
        this.wordpress = props.wordpress;

        cb();
    }.bind(this));
};

function convertToSlug(text) {
    return text
        .toLowerCase()
        .replace(/ä+/g, 'a')
        .replace(/ö+/g, 'o')
        .replace(/[^\w ]+/g, '')
        .replace(/ +/g, '-')
        ;
}

SiteGenerator.prototype.app = function app() {
    var appUrl = 'app';

    if (this.wordpress) {
        this.slugSiteName = convertToSlug(this.siteName);

        /*this.directory('wordpress', appUrl);*/
        this.directory('_s', '');
        appUrl = '_s';
    }

    this.mkdir(appUrl + '/assets/scss/lib');
    this.mkdir(appUrl + '/assets/scss/fonts');
    this.mkdir(appUrl + '/assets/js/lib');
    this.mkdir(appUrl + '/assets/php');

    this.template('Gruntfile.js', 'Gruntfile.js');
    this.template('index.html', appUrl + '/index.html');

    this.template('_bower.json', 'bower.json');
    this.template('_config.json', 'config.json');
    this.template('_package.json', 'package.json');
    this.copy('.htaccess', appUrl + '/.htaccess');

    this.copy('assets/img/sprite-assets/trans.png', appUrl + '/assets/img/sprite-assets/trans.png');
    this.copy('assets/scss/style.scss', appUrl + '/assets/scss/style.scss');
    this.copy('assets/scss/lteie8.scss', appUrl + '/assets/scss/lteie8.scss');

    this.copy('assets/scss/lib/_normalize.scss', appUrl + '/assets/scss/lib/_normalize.scss');

    this.copy('assets/scss/global/_fonts.scss', appUrl + '/assets/scss/global/_fonts.scss');
    this.copy('assets/scss/global/_variables.scss', appUrl + '/assets/scss/global/_variables.scss');
    this.copy('assets/scss/global/_functions.scss', appUrl + '/assets/scss/global/_functions.scss');
    this.copy('assets/scss/global/_mixins.scss', appUrl + '/assets/scss/global/_mixins.scss');
    this.copy('assets/scss/global/_framework_media.scss', appUrl + '/assets/scss/global/_framework_media.scss');
    this.copy('assets/scss/global/_framework_nav.scss', appUrl + '/assets/scss/global/_framework_nav.scss');

    this.copy('assets/scss/local/_typography.scss', appUrl + '/assets/scss/local/_typography.scss');
    this.copy('assets/scss/local/_helpers.scss', appUrl + '/assets/scss/local/_helpers.scss');
    this.copy('assets/scss/local/_images.scss', appUrl + '/assets/scss/local/_images.scss');
    this.copy('assets/scss/local/_forms.scss', appUrl + '/assets/scss/local/_forms.scss');
    this.copy('assets/scss/local/_lists.scss', appUrl + '/assets/scss/local/_lists.scss');
    this.copy('assets/scss/local/_local.scss', appUrl + '/assets/scss/local/_local.scss');

    this.copy('assets/js/script.js', appUrl + '/assets/js/script.js');

    if (this.wordpress) {
        this.directory('assets/scss/wordpress', appUrl + '/assets/scss/object');
    } else {
        this.directory('assets/scss/object', appUrl + '/assets/scss/object');
    }
};

SiteGenerator.prototype.runtime = function runtime() {
    this.copy('bowerrc', '.bowerrc');
    this.copy('gitignore', '.gitignore');
};

SiteGenerator.prototype.projectfiles = function projectfiles() {
    this.copy('editorconfig', '.editorconfig');
    this.copy('jshintrc', '.jshintrc');
};
<|endoftext|>


<commit_before>import {
  StackNavigator,
} from 'react-navigation';
import SearchScreen from './scenes/SearchScreen';

const GitHubProjects = StackNavigator({
  Search: { screen: SearchScreen },
});

export default GitHubProjects;

<commit_msg>Add Title to Navbar for search screen<commit_after>import {
  StackNavigator,
} from 'react-navigation';
import SearchScreen from './scenes/SearchScreen';

const GitHubProjects = StackNavigator({
  Search: {
    screen: SearchScreen,
    navigationOptions: {
      title: 'GitHub Search'
    }},
});

export default GitHubProjects;

<|endoftext|>


<commit_before>var fs = require('fs'),
    join = require('path').join,
    express = require('express'),
    exphbs = require('express-handlebars'),
    mongoose = require('mongoose'),
    config = require('./config'),
    app = express(),
    cors = require('cors'),
    bodyParser = require('body-parser'),
    passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy;

app.engine('.hbs', exphbs({extname: '.hbs', defaultLayout: 'home', layoutsDir: 'app/views/layouts/'}));
app.set('view engine', '.hbs');

var connect = function () {
    mongoose.connect(config.db);
};

var port = process.env.PORT || config.PORT;

/*connect();*/

app.use(require('express-session')({
    secret: 'ep enroll ui',
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(cors());

// Bootstrap models
fs.readdirSync(join(__dirname, 'models')).forEach(function (file) {
    if (~file.indexOf('.js')) require(join(__dirname, 'models', file));
});
var Users = mongoose.model('Users');

passport.use(new LocalStrategy(Users.authenticate()));
passport.serializeUser(Users.serializeUser());
passport.deserializeUser(Users.deserializeUser());

app.set('views', __dirname + '/views/');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + '/public'));

// Bootstrap routes
require('./routes')(app);

var server = app.listen(port, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at http://%s:%s', host, port);
});<commit_msg>connectdb<commit_after>var fs = require('fs'),
    join = require('path').join,
    express = require('express'),
    exphbs = require('express-handlebars'),
    mongoose = require('mongoose'),
    config = require('./config'),
    app = express(),
    cors = require('cors'),
    bodyParser = require('body-parser'),
    passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy;

app.engine('.hbs', exphbs({extname: '.hbs', defaultLayout: 'home', layoutsDir: 'app/views/layouts/'}));
app.set('view engine', '.hbs');

var connect = function () {
    mongoose.connect(config.db);
};

var port = process.env.PORT || config.PORT;

connect();

app.use(require('express-session')({
    secret: 'ep enroll ui',
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json({ type: 'application/*+json' }));
app.use(cors());

// Bootstrap models
fs.readdirSync(join(__dirname, 'models')).forEach(function (file) {
    if (~file.indexOf('.js')) require(join(__dirname, 'models', file));
});
var Users = mongoose.model('Users');

passport.use(Users.createStrategy());
passport.serializeUser(Users.serializeUser());
passport.deserializeUser(Users.deserializeUser());

app.set('views', __dirname + '/views/');
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + '/public'));

// Bootstrap routes
require('./routes')(app);

var server = app.listen(port, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log('Example app listening at http://%s:%s', host, port);
});<|endoftext|>


<commit_before>'use babel';
'use strict';

const React = require('react');
const ReactDOM = require('react-dom');

class Token extends React.Component {
  render() {
    let color;
    if (this.props.value > -1) {
      color = [
        'rgb(167, 0, 50)',
        'rgb(33, 130, 200)',
        'rgb(242, 203, 0)',
        'rgb(67, 177, 0)',
        'rgb(32, 32, 32)',
        'rgb(191, 18, 136)',
      ][this.props.value];
    } else {
      color = 'gray';
    }
    return <div className={`${this.props.classNamePrefix}token ${this.props.isHighlighted ? 'highlighted' : ''} `} style={{
      backgroundColor: color
    }} onClick={this.props.onClick}/>
  }
}

class Row extends React.Component {
  render() {
    const { tokens, highlightToken, classNamePrefix } = this.props;
    return <div className={`${classNamePrefix}row`}>{tokens.map((token, i) => {
      return <Token key={i} classNamePrefix={classNamePrefix} isHighlighted={token === highlightToken} value={token} onClick={() => this.props.onClick ? this.props.onClick(token, i) : ''} />
    })}
;
  }
}

(function () {
  const height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
  document.body.style.height = `${height - 4}px`;

  var tokens = [0,1,2,3,4,5];
  var secret = pickRandomTokens(tokens, 4, false);
  var numberOfAttempts = 0;
  var attempts = Array.apply(null, {length: 6}).map(() => newAttempt());
  var currentAttempt = newAttempt();
  var currentToken = 0;

  render();

  function render() {
    ReactDOM.render(

        {attempts.map((attempt, i) => {
          return

            <Row classNamePrefix="attempt__" tokens={attempt} />

              {hits(secret, attempt)}

              {nearbyHits(secret, attempt)}

        })}

          <Row classNamePrefix="current__" tokens={currentAttempt} onClick={(token, i) => {
            currentAttempt[i] = currentToken;
            render();
          }} />
          <button className="current__solve" disabled={!isValidAttempt(currentAttempt)} onClick={() => {
            if (isValidAttempt(currentAttempt)) {
              if (hits(secret, currentAttempt) == 4) {
                if (typeof(localStorage) !== "undefined") {
                  let wins = parseInt(localStorage.getItem('wins'), 10) || 0;
                  wins++;
                  localStorage.setItem('wins', wins);
                  alert(`You won the ${wins} time!`);
                  window.location.reload();
                } else {
                  alert('You won! Congratulations!');
                }
              }
              attempts.push(currentAttempt);
              attempts.shift();
              currentAttempt = currentAttempt.slice(0);
              numberOfAttempts++;
              render();
            }
          }}>Solve</button>

        <Row classNamePrefix="source__" tokens={tokens} highlightToken={currentToken} onClick={(token, i) => {
          currentToken = token;
          render();
        }} />

,
      document.getElementsByTagName('main')[0]
    );
  }
})();

function newAttempt() {
  return [-1, -1, -1, -1]
}

function isValidAttempt(attempt) {
  return attempt.indexOf(-1) === -1;
}

function pickRandomTokens(_tokens, numberOfTokens, allowDuplicates) {
  var tokens = _tokens.slice(0);
  var pickedTokens = [];
  for (var i = 0; i < numberOfTokens; i++) {
    let token;
    const random = Math.round(Math.random() * (tokens.length - 1));
    if (allowDuplicates) {
      token = random;
    } else {
      token = tokens.splice(random, 1)[0];
    }
    pickedTokens.push(token);
  }
  return pickedTokens;
}

function hits(secret, attempt) {
  var score = 0;
  secret.forEach(function (token, i) {
    if (attempt.indexOf(token) > -1 && attempt[i] === token) {
      score++;
    }
  });
  return score;
}

function nearbyHits(secret, _attempt) {
  var attempt = _attempt.slice(0);
  var score = 0;
  secret.forEach(function (token, i) {
    var j = attempt.indexOf(token);
    if (j > -1) {
      attempt.splice(j, 1);
      score++;
    }
  });
  return score - hits(secret, _attempt);
}
<commit_msg>Refactor App<commit_after>'use babel';
'use strict';

const React = require('react');
const ReactDOM = require('react-dom');

class Token extends React.Component {
  render() {
    let color;
    if (this.props.value > -1) {
      color = [
        'rgb(167, 0, 50)',
        'rgb(33, 130, 200)',
        'rgb(242, 203, 0)',
        'rgb(67, 177, 0)',
        'rgb(32, 32, 32)',
        'rgb(191, 18, 136)',
      ][this.props.value];
    } else {
      color = 'gray';
    }
    return <div className={`${this.props.classNamePrefix}token ${this.props.isHighlighted ? 'highlighted' : ''} `} style={{
      backgroundColor: color
    }} onClick={this.props.onClick}/>
  }
}

class Row extends React.Component {
  render() {
    const { tokens, highlightToken, classNamePrefix } = this.props;
    return <div className={`${classNamePrefix}row`}>{tokens.map((token, i) => {
      return <Token key={i} classNamePrefix={classNamePrefix} isHighlighted={token === highlightToken} value={token} onClick={() => this.props.onClick ? this.props.onClick(token, i) : ''} />
    })}
;
  }
}

class App extends React.Component {
  render() {
    const {tokens, secret, numberOfAttempts, attempts, currentAttempt, currentToken} = this.props;
    const {changeCurrentAttempt, changeCurrentToken, solve} = this.props;
    return

      {attempts.map((attempt, i) => {
        return

          <Row classNamePrefix="attempt__" tokens={attempt} />

            {hits(secret, attempt)}

            {nearbyHits(secret, attempt)}

      })}

        <Row classNamePrefix="current__" tokens={currentAttempt} onClick={changeCurrentAttempt} />
        <button className="current__solve" disabled={!isValidAttempt(currentAttempt)} onClick={solve}>Solve</button>

      <Row classNamePrefix="source__" tokens={tokens} highlightToken={currentToken} onClick={changeCurrentToken} />

;
  }
}

(function () {
  const height = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
  document.body.style.height = `${height - 4}px`;

  const tokens = [0,1,2,3,4,5];

  const props = {
    tokens: tokens,
    secret: pickRandomTokens(tokens, 4, false),
    numberOfAttempts: 0,
    attempts: Array.apply(null, {length: 6}).map(() => newAttempt()),
    currentAttempt: newAttempt(),
    currentToken: 0,
    changeCurrentAttempt: (token, i) => {
      props.currentAttempt[i] = props.currentToken;
      render();
    },
    changeCurrentToken: (token, i) => {
      props.currentToken = token;
      render();
    },
    solve: () => {
      if (isValidAttempt(props.currentAttempt)) {
        if (hits(props.secret, props.currentAttempt) == 4) {
          if (typeof(localStorage) !== "undefined") {
            let wins = parseInt(localStorage.getItem('wins'), 10) || 0;
            wins++;
            localStorage.setItem('wins', wins);
            alert(`You won the ${wins} time!`);
            window.location.reload();
          } else {
            alert('You won! Congratulations!');
          }
        }
        props.attempts.push(props.currentAttempt);
        props.attempts.shift();
        props.currentAttempt = props.currentAttempt.slice(0);
        props.numberOfAttempts++;
        render();
      }
    }
  };

  render();

  function render() {
    ReactDOM.render(
      <App {...props} />,
      document.getElementsByTagName('main')[0]
    );
  }
})();

function newAttempt() {
  return [-1, -1, -1, -1]
}

function isValidAttempt(attempt) {
  return attempt.indexOf(-1) === -1;
}

function pickRandomTokens(_tokens, numberOfTokens, allowDuplicates) {
  var tokens = _tokens.slice(0);
  var pickedTokens = [];
  for (var i = 0; i < numberOfTokens; i++) {
    let token;
    const random = Math.round(Math.random() * (tokens.length - 1));
    if (allowDuplicates) {
      token = random;
    } else {
      token = tokens.splice(random, 1)[0];
    }
    pickedTokens.push(token);
  }
  return pickedTokens;
}

function hits(secret, attempt) {
  var score = 0;
  secret.forEach(function (token, i) {
    if (attempt.indexOf(token) > -1 && attempt[i] === token) {
      score++;
    }
  });
  return score;
}

function nearbyHits(secret, _attempt) {
  var attempt = _attempt.slice(0);
  var score = 0;
  secret.forEach(function (token, i) {
    var j = attempt.indexOf(token);
    if (j > -1) {
      attempt.splice(j, 1);
      score++;
    }
  });
  return score - hits(secret, _attempt);
}
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');

var AngularComponentGenerator = module.exports = function AngularComponentGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });
  });

  this.invoke('karma:app', {
    options: {
      coffee: true,
      travis: true,
      'skip-install': this.options['skip-install'],
      components: [
        'angular/angular.js',
        'angular-resource/angular-resource.js',
        'angular-cookies/angular-cookies.js',
        'angular-sanitize/angular-sanitize.js',
        'angular-route/angular-route.js',
        'angular-mocks/angular-mocks.js'
      ]
    }
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(AngularComponentGenerator, yeoman.generators.Base);

AngularComponentGenerator.prototype.app = function app() {
  this.mkdir('app');
  this.mkdir('app/scripts');
  this.copy('scripts/directive.coffee', 'app/scripts/directive.coffee');
};

AngularComponentGenerator.prototype.test = function test() {
  this.mkdir('test');
  this.mkdir('test/spec');
  this.copy('test/directive.coffee', 'test/spec/directive.coffee');
};

AngularComponentGenerator.prototype.packageFiles = function packageFiles() {
  this.copy('_package.json', 'package.json');
  this.copy('_bower.json', 'bower.json');
  this.copy('Gruntfile.js', 'Gruntfile.js');
};

AngularComponentGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
  this.copy('test/jshintrc', 'test/.jshintrc');
};<commit_msg>ask questions, limit to only directive right now<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var spawn = require('child_process').spawn;

var AngularComponentGenerator = module.exports = function AngularComponentGenerator(args, options, config) {
  yeoman.generators.Base.apply(this, arguments);

  this.on('end', function () {
    this.installDependencies({ skipInstall: options['skip-install'] });

    this.invoke('karma:app', {
      options: {
        coffee: true,
        travis: true,
        'skip-install': this.options['skip-install'],
        components: [
          'angular/angular.js',
          'angular-resource/angular-resource.js',
          'angular-cookies/angular-cookies.js',
          'angular-sanitize/angular-sanitize.js',
          'angular-route/angular-route.js',
          'angular-mocks/angular-mocks.js'
        ]
      }
    });
  });

  this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json')));
};

util.inherits(AngularComponentGenerator, yeoman.generators.Base);

AngularComponentGenerator.prototype.askForType = function askForType() {
  var cb = this.async();

  this.prompt([{
    type: 'input',
    name: 'name',
    message: 'What is the name of your component?'
  },{
    type: 'list',
    name: 'type',
    message: 'What type of component would you like to create?',
    choices: ['directive'],
    default: 'directive'
  }], function (props) {
    this.env.options.name = props.name;
    this.env.options.type = props.type;

    cb();
  }.bind(this));
};

AngularComponentGenerator.prototype.app = function app() {
  this.mkdir('app');
  this.mkdir('app/scripts');
};

AngularComponentGenerator.prototype.test = function test() {
  this.mkdir('test');
  this.mkdir('test/spec');
};

AngularComponentGenerator.prototype.component = function component() {
  if (this.env.options.type === 'directive') {
    this.copy('scripts/directive.coffee', 'app/scripts/' + this.env.options.name + '.coffee');
    this.copy('test/directive.coffee',    'test/spec/' + this.env.options.name + '.coffee');
  }
};

AngularComponentGenerator.prototype.packageFiles = function packageFiles() {
  this.copy('_package.json', 'package.json');
  this.copy('_bower.json', 'bower.json');
  this.copy('Gruntfile.js', 'Gruntfile.js');
};

AngularComponentGenerator.prototype.projectfiles = function projectfiles() {
  this.copy('editorconfig', '.editorconfig');
  this.copy('jshintrc', '.jshintrc');
  this.copy('test/jshintrc', 'test/.jshintrc');
};<|endoftext|>


<commit_before>var path = require('path');
var express = require('express');
var logfmt = require('logfmt');
var api = require('./api');
var site = require('./site');

var app = express();
var port = process.env.PORT || 8000;

app.use(express.favicon());
app.configure('production', function() {
  app.use(logfmt.requestLogger());
});
app.configure('development', function() {
  app.use(express.logger('dev'));
});
app.use(express.compress());
app.use('/api', api);
app.use(site);
app.use(express.errorHandler());

app.listen(port, function() {
  console.log('Listening on ' + port);
});<commit_msg>Remove unnecessary dependencies<commit_after>var express = require('express');
var api = require('./api');
var site = require('./site');

var app = express();
var port = process.env.PORT || 8000;

app.use(express.favicon());
app.configure('production', function() {
  app.use(require('logfmt').requestLogger());
});
app.configure('development', function() {
  app.use(express.logger('dev'));
});
app.use(express.compress());
app.use('/api', api);
app.use(site);
app.use(express.errorHandler());

app.listen(port, function() {
  console.log('Listening on ' + port);
});<|endoftext|>


<commit_before>'use strict';
/* eslint no-inline-comments: 0 */

const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const ipc = electron.ipcMain;
const autoUpdater = electron.autoUpdater;

const Config = require('electron-config');
const fs = require('fs');
const path = require('path');
const spawn = require('child_process').spawn;
const robot = require('robotjs');
const logger = require('./logger')();

const Woopra = require('woopra');
const woopra = new Woopra('ControlCast.tv', {});
const simpleflake = require('simpleflakes');

// Squirrel Auto Update Handlers

const target = path.basename(process.execPath);
function runCommand(args, callback) {
  const updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe');
  logger.debug('Spawning `%s` with args `%s`', updateExe, args);
  spawn(updateExe, args, { detached: true }).on('close', callback);
}

function handleStartupEvent() {
  if (process.platform !== 'win32') {
    return false;
  }
  const squirrelCommand = process.argv[1];
  switch (squirrelCommand) {
    case '--squirrel-install':
    case '--squirrel-updated':
      runCommand([`--createShortcut=${target}`, '--shortcut-locations=Desktop,StartMenu'], () => {
        app.quit();
      });
      return true;
    case '--squirrel-uninstall':
      runCommand([`--removeShortcut=${target}`, '--shortcut-locations=Desktop,StartMenu'], () => {
        app.quit();
      });
      return true;
    case '--squirrel-obsolete':
      app.quit();
      return true;
    default:
      return false;
  }
}

if (handleStartupEvent()) {
  return;
}

// Force Single Instance

const shouldQuit = app.makeSingleInstance(() => {
  // Restore and focus window if instance exists on load
  if (mainWindow) {
    if (mainWindow.isMinimized()) mainWindow.restore();
    mainWindow.focus();
  }
});

// Application is already running
if (shouldQuit) {
  app.quit();
  return;
}

// Application Init

let mainWindow = null; // Main application window
let portWindow = null; // Config load error window
let forceQuit = null; // Bool to force quit app from tray

app.setAppUserModelId('com.squirrel.ControlCast.ControlCast');
app.setPath('userData', path.join(process.env.APPDATA, 'ControlCast'));

global.app_version = require('../package.json').version; // Store app version for in app displays
global.release_url = require('../package.json').releaseUrl; // Store releaseUrl for update queries

robot.setKeyboardDelay(50); // Set delay for each keypress for OBS

const configVersion = 5;
const config = new Config({
  defaults: {
    app: {
      version: configVersion,
      id: simpleflake.simpleflake().toString(),
      pos: {
        x: null,
        y: null,
      },
      close_to_tray: false,
      auto_start: false,
      start_minimized: false,
      clr: {
        enabled: false,
        port: 3000,
      },
    },
    keys: {},
  },
});

updateOldConfig();
updateNewConfig();
woopra.identify(config.get('app.id')).push();

app.on('window-all-closed', () => { // Quit when all windows are closed.
  if (process.platform !== 'darwin') app.quit();
});

app.on('ready', () => { // Application has finished loading
  createMainWindow(); // Show Main Window
});

// Main Application Window

function createMainWindow() { // Loads main application window
  mainWindow = new BrowserWindow({ // Main window options
    x: config.get('app.pos.x'),
    y: config.get('app.pos.y'),
    width: 900,
    height: 760,
    resizable: false,
    icon: path.join(__dirname, 'images/icon.ico'),
    title: `ControlCast - ${global.app_version}`,
    show: false,
  });

  mainWindow.on('closed', () => { // Destroy window object on close
    mainWindow = null;
  });

  mainWindow.on('close', (e) => { // App is about to close
    if (config.get('app.close_to_tray') && !forceQuit) { // Minimize on close if Close To Tray and not force quit
      mainWindow.setSkipTaskbar(true); // Hide Taskbar Icon
      mainWindow.minimize(); // Minimize main window
      e.preventDefault(); // Cancel close process
      return;
    }
    if (mainWindow) mainWindow.webContents.send('all_dark'); // Tell the launchpad to turn off all lights on close
    const pos = mainWindow.getPosition(); // Save last position of the window for next time the app is run
    // Only save if position changed
    if (config.get('app.pos.x') !== pos[0] || config.get('app.pos.y') !== pos[1]) {
      config.set('app.pos', { x: pos[0], y: pos[1] });
    }
  });

  mainWindow.setMenu(null); // Disable the default app menu
  mainWindow.loadURL(path.join('file://', __dirname, '/index.html')); // Display the main window html

  mainWindow.on('ready-to-show', () => {
    if (config.get('app.start_minimized')) {
      if (config.get('app.close_to_tray')) mainWindow.setSkipTaskbar(true);
      mainWindow.minimize();
    } else {
      mainWindow.show();
    }
  });
}

// Port Window

function createPortWindow() { // Window to tell us what port the application is running on
  const pos = mainWindow.getPosition(); // Get main window position
  const size = mainWindow.getSize(); // Get main window size
  const x = Math.floor(((size[0] - 320) / 2) + pos[0]); // Determine x pos to center port window
  const y = Math.floor(((size[1] - 180) / 2) + pos[1]); // Determine y pos to center port window

  portWindow = new BrowserWindow({
    x,
    y,
    width: 320,
    height: 180,
    resizable: false,
    icon: path.join(__dirname, 'images/icon.ico'),
  });

  portWindow.on('closed', () => { // Destroy window object on close
    portWindow = null;
  });

  portWindow.setMenu(null); // Disable the default menu
  portWindow.loadURL(path.join('file://', __dirname, '/port.html')); // Display the port window html
}

// IPC Messages

ipc.on('windows_auto_start', (e, enabled) => {
  config.set('app.auto_start', enabled);
  if (enabled) {
    runCommand([`--createShortcut=${target}`, '--shortcut-locations=Startup'], () => {
      // Do Nothing
    });
  } else {
    runCommand([`--removeShortcut=${target}`, '--shortcut-locations=Startup'], () => {
      // Do Nothing
    });
  }
});

ipc.on('force_quit', () => {
  forceQuit = true; // Quit selected from tray menu, force close the app
  app.quit();
});

ipc.on('quit_and_install', () => {
  forceQuit = true;
  autoUpdater.quitAndInstall();
});

ipc.on('robot_key', (e, data) => {
  try {
    robot.keyToggle(data.key, data.action);
  } catch (err) {
    logger.error(`robot error, key: ${data.key}`, err);
  }
});

ipc.on('change_port', () => {
  createPortWindow();
});

ipc.on('set_port', (e, data) => {
  if (config.get('app.clr.port') === data) return; // Only save and reset if changed
  config.set('app.clr.port', data); // Set option and save
  if (mainWindow) mainWindow.webContents.send('port_changed'); // Restarts the CLR browser on new port
});

// Config / Settings Changes

function updateOldConfig() {
  const oldConfigPath = path.join(process.cwd(), '../config.json');
  if (!fs.existsSync(oldConfigPath)) return;
  let oldConfig;
  try {
    oldConfig = require(oldConfigPath);
  } catch (e) {
    logger.error('Error loading old config file to transfer', e);
    return;
  }
  while (config.get('app.version') > oldConfig.app.version) {
    switch (oldConfig.app.version) {
      case 2:
        oldConfig.app.id = simpleflake.simpleflake().toString();
        oldConfig.app.version = 3;
        break;
      case 3:
        for (const key in oldConfig.keys) {
          if (oldConfig.keys.hasOwnProperty(key)) {
            oldConfig.keys[key].hotkey.string = oldConfig.keys[key].hotkey.string.replace('CTRL', 'L-CTRL')
              .replace('SHIFT', 'L-SHIFT')
              .replace('ALT', 'L-ALT');
          }
        }
        oldConfig.app.version = 4;
        break;
      case 4:
        oldConfig.app.start_minimized = false;
        oldConfig.app.version = 5;
        break;
      default:
      // Do Nothing
    }
  }
  config.set(oldConfig);
  fs.unlink(oldConfigPath, err => {
    if (err) logger.error('Error removing old config file', err);
  });
}

function updateNewConfig() {
  while (config.get('app.version') < configVersion) {
    switch (config.get('app.version')) {
      case 5:
        break;
      default:
      // Do Nothing
    }
  }
}
<commit_msg>add api path to existing key configs<commit_after>'use strict';
/* eslint no-inline-comments: 0 */

const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const ipc = electron.ipcMain;
const autoUpdater = electron.autoUpdater;

const Config = require('electron-config');
const fs = require('fs');
const path = require('path');
const spawn = require('child_process').spawn;
const robot = require('robotjs');
const logger = require('./logger')();

const Woopra = require('woopra');
const woopra = new Woopra('ControlCast.tv', {});
const simpleflake = require('simpleflakes');

// Squirrel Auto Update Handlers

const target = path.basename(process.execPath);
function runCommand(args, callback) {
  const updateExe = path.resolve(path.dirname(process.execPath), '..', 'Update.exe');
  logger.debug('Spawning `%s` with args `%s`', updateExe, args);
  spawn(updateExe, args, { detached: true }).on('close', callback);
}

function handleStartupEvent() {
  if (process.platform !== 'win32') {
    return false;
  }
  const squirrelCommand = process.argv[1];
  switch (squirrelCommand) {
    case '--squirrel-install':
    case '--squirrel-updated':
      runCommand([`--createShortcut=${target}`, '--shortcut-locations=Desktop,StartMenu'], () => {
        app.quit();
      });
      return true;
    case '--squirrel-uninstall':
      runCommand([`--removeShortcut=${target}`, '--shortcut-locations=Desktop,StartMenu'], () => {
        app.quit();
      });
      return true;
    case '--squirrel-obsolete':
      app.quit();
      return true;
    default:
      return false;
  }
}

if (handleStartupEvent()) {
  return;
}

// Force Single Instance

const shouldQuit = app.makeSingleInstance(() => {
  // Restore and focus window if instance exists on load
  if (mainWindow) {
    if (mainWindow.isMinimized()) mainWindow.restore();
    mainWindow.focus();
  }
});

// Application is already running
if (shouldQuit) {
  app.quit();
  return;
}

// Application Init

let mainWindow = null; // Main application window
let portWindow = null; // Config load error window
let forceQuit = null; // Bool to force quit app from tray

app.setAppUserModelId('com.squirrel.ControlCast.ControlCast');
app.setPath('userData', path.join(process.env.APPDATA, 'ControlCast'));

global.app_version = require('../package.json').version; // Store app version for in app displays
global.release_url = require('../package.json').releaseUrl; // Store releaseUrl for update queries

robot.setKeyboardDelay(50); // Set delay for each keypress for OBS

const configVersion = 6;
const config = new Config({
  defaults: {
    app: {
      version: configVersion,
      id: simpleflake.simpleflake().toString(),
      pos: {
        x: null,
        y: null,
      },
      close_to_tray: false,
      auto_start: false,
      start_minimized: false,
      clr: {
        enabled: false,
        port: 3000,
      },
    },
    keys: {},
  },
});

const oldConfigPath = path.join(process.cwd(), './config.json');

updateOldConfig();
fs.exists(oldConfigPath, exists => {
  if (exists) {
    fs.unlink(oldConfigPath, err => {
      if (err) logger.error('Error removing old config file', err);
    });
  }
});
updateNewConfig();
woopra.identify(config.get('app.id')).push();

app.on('window-all-closed', () => { // Quit when all windows are closed.
  if (process.platform !== 'darwin') app.quit();
});

app.on('ready', () => { // Application has finished loading
  createMainWindow(); // Show Main Window
});

// Main Application Window

function createMainWindow() { // Loads main application window
  mainWindow = new BrowserWindow({ // Main window options
    x: config.get('app.pos.x'),
    y: config.get('app.pos.y'),
    width: 900,
    height: 760,
    resizable: false,
    icon: path.join(__dirname, 'images/icon.ico'),
    title: `ControlCast - ${global.app_version}`,
    show: false,
  });

  mainWindow.on('closed', () => { // Destroy window object on close
    mainWindow = null;
  });

  mainWindow.on('close', (e) => { // App is about to close
    if (config.get('app.close_to_tray') && !forceQuit) { // Minimize on close if Close To Tray and not force quit
      mainWindow.setSkipTaskbar(true); // Hide Taskbar Icon
      mainWindow.minimize(); // Minimize main window
      e.preventDefault(); // Cancel close process
      return;
    }
    if (mainWindow) mainWindow.webContents.send('all_dark'); // Tell the launchpad to turn off all lights on close
    const pos = mainWindow.getPosition(); // Save last position of the window for next time the app is run
    // Only save if position changed
    if (config.get('app.pos.x') !== pos[0] || config.get('app.pos.y') !== pos[1]) {
      config.set('app.pos', { x: pos[0], y: pos[1] });
    }
  });

  mainWindow.setMenu(null); // Disable the default app menu
  mainWindow.loadURL(path.join('file://', __dirname, '/index.html')); // Display the main window html

  mainWindow.on('ready-to-show', () => {
    if (config.get('app.start_minimized')) {
      if (config.get('app.close_to_tray')) mainWindow.setSkipTaskbar(true);
      mainWindow.minimize();
    } else {
      mainWindow.show();
    }
  });
}

// Port Window

function createPortWindow() { // Window to tell us what port the application is running on
  const pos = mainWindow.getPosition(); // Get main window position
  const size = mainWindow.getSize(); // Get main window size
  const x = Math.floor(((size[0] - 320) / 2) + pos[0]); // Determine x pos to center port window
  const y = Math.floor(((size[1] - 180) / 2) + pos[1]); // Determine y pos to center port window

  portWindow = new BrowserWindow({
    x,
    y,
    width: 320,
    height: 180,
    resizable: false,
    icon: path.join(__dirname, 'images/icon.ico'),
  });

  portWindow.on('closed', () => { // Destroy window object on close
    portWindow = null;
  });

  portWindow.setMenu(null); // Disable the default menu
  portWindow.loadURL(path.join('file://', __dirname, '/port.html')); // Display the port window html
}

// IPC Messages

ipc.on('windows_auto_start', (e, enabled) => {
  config.set('app.auto_start', enabled);
  if (enabled) {
    runCommand([`--createShortcut=${target}`, '--shortcut-locations=Startup'], () => {
      // Do Nothing
    });
  } else {
    runCommand([`--removeShortcut=${target}`, '--shortcut-locations=Startup'], () => {
      // Do Nothing
    });
  }
});

ipc.on('force_quit', () => {
  forceQuit = true; // Quit selected from tray menu, force close the app
  app.quit();
});

ipc.on('quit_and_install', () => {
  forceQuit = true;
  autoUpdater.quitAndInstall();
});

ipc.on('robot_key', (e, data) => {
  try {
    robot.keyToggle(data.key, data.action);
  } catch (err) {
    logger.error(`robot error, key: ${data.key}`, err);
  }
});

ipc.on('change_port', () => {
  createPortWindow();
});

ipc.on('set_port', (e, data) => {
  if (config.get('app.clr.port') === data) return; // Only save and reset if changed
  config.set('app.clr.port', data); // Set option and save
  if (mainWindow) mainWindow.webContents.send('port_changed'); // Restarts the CLR browser on new port
});

// Config / Settings Changes

function updateOldConfig() {
  if (!fs.existsSync(oldConfigPath)) return;
  let oldConfig;
  try {
    oldConfig = require(oldConfigPath);
  } catch (e) {
    logger.error('Error loading old config file to transfer', e);
    return;
  }
  while (config.get('app.version') > oldConfig.app.version) {
    switch (oldConfig.app.version) {
      case 2:
        oldConfig.app.id = simpleflake.simpleflake().toString();
        oldConfig.app.version = 3;
        break;
      case 3:
        for (const key in oldConfig.keys) {
          if (oldConfig.keys.hasOwnProperty(key)) {
            oldConfig.keys[key].hotkey.string = oldConfig.keys[key].hotkey.string.replace('CTRL', 'L-CTRL')
              .replace('SHIFT', 'L-SHIFT')
              .replace('ALT', 'L-ALT');
          }
        }
        oldConfig.app.version = 4;
        break;
      case 4:
        oldConfig.app.start_minimized = false;
        oldConfig.app.version = 5;
        break;
      default:
      // Do Nothing
    }
  }
  config.set(oldConfig);
}

function updateNewConfig() {
  while (config.get('app.version') < configVersion) {
    const keys = config.get('keys');
    switch (config.get('app.version')) {
      case 5:
        for (const key in keys) {
          if (keys.hasOwnProperty(key)) {
            keys[key].api = {
              path: '',
            };
          }
        }
        config.set('keys', keys);
        config.set('app.version', 6);
        break;
      default:
      // Do Nothing
    }
  }
}
<|endoftext|>


<commit_before>var newrelic;
if (process.env.NEW_RELIC_ENABLED) {
  newrelic = require('newrelic');
}
else {
  newrelic = {
    getBrowserTimingHeader: function () {
      return "<!-- New Relic RUM disabled -->";
    }
  };
}

const config = require('./lib/config');
const nunjucks = require('nunjucks');
const express = require('express');
const path = require('path');
const middleware = require('./middleware');
const views = require('./views');
const api = require('./api');
const persona = require('express-persona-observer');
const http = require('http');

var app = express();

var env = new nunjucks.Environment(new nunjucks.FileSystemLoader([path.join(__dirname, './templates'),
                                                                  path.join(__dirname, './static/templates')]),
                                   { autoescape: true, watch: true });

env.express(app);

app.locals.newrelic = newrelic;

require('express-monkey-patch')(app);

var staticDir = path.join(__dirname, '/static');
var staticRoot = '/static';

app.use(function (req, res, next) {
  res.locals.static = function static (staticPath) {
    return path.join(app.mountPoint, staticRoot, staticPath);
  };
  next();
});

if (config('ENABLE_GELF_LOGS')) {
  var messina = require('messina');
  logger = messina('badgekit-' + config('NODE_ENV', 'development'));
  logger.init();
  app.use(logger.middleware());
}
else {
  app.use(express.logger());
}

app.use(express.compress());
app.use(express.bodyParser());
app.use(middleware.session());
app.use(middleware.csrf({ whitelist: [ '/persona/login', '/persona/logout', '/persona/verify', '/api/user'] }));
app.use(middleware.sass(staticDir, staticRoot));
app.use(middleware.addCsrfToken);
app.use(middleware.debug);
app.use(staticRoot, express.static(staticDir));

persona.express(app, { audience: config('PERSONA_AUDIENCE'),
                       redirects: { notLoggedIn: '/', notLoggedOut: '/directory' },
                       selectors: { login: '.js-login', logout: '.js-logout' },
                       middleware: middleware.clearSession });

var secureRouteHandlers = [persona.ensureLoggedIn(), middleware.verifyPermission(config('ACCESS_LIST', []), 'sorry.html')];
var secureApiHandlers = [middleware.verifyApiRequest()];

app.get('/', 'home', [persona.ensureLoggedOut()], views.home);
app.get('/directory', 'directory', secureRouteHandlers, views.directory.home);
app.get('/directory/addBadge', 'directory.addBadge', secureRouteHandlers, views.directory.addBadge);
app.get('/directory/useTemplate', 'directory.useTemplate', secureRouteHandlers, views.directory.useTemplate);

app.get('/badge/:badgeId', 'badge', secureRouteHandlers, views.badge.home);
app.get('/badge/:badgeId/edit', 'badge.edit', secureRouteHandlers, views.badge.edit);
app.del('/badge/:badgeId/delete', 'badge.delete', secureRouteHandlers, views.badge.del);
app.post('/badge/:badgeId/edit', 'badge.save', secureRouteHandlers, views.badge.save);
app.post('/badge/:badgeId/archive', 'badge.archive', secureRouteHandlers, views.badge.archive);
app.post('/badge/:badgeId/publish', 'badge.publish', secureRouteHandlers, views.badge.publish);
app.post('/badge/:badgeId/copy', 'badge.copy', secureRouteHandlers, views.badge.copy);
app.get('/badge/:badgeId/design', 'studio.edit', secureRouteHandlers, views.studio.edit);
app.post('/badge/:badgeId/design', 'studio.save', secureRouteHandlers, views.studio.save);

app.get('/badge/:badgeId/issueByEmail', 'badge.issueByEmail', secureRouteHandlers, views.badge.renderIssueByEmail);
app.post('/badge/:badgeId/issueByEmail', 'badge.issueByEmail', secureRouteHandlers, views.badge.issueByEmail);

app.get('/badge/:badgeId/issueByClaimCode', 'badge.issueByClaimCode', secureRouteHandlers, views.badge.renderIssueByClaimCode);
app.post('/badge/:badgeId/issueByClaimCode', 'badge.issueByClaimCode', secureRouteHandlers, views.badge.issueByClaimCode);

app.get('/images/badge/:badgeId', 'badge.image', views.badge.image);

app.get('/settings', 'settings', secureRouteHandlers, views.settings.home);
app.get('/settings/systems', 'settings.systems', secureRouteHandlers, views.settings.systems);
app.get('/settings/issuers', 'settings.issuers', secureRouteHandlers, views.settings.issuers);
app.get('/settings/programs', 'settings.programs', secureRouteHandlers, views.settings.programs);
app.get('/settings/context', 'settings.context', secureRouteHandlers, views.settings.context);
app.post('/settings/context', 'settings.setContext', secureRouteHandlers, views.settings.setContext);
app.get('/settings/context/data', 'settings.contextData', secureRouteHandlers, views.settings.contextData);
app.get('/settings/users', 'settings.users', secureRouteHandlers, views.settings.users);
app.post('/settings/users', 'settings.editUser', secureRouteHandlers, views.settings.editUser);
app.del('/settings/users', 'settings.deleteUser', secureRouteHandlers, views.settings.deleteUser);

app.get('/studio/backgrounds', 'studio.backgrounds', secureRouteHandlers, views.badge.getBackgrounds);
app.get('/studio/texts', 'studio.texts', secureRouteHandlers, views.badge.getTexts);
app.get('/studio/icons', 'studio.icons', secureRouteHandlers, views.badge.getIcons);
app.get('/studio/colors', 'studio.colors', secureRouteHandlers, views.badge.getColors);

app.get('/applications', 'applications', secureRouteHandlers, views.applications.home);
app.get('/applications/:badgeId', 'applications.forBadge', secureRouteHandlers, views.applications.forBadge);
app.get('/applications/:badgeId/:applicationId', 'application', secureRouteHandlers, views.applications.application);
app.post('/applications/:badgeId/:applicationId', 'application.submit', secureRouteHandlers, views.applications.submitReview);

app.get('/help', 'help', views.help.home);
app.get('/about', 'about', views.about.home);

app.get('/system/:systemId/badge/:badgeId/criteria', 'badge.criteria', views.badge.criteria);

app.get('/share', 'share', secureRouteHandlers, views.share.home);
app.post('/share', 'share.subscribe', secureRouteHandlers, views.share.subscribe);
app.get('/share/:shareId', 'share.template', views.share.template);

app.post('/api/user', 'api.user.add', secureApiHandlers, api.user.addUser);
app.del('/api/user', 'api.user.delete', secureApiHandlers, api.user.deleteUser);

app.get('*', function (req, res, next) {
  var error = new Error('Page not found');

  Object.defineProperties(error, {
    name: {value: 'ResourceNotFoundError'},
    code: {value: 404},
  });

  next(error);
});

app.all('*', function (req, res, next) {
  var error = new Error('Method not allowed');

  Object.defineProperties(error, {
    name: {value: 'MethodNotAllowedError'},
    code: {value: 405},
  });

  next(error);
});

app.use(function (err, req, res, next) {
  const status = err.code || 500;
  const msg = http.STATUS_CODES[status] || err.message;

  res.status(status).render('error.html', {
    message: msg,
    error: err
  });
});

if (!module.parent) {
  const port = config('PORT', 3000);

  app.listen(port, function(err) {
    if (err) {
      throw err;
    }

    console.log('Listening on port ' + port + '.');
  });
} else {
  module.exports = http.createServer(app);
}
<commit_msg>Adding default for ENABLE_GELF_LOGS<commit_after>var newrelic;
if (process.env.NEW_RELIC_ENABLED) {
  newrelic = require('newrelic');
}
else {
  newrelic = {
    getBrowserTimingHeader: function () {
      return "<!-- New Relic RUM disabled -->";
    }
  };
}

const config = require('./lib/config');
const nunjucks = require('nunjucks');
const express = require('express');
const path = require('path');
const middleware = require('./middleware');
const views = require('./views');
const api = require('./api');
const persona = require('express-persona-observer');
const http = require('http');

var app = express();

var env = new nunjucks.Environment(new nunjucks.FileSystemLoader([path.join(__dirname, './templates'),
                                                                  path.join(__dirname, './static/templates')]),
                                   { autoescape: true, watch: true });

env.express(app);

app.locals.newrelic = newrelic;

require('express-monkey-patch')(app);

var staticDir = path.join(__dirname, '/static');
var staticRoot = '/static';

app.use(function (req, res, next) {
  res.locals.static = function static (staticPath) {
    return path.join(app.mountPoint, staticRoot, staticPath);
  };
  next();
});

if (config('ENABLE_GELF_LOGS', false)) {
  var messina = require('messina');
  logger = messina('badgekit-' + config('NODE_ENV', 'development'));
  logger.init();
  app.use(logger.middleware());
}
else {
  app.use(express.logger());
}

app.use(express.compress());
app.use(express.bodyParser());
app.use(middleware.session());
app.use(middleware.csrf({ whitelist: [ '/persona/login', '/persona/logout', '/persona/verify', '/api/user'] }));
app.use(middleware.sass(staticDir, staticRoot));
app.use(middleware.addCsrfToken);
app.use(middleware.debug);
app.use(staticRoot, express.static(staticDir));

persona.express(app, { audience: config('PERSONA_AUDIENCE'),
                       redirects: { notLoggedIn: '/', notLoggedOut: '/directory' },
                       selectors: { login: '.js-login', logout: '.js-logout' },
                       middleware: middleware.clearSession });

var secureRouteHandlers = [persona.ensureLoggedIn(), middleware.verifyPermission(config('ACCESS_LIST', []), 'sorry.html')];
var secureApiHandlers = [middleware.verifyApiRequest()];

app.get('/', 'home', [persona.ensureLoggedOut()], views.home);
app.get('/directory', 'directory', secureRouteHandlers, views.directory.home);
app.get('/directory/addBadge', 'directory.addBadge', secureRouteHandlers, views.directory.addBadge);
app.get('/directory/useTemplate', 'directory.useTemplate', secureRouteHandlers, views.directory.useTemplate);

app.get('/badge/:badgeId', 'badge', secureRouteHandlers, views.badge.home);
app.get('/badge/:badgeId/edit', 'badge.edit', secureRouteHandlers, views.badge.edit);
app.del('/badge/:badgeId/delete', 'badge.delete', secureRouteHandlers, views.badge.del);
app.post('/badge/:badgeId/edit', 'badge.save', secureRouteHandlers, views.badge.save);
app.post('/badge/:badgeId/archive', 'badge.archive', secureRouteHandlers, views.badge.archive);
app.post('/badge/:badgeId/publish', 'badge.publish', secureRouteHandlers, views.badge.publish);
app.post('/badge/:badgeId/copy', 'badge.copy', secureRouteHandlers, views.badge.copy);
app.get('/badge/:badgeId/design', 'studio.edit', secureRouteHandlers, views.studio.edit);
app.post('/badge/:badgeId/design', 'studio.save', secureRouteHandlers, views.studio.save);

app.get('/badge/:badgeId/issueByEmail', 'badge.issueByEmail', secureRouteHandlers, views.badge.renderIssueByEmail);
app.post('/badge/:badgeId/issueByEmail', 'badge.issueByEmail', secureRouteHandlers, views.badge.issueByEmail);

app.get('/badge/:badgeId/issueByClaimCode', 'badge.issueByClaimCode', secureRouteHandlers, views.badge.renderIssueByClaimCode);
app.post('/badge/:badgeId/issueByClaimCode', 'badge.issueByClaimCode', secureRouteHandlers, views.badge.issueByClaimCode);

app.get('/images/badge/:badgeId', 'badge.image', views.badge.image);

app.get('/settings', 'settings', secureRouteHandlers, views.settings.home);
app.get('/settings/systems', 'settings.systems', secureRouteHandlers, views.settings.systems);
app.get('/settings/issuers', 'settings.issuers', secureRouteHandlers, views.settings.issuers);
app.get('/settings/programs', 'settings.programs', secureRouteHandlers, views.settings.programs);
app.get('/settings/context', 'settings.context', secureRouteHandlers, views.settings.context);
app.post('/settings/context', 'settings.setContext', secureRouteHandlers, views.settings.setContext);
app.get('/settings/context/data', 'settings.contextData', secureRouteHandlers, views.settings.contextData);
app.get('/settings/users', 'settings.users', secureRouteHandlers, views.settings.users);
app.post('/settings/users', 'settings.editUser', secureRouteHandlers, views.settings.editUser);
app.del('/settings/users', 'settings.deleteUser', secureRouteHandlers, views.settings.deleteUser);

app.get('/studio/backgrounds', 'studio.backgrounds', secureRouteHandlers, views.badge.getBackgrounds);
app.get('/studio/texts', 'studio.texts', secureRouteHandlers, views.badge.getTexts);
app.get('/studio/icons', 'studio.icons', secureRouteHandlers, views.badge.getIcons);
app.get('/studio/colors', 'studio.colors', secureRouteHandlers, views.badge.getColors);

app.get('/applications', 'applications', secureRouteHandlers, views.applications.home);
app.get('/applications/:badgeId', 'applications.forBadge', secureRouteHandlers, views.applications.forBadge);
app.get('/applications/:badgeId/:applicationId', 'application', secureRouteHandlers, views.applications.application);
app.post('/applications/:badgeId/:applicationId', 'application.submit', secureRouteHandlers, views.applications.submitReview);

app.get('/help', 'help', views.help.home);
app.get('/about', 'about', views.about.home);

app.get('/system/:systemId/badge/:badgeId/criteria', 'badge.criteria', views.badge.criteria);

app.get('/share', 'share', secureRouteHandlers, views.share.home);
app.post('/share', 'share.subscribe', secureRouteHandlers, views.share.subscribe);
app.get('/share/:shareId', 'share.template', views.share.template);

app.post('/api/user', 'api.user.add', secureApiHandlers, api.user.addUser);
app.del('/api/user', 'api.user.delete', secureApiHandlers, api.user.deleteUser);

app.get('*', function (req, res, next) {
  var error = new Error('Page not found');

  Object.defineProperties(error, {
    name: {value: 'ResourceNotFoundError'},
    code: {value: 404},
  });

  next(error);
});

app.all('*', function (req, res, next) {
  var error = new Error('Method not allowed');

  Object.defineProperties(error, {
    name: {value: 'MethodNotAllowedError'},
    code: {value: 405},
  });

  next(error);
});

app.use(function (err, req, res, next) {
  const status = err.code || 500;
  const msg = http.STATUS_CODES[status] || err.message;

  res.status(status).render('error.html', {
    message: msg,
    error: err
  });
});

if (!module.parent) {
  const port = config('PORT', 3000);

  app.listen(port, function(err) {
    if (err) {
      throw err;
    }

    console.log('Listening on port ' + port + '.');
  });
} else {
  module.exports = http.createServer(app);
}
<|endoftext|>


<commit_before>'use strict';

import React, { Component } from 'react';
import {
	AppRegistry,
	NavigatorIOS,
	BackAndroid,
	StatusBar,
	AppState
} from 'react-native';
import TimerMixin from 'react-timer-mixin';

// SETUP / UTIL / NAV
var AppSettings = 			require('./AppSettings'),
	general = 				require('./util/general'),
	logger = 				require('./util/logger'),

// VIEWS
	Home = 					require('./views/Home'),
	ShuttleStop = 			require('./views/ShuttleStop'),
	SurfReport = 			require('./views/weather/SurfReport'),
	DiningList = 			require('./views/DiningList'),
	DiningDetail = 			require('./views/DiningDetail'),
	TopStoriesDetail = 		require('./views/topStories/TopStoriesDetail'),
	EventDetail = 			require('./views/events/EventDetail'),
	WebWrapper = 			require('./views/WebWrapper');

import WelcomeWeekView from './views/welcomeWeek/WelcomeWeekView';
import EventListView from './views/events/EventListView';
import TopStoriesListView from './views/topStories/TopStoriesListView';

// NAV
import NavigationBarWithRouteMapper from './views/NavigationBarWithRouteMapper';

// Code Push
import codePush from 'react-native-code-push';
let codePushOptions = { checkFrequency: codePush.CheckFrequency.ON_APP_RESUME, installMode: codePush.InstallMode.ON_NEXT_RESUME };

/**
 * Timeout that allows for pause and resume
**/
function Timer(callback, delay) {
	var timerId, start, remaining = delay;

	this.pause = function() {
		clearTimeout(timerId);
		remaining -= new Date() - start;
	};

	this.resume = function() {
		start = new Date();
		clearTimeout(timerId);
		timerId = setTimeout(callback, remaining);
	};

	this.do = function() {
		clearTimeout(timerId);
		callback();
	}

	this.getID = function() {
		return timerId;
	};

	this.resume();
}
var timers = {};

var nowucsandiego = React.createClass({

	mixins: [TimerMixin],

	getInitialState() {
		return {
			inHome: true,
		};
	},

	componentWillMount() {
		AppState.addEventListener('change', this.handleAppStateChange);
	},

	componentDidMount() {
		if (general.platformAndroid() || AppSettings.NAVIGATOR_ENABLED) {
			// Listen to route focus changes
			// Should be a better way to do this...
			this.refs.navRef.refs.navRef.navigationContext.addListener('willfocus', (event) => {
				const route = event.data.route;

				// Make sure renders/card refreshes are only happening when in home route
				if (route.id === "Home") {
					this.setState({inHome: true});
					this._resumeTimeout();
				} else {
					this.setState({inHome: false});
					this._pauseTimeout();
				}
			});

			// Listen to back button on Android
			BackAndroid.addEventListener('hardwareBackPress', () => {
				var route = this.refs.navRef.refs.navRef.getCurrentRoutes().pop();

				if(route.id === "Home") {
					BackAndroid.exitApp();
					return false;

				} else {
					this.refs.navRef.refs.navRef.pop();
					return true;
				}
			});
		}
		else {
			// Pause/resume timeouts
			this.refs.navRef.navigationContext.addListener('didfocus', (event) => {
				const route = event.data.route;

				// Make sure renders/card refreshes are only happening when in home route
				if (route.id === undefined) { //undefined is foxusing "Home"... weird I know
					this.setState({inHome: true});
					this._resumeTimeout();
				} else {
					this.setState({inHome: false});
					this._pauseTimeout();
				}
			});

			// Make all back buttons use text "Back"
			this.refs.navRef.navigationContext.addListener('willfocus', (event) => {
				const route = event.data.route;
				route.backButtonTitle = "Back";
			});
		}
	},

	componentWillUnmount() {
		AppState.removeEventListener('change', this.handleAppStateChange);
		this._pauseTimeout();
	},

	newTimeout: function(key, callback, delay) {
		timers[key] = (new Timer(callback, delay));
	},

	_pauseTimeout: function() {
		for (var key in timers) {
			timers[key].pause();
		}
	},

	_resumeTimeout: function() {
		for (var key in timers) {
			timers[key].resume();
		}
	},

	doTimeout: function() {
		for (var key in timers) {
			timers[key].do();
		}
	},

	render: function() {

		if (general.platformIOS()) {
			StatusBar.setBarStyle('light-content');
		}

		if (general.platformAndroid() || AppSettings.NAVIGATOR_ENABLED) {
			return (
				<NavigationBarWithRouteMapper
					ref="navRef"
					route={{id: 'Home', name: 'Home', title: 'now@ucsandiego'}}
					renderScene={this.renderScene}
				/>
			);
		} else {
			return (
				<NavigatorIOS
					initialRoute={{
						component: Home,
						title: AppSettings.APP_NAME,
						passProps: {
							isSimulator: this.props.isSimulator,
							new_timeout: this.newTimeout,
							do_timeout: this.doTimeout
						},
						backButtonTitle: "Back"
					}}
					style={{flex: 1}}
					tintColor='#FFFFFF'
					barTintColor='#006C92'
					titleTextColor='#FFFFFF'
					navigationBarHidden={false}
					translucent={true}
					ref="navRef"
				/>
			);
		}
	},

	renderScene: function(route, navigator, index, navState) {

		switch (route.id) {
			case 'Home': 				return (<Home route={route} navigator={navigator} new_timeout={this.newTimeout} do_timeout={this.doTimeout}/>);
			case 'ShuttleStop': 		return (<ShuttleStop route={route} navigator={navigator} />);
			case 'SurfReport': 			return (<SurfReport route={route} navigator={navigator} />);
			case 'DiningList': 			return (<DiningList route={route} navigator={navigator} />);
			case 'DiningDetail': 		return (<DiningDetail route={route} navigator={navigator} />);
			case 'TopStoriesDetail': 	return (<TopStoriesDetail route={route} navigator={navigator} />);
			case 'EventDetail': 		return (<EventDetail route={route} navigator={navigator} />);
			case 'WebWrapper': 			return (<WebWrapper route={route} navigator={navigator} />);
			case 'WelcomeWeekView': 	return (<WelcomeWeekView route={route} navigator={navigator} />);
			case 'EventListView': 		return (<EventListView route={route} navigator={navigator} />);
			case 'TopStoriesListView': 	return (<TopStoriesListView route={route} navigator={navigator} />);
			default: 					return (<Home route={route} navigator={navigator} new_timeout={this.newTimeout} do_timeout={this.doTimeout}/>);
		}
	},

	handleAppStateChange(currentAppState) {
		if (currentAppState === 'active') {
			if(this.state.inHome) {
				this._resumeTimeout();
			}
		}
		else if(currentAppState === 'background') {
			this._pauseTimeout();
		}
	},
});

nowucsandiego = codePush(codePushOptions)(nowucsandiego);
module.exports = nowucsandiego;<commit_msg>Pulling codepush for further testing<commit_after>'use strict';

import React, { Component } from 'react';
import {
	AppRegistry,
	NavigatorIOS,
	BackAndroid,
	StatusBar,
	AppState
} from 'react-native';
import TimerMixin from 'react-timer-mixin';

// SETUP / UTIL / NAV
var AppSettings = 			require('./AppSettings'),
	general = 				require('./util/general'),
	logger = 				require('./util/logger'),

// VIEWS
	Home = 					require('./views/Home'),
	ShuttleStop = 			require('./views/ShuttleStop'),
	SurfReport = 			require('./views/weather/SurfReport'),
	DiningList = 			require('./views/DiningList'),
	DiningDetail = 			require('./views/DiningDetail'),
	TopStoriesDetail = 		require('./views/topStories/TopStoriesDetail'),
	EventDetail = 			require('./views/events/EventDetail'),
	WebWrapper = 			require('./views/WebWrapper');

import WelcomeWeekView from './views/welcomeWeek/WelcomeWeekView';
import EventListView from './views/events/EventListView';
import TopStoriesListView from './views/topStories/TopStoriesListView';

// NAV
import NavigationBarWithRouteMapper from './views/NavigationBarWithRouteMapper';

/**
 * Timeout that allows for pause and resume
**/
function Timer(callback, delay) {
	var timerId, start, remaining = delay;

	this.pause = function() {
		clearTimeout(timerId);
		remaining -= new Date() - start;
	};

	this.resume = function() {
		start = new Date();
		clearTimeout(timerId);
		timerId = setTimeout(callback, remaining);
	};

	this.do = function() {
		clearTimeout(timerId);
		callback();
	}

	this.getID = function() {
		return timerId;
	};

	this.resume();
}
var timers = {};

var nowucsandiego = React.createClass({

	mixins: [TimerMixin],

	getInitialState() {
		return {
			inHome: true,
		};
	},

	componentWillMount() {
		AppState.addEventListener('change', this.handleAppStateChange);
	},

	componentDidMount() {
		if (general.platformAndroid() || AppSettings.NAVIGATOR_ENABLED) {
			// Listen to route focus changes
			// Should be a better way to do this...
			this.refs.navRef.refs.navRef.navigationContext.addListener('willfocus', (event) => {
				const route = event.data.route;

				// Make sure renders/card refreshes are only happening when in home route
				if (route.id === "Home") {
					this.setState({inHome: true});
					this._resumeTimeout();
				} else {
					this.setState({inHome: false});
					this._pauseTimeout();
				}
			});

			// Listen to back button on Android
			BackAndroid.addEventListener('hardwareBackPress', () => {
				var route = this.refs.navRef.refs.navRef.getCurrentRoutes().pop();

				if(route.id === "Home") {
					BackAndroid.exitApp();
					return false;

				} else {
					this.refs.navRef.refs.navRef.pop();
					return true;
				}
			});
		}
		else {
			// Pause/resume timeouts
			this.refs.navRef.navigationContext.addListener('didfocus', (event) => {
				const route = event.data.route;

				// Make sure renders/card refreshes are only happening when in home route
				if (route.id === undefined) { //undefined is foxusing "Home"... weird I know
					this.setState({inHome: true});
					this._resumeTimeout();
				} else {
					this.setState({inHome: false});
					this._pauseTimeout();
				}
			});

			// Make all back buttons use text "Back"
			this.refs.navRef.navigationContext.addListener('willfocus', (event) => {
				const route = event.data.route;
				route.backButtonTitle = "Back";
			});
		}
	},

	componentWillUnmount() {
		AppState.removeEventListener('change', this.handleAppStateChange);
		this._pauseTimeout();
	},

	newTimeout: function(key, callback, delay) {
		timers[key] = (new Timer(callback, delay));
	},

	_pauseTimeout: function() {
		for (var key in timers) {
			timers[key].pause();
		}
	},

	_resumeTimeout: function() {
		for (var key in timers) {
			timers[key].resume();
		}
	},

	doTimeout: function() {
		for (var key in timers) {
			timers[key].do();
		}
	},

	render: function() {

		if (general.platformIOS()) {
			StatusBar.setBarStyle('light-content');
		}

		if (general.platformAndroid() || AppSettings.NAVIGATOR_ENABLED) {
			return (
				<NavigationBarWithRouteMapper
					ref="navRef"
					route={{id: 'Home', name: 'Home', title: 'now@ucsandiego'}}
					renderScene={this.renderScene}
				/>
			);
		} else {
			return (
				<NavigatorIOS
					initialRoute={{
						component: Home,
						title: AppSettings.APP_NAME,
						passProps: {
							isSimulator: this.props.isSimulator,
							new_timeout: this.newTimeout,
							do_timeout: this.doTimeout
						},
						backButtonTitle: "Back"
					}}
					style={{flex: 1}}
					tintColor='#FFFFFF'
					barTintColor='#006C92'
					titleTextColor='#FFFFFF'
					navigationBarHidden={false}
					translucent={true}
					ref="navRef"
				/>
			);
		}
	},

	renderScene: function(route, navigator, index, navState) {

		switch (route.id) {
			case 'Home': 				return (<Home route={route} navigator={navigator} new_timeout={this.newTimeout} do_timeout={this.doTimeout}/>);
			case 'ShuttleStop': 		return (<ShuttleStop route={route} navigator={navigator} />);
			case 'SurfReport': 			return (<SurfReport route={route} navigator={navigator} />);
			case 'DiningList': 			return (<DiningList route={route} navigator={navigator} />);
			case 'DiningDetail': 		return (<DiningDetail route={route} navigator={navigator} />);
			case 'TopStoriesDetail': 	return (<TopStoriesDetail route={route} navigator={navigator} />);
			case 'EventDetail': 		return (<EventDetail route={route} navigator={navigator} />);
			case 'WebWrapper': 			return (<WebWrapper route={route} navigator={navigator} />);
			case 'WelcomeWeekView': 	return (<WelcomeWeekView route={route} navigator={navigator} />);
			case 'EventListView': 		return (<EventListView route={route} navigator={navigator} />);
			case 'TopStoriesListView': 	return (<TopStoriesListView route={route} navigator={navigator} />);
			default: 					return (<Home route={route} navigator={navigator} new_timeout={this.newTimeout} do_timeout={this.doTimeout}/>);
		}
	},

	handleAppStateChange(currentAppState) {
		if (currentAppState === 'active') {
			if(this.state.inHome) {
				this._resumeTimeout();
			}
		}
		else if(currentAppState === 'background') {
			this._pauseTimeout();
		}
	},
});

module.exports = nowucsandiego;<|endoftext|>


<commit_before>import {getApi} from '../common/oauth';
const remote = require('electron').remote;
const Menu = remote.Menu;
const MenuItem = remote.MenuItem;
const clipboard = require('electron').clipboard;
const Vue = require('vue');
var setting = JSON.parse(localStorage["ulttwiclient"] || '{}');
console.log(setting.tokens);

window.addEventListener('load',()=>{
  Vue.filter('expand_url', function (text, entities){
    entities.urls.forEach((url)=>{
      text = text.replace(url.url, url.display_url);
    });
    if (entities.media) {
      entities.media.forEach((m)=>{
        text = text.replace(m.url, m.display_url);
      });
    }
    return text;
  });
  // context menu on status
  var contextMenuForTweet = Menu.buildFromTemplate([
    {label: "ツイートに返信する", click: ()=>{vm.sendReply(vm.selectedTweet);}},
    {label: "ツイートをふぁぼる", click: ()=>{vm.favoriteTweet(vm.selectedTweet);}},
    {type: 'separator'},
    {label: "ツイートのJSONを取得", click: ()=>{clipboard.writeText(JSON.stringify(vm.selectedTweet));}}
  ]);
  var vm = new Vue({
    el: "#container",
    data: {
      newTweet: {
        text: "",
        in_reply_to_status_id: ""
      },
      selectedTweet: {},
      sendReplyDestTweet: {},
      me: {},
      streaming: false,
      showingImage: false,
      image: {},
      tweets: [],
      notifications: []
    },
    computed: {
      calculateRemainChar: function() {
        return 140 - this.newTweet.text.length;
      }
    },
    methods: {
      sendTweet: function (params) {
        api.post('statuses/update', {
          status: params.text,
          in_reply_to_status_id: params.in_reply_to_status_id
        }, (error, tweet, response)=>{
          if (error) {
            this.createNotification("ツイートの投稿に失敗しました", this.newTweet.text, null, 'fail');
            return console.log('error', error.map((e)=>e.message).join("\n"),  error);
          }
          console.log(tweet, response);
          this.createNotification("ツイートが投稿されました", this.newTweet.text, null, 'tweet');
          this.newTweet.text = '';
          this.newTweet.in_reply_to_status_id = '';
          this.sendReplyDestTweet = {};
        });
      },
      clearReply: function () {
        this.newTweet.text = this.newTweet.text.replace(/@[a-zA-Z0-9_]+/g, '');
        this.newTweet.in_reply_to_status_id = '';
        this.sendReplyDestTweet = {};
      },
      startStreaming: function () {
        console.info("start streaming");
        this.streaming = true;
        api.stream('user', {}, (stream)=>{
          stream.on('data', (data)=>{
            console.log(data);
            if (data.friends) {
              return;
            } else if (data.delete) {
              console.log(data.delete);
              this.deleteTweet(data.delete.status.id_str);
            } else if (data.scrub_geo) {
              // location deletion
            } else if (data.limit) {
              // limit notices
            } else if (data.status_withheld) {
              // withheld content notices (status)
            } else if (data.user_withheld) {
              // withheld content notices (user)
            } else if (data.disconnect) {
              // disconnect messages
            } else if (data.warning) {
              // stall warnings
            } else if (data.event) {
              // catch some event
            } else {
              // status
              this.tweets.push(data);
              if (this.isMentionsForYou(data)) {
                this.createNotification("あなた宛のメンションがあります", data.text, data.user.profile_image_url_https, 'tweet');
              }
            }
          });
          stream.on('favorite', (data)=>{
            if (data.target.screen_name === this.me.screen_name) {
              this.createNotification("あなたのツイートがいいねされました", data.target_object.text, data.target.profile_image_url_https, 'favorite');
            }
          });
          stream.on('unfavorite', (data)=>{
            if (data.target.screen_name === this.me.screen_name) {
              this.createNotification("あなたのツイートがいいね取り消しされました", data.target_object.text, data.target.profile_image_url_https, 'unfavorite');
            }
          });
          stream.on('follow', (data)=>{
            if (data.target.screen_name === this.me.screen_name) {
              this.createNotification(data.source.name + " さんにフォローされました", data.source.description, data.source.profile_image_url_https, 'follow');
            }
          });
          stream.on('list_member_added', (data)=>{
            if (data.target.screen_name === this.me.screen_name) {
              this.createNotification(data.source.name + " さんにリスト "+data.target_object.name+" に追加されました", data.target_object.description, data.source.profile_image_url_https, 'list_member_added');
            }
          });
        });
      },
      favoriteTweet: function (tweet) {
        console.log(tweet.id_str);
        var favorites_url = tweet.favorited ? 'favorites/destroy' : 'favorites/create';
        var favorites_id = tweet.retweeted_status ? tweet.retweeted_status.id_str : tweet.id_str
        api.post(favorites_url, {id: favorites_id}, (error, _tweet, response)=>{
          if (error) {
            this.createNotification("ツイートをいいねできませんでした", tweet.text, null, 'fail');
            return console.log('error', error.map((e)=>e.message).join("\n"),  error);
          }
          console.log(_tweet, response);
          if (tweet.favorited)
            this.createNotification("ツイートをいいね取り消ししました", tweet.text, null, 'unfavorite');
          else
            this.createNotification("ツイートをいいねしました", tweet.text, null, 'favorite');
          tweet.favorited = _tweet.favorited;
          tweet.favotite_count = _tweet.favorite_count;
        });
      },
      showImage: function(url, size) {
        this.image = {url: url, width: size.w, height: size.h};
        this.showingImage = true;
      },
      closeImage: function() {
        this.image = {};
        this.showingImage = false;
      },
      sendReply: function(tweet) {
        console.log(tweet.id_str);
        this.sendReplyDestTweet = tweet;
        this.newTweet.text = "@" + tweet.user.screen_name + " ";
        this.newTweet.in_reply_to_status_id = tweet.id_str;
        this.$els.submit_box.focus();
      },
      hasMedias: function(tweet) {
        return 'extended_entities' in tweet && 'media' in tweet.extended_entities;
      },
      isMentionsForYou: function(tweet) {
        return tweet.text.match('@' + this.me.screen_name) && !tweet.retweeted_status;
      },
      deleteTweet: function(id_str) {
        this.tweets.forEach((t,i) => {
          if (t.id_str === id_str)
            this.tweets.splice(i, 1);
        })
      },
      createNotification: function(title, body, icon, kind) {
        let notification = {title, body, kind};
        this.notifications.push(notification);
        const removeMSecond = 6000;
        window.setTimeout(()=>{
          this.removeNotification(notification);
        }, removeMSecond);
        if (!remote.getCurrentWindow().isFocused()) {
          new Notification(title, {icon: icon, body: body});
        }
      },
      removeNotification: function(notification) {
        this.notifications.forEach((n,i) => {
          if (n === notification)
            this.notifications.splice(i, 1);
        })
      },
      contextMenuOnTweet: function(tweet) {
        this.selectedTweet = tweet;
        contextMenuForTweet.popup(remote.getCurrentWindow());
      }
    }
  });
  if(setting.tokens){
    var api = getApi(setting.tokens);
    api.get('account/verify_credentials', {}, (error, data, response)=>{
      if (error) {
        return console.log('error', error.map((e)=>e.message).join("\n"),  error);
      }
      vm.me = data;
    });
    api.get('statuses/home_timeline', {count: 200}, function(error, tweets, response){
      if (error) {
        console.log('error', error.map((e)=>e.message).join("\n"),  error);
      }
      console.log('tweets',tweets.map((t)=>t.text).join("\n"), tweets);
      tweets.forEach((tweet)=>{
        vm.tweets.push(tweet);
      });
    });
    vm.startStreaming();
  }else{
    console.warn("did not oauth");
  }
});
<commit_msg>@返信を取り消したときの入力欄の文字列置換<commit_after>import {getApi} from '../common/oauth';
const remote = require('electron').remote;
const Menu = remote.Menu;
const MenuItem = remote.MenuItem;
const clipboard = require('electron').clipboard;
const Vue = require('vue');
var setting = JSON.parse(localStorage["ulttwiclient"] || '{}');
console.log(setting.tokens);

window.addEventListener('load',()=>{
  Vue.filter('expand_url', function (text, entities){
    entities.urls.forEach((url)=>{
      text = text.replace(url.url, url.display_url);
    });
    if (entities.media) {
      entities.media.forEach((m)=>{
        text = text.replace(m.url, m.display_url);
      });
    }
    return text;
  });
  // context menu on status
  var contextMenuForTweet = Menu.buildFromTemplate([
    {label: "ツイートに返信する", click: ()=>{vm.sendReply(vm.selectedTweet);}},
    {label: "ツイートをふぁぼる", click: ()=>{vm.favoriteTweet(vm.selectedTweet);}},
    {type: 'separator'},
    {label: "ツイートのJSONを取得", click: ()=>{clipboard.writeText(JSON.stringify(vm.selectedTweet));}}
  ]);
  var vm = new Vue({
    el: "#container",
    data: {
      newTweet: {
        text: "",
        in_reply_to_status_id: ""
      },
      selectedTweet: {},
      sendReplyDestTweet: {},
      me: {},
      streaming: false,
      showingImage: false,
      image: {},
      tweets: [],
      notifications: []
    },
    computed: {
      calculateRemainChar: function() {
        return 140 - this.newTweet.text.length;
      }
    },
    methods: {
      sendTweet: function (params) {
        api.post('statuses/update', {
          status: params.text,
          in_reply_to_status_id: params.in_reply_to_status_id
        }, (error, tweet, response)=>{
          if (error) {
            this.createNotification("ツイートの投稿に失敗しました", this.newTweet.text, null, 'fail');
            return console.log('error', error.map((e)=>e.message).join("\n"),  error);
          }
          console.log(tweet, response);
          this.createNotification("ツイートが投稿されました", this.newTweet.text, null, 'tweet');
          this.newTweet.text = '';
          this.newTweet.in_reply_to_status_id = '';
          this.sendReplyDestTweet = {};
        });
      },
      clearReply: function () {
        this.newTweet.text = this.newTweet.text.replace(/@[a-zA-Z0-9_]+\s*/g, '');
        this.newTweet.in_reply_to_status_id = '';
        this.sendReplyDestTweet = {};
      },
      startStreaming: function () {
        console.info("start streaming");
        this.streaming = true;
        api.stream('user', {}, (stream)=>{
          stream.on('data', (data)=>{
            console.log(data);
            if (data.friends) {
              return;
            } else if (data.delete) {
              console.log(data.delete);
              this.deleteTweet(data.delete.status.id_str);
            } else if (data.scrub_geo) {
              // location deletion
            } else if (data.limit) {
              // limit notices
            } else if (data.status_withheld) {
              // withheld content notices (status)
            } else if (data.user_withheld) {
              // withheld content notices (user)
            } else if (data.disconnect) {
              // disconnect messages
            } else if (data.warning) {
              // stall warnings
            } else if (data.event) {
              // catch some event
            } else {
              // status
              this.tweets.push(data);
              if (this.isMentionsForYou(data)) {
                this.createNotification("あなた宛のメンションがあります", data.text, data.user.profile_image_url_https, 'tweet');
              }
            }
          });
          stream.on('favorite', (data)=>{
            if (data.target.screen_name === this.me.screen_name) {
              this.createNotification("あなたのツイートがいいねされました", data.target_object.text, data.target.profile_image_url_https, 'favorite');
            }
          });
          stream.on('unfavorite', (data)=>{
            if (data.target.screen_name === this.me.screen_name) {
              this.createNotification("あなたのツイートがいいね取り消しされました", data.target_object.text, data.target.profile_image_url_https, 'unfavorite');
            }
          });
          stream.on('follow', (data)=>{
            if (data.target.screen_name === this.me.screen_name) {
              this.createNotification(data.source.name + " さんにフォローされました", data.source.description, data.source.profile_image_url_https, 'follow');
            }
          });
          stream.on('list_member_added', (data)=>{
            if (data.target.screen_name === this.me.screen_name) {
              this.createNotification(data.source.name + " さんにリスト "+data.target_object.name+" に追加されました", data.target_object.description, data.source.profile_image_url_https, 'list_member_added');
            }
          });
        });
      },
      favoriteTweet: function (tweet) {
        console.log(tweet.id_str);
        var favorites_url = tweet.favorited ? 'favorites/destroy' : 'favorites/create';
        var favorites_id = tweet.retweeted_status ? tweet.retweeted_status.id_str : tweet.id_str
        api.post(favorites_url, {id: favorites_id}, (error, _tweet, response)=>{
          if (error) {
            this.createNotification("ツイートをいいねできませんでした", tweet.text, null, 'fail');
            return console.log('error', error.map((e)=>e.message).join("\n"),  error);
          }
          console.log(_tweet, response);
          if (tweet.favorited)
            this.createNotification("ツイートをいいね取り消ししました", tweet.text, null, 'unfavorite');
          else
            this.createNotification("ツイートをいいねしました", tweet.text, null, 'favorite');
          tweet.favorited = _tweet.favorited;
          tweet.favotite_count = _tweet.favorite_count;
        });
      },
      showImage: function(url, size) {
        this.image = {url: url, width: size.w, height: size.h};
        this.showingImage = true;
      },
      closeImage: function() {
        this.image = {};
        this.showingImage = false;
      },
      sendReply: function(tweet) {
        console.log(tweet.id_str);
        this.sendReplyDestTweet = tweet;
        this.newTweet.text = "@" + tweet.user.screen_name + " ";
        this.newTweet.in_reply_to_status_id = tweet.id_str;
        this.$els.submit_box.focus();
      },
      hasMedias: function(tweet) {
        return 'extended_entities' in tweet && 'media' in tweet.extended_entities;
      },
      isMentionsForYou: function(tweet) {
        return tweet.text.match('@' + this.me.screen_name) && !tweet.retweeted_status;
      },
      deleteTweet: function(id_str) {
        this.tweets.forEach((t,i) => {
          if (t.id_str === id_str)
            this.tweets.splice(i, 1);
        })
      },
      createNotification: function(title, body, icon, kind) {
        let notification = {title, body, kind};
        this.notifications.push(notification);
        const removeMSecond = 6000;
        window.setTimeout(()=>{
          this.removeNotification(notification);
        }, removeMSecond);
        if (!remote.getCurrentWindow().isFocused()) {
          new Notification(title, {icon: icon, body: body});
        }
      },
      removeNotification: function(notification) {
        this.notifications.forEach((n,i) => {
          if (n === notification)
            this.notifications.splice(i, 1);
        })
      },
      contextMenuOnTweet: function(tweet) {
        this.selectedTweet = tweet;
        contextMenuForTweet.popup(remote.getCurrentWindow());
      }
    }
  });
  if(setting.tokens){
    var api = getApi(setting.tokens);
    api.get('account/verify_credentials', {}, (error, data, response)=>{
      if (error) {
        return console.log('error', error.map((e)=>e.message).join("\n"),  error);
      }
      vm.me = data;
    });
    api.get('statuses/home_timeline', {count: 200}, function(error, tweets, response){
      if (error) {
        console.log('error', error.map((e)=>e.message).join("\n"),  error);
      }
      console.log('tweets',tweets.map((t)=>t.text).join("\n"), tweets);
      tweets.forEach((tweet)=>{
        vm.tweets.push(tweet);
      });
    });
    vm.startStreaming();
  }else{
    console.warn("did not oauth");
  }
});
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var manager = require('./model');
var encode32 = require("encode32");

router.get('/', function (req, res) {
	var number = Math.floor((Math.random() * 1064000000000) + 36000000000);
	var code = encode32.encode(number);
	var decoded = encode32.decode(code);
	res.render('index', {title: 'Express', number:number, code: code, decoded: decoded});

});

router.get('/spam', function (req, res) {
	var params = {};
	for (i = 0; i < 10000; i++) {
	manager.createOne(params);
	}
	res.send(200, "OK");
});

module.exports = router;
<commit_msg>Made changes to accomodate 6chars from 8 chars<commit_after>var express = require('express');
var router = express.Router();
var manager = require('./model');
var encode32 = require("encode32");

router.get('/', function (req, res) {
	var number = Math.floor((Math.random() * 1064000000) + 36000000);
	var code = encode32.encode(number);
	var decoded = encode32.decode(code);
	res.render('index', {title: 'Express', number:number, code: code, decoded: decoded});

});

router.get('/spam', function (req, res) {
	var params = {};
	for (i = 0; i < 10000; i++) {
	manager.createOne(params);
	}
	res.send(200, "OK");
});

module.exports = router;
<|endoftext|>


<commit_before>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');

var PlenarioGenerator = yeoman.generators.Base.extend({
  initializing: function () {
    this.pkg = require('../package.json');
  },

  prompting: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the groundbreaking Plenario generator!'
    ));

    var prompts = [{
      type: 'confirm',
      name: 'someOption',
      message: 'Would you like to enable this option?',
      default: true
    }];

    this.prompt(prompts, function (props) {
      this.someOption = props.someOption;

      done();
    }.bind(this));
  },

  writing: {
    app: function () {
      this.dest.mkdir('app');
      this.dest.mkdir('app/templates');

      this.src.copy('_package.json', 'package.json');
      this.src.copy('_bower.json', 'bower.json');
    },

    projectfiles: function () {
      this.src.copy('editorconfig', '.editorconfig');
      this.src.copy('jshintrc', '.jshintrc');
    }
  },

  end: function () {
    this.installDependencies();
  }
});

module.exports = PlenarioGenerator;
<commit_msg>make an index page<commit_after>'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');

var PlenarioGenerator = yeoman.generators.Base.extend({
  initializing: function () {
    this.pkg = require('../package.json');
  },

  prompting: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay(
      'Welcome to the groundbreaking Plenario generator!'
    ));

    var prompts = [{
      type: 'confirm',
      name: 'someOption',
      message: 'Would you like to enable this option?',
      default: true
    }];

    this.prompt(prompts, function (props) {
      this.someOption = props.someOption;

      done();
    }.bind(this));
  },

  writing: {
    app: function () {
      this.dest.mkdir('app');
      this.dest.mkdir('app/templates');

      this.src.copy('_package.json', 'package.json');
      this.src.copy('_bower.json', 'bower.json');
      this.src.copy('_index.html', 'app/index.html');
    },

    projectfiles: function () {
      this.src.copy('editorconfig', '.editorconfig');
      this.src.copy('jshintrc', '.jshintrc');
    }
  },

  end: function () {
    this.installDependencies();
  }
});

module.exports = PlenarioGenerator;
<|endoftext|>