<commit_before>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import path from 'path';
import webpack from 'webpack';
import AssetsPlugin from 'assets-webpack-plugin';
import nodeExternals from 'webpack-node-externals';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';

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

const isDebug = !process.argv.includes('--release');
const isVerbose = process.argv.includes('--verbose');
const isAnalyze =
  process.argv.includes('--analyze') || process.argv.includes('--analyse');

const reScript = /\.jsx?$/;
const reStyle = /\.(css|less|scss|sss)$/;
const reImage = /\.(bmp|gif|jpe?g|png|svg)$/;
const staticAssetName = isDebug
  ? '[path][name].[ext]?[hash:8]'
  : '[hash:8].[ext]';

//
// Common configuration chunk to be used for both
// client-side (client.js) and server-side (server.js) bundles
// -----------------------------------------------------------------------------

const config = {
  context: path.resolve(__dirname, '..'),

  output: {
    path: path.resolve(__dirname, '../build/public/assets'),
    publicPath: '/assets/',
    pathinfo: isVerbose,
    filename: isDebug ? '[name].js' : '[name].[chunkhash:8].js',
    chunkFilename: isDebug
      ? '[name].chunk.js'
      : '[name].[chunkhash:8].chunk.js',
    devtoolModuleFilenameTemplate: info =>
      path.resolve(info.absoluteResourcePath),
  },

  resolve: {
    // Allow absolute paths in imports, e.g. import Button from 'components/Button'
    // Keep in sync with .flowconfig and .eslintrc
    modules: ['node_modules', 'src'],
  },

  module: {
    // Make missing exports an error instead of warning
    strictExportPresence: true,

    rules: [
      // Rules for JS / JSX
      {
        test: reScript,
        include: path.resolve(__dirname, '../src'),
        loader: 'babel-loader',
        options: {
          // https://github.com/babel/babel-loader#options
          cacheDirectory: isDebug,

          // https://babeljs.io/docs/usage/options/
          babelrc: false,
          presets: [
            // A Babel preset that can automatically determine the Babel plugins and polyfills
            // https://github.com/babel/babel-preset-env
            [
              'env',
              {
                targets: {
                  browsers: pkg.browserslist,
                  uglify: true,
                },
                modules: false,
                useBuiltIns: false,
                debug: false,
              },
            ],
            // Experimental ECMAScript proposals
            // https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-
            'stage-2',
            // JSX, Flow
            // https://github.com/babel/babel/tree/master/packages/babel-preset-react
            'react',
            // Optimize React code for the production build
            // https://github.com/thejameskyle/babel-react-optimize
            ...(isDebug ? [] : ['react-optimize']),
          ],
          plugins: [
            // Adds component stack to warning messages
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-jsx-source
            ...(isDebug ? ['transform-react-jsx-source'] : []),
            // Adds __self attribute to JSX which React will use for some warnings
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-jsx-self
            ...(isDebug ? ['transform-react-jsx-self'] : []),
          ],
        },
      },

      // Rules for Style Sheets
      {
        test: reStyle,
        rules: [
          // Convert CSS into JS module
          {
            issuer: { not: [reStyle] },
            use: 'isomorphic-style-loader',
          },

          // Process external/third-party styles
          {
            exclude: path.resolve(__dirname, '../src'),
            loader: 'css-loader',
            options: {
              sourceMap: isDebug,
              minimize: !isDebug,
              discardComments: { removeAll: true },
            },
          },

          // Process internal/project styles (from src folder)
          {
            include: path.resolve(__dirname, '../src'),
            loader: 'css-loader',
            options: {
              // CSS Loader https://github.com/webpack/css-loader
              importLoaders: 1,
              sourceMap: isDebug,
              // CSS Modules https://github.com/css-modules/css-modules
              modules: true,
              localIdentName: isDebug
                ? '[name]-[local]-[hash:base64:5]'
                : '[hash:base64:5]',
              // CSS Nano http://cssnano.co/options/
              minimize: !isDebug,
              discardComments: { removeAll: true },
            },
          },

          // Apply PostCSS plugins including autoprefixer
          {
            loader: 'postcss-loader',
            options: {
              config: {
                path: './tools/postcss.config.js',
              },
            },
          },

          // Compile Less to CSS
          // https://github.com/webpack-contrib/less-loader
          // Install dependencies before uncommenting: yarn add --dev less-loader less
          // {
          //   test: /\.less$/,
          //   loader: 'less-loader',
          // },

          // Compile Sass to CSS
          // https://github.com/webpack-contrib/sass-loader
          // Install dependencies before uncommenting: yarn add --dev sass-loader node-sass
          // {
          //   test: /\.scss$/,
          //   loader: 'sass-loader',
          // },
        ],
      },

      // Rules for images
      {
        test: reImage,
        oneOf: [
          // Inline lightweight images into CSS
          {
            issuer: reStyle,
            oneOf: [
              // Inline lightweight SVGs as UTF-8 encoded DataUrl string
              {
                test: /\.svg$/,
                loader: 'svg-url-loader',
                options: {
                  name: staticAssetName,
                  limit: 4096, // 4kb
                },
              },

              // Inline lightweight images as Base64 encoded DataUrl string
              {
                loader: 'url-loader',
                options: {
                  name: staticAssetName,
                  limit: 4096, // 4kb
                },
              },
            ],
          },

          // Or return public URL to image resource
          {
            loader: 'file-loader',
            options: {
              name: staticAssetName,
            },
          },
        ],
      },

      // Convert plain text into JS module
      {
        test: /\.txt$/,
        loader: 'raw-loader',
      },

      // Convert Markdown into HTML
      {
        test: /\.md$/,
        loader: path.resolve(__dirname, './lib/markdown-loader.js'),
      },

      // Return public URL for all assets unless explicitly excluded
      // DO NOT FORGET to update `exclude` list when you adding a new loader
      {
        exclude: [reScript, reStyle, reImage, /\.json$/, /\.txt$/, /\.md$/],
        loader: 'file-loader',
        options: {
          name: staticAssetName,
        },
      },

      // Exclude dev modules from production build
      ...(isDebug
        ? []
        : [
            {
              test: path.resolve(
                __dirname,
                '../node_modules/react-deep-force-update/lib/index.js',
              ),
              loader: 'null-loader',
            },
          ]),
    ],
  },

  // Don't attempt to continue if there are any errors.
  bail: !isDebug,

  cache: isDebug,

  // Specify what bundle information gets displayed
  // https://webpack.js.org/configuration/stats/
  stats: {
    cached: isVerbose,
    cachedAssets: isVerbose,
    chunks: isVerbose,
    chunkModules: isVerbose,
    colors: true,
    hash: isVerbose,
    modules: isVerbose,
    reasons: isDebug,
    timings: true,
    version: isVerbose,
  },

  // Choose a developer tool to enhance debugging
  // https://webpack.js.org/configuration/devtool/#devtool
  devtool: isDebug ? 'cheap-module-inline-source-map' : 'source-map',
};

//
// Configuration for the client-side bundle (client.js)
// -----------------------------------------------------------------------------

const clientConfig = {
  ...config,

  name: 'client',
  target: 'web',

  entry: {
    client: ['babel-polyfill', './src/client.js'],
  },

  plugins: [
    // Define free variables
    // https://webpack.js.org/plugins/define-plugin/
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
      'process.env.BROWSER': true,
      __DEV__: isDebug,
    }),

    // Emit a file with assets paths
    // https://github.com/sporto/assets-webpack-plugin#options
    new AssetsPlugin({
      path: path.resolve(__dirname, '../build'),
      filename: 'assets.json',
      prettyPrint: true,
    }),
    // Move modules that occur in multiple entry chunks to a new entry chunk (the commons chunk).
    // https://webpack.js.org/plugins/commons-chunk-plugin/
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: module => /node_modules/.test(module.resource),
    }),

    ...(isDebug
      ? []
      : [
          // Decrease script evaluation time
          // https://github.com/webpack/webpack/blob/master/examples/scope-hoisting/README.md
          new webpack.optimize.ModuleConcatenationPlugin(),
          // Minimize all JavaScript output of chunks
          // https://github.com/mishoo/UglifyJS2#compressor-options
          new webpack.optimize.UglifyJsPlugin({
            include: /\.js$/,
            sourceMap: false,
            beautify: false,
            compress: {
              screw_ie8: true, // React doesn't support IE8
              warnings: isVerbose,
              unused: true,
              dead_code: true,
            },
            mangle: {
              screw_ie8: true,
            },
            output: {
              comments: false,
              screw_ie8: true,
            },
          }),
        ]),

    // Webpack Bundle Analyzer
    // https://github.com/th0r/webpack-bundle-analyzer
    ...(isAnalyze ? [new BundleAnalyzerPlugin()] : []),
  ],

  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  // https://webpack.js.org/configuration/node/
  // https://github.com/webpack/node-libs-browser/tree/master/mock
  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
  },
};

//
// Configuration for the server-side bundle (server.js)
// -----------------------------------------------------------------------------

const serverConfig = {
  ...config,

  name: 'server',
  target: 'node',

  entry: {
    server: ['babel-polyfill', './src/server.js'],
  },

  output: {
    ...config.output,
    path: path.resolve(__dirname, '../build'),
    filename: '[name].js',
    chunkFilename: 'chunks/[name].js',
    libraryTarget: 'commonjs2',
  },

  // Webpack mutates resolve object, so clone it to avoid issues
  // https://github.com/webpack/webpack/issues/4817
  resolve: {
    ...config.resolve,
  },

  module: {
    ...config.module,

    rules: overrideRules(config.module.rules, rule => {
      // Override babel-preset-env configuration for Node.js
      if (rule.loader === 'babel-loader') {
        return {
          ...rule,
          options: {
            ...rule.options,
            presets: rule.options.presets.map(preset =>
              preset[0] !== 'env'
                ? preset
                : [
                    'env',
                    {
                      targets: {
                        node: pkg.engines.node.match(/(\d+\.?)+/)[0],
                      },
                      modules: false,
                      useBuiltIns: false,
                      debug: false,
                    },
                  ],
            ),
          },
        };
      }

      // Override paths to static assets
      if (
        rule.loader === 'file-loader' ||
        rule.loader === 'url-loader' ||
        rule.loader === 'svg-url-loader'
      ) {
        return {
          ...rule,
          options: {
            ...rule.options,
            name: `public/assets/${rule.options.name}`,
            publicPath: url => url.replace(/^public/, ''),
          },
        };
      }

      return rule;
    }),
  },

  externals: [
    './assets.json',
    nodeExternals({
      whitelist: [reStyle, reImage],
    }),
  ],

  plugins: [
    // Define free variables
    // https://webpack.js.org/plugins/define-plugin/
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
      'process.env.BROWSER': false,
      __DEV__: isDebug,
    }),

    // Adds a banner to the top of each generated chunk
    // https://webpack.js.org/plugins/banner-plugin/
    new webpack.BannerPlugin({
      banner: 'require("source-map-support").install();',
      raw: true,
      entryOnly: false,
    }),
  ],

  // Do not replace node globals with polyfills
  // https://webpack.js.org/configuration/node/
  node: {
    console: false,
    global: false,
    process: false,
    Buffer: false,
    __filename: false,
    __dirname: false,
  },
};

// export default [clientConfig, serverConfig];
export default [clientConfig, serverConfig];
<commit_msg>adding back source map<commit_after>/**
 * React Starter Kit (https://www.reactstarterkit.com/)
 *
 * Copyright © 2014-present Kriasoft, LLC. All rights reserved.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE.txt file in the root directory of this source tree.
 */

import path from 'path';
import webpack from 'webpack';
import AssetsPlugin from 'assets-webpack-plugin';
import nodeExternals from 'webpack-node-externals';
import { BundleAnalyzerPlugin } from 'webpack-bundle-analyzer';

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

const isDebug = !process.argv.includes('--release');
const isVerbose = process.argv.includes('--verbose');
const isAnalyze =
  process.argv.includes('--analyze') || process.argv.includes('--analyse');

const reScript = /\.jsx?$/;
const reStyle = /\.(css|less|scss|sss)$/;
const reImage = /\.(bmp|gif|jpe?g|png|svg)$/;
const staticAssetName = isDebug
  ? '[path][name].[ext]?[hash:8]'
  : '[hash:8].[ext]';

//
// Common configuration chunk to be used for both
// client-side (client.js) and server-side (server.js) bundles
// -----------------------------------------------------------------------------

const config = {
  context: path.resolve(__dirname, '..'),

  output: {
    path: path.resolve(__dirname, '../build/public/assets'),
    publicPath: '/assets/',
    pathinfo: isVerbose,
    filename: isDebug ? '[name].js' : '[name].[chunkhash:8].js',
    chunkFilename: isDebug
      ? '[name].chunk.js'
      : '[name].[chunkhash:8].chunk.js',
    devtoolModuleFilenameTemplate: info =>
      path.resolve(info.absoluteResourcePath),
  },

  resolve: {
    // Allow absolute paths in imports, e.g. import Button from 'components/Button'
    // Keep in sync with .flowconfig and .eslintrc
    modules: ['node_modules', 'src'],
  },

  module: {
    // Make missing exports an error instead of warning
    strictExportPresence: true,

    rules: [
      // Rules for JS / JSX
      {
        test: reScript,
        include: path.resolve(__dirname, '../src'),
        loader: 'babel-loader',
        options: {
          // https://github.com/babel/babel-loader#options
          cacheDirectory: isDebug,

          // https://babeljs.io/docs/usage/options/
          babelrc: false,
          presets: [
            // A Babel preset that can automatically determine the Babel plugins and polyfills
            // https://github.com/babel/babel-preset-env
            [
              'env',
              {
                targets: {
                  browsers: pkg.browserslist,
                  uglify: true,
                },
                modules: false,
                useBuiltIns: false,
                debug: false,
              },
            ],
            // Experimental ECMAScript proposals
            // https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-
            'stage-2',
            // JSX, Flow
            // https://github.com/babel/babel/tree/master/packages/babel-preset-react
            'react',
            // Optimize React code for the production build
            // https://github.com/thejameskyle/babel-react-optimize
            ...(isDebug ? [] : ['react-optimize']),
          ],
          plugins: [
            // Adds component stack to warning messages
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-jsx-source
            ...(isDebug ? ['transform-react-jsx-source'] : []),
            // Adds __self attribute to JSX which React will use for some warnings
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-jsx-self
            ...(isDebug ? ['transform-react-jsx-self'] : []),
          ],
        },
      },

      // Rules for Style Sheets
      {
        test: reStyle,
        rules: [
          // Convert CSS into JS module
          {
            issuer: { not: [reStyle] },
            use: 'isomorphic-style-loader',
          },

          // Process external/third-party styles
          {
            exclude: path.resolve(__dirname, '../src'),
            loader: 'css-loader',
            options: {
              sourceMap: isDebug,
              minimize: !isDebug,
              discardComments: { removeAll: true },
            },
          },

          // Process internal/project styles (from src folder)
          {
            include: path.resolve(__dirname, '../src'),
            loader: 'css-loader',
            options: {
              // CSS Loader https://github.com/webpack/css-loader
              importLoaders: 1,
              sourceMap: isDebug,
              // CSS Modules https://github.com/css-modules/css-modules
              modules: true,
              localIdentName: isDebug
                ? '[name]-[local]-[hash:base64:5]'
                : '[hash:base64:5]',
              // CSS Nano http://cssnano.co/options/
              minimize: !isDebug,
              discardComments: { removeAll: true },
            },
          },

          // Apply PostCSS plugins including autoprefixer
          {
            loader: 'postcss-loader',
            options: {
              config: {
                path: './tools/postcss.config.js',
              },
            },
          },

          // Compile Less to CSS
          // https://github.com/webpack-contrib/less-loader
          // Install dependencies before uncommenting: yarn add --dev less-loader less
          // {
          //   test: /\.less$/,
          //   loader: 'less-loader',
          // },

          // Compile Sass to CSS
          // https://github.com/webpack-contrib/sass-loader
          // Install dependencies before uncommenting: yarn add --dev sass-loader node-sass
          // {
          //   test: /\.scss$/,
          //   loader: 'sass-loader',
          // },
        ],
      },

      // Rules for images
      {
        test: reImage,
        oneOf: [
          // Inline lightweight images into CSS
          {
            issuer: reStyle,
            oneOf: [
              // Inline lightweight SVGs as UTF-8 encoded DataUrl string
              {
                test: /\.svg$/,
                loader: 'svg-url-loader',
                options: {
                  name: staticAssetName,
                  limit: 4096, // 4kb
                },
              },

              // Inline lightweight images as Base64 encoded DataUrl string
              {
                loader: 'url-loader',
                options: {
                  name: staticAssetName,
                  limit: 4096, // 4kb
                },
              },
            ],
          },

          // Or return public URL to image resource
          {
            loader: 'file-loader',
            options: {
              name: staticAssetName,
            },
          },
        ],
      },

      // Convert plain text into JS module
      {
        test: /\.txt$/,
        loader: 'raw-loader',
      },

      // Convert Markdown into HTML
      {
        test: /\.md$/,
        loader: path.resolve(__dirname, './lib/markdown-loader.js'),
      },

      // Return public URL for all assets unless explicitly excluded
      // DO NOT FORGET to update `exclude` list when you adding a new loader
      {
        exclude: [reScript, reStyle, reImage, /\.json$/, /\.txt$/, /\.md$/],
        loader: 'file-loader',
        options: {
          name: staticAssetName,
        },
      },

      // Exclude dev modules from production build
      ...(isDebug
        ? []
        : [
            {
              test: path.resolve(
                __dirname,
                '../node_modules/react-deep-force-update/lib/index.js',
              ),
              loader: 'null-loader',
            },
          ]),
    ],
  },

  // Don't attempt to continue if there are any errors.
  bail: !isDebug,

  cache: isDebug,

  // Specify what bundle information gets displayed
  // https://webpack.js.org/configuration/stats/
  stats: {
    cached: isVerbose,
    cachedAssets: isVerbose,
    chunks: isVerbose,
    chunkModules: isVerbose,
    colors: true,
    hash: isVerbose,
    modules: isVerbose,
    reasons: isDebug,
    timings: true,
    version: isVerbose,
  },

  // Choose a developer tool to enhance debugging
  // https://webpack.js.org/configuration/devtool/#devtool
  devtool: isDebug ? 'cheap-module-inline-source-map' : 'source-map',
};

//
// Configuration for the client-side bundle (client.js)
// -----------------------------------------------------------------------------

const clientConfig = {
  ...config,

  name: 'client',
  target: 'web',

  entry: {
    client: ['babel-polyfill', './src/client.js'],
  },

  plugins: [
    // Define free variables
    // https://webpack.js.org/plugins/define-plugin/
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
      'process.env.BROWSER': true,
      __DEV__: isDebug,
    }),

    // Emit a file with assets paths
    // https://github.com/sporto/assets-webpack-plugin#options
    new AssetsPlugin({
      path: path.resolve(__dirname, '../build'),
      filename: 'assets.json',
      prettyPrint: true,
    }),
    // Move modules that occur in multiple entry chunks to a new entry chunk (the commons chunk).
    // https://webpack.js.org/plugins/commons-chunk-plugin/
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks: module => /node_modules/.test(module.resource),
    }),

    ...(isDebug
      ? []
      : [
          // Decrease script evaluation time
          // https://github.com/webpack/webpack/blob/master/examples/scope-hoisting/README.md
          new webpack.optimize.ModuleConcatenationPlugin(),
          // Minimize all JavaScript output of chunks
          // https://github.com/mishoo/UglifyJS2#compressor-options
          new webpack.optimize.UglifyJsPlugin({
            // include: /\.js$/,
            sourceMap: true,
            // beautify: false,
            compress: {
              screw_ie8: true, // React doesn't support IE8
              warnings: isVerbose,
              unused: true,
              dead_code: true,
            },
            mangle: {
              screw_ie8: true,
            },
            output: {
              comments: false,
              screw_ie8: true,
            },
          }),
        ]),

    // Webpack Bundle Analyzer
    // https://github.com/th0r/webpack-bundle-analyzer
    ...(isAnalyze ? [new BundleAnalyzerPlugin()] : []),
  ],

  // Some libraries import Node modules but don't use them in the browser.
  // Tell Webpack to provide empty mocks for them so importing them works.
  // https://webpack.js.org/configuration/node/
  // https://github.com/webpack/node-libs-browser/tree/master/mock
  node: {
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
  },
};

//
// Configuration for the server-side bundle (server.js)
// -----------------------------------------------------------------------------

const serverConfig = {
  ...config,

  name: 'server',
  target: 'node',

  entry: {
    server: ['babel-polyfill', './src/server.js'],
  },

  output: {
    ...config.output,
    path: path.resolve(__dirname, '../build'),
    filename: '[name].js',
    chunkFilename: 'chunks/[name].js',
    libraryTarget: 'commonjs2',
  },

  // Webpack mutates resolve object, so clone it to avoid issues
  // https://github.com/webpack/webpack/issues/4817
  resolve: {
    ...config.resolve,
  },

  module: {
    ...config.module,

    rules: overrideRules(config.module.rules, rule => {
      // Override babel-preset-env configuration for Node.js
      if (rule.loader === 'babel-loader') {
        return {
          ...rule,
          options: {
            ...rule.options,
            presets: rule.options.presets.map(preset =>
              preset[0] !== 'env'
                ? preset
                : [
                    'env',
                    {
                      targets: {
                        node: pkg.engines.node.match(/(\d+\.?)+/)[0],
                      },
                      modules: false,
                      useBuiltIns: false,
                      debug: false,
                    },
                  ],
            ),
          },
        };
      }

      // Override paths to static assets
      if (
        rule.loader === 'file-loader' ||
        rule.loader === 'url-loader' ||
        rule.loader === 'svg-url-loader'
      ) {
        return {
          ...rule,
          options: {
            ...rule.options,
            name: `public/assets/${rule.options.name}`,
            publicPath: url => url.replace(/^public/, ''),
          },
        };
      }

      return rule;
    }),
  },

  externals: [
    './assets.json',
    nodeExternals({
      whitelist: [reStyle, reImage],
    }),
  ],

  plugins: [
    // Define free variables
    // https://webpack.js.org/plugins/define-plugin/
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': isDebug ? '"development"' : '"production"',
      'process.env.BROWSER': false,
      __DEV__: isDebug,
    }),

    // Adds a banner to the top of each generated chunk
    // https://webpack.js.org/plugins/banner-plugin/
    new webpack.BannerPlugin({
      banner: 'require("source-map-support").install();',
      raw: true,
      entryOnly: false,
    }),
  ],

  // Do not replace node globals with polyfills
  // https://webpack.js.org/configuration/node/
  node: {
    console: false,
    global: false,
    process: false,
    Buffer: false,
    __filename: false,
    __dirname: false,
  },
};

// export default [clientConfig, serverConfig];
export default [clientConfig, serverConfig];
<|endoftext|>


<commit_before>require('dotenv').load();

var express = require('express');
var router = express.Router();
var knex = require('../db/knex');
var db = require('mongodb');
var promise = require('bluebird')

function Batches(){
  return knex('batches');
}

function Users(){
  return knex('users');
}

/* GET batches for dashboard */

router.get('/', function(req, res, next){
  var returnArray = [];
  Batches().where('user_id', req.user.id).select().then(function(batches) {
    return promise.map(batches, function(batch) {
      var batchId = batch.id;
      db.MongoClient.connect(process.env.MONGOLAB_URI, function(err, db){
        var brews = db.collection('brews');
        // console.log(batch);
         return brews.find({
          brew_id:batchId
        }).limit(1).next(function(err, data){
          batch.schedule = data.schedule;

          returnArray.push(batch);
          return batch
        })
      });
    }).then(function(data){
      console.log('from map ', data)
    })
  }).then(function(batches) {
    console.log('from outside', batches)
    res.send(returnArray);
  })
  // console.log(req.user);
  // res.send("req.decoded");
  // Batches().select().then(function(data){
  //   res.send(data);
  // });
})

router.post('/', function(req, res, next){
  Batches().insert({
    user_id: req.body.user_id,
    beer_id: req.body.styleNumber,
    name: req.body.name
  }, 'id').then(function(data){
    console.log(data);
    db.MongoClient.connect(process.env.MONGOLAB_URI, function(err, db){
      var brews = db.collection('brews');
      brews.insert({
        brew_id:data[0],
        schedule: req.body.schedule
      }, function(){
        res.send("success");
      })
    });
  });
});

router.delete('/', function(req, res, next){
  Batches().where('id', req.body.id).del()
  .then(function(){
    res.end();
  })
})

module.exports = router;
<commit_msg>get brews<commit_after>require('dotenv').load();

var express = require('express');
var router = express.Router();
var knex = require('../db/knex');
var db = require('mongodb');
var promise = require('bluebird')

function Batches(){
  return knex('batches');
}

function Users(){
  return knex('users');
}

/* GET batches for dashboard */

router.get('/', function(req, res, next){
  Batches().where('user_id', req.user.id).select().then(function(batches) {
    return promise.map(batches, function(batch) {
      var batchId = batch.id;
      return new Promise(function(res, rej){
        db.MongoClient.connect(process.env.MONGOLAB_URI, function(err, db){
        var brews = db.collection('brews');
        // console.log(batch);
         brews.find({
          brew_id:batchId
        }).limit(1).next(function(err, data){
          batch.schedule = data.schedule;
          console.log(batch);
          res(batch)
          })
        })
      });
    })
  }).then(function(batches) {
    console.log('from outside', batches)
    res.send(batches);
  })
  // console.log(req.user);
  // res.send("req.decoded");
  // Batches().select().then(function(data){
  //   res.send(data);
  // });
})

router.post('/', function(req, res, next){
  Batches().insert({
    user_id: req.body.user_id,
    beer_id: req.body.styleNumber,
    name: req.body.name
  }, 'id').then(function(data){
    console.log(data);
    db.MongoClient.connect(process.env.MONGOLAB_URI, function(err, db){
      var brews = db.collection('brews');
      brews.insert({
        brew_id:data[0],
        schedule: req.body.schedule
      }, function(){
        res.send("success");
      })
    });
  });
});

router.delete('/', function(req, res, next){
  Batches().where('id', req.body.id).del()
  .then(function(){
    res.end();
  })
})

module.exports = router;
<|endoftext|>


<commit_before>var firebase = new Firebase("https://lips.firebaseio.com/");

function initializeCalMatList() {
  var calMatListRef = firebase.child("calibrationMatrixList");
  calMatListRef.once('value', function(snapshot) {
    var calMatList = snapshot.val();
    if (calMatList) {
      console.log('already initialized calibrationMatrixList');
    }
    else {
      calMatList = [];
      calMatList[0] = false;
      calMatListRef.set(calMatList);
    }
  });
}

var makeSaveCalibrationMatrix = function(word, matrix) {
  var invoked = false;
  var saveCalibrationMatrix = function() {
    if (invoked) {
      console.log("saveCalibrationMatrix may only be invoked once");
    }
    else {
      var calMatListRef = firebase.child("calibrationMatrixList");
      calMatListRef.once('value', function(snapshot) {
        var calMatList = snapshot.val();
        var nextItem = calMatList.length;
        var jsonObj = {};
        jsonObj[word] = matrix;
        calMatList[nextItem] = jsonObj;
        calMatListRef.set(calMatList);
      });
      invoked = true;
    }
    return invoked;
  };
  return saveCalibrationMatrix;
};

var askSaveCalibrationMatrix = function(word, matrix) {
  var saved;
  var QUESTION_TEXT = "Save calibration matrix for word: " + word;
  var saveCalMat = makeSaveCalibrationMatrix(word, matrix);
  var userAnswer = confirm(QUESTION_TEXT);

  if (userAnswer) {
    saveCalMat();
    saved = true;
  }
  else {
    saved = false;
  }
  return saved;
}<commit_msg>improved object stored in db<commit_after>var firebase = new Firebase("https://lips.firebaseio.com/");

function initializeCalMatList() {
  var calMatListRef = firebase.child("calibrationMatrixList");
  calMatListRef.once('value', function(snapshot) {
    var calMatList = snapshot.val();
    if (calMatList) {
      console.log('already initialized calibrationMatrixList');
    }
    else {
      calMatList = [];
      calMatList[0] = false;
      calMatListRef.set(calMatList);
    }
  });
}

var makeSaveCalibrationMatrix = function(word, matrix) {
  var invoked = false;
  var saveCalibrationMatrix = function() {
    if (invoked) {
      console.log("saveCalibrationMatrix may only be invoked once");
    }
    else {
      var calMatListRef = firebase.child("calibrationMatrixList");
      calMatListRef.once('value', function(snapshot) {
        var calMatList = snapshot.val();
        var nextItem = calMatList.length;
        var jsonObj = {
          word: word,
          matrix: matrix
        };
        // jsonObj[word] = matrix;
        calMatList[nextItem] = jsonObj;
        calMatListRef.set(calMatList);
      });
      invoked = true;
    }
    return invoked;
  };
  return saveCalibrationMatrix;
};

var askSaveCalibrationMatrix = function(word, matrix) {
  var saved;
  var QUESTION_TEXT = "Save calibration matrix for word: " + word;
  var saveCalMat = makeSaveCalibrationMatrix(word, matrix);
  var userAnswer = confirm(QUESTION_TEXT);

  if (userAnswer) {
    saveCalMat();
    saved = true;
  }
  else {
    saved = false;
  }
  return saved;
}<|endoftext|>


<commit_before>function loadDBFromFile(url, callback) {
    fetch(url, { method: 'GET' })
        //.then(function (response) { return response.json() })
        .then(function (response) { return response.text(); })
        .then(function (text) { return JSON.parse(text); })
        .then(DC.loadData)
        .then(callback)
        .catch(function (error) { console.log(error); });
}

var DC = (function () {
    var db;
    var sd;
    var lvup_rate = 0.005245;
    var lb_rate = {
        normal: 0.025775,
        high: 0.041275
    }
    var key_mp = 'mp';
    var key_bs_mp = 'bs_mp';
    var key_mp_dec = 'mp_dec';
    var key_atk = 'atk';
    var key_bs_atk = 'bs_atk';

    function loadData(raw) {
        db = raw;
        //init relation
        for (var i = 0; i < db.relation.length; i++) {
            var rel = db.relation[i];
            refer(db[rel.src], db[rel.dst], rel.key);
        }
        //init condition object
        createConditionObject(db.armor, 'conditional');
        createConditionObject(db.accessory, 'conditional');
        createConditionObject(db.preset, 'condition');
        //init static data
        sd = {};
        return db;
    }
    function getData() {
        return db;
    }
    function refer(src, dst, key) {
        for (var i in src) {
            var value = src[i][key];
            src[i][key] = dst[value];
        }
    }
    function createConditionObject(object, key) {
        for (var i in object) {
            var condition = {};
            var condition_string = object[i][key];
            if (condition_string !== 0) {
                var conditions = condition_string.split(/,/);
                for (var j in conditions) {
                    var sp = conditions[j].split(/:/);
                    condition.expression = sp[0];
                    var values = sp[1].split(/&/);
                    condition.values = {};
                    for (var k in values) {
                        var kv = values[k].split(/=/);
                        condition.values[kv[0]] = parse(kv[1]);
                    }
                }
                object[i][key] = condition;
            }
        }
    }
    function calcRateAtTryout(c, lv, lb, wep, r, amr, acc, boss, damage) {
        var dcv = getDamageCalculationVariables(c, lv, lb, wep, r, amr, acc, boss);
        dcv.rate = damage / ((dcv.atk * dcv.bs * (1 + (1 - dcv.buff) / 1.5) - dcv.def) * dcv.mod) * 1.1;
        return dcv;
    }
    function calcRate(c, lv, lb, wep, r, amr, acc, boss, damage) {
        var dcv = getDamageCalculationVariables(c, lv, lb, wep, r, amr, acc, boss);
        dcv.rate = damage / ((dcv.atk * dcv.bs * dcv.buff - dcv.def) * dcv.mod);
        return dcv;
    }
    function calcDamage(c, lv, lb, wep, r, amr, acc, boss, custom_rate) {
        var dcv = getDamageCalculationVariables(c, lv, lb, wep, r, amr, acc, boss);
        if (custom_rate) { dcv.rate = custom_rate; }
        dcv.damage = (dcv.atk * dcv.bs * dcv.buff - dcv.def) * dcv.rate * dcv.mod;
        return dcv;
    }
    function getDamageCalculationVariables(c, lv, lb, wep, r, amr, acc, boss) {
        var sv = getSV(c, lv, lb, wep, r, amr, acc);
        var sve = sv['default'];
        if (boss.element) {
            sve = sv[boss.element.id];
        }

        var exp_obj = { c: c, hp: 100, vs: boss.element ? boss.element.id : undefined, combo: boss.combo };
        var bs_con_amr = amr && Expression.eval(amr.conditional.expression, exp_obj) ? amr.conditional.values : {};
        var bs_con_acc = acc && Expression.eval(acc.conditional.expression, exp_obj) ? acc.conditional.values : {};
        var atk = sv.atk + getEqValue(bs_con_amr, key_atk) + getEqValue(bs_con_acc, key_atk);
        var bs_atk = sve.bs_atk + getEqValue(bs_con_amr, key_bs_atk) + getEqValue(bs_con_acc, key_bs_atk);

        var buff;
        if (boss.gbuff === undefined) {
            buff = sv.c.s3_atk;
        } else {
            buff = Math.max(sv.c.s3_atk, boss.gbuff);
        }
        buff *= boss.trophy;

        var debuff = 1.0;
        if (boss.debuff) { debuff = boss.debuff; }

        var def;
        if (boss.debuff < 1.0) { //debuff on
            def = boss.def * debuff;
        } else { //debuff off
            def = boss.def * (1 - sv.c.s3_debuf_pnr + sv.c.s3_debuf * sv.c.s3_debuf_pnr);
        }

        var emod = 1;
        if (sve.eRate) { emod *= boss[sve.eRate]; }
        var dtmod = 1;
        for (var t in db.dtype) { dtmod += (boss[t] - 1) * sv.dtmod[t]; }

        var cmod = Expression.eval(boss.condition.expression, exp_obj) ? boss.condition.values.mod : 1;

        var combo = 1 + Math.floor(boss.combo / 10) * 0.05;
        if (boss.combo > 20) { combo *= sv.c.combo_damage_20; }
        if (boss.combo > 30) { combo *= sv.c.combo_damage_30; }
        var mod = Math.min(combo * sve.mod_dmg * emod * dtmod * boss.repRate * boss.racc * boss.etcMod * cmod, boss.limit);
        if (boss.crit > 0) {
            mod *= sve.mod_crit;
        }
        var dcv = {
            atk: atk,
            bs: (1 + bs_atk),
            buff: buff,
            def: def,
            rate: sv.c.s3_rate,
            mod: mod,
            sv: sv
        };
        return dcv;
    }
    function getSV(c, lv, lb, wep, r, amr, acc) {
        var obj = sd;
        obj = getSubObject(obj, c.id);
        obj = getSubObject(obj, lv);
        obj = getSubObject(obj, lb);
        obj = getSubObject(obj, wep ? wep.id : 'undefined');
        obj = getSubObject(obj, r);
        obj = getSubObject(obj, amr ? amr.id : 'undefined');
        obj = getSubObject(obj, acc ? acc.id : 'undefined');
        if (Object.keys(obj).length <= 0) {
            obj = createSV(c, lv, lb, wep, r, amr, acc, obj);
        }
        return obj;
    }
    function getSubObject(obj, key) {
        if (obj[key] === undefined) {
            obj[key] = {};
        }
        return obj[key];
    }
    function createSV(c, lv, lb, wep, r, amr, acc, sv) {
        sv.c = c;
        sv.lv = lv;
        sv.wep = wep;
        sv.r = r;
        sv.amr = amr;
        sv.acc = acc;
        sv.mp = (c.mp + getEqValueWithElem(c, amr, key_mp) + getEqValueWithElem(c, acc, key_mp)) * (1 + c.bs_mp + getEqValue(amr, key_bs_mp) + getEqValue(acc, key_bs_mp));
        sv.cost = c.s3_mp - c.s3_mp * getEqValue(wep, key_mp_dec);

        var lv_dif = lv - 80;
        var ss_atk = c.ss_atk;
        if (lv > 80) {
            ss_atk += c.ss_atk_85;
        }
        sv.lb = Math.min(lb, Math.floor(lv_dif / 5))
        sv.atk_c = c.atk + c.atk * lv_dif * lvup_rate + c.atk * sv.lb * lb_rate[c.lvup] + ss_atk;
        sv.atk_eq = getWeaponAtk(c, wep, r) + getEqValueWithElem(c, amr, key_atk) + getEqValueWithElem(c, acc, key_atk);
        sv.atk = sv.atk_c + sv.atk_eq;
        createSVE(sv, 'default');
        for (var elem in db.element) {
            createSVE(sv, elem);
        }
        sv.dtmod = {}
        for (var t in db.dtype) {
            sv.dtmod[t] = c['dtr_' + t];
        }
        return sv;
    }
    function createSVE(sv, elem) {
        var sve = {};
        sv[elem] = sve;
        sve.bs_atk_eq = getWeaponBSAtk(sv.wep, sv.r) + getEqValue(sv.amr, key_bs_atk) + getEqValue(sv.acc, key_bs_atk);
        sve.bs_atk = sv.c.bs_atk + sve.bs_atk_eq;
        sve.mod_dmg = sv.c.ss_dmg;
        sve.mod_crit = sv.c.cri_dmg * sv.c.ss_cri_dmg * (1 + getWeaponCriEDmg(sv.wep, sv.r, elem));
        if (sv.c.element.weak === elem) {
            sve.eRate = 'enRate';
        } else {
            if (sv.c.element.strong === elem) {
                sve.eRate = 'epRate';
            }
            sve.mod_dmg *= sv.c.ss_elem_dmg;
            if (sv.lv > 85) {
                sve.mod_dmg *= sv.c.ss_elem_dmg_90;
            }
            sve.mod_crit *= sv.c.ss_elem_cri_dmg;
        }
    }
    function getWeaponAtk(c, wep, r) {
        var atk = getEqValueWithElem(c, wep, key_atk);
        switch (r) {
            case 4:
                return atk * 1;
            case 5:
                return atk * 1.36;
            default:
                return atk * 0;
        }
    }
    function getWeaponBSAtk(wep, r) {
        if (wep) {
            switch (r) {
                case 4:
                    return wep.bs_atk;
                case 5:
                    return wep.bs_atk5;
                default:
                    return 0;
            }
        }
        return 0;
    }
    function getWeaponCriEDmg(wep, r, vs) {
        if (wep && wep.element.strong === vs) {
            switch (r) {
                case 4:
                    return wep.bs_cri_edmg;
                case 5:
                    return wep.bs_cri_edmg5;
                default:
                    return 0;
            }
        }
        return 0;
    }
    function getEqValueWithElem(c, eq, key) {
        var value = getEqValue(eq, key);
        if (value && c.element === eq.element) {
            return value * 1.2;
        } else {
            return value;
        }
    }
    function getEqValue(eq, key) {
        if (eq === undefined || eq[key] === undefined) { return 0; }
        return eq[key];
    }
    function get(itemKey, mKey, mValue) {
        var items = db[itemKey];
        for (var i in items) {
            var item = items[i];
            if (item[mKey] === mValue) {
                return item;
            }
        }
        return undefined;
    }
    function getChar(id) {
        if (id) { return db.base[id]; }
        return db.base;
    }
    function getWeapon(id) {
        if (id) { return db.weapon[id]; }
        return db.weapon;
    }
    function getArmor(id) {
        if (id) { return db.armor[id]; }
        return db.armor;
    }
    function getAccessory(id) {
        if (id) { return db.accessory[id]; }
        return db.accessory;
    }
    function getBoss(name) {
        if (name) { return get('preset', 'name', name); }
        return db.preset;
    }
    function getCname(id) {
        if (id) { return db.cname[id]; }
        return db.cname;
    }
    function getElement(id) {
        if (id) { return db.element[id]; }
        return db.element;
    }
    function getType(id) {
        if (id) { return db.type[id]; }
        return db.type;
    }
    function getDtype(id) {
        if (id) { return db.dtype[id]; }
        return db.dtype;
    }
    return {
        loadData: loadData,
        getData: getData,
        getSV: getSV,
        calcRateAtTryout: calcRateAtTryout,
        calcRate: calcRate,
        calcDamage: calcDamage,
        get: get,
        getChar: getChar,
        getWeapon: getWeapon,
        getArmor: getArmor,
        getAccessory: getAccessory,
        getBoss: getBoss,
        getCname: getCname,
        getElement: getElement,
        getType: getType,
        getDtype: getDtype
    }
})();
<commit_msg>bug fix for element modifier<commit_after>function loadDBFromFile(url, callback) {
    fetch(url, { method: 'GET' })
        //.then(function (response) { return response.json() })
        .then(function (response) { return response.text(); })
        .then(function (text) { return JSON.parse(text); })
        .then(DC.loadData)
        .then(callback)
        .catch(function (error) { console.log(error); });
}

var DC = (function () {
    var db;
    var sd;
    var lvup_rate = 0.005245;
    var lb_rate = {
        normal: 0.025775,
        high: 0.041275
    }
    var key_mp = 'mp';
    var key_bs_mp = 'bs_mp';
    var key_mp_dec = 'mp_dec';
    var key_atk = 'atk';
    var key_bs_atk = 'bs_atk';

    function loadData(raw) {
        db = raw;
        //init relation
        for (var i = 0; i < db.relation.length; i++) {
            var rel = db.relation[i];
            refer(db[rel.src], db[rel.dst], rel.key);
        }
        //init condition object
        createConditionObject(db.armor, 'conditional');
        createConditionObject(db.accessory, 'conditional');
        createConditionObject(db.preset, 'condition');
        //init static data
        sd = {};
        return db;
    }
    function getData() {
        return db;
    }
    function refer(src, dst, key) {
        for (var i in src) {
            var value = src[i][key];
            src[i][key] = dst[value];
        }
    }
    function createConditionObject(object, key) {
        for (var i in object) {
            var condition = {};
            var condition_string = object[i][key];
            if (condition_string !== 0) {
                var conditions = condition_string.split(/,/);
                for (var j in conditions) {
                    var sp = conditions[j].split(/:/);
                    condition.expression = sp[0];
                    var values = sp[1].split(/&/);
                    condition.values = {};
                    for (var k in values) {
                        var kv = values[k].split(/=/);
                        condition.values[kv[0]] = parse(kv[1]);
                    }
                }
                object[i][key] = condition;
            }
        }
    }
    function calcRateAtTryout(c, lv, lb, wep, r, amr, acc, boss, damage) {
        var dcv = getDamageCalculationVariables(c, lv, lb, wep, r, amr, acc, boss);
        dcv.rate = damage / ((dcv.atk * dcv.bs * (1 + (1 - dcv.buff) / 1.5) - dcv.def) * dcv.mod) * 1.1;
        return dcv;
    }
    function calcRate(c, lv, lb, wep, r, amr, acc, boss, damage) {
        var dcv = getDamageCalculationVariables(c, lv, lb, wep, r, amr, acc, boss);
        dcv.rate = damage / ((dcv.atk * dcv.bs * dcv.buff - dcv.def) * dcv.mod);
        return dcv;
    }
    function calcDamage(c, lv, lb, wep, r, amr, acc, boss, custom_rate) {
        var dcv = getDamageCalculationVariables(c, lv, lb, wep, r, amr, acc, boss);
        if (custom_rate) { dcv.rate = custom_rate; }
        dcv.damage = (dcv.atk * dcv.bs * dcv.buff - dcv.def) * dcv.rate * dcv.mod;
        return dcv;
    }
    function getDamageCalculationVariables(c, lv, lb, wep, r, amr, acc, boss) {
        var sv = getSV(c, lv, lb, wep, r, amr, acc);
        var sve = sv['default'];
        if (boss.element) {
            sve = sv[boss.element.id];
        }

        var exp_obj = { c: c, hp: 100, vs: boss.element ? boss.element.id : undefined, combo: boss.combo };
        var bs_con_amr = amr && Expression.eval(amr.conditional.expression, exp_obj) ? amr.conditional.values : {};
        var bs_con_acc = acc && Expression.eval(acc.conditional.expression, exp_obj) ? acc.conditional.values : {};
        var atk = sv.atk + getEqValue(bs_con_amr, key_atk) + getEqValue(bs_con_acc, key_atk);
        var bs_atk = sve.bs_atk + getEqValue(bs_con_amr, key_bs_atk) + getEqValue(bs_con_acc, key_bs_atk);

        var buff;
        if (boss.gbuff === undefined) {
            buff = sv.c.s3_atk;
        } else {
            buff = Math.max(sv.c.s3_atk, boss.gbuff);
        }
        buff *= boss.trophy;

        var debuff = 1.0;
        if (boss.debuff) { debuff = boss.debuff; }

        var def;
        if (boss.debuff < 1.0) { //debuff on
            def = boss.def * debuff;
        } else { //debuff off
            def = boss.def * (1 - sv.c.s3_debuf_pnr + sv.c.s3_debuf * sv.c.s3_debuf_pnr);
        }

        var emod = 1;
        if (sve.eRate) { emod *= boss[sve.eRate]; }
        var dtmod = 1;
        for (var t in db.dtype) { dtmod += (boss[t] - 1) * sv.dtmod[t]; }

        var cmod = Expression.eval(boss.condition.expression, exp_obj) ? boss.condition.values.mod : 1;

        var combo = 1 + Math.floor(boss.combo / 10) * 0.05;
        if (boss.combo > 20) { combo *= sv.c.combo_damage_20; }
        if (boss.combo > 30) { combo *= sv.c.combo_damage_30; }
        var mod = Math.min(combo * sve.mod_dmg * emod * dtmod * boss.repRate * boss.racc * boss.etcMod * cmod, boss.limit);
        if (boss.crit > 0) {
            mod *= sve.mod_crit;
        }
        var dcv = {
            atk: atk,
            bs: (1 + bs_atk),
            buff: buff,
            def: def,
            rate: sv.c.s3_rate,
            mod: mod,
            sv: sv
        };
        return dcv;
    }
    function getSV(c, lv, lb, wep, r, amr, acc) {
        var obj = sd;
        obj = getSubObject(obj, c.id);
        obj = getSubObject(obj, lv);
        obj = getSubObject(obj, lb);
        obj = getSubObject(obj, wep ? wep.id : 'undefined');
        obj = getSubObject(obj, r);
        obj = getSubObject(obj, amr ? amr.id : 'undefined');
        obj = getSubObject(obj, acc ? acc.id : 'undefined');
        if (Object.keys(obj).length <= 0) {
            obj = createSV(c, lv, lb, wep, r, amr, acc, obj);
        }
        return obj;
    }
    function getSubObject(obj, key) {
        if (obj[key] === undefined) {
            obj[key] = {};
        }
        return obj[key];
    }
    function createSV(c, lv, lb, wep, r, amr, acc, sv) {
        sv.c = c;
        sv.lv = lv;
        sv.wep = wep;
        sv.r = r;
        sv.amr = amr;
        sv.acc = acc;
        sv.mp = (c.mp + getEqValueWithElem(c, amr, key_mp) + getEqValueWithElem(c, acc, key_mp)) * (1 + c.bs_mp + getEqValue(amr, key_bs_mp) + getEqValue(acc, key_bs_mp));
        sv.cost = c.s3_mp - c.s3_mp * getEqValue(wep, key_mp_dec);

        var lv_dif = lv - 80;
        var ss_atk = c.ss_atk;
        if (lv > 80) {
            ss_atk += c.ss_atk_85;
        }
        sv.lb = Math.min(lb, Math.floor(lv_dif / 5))
        sv.atk_c = c.atk + c.atk * lv_dif * lvup_rate + c.atk * sv.lb * lb_rate[c.lvup] + ss_atk;
        sv.atk_eq = getWeaponAtk(c, wep, r) + getEqValueWithElem(c, amr, key_atk) + getEqValueWithElem(c, acc, key_atk);
        sv.atk = sv.atk_c + sv.atk_eq;
        createSVE(sv, 'default');
        for (var elem in db.element) {
            createSVE(sv, elem);
        }
        sv.dtmod = {}
        for (var t in db.dtype) {
            sv.dtmod[t] = c['dtr_' + t];
        }
        return sv;
    }
    function createSVE(sv, elem) {
        var sve = {};
        sv[elem] = sve;
        sve.bs_atk_eq = getWeaponBSAtk(sv.wep, sv.r) + getEqValue(sv.amr, key_bs_atk) + getEqValue(sv.acc, key_bs_atk);
        sve.bs_atk = sv.c.bs_atk + sve.bs_atk_eq;
        sve.mod_dmg = sv.c.ss_dmg;
        sve.mod_crit = sv.c.cri_dmg * sv.c.ss_cri_dmg * (1 + getWeaponCriEDmg(sv.wep, sv.r, elem));
        if (sv.c.element.weak === elem) {
            sve.eRate = 'enRate';
        }
        switch (elem) {
            case sv.c.element.strong:
                sve.eRate = 'epRate';
            case 'default':
                sve.mod_dmg *= sv.c.ss_elem_dmg;
                if (sv.lv > 85) {
                    sve.mod_dmg *= sv.c.ss_elem_dmg_90;
                }
                sve.mod_crit *= sv.c.ss_elem_cri_dmg;
        }
    }
    function getWeaponAtk(c, wep, r) {
        var atk = getEqValueWithElem(c, wep, key_atk);
        switch (r) {
            case 4:
                return atk * 1;
            case 5:
                return atk * 1.36;
            default:
                return atk * 0;
        }
    }
    function getWeaponBSAtk(wep, r) {
        if (wep) {
            switch (r) {
                case 4:
                    return wep.bs_atk;
                case 5:
                    return wep.bs_atk5;
                default:
                    return 0;
            }
        }
        return 0;
    }
    function getWeaponCriEDmg(wep, r, vs) {
        if (wep && wep.element.strong === vs) {
            switch (r) {
                case 4:
                    return wep.bs_cri_edmg;
                case 5:
                    return wep.bs_cri_edmg5;
                default:
                    return 0;
            }
        }
        return 0;
    }
    function getEqValueWithElem(c, eq, key) {
        var value = getEqValue(eq, key);
        if (value && c.element === eq.element) {
            return value * 1.2;
        } else {
            return value;
        }
    }
    function getEqValue(eq, key) {
        if (eq === undefined || eq[key] === undefined) { return 0; }
        return eq[key];
    }
    function get(itemKey, mKey, mValue) {
        var items = db[itemKey];
        for (var i in items) {
            var item = items[i];
            if (item[mKey] === mValue) {
                return item;
            }
        }
        return undefined;
    }
    function getChar(id) {
        if (id) { return db.base[id]; }
        return db.base;
    }
    function getWeapon(id) {
        if (id) { return db.weapon[id]; }
        return db.weapon;
    }
    function getArmor(id) {
        if (id) { return db.armor[id]; }
        return db.armor;
    }
    function getAccessory(id) {
        if (id) { return db.accessory[id]; }
        return db.accessory;
    }
    function getBoss(name) {
        if (name) { return get('preset', 'name', name); }
        return db.preset;
    }
    function getCname(id) {
        if (id) { return db.cname[id]; }
        return db.cname;
    }
    function getElement(id) {
        if (id) { return db.element[id]; }
        return db.element;
    }
    function getType(id) {
        if (id) { return db.type[id]; }
        return db.type;
    }
    function getDtype(id) {
        if (id) { return db.dtype[id]; }
        return db.dtype;
    }
    return {
        loadData: loadData,
        getData: getData,
        getSV: getSV,
        calcRateAtTryout: calcRateAtTryout,
        calcRate: calcRate,
        calcDamage: calcDamage,
        get: get,
        getChar: getChar,
        getWeapon: getWeapon,
        getArmor: getArmor,
        getAccessory: getAccessory,
        getBoss: getBoss,
        getCname: getCname,
        getElement: getElement,
        getType: getType,
        getDtype: getDtype
    }
})();
<|endoftext|>


<commit_before>// __main__:
function go() {
  'use strict';
  // 'global' consts:
  var theBoard;
  var stoneImages = {w: '', b: ''};
  var playerColor = 'w';

  buildBoard(theBoard, 9);

  // Templates:
  function Board(boardSize, imgPath) {
    var t, c, r;
    this.imgSrc = imgPath;
    this.intersections = [];

    this.generateTableHtml = function () {
      var t = '
';
      for (c = 0; c < boardSize; ++c) {
        t += '
';
        for (r = 0; r < boardSize; ++r) {
          t += '	';
        }
        t += '
';
      }
      t += '
';
      return t;
    };
    this.getCellNum = function (col, row) {
      if (col >= boardSize || row >= boardSize)
        throw new RangeError('Invalid col or row in getCellNum()');
      return col*boardSize + row;
    };
    this.getColRow = function (cellNum) {
      if (cellNum > boardSize - 1)
        throw new RangeError('Invalid cellNum in getColRow()');
      return [cellNum % (boardSize -1), Math.floor(cellNum/boardSize)];
    };
  }

  // Methods:
  function buildBoard(theBoard, boardSize) {
    var tableCss;
    var boardDiv = document.getElementById('board');
    switch (boardSize) {
      case 9:
        theBoard = new Board(boardSize, 'images/board_9x9_550x550.png');
        stoneImages.w = 'images/stone_white_55x55.png';
        stoneImages.b = 'images/stone_black_55x55.png';
        tableCss = {'width': '530px',
                    'height': '530px',
                    'margin': '10px'};
        break;
      case 13:
        theBoard = new Board(boardSize);
        theBoard.imgSrc = 'images/board_13x13_550x550.png';
        break;
      case 19:
        theBoard = new Board(boardSize);
        theBoard.imgSrc = 'images/board_19x19_550x550.png';
        break;
      default:
        throw 'Invalid boardSize passed to makeBoard()';
    }
    // set board and table HTML and CSS
    boardDiv.style.backgroundImage = 'url("' + theBoard.imgSrc + '")';
    boardDiv.innerHTML = theBoard.generateTableHtml();
    $('#table').css(tableCss);
    $('.cell').click(function () {
      placeStone(theBoard, this);
    });
  }

  function togglePlayerColor() {
    if (playerColor === 'w')
      playerColor = 'b';
    else
      playerColor = 'w';
  }

  function placeStone(theBoard, that) {
    var cellNum = that.id.split('_')[1]; // get number after underscore
    if (theBoard.intersections[cellNum] === 'w' || theBoard.intersections[cellNum] === 'b')
      return;
    theBoard.intersections[cellNum] = playerColor;
    $(that).css({'background-image': 'url("' + stoneImages[playerColor] + '")',
                   'background-repeat': 'no-repeat',
                   'background-position': 'center center'});
    togglePlayerColor();
  }
} // END: go()

<commit_msg>Pass, Undo, and Restart buttons working.<commit_after>// __main__:
function go() {
  'use strict';
  // 'global' consts:
  var theBoard,
      intersections = [],
      moves = [],
      stoneImages = {w: '', b: ''},
      playerColor = 'w';

  buildBoard(theBoard, 9);

  // Templates:
  function Board(boardSize, imgPath) {
    var t, c, r;
    this.imgSrc = imgPath;

    this.generateTableHtml = function () {
      var t = '
';
      for (c = 0; c < boardSize; ++c) {
        t += '
';
        for (r = 0; r < boardSize; ++r) {
          t += '	';
        }
        t += '
';
      }
      t += '
';
      return t;
    };
    this.getCellNum = function (col, row) {
      if (col >= boardSize || row >= boardSize)
        throw new RangeError('Invalid col or row in getCellNum()');
      return col*boardSize + row;
    };
    this.getColRow = function (cellNum) {
      if (cellNum > boardSize - 1)
        throw new RangeError('Invalid cellNum in getColRow()');
      return [cellNum % (boardSize -1), Math.floor(cellNum/boardSize)];
    };
  }

  // Methods:
  function buildBoard(theBoard, boardSize) {
    var tableCss;
    var boardDiv = document.getElementById('board');
    switch (boardSize) {
      case 9:
        theBoard = new Board(boardSize, 'images/board_9x9_550x550.png');
        stoneImages.w = 'images/stone_white_55x55.png';
        stoneImages.b = 'images/stone_black_55x55.png';
        tableCss = {'width': '530px',
                    'height': '530px',
                    'margin': '10px'};
        break;
      case 13:
        theBoard = new Board(boardSize);
        theBoard.imgSrc = 'images/board_13x13_550x550.png';
        break;
      case 19:
        theBoard = new Board(boardSize);
        theBoard.imgSrc = 'images/board_19x19_550x550.png';
        break;
      default:
        throw 'Invalid boardSize passed to makeBoard()';
    }
    // set board and table HTML and CSS
    boardDiv.style.backgroundImage = 'url("' + theBoard.imgSrc + '")';
    boardDiv.innerHTML = theBoard.generateTableHtml();
    $('#table').css(tableCss);
    $('.cell').click(function () {
      placeStone(this);
    });
  }

  function placeStone(that) {
    var cellNum = that.id.split('_')[1]; // get number after underscore
    if (intersections[cellNum] === 'w' || intersections[cellNum] === 'b')
      return;
    intersections[cellNum] = playerColor;
    moves[moves.length] = Number(cellNum);
    console.log(moves);
    $(that).css({'background-image': 'url("' + stoneImages[playerColor] + '")',
                   'background-repeat': 'no-repeat',
                   'background-position': 'center center'});
    // TODO: submitMoveToServer();
    togglePlayerColor();
  }

  function togglePlayerColor() {
    if (playerColor === 'w')
      playerColor = 'b';
    else
      playerColor = 'w';
  }

  // button click handlers
  document.getElementById('pass_button').onclick = function () {
    // TODO: submitMoveToServer();
    moves[moves.length] = 'pass';
    togglePlayerColor();
  };

  document.getElementById('undo_button').onclick = function () {
    var lastMove = moves.pop();
    if (typeof lastMove === 'number') {
      var cellId = 'cell_' + lastMove;
      document.getElementById(cellId).style.backgroundImage = 'none';
      intersections[lastMove] = '';
      togglePlayerColor();
      // TODO: submitMoveToServer();
    }
    else if (lastMove === 'pass') {
      // TODO: submitMoveToServer();
      togglePlayerColor();
    }
    return; // handles pop from empty array too
  };

  document.getElementById('restart_button').onclick = function () {
    // should generate some grander restart procedure with eventual settings screen...
    // TODO: restartServer();
    intersections = [];
    moves = [];
    $('.cell').css('backgroundImage', 'none');
  };

} // END: go()

<|endoftext|>


<commit_before>'use_strict';

const express = require('express');
const router = express.Router();

const database = require('../sperm-whale/database');

// GET: list of all courses
router.get('/', function getAllCourses(req, res) {
  database.getAllCourses(function(err, r) {
    res.json(r);
  });
});

// GET: Lookup a course by abbreviation
router.get('/:subject/:number', function getCourse(req, res) {
  database.getCourse(req.params.subject, req.params.number, function(err, r) {
    res.json(r);
  });
});

module.exports = router;
<commit_msg>Fixed database call now that we’re storing courseNumber as int<commit_after>'use_strict';

const express = require('express');
const router = express.Router();

const database = require('../sperm-whale/database');

// GET: list of all courses
router.get('/', function getAllCourses(req, res) {
  database.getAllCourses(function(err, r) {
    res.json(r);
  });
});

// GET: Lookup a course by abbreviation
router.get('/:subject/:number', function getCourse(req, res) {
  database.getCourse(req.params.subject, parseInt(req.params.number), function(err, r) {
    res.json(r);
  });
});

module.exports = router;
<|endoftext|>


<commit_before>/* Event Emitter */
var util = require('util');
var EventEmitter = require('events').EventEmitter;

/* ZeroMQ */
var zmq = require('zmq')
  , sock = zmq.socket('sub')
  , sock2 = zmq.socket('pub');

sock.bindSync('tcp://127.0.0.1:5001');

/* Request */
var request = require('request');

// The EventEmitter Object that will report events back to the controller
var Meerkat = function() {

    // we need to store the reference of `this` to `self`, so that we can use the current context in the setTimeout (or any callback) functions
    // using `this` in the setTimeout functions will refer to those funtions, not the Radio class
    var self = this;

    var methodstuff = function() {
	  switch ( topic ) {
	    case 'perchEvent':
	        //Parse the message
	        console.log("PerchEvent");

	        self.emit('perchEvent', message)

	        break;
	    case MeatFinishedDropping:
	        //Parse the message
	        console.log("MeatFinishedDropping");

	        self.emit('MeatDropped', message)

	        break;
	    case LightChanged:
	        //Parse the message
	        console.log("LightChanged");

	        self.emit('LightChanged', message)

	        break;
	    default:
	        console.log("unhandled event");

	        self.emit('dunno', message)

		}
	}

    // EventEmitters inherit a single event listener, see it in action
    this.on('newListener', function(listener) {
        console.log('Event Listener: ' + listener);
    });

};

// Connect to Lagarto over ZMQ to subscrbe to events
	sock.connect('tcp://127.0.0.1:5001');
	sock.subscribe('');
	console.log('Subscriber connected to port 5001');

	sock.on('message', function(topic, message) {
	  console.log('received a message related to:', topic, 'containing message:', message);
	});

// extend the EventEmitter class using our Meerkat class
util.inherits(Meerkat, EventEmitter);

// Methods to be exported
var exports = module.exports = {};

// we specify that this module is a refrence to the Meerkat class
exports.Meerkat = Meerkat;

// Test method to be removed...
exports.sendMessage = function() {
  console.log('sending a multipart message envelope');
  sock2.send(['', 'meow!']);
};

//
// Detecting Devices Methods
//
exports.getDevices = function() {

	//Perhaps this should pre cache??

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=7.11.0&value=true', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent")
      }
    })
};

//
// Meat Events
//
exports.dropMeat = function(experimentalNodeID) {

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=7.11.0&value=true', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent")
      }
    })
};

exports.getRemainingMeat = function(experimentalNodeID) {

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=7.11.0&value=true', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent")
      }
    })

};

//
// Light Events
//
exports.turnLightOn = function(experimentalLightID) {

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=7.11.0&value=true', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent")
      }
    })

};

exports.turnLightsOff = function() {

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=7.11.0&value=true', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent")
      }
    })

};<commit_msg>testing zmq<commit_after>/* Event Emitter */
var util = require('util');
var EventEmitter = require('events').EventEmitter;

/* ZeroMQ */
var zmq = require('zmq')
  , sock = zmq.socket('sub')
  , sock2 = zmq.socket('pub');

sock2.bindSync('tcp://127.0.0.1:5001');

/* Request */
var request = require('request');

// The EventEmitter Object that will report events back to the controller
var Meerkat = function() {

    // we need to store the reference of `this` to `self`, so that we can use the current context in the setTimeout (or any callback) functions
    // using `this` in the setTimeout functions will refer to those funtions, not the Radio class
    var self = this;

    var methodstuff = function() {
	  switch ( topic ) {
	    case 'perchEvent':
	        //Parse the message
	        console.log("PerchEvent");

	        self.emit('perchEvent', message)

	        break;
	    case MeatFinishedDropping:
	        //Parse the message
	        console.log("MeatFinishedDropping");

	        self.emit('MeatDropped', message)

	        break;
	    case LightChanged:
	        //Parse the message
	        console.log("LightChanged");

	        self.emit('LightChanged', message)

	        break;
	    default:
	        console.log("unhandled event");

	        self.emit('dunno', message)

		}
	}

    // EventEmitters inherit a single event listener, see it in action
    this.on('newListener', function(listener) {
        console.log('Event Listener: ' + listener);
    });

};

// Connect to Lagarto over ZMQ to subscrbe to events
sock.connect('tcp://127.0.0.1:5001');
sock.subscribe('');
console.log('Subscriber connected to port 5001');

sock.on('message', function(topic, message) {
  console.log('received a message related to:', topic, 'containing message:', message);
});

// extend the EventEmitter class using our Meerkat class
util.inherits(Meerkat, EventEmitter);

// Methods to be exported
var exports = module.exports = {};

// we specify that this module is a refrence to the Meerkat class
exports.Meerkat = Meerkat;

// Test method to be removed...
exports.sendMessage = function() {
  console.log('sending a multipart message envelope');
  sock2.send(['', 'meow!']);
};

//
// Detecting Devices Methods
//
exports.getDevices = function() {

	//Perhaps this should pre cache??

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=7.11.0&value=true', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent")
      }
    })
};

//
// Meat Events
//
exports.dropMeat = function(experimentalNodeID) {

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=7.11.0&value=true', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent")
      }
    })
};

exports.getRemainingMeat = function(experimentalNodeID) {

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=7.11.0&value=true', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent")
      }
    })

};

//
// Light Events
//
exports.turnLightOn = function(experimentalLightID) {

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=7.11.0&value=true', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent")
      }
    })

};

exports.turnLightsOff = function() {

	// Sent command to Lagarto
	request('http://127.0.0.1:8001/values?id=7.11.0&value=true', function (error, response, body) {
      if (!error && response.statusCode == 200) {
        console.log("Sent")
      }
    })

};<|endoftext|>


<commit_before>$(document).ready(function(){
 var headerH=$('header').height();
 $(window).scroll(function(){
  var wTop=$(this).scrollTop(),
  wHeight=$(this).height();
  $('.content article').each(function(){
   var aPos=$(this).offset().top,
   aHeight=$(this).height(),
   aLink=$(this).attr('id');
        if(wTop+headerH>aPos && wTop+headerH<aPos+aHeight){
         $('[data-active="'+aLink+'"]').addClass('active');
        }
        else{
         $('[data-active="'+aLink+'"]').removeClass('active');
        }
        if(wTop+$('header').height()+wHeight/2>aPos && wTop+$('header').height()+wHeight/2<aPos+aHeight){
         $('[data-active="'+aLink+'"]').addClass('active1');
        }
        else{
         $('[data-active="'+aLink+'"]').removeClass('active1');
        }
      });
 });
 $('[data-active]').click(function(){
  var aScroll=$(this).attr('data-active'),
  aScrollPos=$('#'+aScroll).offset().top;
  $('html, body').animate({scrollTop: aScrollPos+headerH}, 300);
 });
});
<commit_msg>Update js.js<commit_after>$(document).ready(function(){
 var headerH=$('header').height();
 $(window).scroll(function(){
  var wTop=$(this).scrollTop(),
  wHeight=$(this).height();
  $('.content article').each(function(){
   var aPos=$(this).offset().top,
   aHeight=$(this).height(),
   aLink=$(this).attr('id');
        if(wTop+headerH>=aPos && wTop+headerH<=aPos+aHeight){
         $('[data-active="'+aLink+'"]').addClass('active');
        }
        else{
         $('[data-active="'+aLink+'"]').removeClass('active');
        }
        if(wTop+$('header').height()+wHeight/2>=aPos && wTop+$('header').height()+wHeight/2<=aPos+aHeight){
         $('[data-active="'+aLink+'"]').addClass('active1');
        }
        else{
         $('[data-active="'+aLink+'"]').removeClass('active1');
        }
      });
 });
 $('[data-active]').click(function(){
  var aScroll=$(this).attr('data-active'),
  aScrollPos=$('#'+aScroll).offset().top;
  $('html, body').animate({scrollTop: aScrollPos-headerH}, 500);
 });
});
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

var passportConf = require('../config/passport');

var Week = require('../models/week');
var Contest = require('../models/contest');
var Entry = require('../models/entry');

router.get('/', passportConf.isAdmin, function(req, res) {
    Entry.find()
        .populate('user', 'profile')
        .populate('contest')
        .populate('roster')
        .exec(function(err, entries) {
        if (err) {
            return res.sendStatus(404);
        }

        Entry.populate(entries, {
            path: 'contest.week',
            select: '-players',
            model: 'Week'
        }, function(err, entries) {
            if (err) {
                return res.sendStatus(404);
            }

            res.json(entries);
        });
    });
});

router.get('/:id', passportConf.isAuthenticated, function(req, res) {
    Entry.findById(req.params.id)
        .populate('user', 'profile')
        .populate('contest')
        .populate('roster')
        .exec(function(err, entry) {
        if (err || (entry == null)) {
            return res.sendStatus(404);
        }

        if (req.user.id !== entry.user.id) {
            return res.sendStatus(401);
        }

        res.json(entry);
    });
});

router.post('/', passportConf.isAuthenticated, function(req, res) {
    var entry = new Entry();
    entry.contest = req.body.contest;
    entry.user = req.body.user || req.user;
    entry.roster = req.body.roster;

    // TODO: Validate that the contest, user, and player references (in the roster) are all valid

    entry.save(function(err, entry) {
        if (err) {
            return res.sendStats(400);
        }

        res.json(entry);
    });
});

router.put('/:id', passportConf.isAuthenticated, function(req, res) {
    Entry.findById(req.params.id, function(err, entry) {
        if (err || (entry == null)) {
            return res.sendStatus(404);
        }

        if ((!req.user.isAdmin) && (req.user.id !== entry.user.id)) {
            return res.sendStatus(401);
        }

        entry.contest = req.body.contest || entry.contest;
        entry.user = req.body.user || entry.user;
        entry.roster = req.body.roster || entry.roster;

        entry.save(function(err, entry) {
            if (err) {
                return res.sendStatus(400);
            }

            res.json(entry);
        });
    });
});

router.delete('/', passportConf.isAdmin, function(req, res) {
    Entry.find().remove(function(err) {
        if (err) {
            return res.sendStatus(500);
        }

        return res.sendStatus(200);
    });
});

router.delete('/:id', passportConf.isAuthenticated, function(req, res) {
    Entry.findById(req.params.id, function(err, entry) {
        if (err) {
            return res.sendStatus(404);
        }

        if ((!req.user.isAdmin) && (req.user.id !== entry.user.id)) {
            return res.sendStatus(401);
        }

        entry.remove(function(err) {
            if (err) throw err;

            res.sendStatus(200);
        });
    });
});

module.exports = router;<commit_msg>Allow non-admins to update and delete their rosters<commit_after>var express = require('express');
var router = express.Router();

var passportConf = require('../config/passport');

var Week = require('../models/week');
var Contest = require('../models/contest');
var Entry = require('../models/entry');

router.get('/', passportConf.isAdmin, function(req, res) {
    Entry.find()
        .populate('user', 'profile')
        .populate('contest')
        .populate('roster')
        .exec(function(err, entries) {
        if (err) {
            return res.sendStatus(404);
        }

        Entry.populate(entries, {
            path: 'contest.week',
            select: '-players',
            model: 'Week'
        }, function(err, entries) {
            if (err) {
                return res.sendStatus(404);
            }

            res.json(entries);
        });
    });
});

router.get('/:id', passportConf.isAuthenticated, function(req, res) {
    Entry.findById(req.params.id)
        .populate('user', 'profile')
        .populate('contest')
        .populate('roster')
        .exec(function(err, entry) {
        if (err || (entry == null)) {
            return res.sendStatus(404);
        }

        if (req.user.id !== entry.user.id) {
            return res.sendStatus(401);
        }

        res.json(entry);
    });
});

router.post('/', passportConf.isAuthenticated, function(req, res) {
    var entry = new Entry();
    entry.contest = req.body.contest;
    entry.user = req.body.user || req.user;
    entry.roster = req.body.roster;

    // TODO: Validate that the contest, user, and player references (in the roster) are all valid

    entry.save(function(err, entry) {
        if (err) {
            return res.sendStats(400);
        }

        res.json(entry);
    });
});

router.put('/:id', passportConf.isAuthenticated, function(req, res) {
    Entry.findById(req.params.id, function(err, entry) {
        if (err || (entry == null)) {
            return res.sendStatus(404);
        }

        if ((!req.user.isAdmin) && (req.user.id !== entry.user)) {
            return res.sendStatus(401);
        }

        entry.contest = req.body.contest || entry.contest;
        entry.user = req.body.user || entry.user;
        entry.roster = req.body.roster || entry.roster;

        entry.save(function(err, entry) {
            if (err) {
                return res.sendStatus(400);
            }

            res.json(entry);
        });
    });
});

router.delete('/', passportConf.isAdmin, function(req, res) {
    Entry.find().remove(function(err) {
        if (err) {
            return res.sendStatus(500);
        }

        return res.sendStatus(200);
    });
});

router.delete('/:id', passportConf.isAuthenticated, function(req, res) {
    Entry.findById(req.params.id, function(err, entry) {
        if (err) {
            return res.sendStatus(404);
        }

        if ((!req.user.isAdmin) && (req.user.id !== entry.user)) {
            return res.sendStatus(401);
        }

        entry.remove(function(err) {
            if (err) throw err;

            res.sendStatus(200);
        });
    });
});

module.exports = router;
<|endoftext|>


<commit_before>var assert = require('assert');

module.exports = function(app, db) {
    app.get('/:shorturl', function(request, response){
        var shorturl = parseInt(request.params.shorturl);
        console.log("shorturl was requested.", shorturl);
        // check if url is in the database
        db.collection('urls').find({ "_id": shorturl }).toArray(function(err, docs) {
                assert.equal(err, null);
                // if not in the database respond with error
                if (docs.length == 0) {
                    response.status(404).json({ error: "short URL invalid"});
                }
                // if it is in the database then respond with the result
                else {
                    response.redirect(docs[0].long_url);
                }

            });

    });
};<commit_msg>Update forwarder methods<commit_after>var assert = require('assert');

module.exports = function(app, db) {
    app.get('/:shorturl', function(request, response){
        var shorturl = parseInt(request.params.shorturl);
        console.log("shorturl was requested.", shorturl);
        // check if url is in the database
        db.collection('urls').find({ "_id": shorturl }).toArray(function(err, docs) {
                assert.equal(err, null);
                // if not in the database respond with error
                if (docs.length == 0) {
                    console.log("No record found for ", shorturl);
                    response.status(404).json({ error: "short URL invalid"});
                }
                // if it is in the database then respond with the result
                else {
                    console.log("Redirecting to ", docs[0].original);
                    response.redirect(docs[0].original);
                }

            });

    });
};<|endoftext|>


<commit_before>$(document).ready(function (){

  for (var project in projects) {
  if (projects.hasOwnProperty(project)) {
     $('#layout').append(`
         <div id="`+project+`">
           <h3 class="`+project+`_close" style="text-align:right; cursor:pointer; padding-right:0.3em">

`+projects[project].dispname+`

               <video class="video_tag" controls preload="metadata">
                 <source src="resources/`+projects[project].video+`" type="video/mp4">
               </video>

Description

`+projects[project].desc+`

Possible Improvements

`+projects[project].improvements+`

Technologies Used

`+projects[project].technologies+`

                 <a class="pure-button button-nav" target="_blank" id="github-icon" href="`+projects[project].github+`">

`)

      $('#'+project).popup({
        color: 'white',
        opacity: 1,
        transition: '0.3s',
        scrolllock: true
      });
  }
}

$( "#accordion" ).accordion({
  collapsible: true,
  heightStyle: "content",
  active: false
});

var keys = {37: 1, 38: 1, 39: 1, 40: 1};

function preventDefault(e) {
  e = e || window.event;
  if (e.preventDefault)
      e.preventDefault();
  e.returnValue = false;
}

function preventDefaultForScrollKeys(e) {
    if (keys[e.keyCode]) {
        preventDefault(e);
        return false;
    }
}

function disableScroll() {
  if (window.addEventListener) // older FF
      window.addEventListener('DOMMouseScroll', preventDefault, false);
  window.onwheel = preventDefault; // modern standard
  window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE
  window.ontouchmove  = preventDefault; // mobile
  document.onkeydown  = preventDefaultForScrollKeys;
}

function enableScroll() {
    if (window.removeEventListener)
        window.removeEventListener('DOMMouseScroll', preventDefault, false);
    window.onmousewheel = document.onmousewheel = null;
    window.onwheel = null;
    window.ontouchmove = null;
    document.onkeydown = null;
}

var scrollsections = ["about","projects","resume","contact"]

for(var i = 0; i < scrollsections.length; i++) {

  $("#"+scrollsections[i]+"-button").click(function (){
          if(this.id == "resume-button") {
            $("#accordion").accordion("option", "active", 0);
          }

          disableScroll();
          $('html, body').stop().animate({
              scrollTop: $("#"+this.id.replace("-button","")).offset().top
          }, 2000, function() {
            enableScroll();
          });

      });
}

$("#send-button").click(function() {
    console.log($('#name').val());
        database.ref("messages/"+Date.now()).set({
          name: $('#name').val(),
          email: $('#email').val(),
          message: $('#message').val()
        });
});
enableScroll();
});
<commit_msg>update<commit_after>$(document).ready(function (){

  for (var project in projects) {
  if (projects.hasOwnProperty(project)) {
     $('#layout').append(`
         <div id="`+project+`">
           <h3 class="`+project+`_close" style="text-align:right; cursor:pointer; padding-right:0.3em">

`+projects[project].dispname+`

               <video class="video_tag" controls preload="metadata">
                 <source src="resources/`+projects[project].video+`" type="video/mp4">
               </video>

Description

`+projects[project].desc+`

Possible Improvements

`+projects[project].improvements+`

Technologies Used

`+projects[project].technologies+`

                 <a class="pure-button button-nav" target="_blank" id="github-icon" href="`+projects[project].github+`">

`)

      $('#'+project).popup({
        color: 'white',
        opacity: 1,
        transition: '0.3s',
        scrolllock: true
      });
  }
}

$( "#accordion" ).accordion({
  collapsible: true,
  heightStyle: "content",
  active: false
});

var keys = {37: 1, 38: 1, 39: 1, 40: 1};

function preventDefault(e) {
  e = e || window.event;
  if (e.preventDefault)
      e.preventDefault();
  e.returnValue = false;
}

function preventDefaultForScrollKeys(e) {
    if (keys[e.keyCode]) {
        preventDefault(e);
        return false;
    }
}

function disableScroll() {
  if (window.addEventListener) // older FF
      window.addEventListener('DOMMouseScroll', preventDefault, false);
  window.onwheel = preventDefault; // modern standard
  window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE
  window.ontouchmove  = preventDefault; // mobile
  document.onkeydown  = preventDefaultForScrollKeys;
}

function enableScroll() {
    if (window.removeEventListener)
        window.removeEventListener('DOMMouseScroll', preventDefault, false);
    window.onmousewheel = document.onmousewheel = null;
    window.onwheel = null;
    window.ontouchmove = null;
    document.onkeydown = null;
}

var scrollsections = ["about","projects","resume","contact"]

for(var i = 0; i < scrollsections.length; i++) {

  $("#"+scrollsections[i]+"-button").click(function (event){
          current_id = jQuery(this).attr("id")
          console.log(current_id)
          if(current_id == "resume-button") {
            $("#accordion").accordion("option", "active", 0);
          }

          disableScroll();
          $('html, body').stop().animate({
              scrollTop: $("#"+current_id.replace("-button","")).offset().top
          }, 2000, function() {
            enableScroll();
          });

      });
}

$("#send-button").click(function() {
    console.log($('#name').val());
        database.ref("messages/"+Date.now()).set({
          name: $('#name').val(),
          email: $('#email').val(),
          message: $('#message').val()
        });
});
enableScroll();
});
<|endoftext|>