<commit_before>'use strict';

// require modules
var tessel = require('tessel');
var ambientlib = require('ambient-attx4');
var Neopixels = require('neopixels');

// initializing modules
var ambient = ambientlib.use(tessel.port.B);
var neopixels = new Neopixels();

// setting constants
var leds = 60;
var triggerDelay = 10;
var threshold = 0.01;
var color = {
  off: [0x00, 0x00, 0x00],
  blue: [0x00, 0x00, 0xFF],
  green: [0x00, 0xFF, 0x00],
  red: [0xFF, 0x00, 0x00]
};
var currentColor = color.off;

// set all LEDs off
neopixels.animate( leds, Buffer.concat(setAll(leds, color.off)) );

// when ready
ambient.on('ready', function () {
  // Set a sound level trigger float between 0 and 1
  ambient.setSoundTrigger(threshold);

  ambient.on('sound-trigger', function(data) {
    console.log('Something happened with sound: ', data);
    var newColor = convertColor(data);
    neopixels.animate( leds, Buffer.concat(setAll(leds, newColor)) );
  });

  // Clear it
  ambient.clearSoundTrigger();

  //After delay reset sound trigger
  setTimeout(function () {
    ambient.setSoundTrigger(threshold);
  }, triggerDelay);
});

// error logging
ambient.on('error', function (err) {
  console.log(err);
});

// set leds to color
function setAll (numLEDs, color) {
  var buf = new Buffer(numLEDs * 3);
  for (var i = 0; i < buf.length; i += 3) {
    buf[i] = color[0];
    buf[i+1] = color[1];
    buf[i+2] = color[2];
  }
  currentColor = color;
  return [buf];
}

function convertColor (decimal) {
  var max = 0.1;
  var halfway = max / 2;
  var output = [0x00, 0x00, 0x00]; // RGB off
  decimal = decimal > 1 ? 1 : decimal;
  if ( decimal === halfway ) {
    output[1] = 0xFF; // G
  } else if ( decimal > halfway ) {
    output[0] = (decimal-halfway)/(halfway) * 0xFF; // R
    output[1] = 0xFF - output[0]; // G
  } else {
    output[1] = decimal / halfway * 0xFF; // G
    output[2] = 0xFF - output[1]; // B
  }
  return output;
}
<commit_msg>slight refactoring of visualizer.js<commit_after>'use strict';

// require modules
var tessel = require('tessel');
var ambientlib = require('ambient-attx4');
var Neopixels = require('neopixels');

// initializing modules
var ambient = ambientlib.use(tessel.port.B);
var neopixels = new Neopixels();

// setting constants
var leds = 60;
var triggerDelay = 10;
var threshold = 0.01;
var color = {
  off: [0x00, 0x00, 0x00],
  green: [0xFF, 0x00, 0x00],
  red: [0x00, 0xFF, 0x00],
  blue: [0x00, 0x00, 0xFF],
  purple: [0x00, 0xFF, 0xFF],
  yellow: [0xFF, 0xFF, 0x00],
  cyan: [0xFF, 0x00, 0xFF]
};
var currentColor = color.off;

// set all LEDs off
neopixels.animate( leds, Buffer.concat(setAll(leds, color.off)) );

// when ready
ambient.on('ready', function () {
  // ready animation for fun
  neopixels.animate( leds, Buffer.concat(tracer(leds)) );
  // Set a sound level trigger float between 0 and 1
  ambient.setSoundTrigger(threshold);

  ambient.on('sound-trigger', function(data) {
    console.log('Tripped sound threshold at level ', data);

    var newColor = convertColor(data);
    neopixels.animate( leds, Buffer.concat(setAll(leds, newColor)) );

    // Clear it
    ambient.clearSoundTrigger();

    //After delay reset sound trigger
    setTimeout(function () {
      ambient.setSoundTrigger(threshold);
    }, triggerDelay);
  });
});

// error logging
ambient.on('error', function (err) {
  console.log(err);
});

function convertColor (decimal) {
  var max = 0.1;
  var halfway = max / 2;
  var output = [0x00, 0x00, 0x00]; // RGB off
  decimal = decimal > 1 ? 1 : decimal;
  if ( decimal === halfway ) {
    output[1] = 0xFF; // G
  } else if ( decimal > halfway ) {
    output[0] = (decimal-halfway)/(halfway) * 0xFF; // R
    output[1] = 0xFF - output[0]; // G
  } else {
    output[1] = decimal / halfway * 0xFF; // G
    output[2] = 0xFF - output[1]; // B
  }
  return output;
}

// set leds to color
function setAll (numLEDs, color) {
  var buf = new Buffer(numLEDs * 3);
  for (var i = 0; i < buf.length; i += 3) {
    buf[i] = color[0];
    buf[i+1] = color[1];
    buf[i+2] = color[2];
  }
  currentColor = color;
  return [buf];
}

// An example animation
function tracer(numLEDs) {
  var trail = 20;
  var arr = new Array(numLEDs);
  for (var i = 0; i < numLEDs; i++) {
    var buf = new Buffer(numLEDs * 3);
    buf.fill(0);
    for (var col = 0; col < 3; col++){
      for (var k = 0; k < trail; k++) {
        buf[(3*(i+numLEDs*col/3)+col+1 +3*k)] = 0xFF*(trail-k)/trail;
      }
    }
    arr[i] = buf;
  }
  var newArr = [];
  for (var i = 0; i < arr.length; i++) {
    newArr.push(arr[i]);
    newArr.push(arr[i]);
    newArr.push(arr[i]);
    newArr.push(arr[i]);
    newArr.push(arr[i]);
    newArr.push(arr[i]);
  }
  return newArr;
}
<|endoftext|>


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

'use strict';
require('v8-compile-cache');
const importLocal = require('import-local');
const parseArgs = require('../lib/utils/parse-args');
const runner = require('../lib/runner');

// Prefer the local installation of webpack-cli
if (importLocal(__filename)) {
    // return;
}
process.title = 'webpack';

const [, , ...rawArgs] = process.argv;
const { cliArgs, nodeArgs } = parseArgs(rawArgs);

runner(nodeArgs, cliArgs);
<commit_msg>fix(webpack-cli): prefer import local (#1345)<commit_after>#!/usr/bin/env node

'use strict';
require('v8-compile-cache');
const importLocal = require('import-local');
const parseArgs = require('../lib/utils/parse-args');
const runner = require('../lib/runner');

// Prefer the local installation of webpack-cli
if (importLocal(__filename)) {
    return;
}
process.title = 'webpack';

const [, , ...rawArgs] = process.argv;
const { cliArgs, nodeArgs } = parseArgs(rawArgs);

runner(nodeArgs, cliArgs);
<|endoftext|>


<commit_before><commit_msg>Update wo.js<commit_after><|endoftext|>


<commit_before>const config = require('config')
const uuid = require('uuid')
const Twitter = require('twitter')
const User = require('../../models/user.js')
const logger = require('../../../lib/logger.js')()

exports.post = function (req, res) {
  let loginToken = null
  const handleCreateUser = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Could not create user.')
      return
    }
    const userJson = { id: user.id, loginToken: loginToken }
    logger.info({ user: userJson }, 'New user created.')
    res.header('Location', config.restapi.baseuri + '/v1/users/' + user.id)
    res.status(201).send(userJson)
  } // END function - handleCreateUser

  const handleUpdateUser = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Could not update user.')
      return
    }

    const userJson = { id: user.id, loginToken: loginToken }
    logger.info({ user: userJson }, 'Existing user issued new login token.')

    res.header('Location', config.restapi.baseuri + '/v1/users/' + user.id)
    res.status(200).send(userJson)
  } // END function - handleUpdateUser

  const handleAuth0TwitterSignIn = function (credentials) {
    const handleFindUser = function (err, user) {
      if (err) {
        logger.error(err)
        res.status(500).send('Error finding user with Auth0 ID.')
        return
      }

      loginToken = uuid.v1()
      if (!user) {
        const u = new User({
          id: credentials.screenName,
          auth0_id: credentials.auth0_id,
          login_tokens: [ loginToken ],
          profile_image_url: credentials.profile_image_url
        })
        u.save(handleCreateUser)
      } else {
        user.id = credentials.screenName
        user.auth0_id = credentials.auth0_id
        user.profile_image_url = credentials.profile_image_url
        user.login_tokens.push(loginToken)
        user.save(handleUpdateUser)
      }
    } // END function - handleFindUser

    User.findOne({ id: credentials.screenName }, handleFindUser)
  } // END function - handleAuth0TwitterSignIn

  const handleTwitterSignIn = function (twitterCredentials) {
    // TODO: Call Twitter API with OAuth access credentials to make sure they are valid
    const handleFindUser = function (err, user) {
      if (err) {
        logger.error(err)
        res.status(500).send('Error finding user with Twitter ID.')
        return
      }
      loginToken = uuid.v1()
      if (!user) {
        const u = new User({
          id: twitterCredentials.screenName,
          twitter_id: twitterCredentials.userId,
          twitter_credentials: {
            access_token_key: twitterCredentials.oauthAccessTokenKey,
            access_token_secret: twitterCredentials.oauthAccessTokenSecret
          },
          login_tokens: [ loginToken ]
        })
        u.save(handleCreateUser)
      } else {
        user.id = twitterCredentials.screenName
        user.twitter_id = twitterCredentials.userId
        user.twitter_credentials = {
          access_token_key: twitterCredentials.oauthAccessTokenKey,
          access_token_secret: twitterCredentials.oauthAccessTokenSecret
        }
        user.login_tokens.push(loginToken)
        user.save(handleUpdateUser)
      }
    } // END function - handleFindUser
    // Try to find user with twitter ID
    User.findOne({ twitter_id: twitterCredentials.userId }, handleFindUser)
  } // END function - handleTwitterSignIn

  /**
   * Returns a randomly-generated 4-digit string of a number between 0000 and 9999
   *
   * @returns {string}
   */
  const generateRandomId = () => Math.floor(Math.random() * 10000).toString().padStart(4, '0')

  const generateId = function (nickname) {
    // TODO - Check if the Id generated is not existing
    const id = generateRandomId()
    return nickname + '-' + id
  }

  const handleAuth0SignIn = async function (credentials) {
    try {
      const user = await User.findOne({ auth0_id: credentials.auth0_id })
      loginToken = uuid.v1()
      if (!user) {
        const numOfUser = await User.count({ id: credentials.nickname })
        // Ensure there is no existing user with id same this nickname
        if (numOfUser === 0) {
          const u = new User({
            id: credentials.nickname,
            auth0_id: credentials.auth0_id,
            email: credentials.email,
            login_tokens: [ loginToken ],
            profile_image_url: credentials.profile_image_url
          })
          u.save(handleCreateUser)
        } else {
          const id = generateId(credentials.nickname)
          const u = new User({
            id: id,
            auth0_id: credentials.auth0_id,
            email: credentials.email,
            login_tokens: [ loginToken ],
            profile_image_url: credentials.profile_image_url
          })
          u.save(handleCreateUser)
        }
      } else {
        user.auth0_id = credentials.auth0_id
        user.profile_image_url = credentials.profile_image_url
        user.email = credentials.email
        user.login_tokens.push(loginToken)
        user.save(handleUpdateUser)
      }
    } catch (err) {
      logger.error(err)
      console.log(err)
      res.status(500).send('Error finding user with Auth0 ID.')
    }
  } // END function - handleAuth0SignIn

  let body
  try {
    body = req.body
  } catch (e) {
    res.status(400).send('Could not parse body as JSON.')
    return
  }

  if (body.hasOwnProperty('twitter')) {
    handleTwitterSignIn(body.twitter)
  } else if (body.hasOwnProperty('auth0_twitter')) {
    handleAuth0TwitterSignIn(body.auth0_twitter)
  } else if (body.hasOwnProperty('auth0')) {
    handleAuth0SignIn(body.auth0)
  } else {
    res.status(400).send('Unknown sign-in method used.')
  }
} // END function - exports.post

exports.get = function (req, res) {
  const handleFindUserById = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Error finding user.')
      return
    }

    if (!user) {
      res.status(404).send('User not found.')
      return
    }

    let twitterApiClient
    try {
      twitterApiClient = new Twitter({
        consumer_key: config.twitter.oauth_consumer_key,
        consumer_secret: config.twitter.oauth_consumer_secret,
        access_token_key: user.twitter_credentials.access_token_key,
        access_token_secret: user.twitter_credentials.access_token_secret
      })
    } catch (e) {
      logger.error('Could not initialize Twitter API client. Error:')
      logger.error(e)
    }

    const sendUserJson = function (data) {
      const auth = (user.login_tokens.indexOf(req.loginToken) > 0)

      user.asJson({ auth: auth }, function (err, userJson) {
        if (err) {
          logger.error(err)
          res.status(500).send('Could not render user JSON.')
          return
        }

        if (data) {
          userJson.profileImageUrl = data.twitter_profile_image_url
        } else {
          userJson.profileImageUrl = user.profile_image_url
        }

        res.status(200).send(userJson)
      })
    } // END function - sendUserJson

    let responseAlreadySent = false

    const handleFetchUserProfileFromTwitter = function (err, res) {
      if (err) {
        logger.error('Twitter API call users/show returned error.')
        logger.error(err)
      }

      if (responseAlreadySent) {
        logger.debug({ profile_image_url: res.profile_image_url }, 'Twitter API users/show call returned but response already sent!')
      } else {
        logger.debug({ profile_image_url: res.profile_image_url }, 'Twitter API users/show call returned. Sending response with Twitter data.')
        responseAlreadySent = true

        if (!res) {
          logger.error('Twitter API call users/show did not return any data.')
        }

        sendUserJson({
          twitter_profile_image_url: res.picture
        })
      }
    } // END function - handleFetchUserProfileFromTwitter

    if (twitterApiClient && !user.profile_image_url) {
      logger.debug('About to call Twitter API: /users/show.json?user_id=' + user.twitter_id)
      twitterApiClient.get('/users/show.json', { user_id: user.twitter_id }, handleFetchUserProfileFromTwitter)
      setTimeout(function () {
        if (!responseAlreadySent) {
          logger.debug(`Timing out Twitter API call after %d milliseconds and sending partial response.`, config.twitter.timeout_ms)
          responseAlreadySent = true
          sendUserJson()
        }
      }, config.twitter.timeout_ms)
    } else {
      sendUserJson()
    }
  } // END function - handleFindUserById

  // Flag error if user ID is not provided
  if (!req.params.user_id) {
    res.status(400).send('Please provide user ID.')
    return
  }

  const userId = req.params.user_id

  const handleFindUserByLoginToken = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Error finding user.')
      return
    }

    if (!user) {
      res.status(401).send('User with that login token not found.')
      return
    }

    User.findOne({ id: userId }, handleFindUserById)
  } // END function - handleFindUserByLoginToken

  if (req.loginToken) {
    User.findOne({ login_tokens: { $in: [ req.loginToken ] } }, handleFindUserByLoginToken)
  } else {
    User.findOne({ id: userId }, handleFindUserById)
  }
} // END function - exports.get

exports.delete = function (req, res) {
  const handleSaveUser = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Could not sign-out user.')
      return
    }
    res.status(204).end()
  } // END function - handleSaveUser

  const handleFindUser = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Error finding user.')
      return
    }

    if (!user) {
      res.status(404).send('User not found.')
      return
    }

    const idx = user.login_tokens.indexOf(req.loginToken)
    if (idx === -1) {
      res.status(401).end()
      return
    }

    user.login_tokens.splice(idx, 1)
    user.save(handleSaveUser)
  } // END function - handleFindUser

  // Flag error if user ID is not provided
  if (!req.params.user_id) {
    res.status(400).send('Please provide user ID.')
    return
  }

  const userId = req.params.user_id
  User.findOne({ id: userId }, handleFindUser)
} // END function - exports.delete

exports.put = function (req, res) {
  let body
  try {
    body = req.body
  } catch (e) {
    res.status(400).send('Could not parse body as JSON.')
    return
  }

  const handleSaveUser = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Could not update user information.')
      return
    }
    res.status(204).end()
  } // END function - handleSaveUser

  const handleFindUser = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Error finding user.')
      return
    }

    if (!user) {
      res.status(404).send('User not found.')
      return
    }

    if (user.login_tokens.indexOf(req.loginToken) === -1) {
      res.status(401).end()
      return
    }

    user.data = body.data || user.data
    user.save(handleSaveUser)
  } // END function - handleFindUser

  // Flag error if user ID is not provided
  if (!req.params.user_id) {
    res.status(400).send('Please provide user ID.')
    return
  }

  const userId = req.params.user_id
  User.findOne({ id: userId }, handleFindUser)
} // END function - exports.put
<commit_msg>api/v1/users: adjust twitter error<commit_after>const config = require('config')
const uuid = require('uuid')
const Twitter = require('twitter')
const User = require('../../models/user.js')
const logger = require('../../../lib/logger.js')()

exports.post = function (req, res) {
  let loginToken = null
  const handleCreateUser = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Could not create user.')
      return
    }
    const userJson = { id: user.id, loginToken: loginToken }
    logger.info({ user: userJson }, 'New user created.')
    res.header('Location', config.restapi.baseuri + '/v1/users/' + user.id)
    res.status(201).send(userJson)
  } // END function - handleCreateUser

  const handleUpdateUser = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Could not update user.')
      return
    }

    const userJson = { id: user.id, loginToken: loginToken }
    logger.info({ user: userJson }, 'Existing user issued new login token.')

    res.header('Location', config.restapi.baseuri + '/v1/users/' + user.id)
    res.status(200).send(userJson)
  } // END function - handleUpdateUser

  const handleAuth0TwitterSignIn = function (credentials) {
    const handleFindUser = function (err, user) {
      if (err) {
        logger.error(err)
        res.status(500).send('Error finding user with Auth0 ID.')
        return
      }

      loginToken = uuid.v1()
      if (!user) {
        const u = new User({
          id: credentials.screenName,
          auth0_id: credentials.auth0_id,
          login_tokens: [ loginToken ],
          profile_image_url: credentials.profile_image_url
        })
        u.save(handleCreateUser)
      } else {
        user.id = credentials.screenName
        user.auth0_id = credentials.auth0_id
        user.profile_image_url = credentials.profile_image_url
        user.login_tokens.push(loginToken)
        user.save(handleUpdateUser)
      }
    } // END function - handleFindUser

    User.findOne({ id: credentials.screenName }, handleFindUser)
  } // END function - handleAuth0TwitterSignIn

  const handleTwitterSignIn = function (twitterCredentials) {
    // TODO: Call Twitter API with OAuth access credentials to make sure they are valid
    const handleFindUser = function (err, user) {
      if (err) {
        logger.error(err)
        res.status(500).send('Error finding user with Twitter ID.')
        return
      }
      loginToken = uuid.v1()
      if (!user) {
        const u = new User({
          id: twitterCredentials.screenName,
          twitter_id: twitterCredentials.userId,
          twitter_credentials: {
            access_token_key: twitterCredentials.oauthAccessTokenKey,
            access_token_secret: twitterCredentials.oauthAccessTokenSecret
          },
          login_tokens: [ loginToken ]
        })
        u.save(handleCreateUser)
      } else {
        user.id = twitterCredentials.screenName
        user.twitter_id = twitterCredentials.userId
        user.twitter_credentials = {
          access_token_key: twitterCredentials.oauthAccessTokenKey,
          access_token_secret: twitterCredentials.oauthAccessTokenSecret
        }
        user.login_tokens.push(loginToken)
        user.save(handleUpdateUser)
      }
    } // END function - handleFindUser
    // Try to find user with twitter ID
    User.findOne({ twitter_id: twitterCredentials.userId }, handleFindUser)
  } // END function - handleTwitterSignIn

  /**
   * Returns a randomly-generated 4-digit string of a number between 0000 and 9999
   *
   * @returns {string}
   */
  const generateRandomId = () => Math.floor(Math.random() * 10000).toString().padStart(4, '0')

  const generateId = function (nickname) {
    // TODO - Check if the Id generated is not existing
    const id = generateRandomId()
    return nickname + '-' + id
  }

  const handleAuth0SignIn = async function (credentials) {
    try {
      const user = await User.findOne({ auth0_id: credentials.auth0_id })
      loginToken = uuid.v1()
      if (!user) {
        const numOfUser = await User.count({ id: credentials.nickname })
        // Ensure there is no existing user with id same this nickname
        if (numOfUser === 0) {
          const u = new User({
            id: credentials.nickname,
            auth0_id: credentials.auth0_id,
            email: credentials.email,
            login_tokens: [ loginToken ],
            profile_image_url: credentials.profile_image_url
          })
          u.save(handleCreateUser)
        } else {
          const id = generateId(credentials.nickname)
          const u = new User({
            id: id,
            auth0_id: credentials.auth0_id,
            email: credentials.email,
            login_tokens: [ loginToken ],
            profile_image_url: credentials.profile_image_url
          })
          u.save(handleCreateUser)
        }
      } else {
        user.auth0_id = credentials.auth0_id
        user.profile_image_url = credentials.profile_image_url
        user.email = credentials.email
        user.login_tokens.push(loginToken)
        user.save(handleUpdateUser)
      }
    } catch (err) {
      logger.error(err)
      console.log(err)
      res.status(500).send('Error finding user with Auth0 ID.')
    }
  } // END function - handleAuth0SignIn

  let body
  try {
    body = req.body
  } catch (e) {
    res.status(400).send('Could not parse body as JSON.')
    return
  }

  if (body.hasOwnProperty('twitter')) {
    handleTwitterSignIn(body.twitter)
  } else if (body.hasOwnProperty('auth0_twitter')) {
    handleAuth0TwitterSignIn(body.auth0_twitter)
  } else if (body.hasOwnProperty('auth0')) {
    handleAuth0SignIn(body.auth0)
  } else {
    res.status(400).send('Unknown sign-in method used.')
  }
} // END function - exports.post

exports.get = function (req, res) {
  const handleFindUserById = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Error finding user.')
      return
    }

    if (!user) {
      res.status(404).send('User not found.')
      return
    }

    let twitterApiClient

    try {
      twitterApiClient = new Twitter({
        consumer_key: config.twitter.oauth_consumer_key,
        consumer_secret: config.twitter.oauth_consumer_secret,
        access_token_key: user.twitter_credentials.access_token_key,
        access_token_secret: user.twitter_credentials.access_token_secret
      })
    } catch (error) {
      logger.error('Could not initialize Twitter API client: ' + error)
    }

    const sendUserJson = function (data) {
      const auth = (user.login_tokens.indexOf(req.loginToken) > 0)

      user.asJson({ auth: auth }, function (err, userJson) {
        if (err) {
          logger.error(err)
          res.status(500).send('Could not render user JSON.')
          return
        }

        if (data) {
          userJson.profileImageUrl = data.twitter_profile_image_url
        } else {
          userJson.profileImageUrl = user.profile_image_url
        }

        res.status(200).send(userJson)
      })
    } // END function - sendUserJson

    let responseAlreadySent = false

    const handleFetchUserProfileFromTwitter = function (err, res) {
      if (err) {
        logger.error('Twitter API call users/show returned error.')
        logger.error(err)
      }

      if (responseAlreadySent) {
        logger.debug({ profile_image_url: res.profile_image_url }, 'Twitter API users/show call returned but response already sent!')
      } else {
        logger.debug({ profile_image_url: res.profile_image_url }, 'Twitter API users/show call returned. Sending response with Twitter data.')
        responseAlreadySent = true

        if (!res) {
          logger.error('Twitter API call users/show did not return any data.')
        }

        sendUserJson({
          twitter_profile_image_url: res.picture
        })
      }
    } // END function - handleFetchUserProfileFromTwitter

    if (twitterApiClient && !user.profile_image_url) {
      logger.debug('About to call Twitter API: /users/show.json?user_id=' + user.twitter_id)
      twitterApiClient.get('/users/show.json', { user_id: user.twitter_id }, handleFetchUserProfileFromTwitter)
      setTimeout(function () {
        if (!responseAlreadySent) {
          logger.debug(`Timing out Twitter API call after %d milliseconds and sending partial response.`, config.twitter.timeout_ms)
          responseAlreadySent = true
          sendUserJson()
        }
      }, config.twitter.timeout_ms)
    } else {
      sendUserJson()
    }
  } // END function - handleFindUserById

  // Flag error if user ID is not provided
  if (!req.params.user_id) {
    res.status(400).send('Please provide user ID.')
    return
  }

  const userId = req.params.user_id

  const handleFindUserByLoginToken = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Error finding user.')
      return
    }

    if (!user) {
      res.status(401).send('User with that login token not found.')
      return
    }

    User.findOne({ id: userId }, handleFindUserById)
  } // END function - handleFindUserByLoginToken

  if (req.loginToken) {
    User.findOne({ login_tokens: { $in: [ req.loginToken ] } }, handleFindUserByLoginToken)
  } else {
    User.findOne({ id: userId }, handleFindUserById)
  }
} // END function - exports.get

exports.delete = function (req, res) {
  const handleSaveUser = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Could not sign-out user.')
      return
    }
    res.status(204).end()
  } // END function - handleSaveUser

  const handleFindUser = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Error finding user.')
      return
    }

    if (!user) {
      res.status(404).send('User not found.')
      return
    }

    const idx = user.login_tokens.indexOf(req.loginToken)
    if (idx === -1) {
      res.status(401).end()
      return
    }

    user.login_tokens.splice(idx, 1)
    user.save(handleSaveUser)
  } // END function - handleFindUser

  // Flag error if user ID is not provided
  if (!req.params.user_id) {
    res.status(400).send('Please provide user ID.')
    return
  }

  const userId = req.params.user_id
  User.findOne({ id: userId }, handleFindUser)
} // END function - exports.delete

exports.put = function (req, res) {
  let body
  try {
    body = req.body
  } catch (e) {
    res.status(400).send('Could not parse body as JSON.')
    return
  }

  const handleSaveUser = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Could not update user information.')
      return
    }
    res.status(204).end()
  } // END function - handleSaveUser

  const handleFindUser = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Error finding user.')
      return
    }

    if (!user) {
      res.status(404).send('User not found.')
      return
    }

    if (user.login_tokens.indexOf(req.loginToken) === -1) {
      res.status(401).end()
      return
    }

    user.data = body.data || user.data
    user.save(handleSaveUser)
  } // END function - handleFindUser

  // Flag error if user ID is not provided
  if (!req.params.user_id) {
    res.status(400).send('Please provide user ID.')
    return
  }

  const userId = req.params.user_id
  User.findOne({ id: userId }, handleFindUser)
} // END function - exports.put
<|endoftext|>


<commit_before>var ConfigurationReader = require('../../../lib/utilities/configuration-reader');
var expect = require('chai').expect;
var path = require('path');
var MockUI = require('ember-cli/tests/helpers/mock-ui');
var Promise = require('ember-cli/lib/ext/promise');
var EOL    = require('os').EOL;
var chalk  = require('chalk');

describe('ConfigurationReader', function() {
  var ui, project;

  beforeEach(function() {
    ui = new MockUI();
    project = { name: function(){ return 'foo'; }}
  });

  describe('environment settings', function() {
    it('knows about its passed environment', function() {
      var reader = new ConfigurationReader({
        environment: 'staging',
        ui: ui,
        project: project
      });

      expect(reader.environment).to.equal('staging');
    });

    it('`development` is default when no environment is passed', function() {
      var reader = new ConfigurationReader({
        ui: ui,
        project: project
      });

      expect(reader.environment).to.equal('development');
    });
  });

  describe('configuration settings', function() {
    it('throws an error when  passed a json deploy-config-file', function() {
      var configPath        = './node-tests/fixtures/config/deploy.json';
      var root              = process.cwd();
      var fixtureConfigPath = path.join(root, configPath);
      var expectedConfig    = require(fixtureConfigPath);

      return new ConfigurationReader({
        configFile: configPath,
        ui: ui,
        project: project
      }).read().then(function(){
        expect(false).to.equal(true);
      }, function(err){
        expect(err.message).to.match(/Cannot load configuration file/);
      });
    });

    it('reads a passed js deploy-config-file if one is passed', function() {
      var configPath        = './node-tests/fixtures/config/deploy.js';
      var root              = process.cwd();
      var fixtureConfigPath = path.join(root, configPath);
      var expectedConfig    = require(fixtureConfigPath)('development');

      return new ConfigurationReader({
        configFile: configPath,
        ui: ui,
        project: project
      }).read().then(function(config){
        expect(config._config).to.eql(expectedConfig);
      });
    });

    it('uses `./config/deploy.js` as default when no config is passed', function() {
      var root           = process.cwd();
      var expectedConfig = require(path.join(root, './config/deploy.js'))('development');

      return new ConfigurationReader({
        ui: ui,
        project: project
      }).read().then(function(config){
        expect(config._config).to.eql(expectedConfig)
      });

    });

    it('raises an error in the case of a passed deploy-config-file that doesn\'t exist', function() {
      var configPath        = './node-tests/fixtures/config/does-not-exist.js';
      var root              = process.cwd();
      return new ConfigurationReader({
        configFile: configPath,
        ui: ui,
        project: project
      }).read().then(function(){
        expect(false).to.equal(true);
      }, function(err){
        expect(err.message).to.equal('Cannot load configuration file \'' + path.join(root, configPath) + '\'. Note that the default location of the ember-cli-deploy config file is now \'config/deploy.js\'');
      });
    });

    it('raises an error if a config doesn\'t exist for the current environment', function() {
      var configPath = './node-tests/fixtures/config/deploy.js';
      return new ConfigurationReader({
        configFile: configPath,
        ui: ui,
        project: project,
        environment: 'non-existent-env'
      }).read().then(function(){
        expect(false).to.equal(true);
      }, function(err){
        expect(err.message).to.match(/You are using the `non-existent-env` environment/);
      });
    });
  });

  describe('store settings', function() {
    it('proxies the store settings for the passed environment', function() {
      var ENVs    = ['development', 'staging'];
      var root    = process.cwd();
      var cfgFile = require(path.join(root, './node-tests/fixtures/config/deploy.js'));

      return Promise.map(ENVs, function(env) {
        var expected = cfgFile(env).store;

        return new ConfigurationReader({
          environment: env,
          ui: ui,
          project: project
        }).read().then(function(config){
          expect(config.get('store')).to.deep.equal(expected);
        });
      });
    });
  });

  describe('assets settings', function() {
    it('proxies the asset setting for the passed environment', function() {
      var ENVs    = ['development', 'staging'];
      var root    = process.cwd();
      var cfgFile = require(path.join(root, './node-tests/fixtures/config/deploy.js'));

      return Promise.map(ENVs, function(env) {
        var expected = cfgFile(env).assets;

        return new ConfigurationReader({
          environment: env,
          ui: ui,
          project: project
        }).read().then(function(config){
          expect(config.get('assets')).to.deep.equal(expected);
        });
      });
    });
  });

  describe('materialized settings', function() {
    it('proxies the materialized settings for the passed environment', function() {
      var ENVs    = ['development', 'staging'];
      var root    = process.cwd();
      var cfgFile = require(path.join(root, './node-tests/fixtures/config-with-defaults/deploy.js'));

      return Promise.map(ENVs, function(ENV) {
        var expected = cfgFile[ENV];

        return new ConfigurationReader({
          environment: ENV,
          ui: ui,
          project: project
        }).read().then(function(config){
          expect(config._materialize()).to.deep.equal(expected);
        });
      });
    });
  })

});
<commit_msg>fix failing test on windows caused by path.join returning backslashes for the path<commit_after>var ConfigurationReader = require('../../../lib/utilities/configuration-reader');
var expect = require('chai').expect;
var path = require('path');
var MockUI = require('ember-cli/tests/helpers/mock-ui');
var Promise = require('ember-cli/lib/ext/promise');
var EOL    = require('os').EOL;
var chalk  = require('chalk');

describe('ConfigurationReader', function() {
  var ui, project;

  beforeEach(function() {
    ui = new MockUI();
    project = { name: function(){ return 'foo'; }}
  });

  describe('environment settings', function() {
    it('knows about its passed environment', function() {
      var reader = new ConfigurationReader({
        environment: 'staging',
        ui: ui,
        project: project
      });

      expect(reader.environment).to.equal('staging');
    });

    it('`development` is default when no environment is passed', function() {
      var reader = new ConfigurationReader({
        ui: ui,
        project: project
      });

      expect(reader.environment).to.equal('development');
    });
  });

  describe('configuration settings', function() {
    it('throws an error when  passed a json deploy-config-file', function() {
      var configPath        = './node-tests/fixtures/config/deploy.json';
      var root              = process.cwd();
      var fixtureConfigPath = path.join(root, configPath);
      var expectedConfig    = require(fixtureConfigPath);

      return new ConfigurationReader({
        configFile: configPath,
        ui: ui,
        project: project
      }).read().then(function(){
        expect(false).to.equal(true);
      }, function(err){
        expect(err.message).to.match(/Cannot load configuration file/);
      });
    });

    it('reads a passed js deploy-config-file if one is passed', function() {
      var configPath        = './node-tests/fixtures/config/deploy.js';
      var root              = process.cwd();
      var fixtureConfigPath = path.join(root, configPath);
      var expectedConfig    = require(fixtureConfigPath)('development');

      return new ConfigurationReader({
        configFile: configPath,
        ui: ui,
        project: project
      }).read().then(function(config){
        expect(config._config).to.eql(expectedConfig);
      });
    });

    it('uses `./config/deploy.js` as default when no config is passed', function() {
      var root           = process.cwd();
      var expectedConfig = require(path.join(root, './config/deploy.js'))('development');

      return new ConfigurationReader({
        ui: ui,
        project: project
      }).read().then(function(config){
        expect(config._config).to.eql(expectedConfig)
      });

    });

    it('raises an error in the case of a passed deploy-config-file that doesn\'t exist', function() {
      var configPath        = './node-tests/fixtures/config/does-not-exist.js';
      var root              = process.cwd();
      return new ConfigurationReader({
        configFile: configPath,
        ui: ui,
        project: project
      }).read().then(function(){
        expect(false).to.equal(true);
      }, function(err){
        expect(err.message).to.equal('Cannot load configuration file \'' + path.join(root, configPath) + '\'. Note that the default location of the ember-cli-deploy config file is now \''+ path.join('config', 'deploy.js')+'\'');
      });
    });

    it('raises an error if a config doesn\'t exist for the current environment', function() {
      var configPath = './node-tests/fixtures/config/deploy.js';
      return new ConfigurationReader({
        configFile: configPath,
        ui: ui,
        project: project,
        environment: 'non-existent-env'
      }).read().then(function(){
        expect(false).to.equal(true);
      }, function(err){
        expect(err.message).to.match(/You are using the `non-existent-env` environment/);
      });
    });
  });

  describe('store settings', function() {
    it('proxies the store settings for the passed environment', function() {
      var ENVs    = ['development', 'staging'];
      var root    = process.cwd();
      var cfgFile = require(path.join(root, './node-tests/fixtures/config/deploy.js'));

      return Promise.map(ENVs, function(env) {
        var expected = cfgFile(env).store;

        return new ConfigurationReader({
          environment: env,
          ui: ui,
          project: project
        }).read().then(function(config){
          expect(config.get('store')).to.deep.equal(expected);
        });
      });
    });
  });

  describe('assets settings', function() {
    it('proxies the asset setting for the passed environment', function() {
      var ENVs    = ['development', 'staging'];
      var root    = process.cwd();
      var cfgFile = require(path.join(root, './node-tests/fixtures/config/deploy.js'));

      return Promise.map(ENVs, function(env) {
        var expected = cfgFile(env).assets;

        return new ConfigurationReader({
          environment: env,
          ui: ui,
          project: project
        }).read().then(function(config){
          expect(config.get('assets')).to.deep.equal(expected);
        });
      });
    });
  });

  describe('materialized settings', function() {
    it('proxies the materialized settings for the passed environment', function() {
      var ENVs    = ['development', 'staging'];
      var root    = process.cwd();
      var cfgFile = require(path.join(root, './node-tests/fixtures/config-with-defaults/deploy.js'));

      return Promise.map(ENVs, function(ENV) {
        var expected = cfgFile[ENV];

        return new ConfigurationReader({
          environment: ENV,
          ui: ui,
          project: project
        }).read().then(function(config){
          expect(config._materialize()).to.deep.equal(expected);
        });
      });
    });
  })

});
<|endoftext|>


<commit_before>// @flow
import Container from '../../forms/container'
import React, {Component} from 'react'
import type {Props} from './index.render'
import {Box, Button, Icon, Input, Text} from '../../../common-adapters'
import {globalMargins, globalStyles} from '../../../styles'

class PaperKeyRender extends Component<void, Props, void> {
  render () {
    return (
      <Box style={stylesBox}>
        <Container
          style={stylesContainer}
          onBack={this.props.onBack}>
          <Text type='Header' style={stylesHeader}>Type in your paper key:</Text>
          <Icon type='icon-paper-key-48' style={stylesIcon} />
          <Input
            autoCorrect={true}
            autoFocus={true}
            style={stylesInput}
            floatingLabelText='Paper key'
            hintText='opp blezzard tofi pando'
            errorText={this.props.error}
            onEnterKeyDown={() => this.props.onSubmit()}
            onChangeText={paperKey => this.props.onChangePaperKey(paperKey)}
            type='passwordVisible'
            value={this.props.paperKey ? this.props.paperKey : null} />
          <Button
            style={stylesButton}
            type='Primary'
            fullWidth={true}
            enabled={this.props.paperKey}
            label='Continue'
            waiting={this.props.waitingForResponse}
            onClick={() => this.props.onSubmit()} />
        </Container>
      </Box>
    )
  }
}

const stylesBox = {
  ...globalStyles.flexBoxColumn,
  padding: 10,
}

const stylesContainer = {
  alignItems: 'center',
}

const stylesButton = {
  marginTop: globalMargins.medium,
  marginBottom: 20,
}

const stylesInput = {
  alignSelf: 'stretch',
  height: 80,
}

const stylesIcon = {
  marginTop: 30,
}

const stylesHeader = {
  marginTop: globalMargins.small,
}

export default PaperKeyRender
<commit_msg>Try multiline paper key<commit_after>// @flow
import Container from '../../forms/container'
import React, {Component} from 'react'
import type {Props} from './index.render'
import {Box, Button, Icon, Input, Text} from '../../../common-adapters'
import {globalMargins, globalStyles} from '../../../styles'

class PaperKeyRender extends Component<void, Props, void> {
  render () {
    return (
      <Box style={stylesBox}>
        <Container
          style={stylesContainer}
          onBack={this.props.onBack}>
          <Text type='Header' style={stylesHeader}>Type in your paper key:</Text>
          <Icon type='icon-paper-key-48' style={stylesIcon} />
          <Input
            multiline={true}
            rows={2}
            autoCorrect={true}
            autoFocus={true}
            style={stylesInput}
            floatingLabelText='Paper key'
            hintText='opp blezzard tofi pando'
            errorText={this.props.error}
            onEnterKeyDown={() => this.props.onSubmit()}
            onChangeText={paperKey => this.props.onChangePaperKey(paperKey)}
            type='passwordVisible'
            value={this.props.paperKey ? this.props.paperKey : null} />
          <Button
            style={stylesButton}
            type='Primary'
            fullWidth={true}
            enabled={this.props.paperKey}
            label='Continue'
            waiting={this.props.waitingForResponse}
            onClick={() => this.props.onSubmit()} />
        </Container>
      </Box>
    )
  }
}

const stylesBox = {
  ...globalStyles.flexBoxColumn,
  padding: 10,
}

const stylesContainer = {
  alignItems: 'center',
}

const stylesButton = {
  marginTop: globalMargins.medium,
  marginBottom: 20,
}

const stylesInput = {
  alignSelf: 'stretch',
  height: 80,
}

const stylesIcon = {
  marginTop: 30,
}

const stylesHeader = {
  marginTop: globalMargins.small,
}

export default PaperKeyRender
<|endoftext|>


<commit_before>define(['marked', 'backbone'], function (marked) {
    'use strict';
    return Backbone.Router.extend({
        routes: {
            '': 'readmeMd',
            "*path.md": "pathMd",
            "*path": "path"
        },
        readmeMd: function () {
            this.pathMd('README');
        },
        pathMd: function (path) {
            var mdFilePath = path + '.md';

            require(['text!' + mdFilePath], function (mdFile) {
                $('div[data-id="region-main"]').html(marked(mdFile));

                $('div[data-id="region-main"] table').addClass('table table-bordered table-hover table-condensed');
            }, function (err) {
                $('div[data-id="region-main"]').html('');
            });
        },
        path: function (path) {
            this.pathMd(path + '/README');
        }
    });
});<commit_msg>升级依赖的 bootstrap、jquery、backbone等版本<commit_after>define(['marked', 'backbone'], function (marked) {
    'use strict';
    return Backbone.Router.extend({
        routes: {
            '': 'readmeMd',
            "*path.md": "pathMd",
            "*path": "path"
        },
        readmeMd: function () {
            this.pathMd('README');
        },
        pathMd: function (path) {
            var mdFilePath = path + '.md';

            require(['text!' + mdFilePath], function (mdFile) {
                $('div[data-id="region-main"]').html(marked(mdFile));

                $('div[data-id="region-main"] table').addClass('table table-bordered table-hover table-condensed');

                $('div[data-id="region-main"] a[href^="http"]').each(function () {
                    $(this).attr('target', '_blank');
                });
            }, function (err) {
                $('div[data-id="region-main"]').html('');
            });
        },
        path: function (path) {
            this.pathMd(path + '/README');
        }
    });
});<|endoftext|>


<commit_before>var ApplicationRoute = Ember.Route.extend({
  beforeModel: function(){
    var user = getUserFromCookie();
    this.controllerFor('user').set('content', user);
  }
});

function getUserFromCookie(){
  var cookies = document.cookie.split(/\s*;\s*/);
  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i],
        match = /^login=.+?\-(.+)/.exec(cookie);
    if (match) {
      return JSON.parse(decodeURIComponent(match[1]));
    }
  }
  return null;
}

export default ApplicationRoute;
<commit_msg>for now allow all users UI only edit writes to ember/ember.js<commit_after>var ApplicationRoute = Ember.Route.extend({
  beforeModel: function(){
    var user = getUserFromCookie();

    if (user) {
      // TODO: get real data
      user.editableRepositories = user.editableRepositories || ['emberjs/ember.js'];
    }

    this.controllerFor('user').set('content', user);
  }
});

function getUserFromCookie(){
  var cookies = document.cookie.split(/\s*;\s*/);
  for (var i = 0; i < cookies.length; i++) {
    var cookie = cookies[i],
        match = /^login=.+?\-(.+)/.exec(cookie);
    if (match) {
      return JSON.parse(decodeURIComponent(match[1]));
    }
  }
  return null;
}

export default ApplicationRoute;
<|endoftext|>


<commit_before>// require("InputValidator");

/*
 * Provides utility methods for a genetic algorithm.
 */
var GAUtilities =
{
    computeAverageFitness: function(population)
    {
        InputValidator.validateNotNull("population", population);

        var sum = 0.0;

        for (var i = 0; i < population.length; i++)
        {
            var genome = population[i];
            var fitness = genome.fitness;
            sum += fitness;
        }

        return sum / population.length;
    },

    createPopulation: function(popSize, genomeFactory)
    {
        InputValidator.validateIsNumber("popSize", popSize);
        InputValidator.validateNotNull("genomeFactory", genomeFactory);

        var answer = [];

        for (var i = 0; i < popSize; i++)
        {
            answer[answer.length] = genomeFactory.create();
        }

        return answer;
    },

    genomeToString: function(genome)
    {
        var answer = genome[0];

        for (var i = 1; i < genome.length; i++)
        {
            answer += " ";
            answer += genome[i];
        }

        return answer;
    },

    genomeToLongString: function(genome)
    {
        var answer = genome.fitness;
        answer += ":\t";
        answer += this.genomeToString(genome);

        return answer;
    },

    populationToString: function(population)
    {
        var answer = "";

        for (var i = 0; i < population.length; i++)
        {
            var genome = population[i];
            answer += this.genomeToLongString(genome);
            answer += "\n";
        }

        return answer;
    },

    round2: function(value)
    {
        var factor = 100.0;

        return Math.round(factor * value) / factor;
    },

    round4: function(value)
    {
        var factor = 10000.0;

        return Math.round(factor * value) / factor;
    },
}
<commit_msg>Added the count() and computeImbalance() functions.<commit_after>// require("InputValidator");

/*
 * Provides utility methods for a genetic algorithm.
 */
var GAUtilities =
{
    computeAverageFitness: function(population)
    {
        InputValidator.validateNotNull("population", population);

        var sum = 0.0;

        for (var i = 0; i < population.length; i++)
        {
            var genome = population[i];
            var fitness = genome.fitness;
            sum += fitness;
        }

        return sum / population.length;
    },

    computeImbalance: function(genome, openGene, closeGene)
    {
        var openCount = this.count(genome, openGene);
        var closeCount = this.count(genome, closeGene);

        return Math.abs(closeCount - openCount);
    },

    count: function(genome, gene)
    {
        var answer = 0;

        for (var i = 0; i < genome.length; i++)
        {
            if (genome[i] == gene)
            {
                answer++;
            }
        }

        return answer;
    },

    createPopulation: function(popSize, genomeFactory)
    {
        InputValidator.validateIsNumber("popSize", popSize);
        InputValidator.validateNotNull("genomeFactory", genomeFactory);

        var answer = [];

        for (var i = 0; i < popSize; i++)
        {
            answer[answer.length] = genomeFactory.create();
        }

        return answer;
    },

    genomeToString: function(genome)
    {
        var answer = genome[0];

        for (var i = 1; i < genome.length; i++)
        {
            answer += " ";
            answer += genome[i];
        }

        return answer;
    },

    genomeToLongString: function(genome)
    {
        var answer = genome.fitness;
        answer += ":\t";
        answer += this.genomeToString(genome);

        return answer;
    },

    populationToString: function(population)
    {
        var answer = "";

        for (var i = 0; i < population.length; i++)
        {
            var genome = population[i];
            answer += this.genomeToLongString(genome);
            answer += "\n";
        }

        return answer;
    },

    round2: function(value)
    {
        var factor = 100.0;

        return Math.round(factor * value) / factor;
    },

    round4: function(value)
    {
        var factor = 10000.0;

        return Math.round(factor * value) / factor;
    },
}
<|endoftext|>


<commit_before>var mongoose = require("mongoose");
var Tournament = mongoose.model("Tournament");
var statsController = require("../../app/controllers/stats-controller");

module.exports = function(app) {

    app.get("/search", function(req, res) {
        res.render("search", {tournamentd : req.session.director});
    });

    app.get("/search/submit", function(req, res) {
        statsController.findTournamentsByNameAndSet(req.query.t_name, req.query.t_qset, function(err, tournaments) {
            if (err) {
                res.status(500).end();
            } else {
                // res.send(tournaments);
                res.render("tournament-search-result", {tournaments : tournaments});
            }
        });
    });

    app.get("/t/:tid/stats", function(req, res, next) {
        var tournament = req.params.tid;
        res.redirect("/t/" + tournament + "/stats/team");
    });

    app.get("/t/:tid/stats/team", function(req, res, next) {
        statsController.getTeamsInfo(req.params.tid, function(err, tournament, teamInfo) {
            if (err) {
                res.status(500).send(err);
            } else if (tournament == null) {
                // console.log(teamInfo);
                res.send("Couldn't find that tournament");
            } else {
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme, divisions : tournament.divisions};
                res.render("quick-teams", {tournament : tournamentData, teamInfo : teamInfo, custom : false});
            }
        });
    });

    app.get("/t/:tid/stats/team/dl", function(req, res, next) {
        // res.send("OK");
        statsController.getTeamsInfo(req.params.tid, function(err, tournament, teamInfo) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.send("Couldn't find that tournament");
            } else {
                var linkTournamentName = tournament.tournament_name.replace(" ", "_").toLowerCase();
                // console.log(linkTeamName);
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme, divisions : tournament.divisions};
                res.render("quick-teams-simple", {tournament : tournamentData, teamInfo : teamInfo, linkName : linkTournamentName});
            }
        });
    });

    app.get("/t/:tid/stats/player", function(req, res, next) {
        statsController.getPlayersInfo(req.params.tid, function(err, tournament, playersInfo) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.send("Couldn't find that tournament");
            } else {
                // console.log(playersInfo);
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme};
                res.render("quick-players", {tournament : tournamentData, playersInfo : playersInfo, custom : false});
            }
        });
    });

    app.get("/t/:tid/stats/player/dl", function(req, res, next) {
        statsController.getPlayersInfo(req.params.tid, function(err, tournament, playersInfo) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.send("Couldn't find that tournament");
            } else {
                var linkTournamentName = tournament.tournament_name.replace(" ", "_").toLowerCase();
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme};
                res.render("quick-players-simple", {tournament : tournamentData, playersInfo : playersInfo, linkName : linkTournamentName});
            }
        });
    });

    app.get("/t/:tid/stats/teamfull", function(req, res, next) {
        statsController.getFullTeamsGameInformation(req.params.tid, function(err, tournament, teamsGames, playersInfo, teamTotals) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.send("Couldn't find that tournament");
            } else {
                // console.log(teamTotals);
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme};
                res.render("full-teams", {tournament : tournamentData, teamsGames : teamsGames, playersInfo : playersInfo, teamTotals : teamTotals});
            }
        });
    });

    app.get("/t/:tid/stats/teamfull/dl", function(req, res, next) {
        statsController.getFullTeamsGameInformation(req.params.tid, function(err, tournament, teamsGames, playersInfo, teamTotals) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.send("Couldn't find that tournament");
            } else {
                // console.log(teamTotals);
                var linkTournamentName = tournament.tournament_name.replace(" ", "_").toLowerCase();
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme};
                res.render("full-team-simple", {tournament : tournamentData, teamsGames : teamsGames, playersInfo : playersInfo, teamTotals : teamTotals,
                    linkName : linkTournamentName});
            }
        });
    });

    app.get("/t/:tid/stats/playerfull", function(req, res, next) {
        statsController.getFullPlayersGameInformation(req.params.tid, function(err, tournament, playersInfo, playerTotals) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.send("Couldn't find that tournament");
            } else {
                // console.log(playerTotals);
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme};
                res.render("full-player", {playersInfo : playersInfo, tournament : tournamentData, playerTotals : playerTotals});
            }
        });
    });

    app.get("/t/:tid/stats/playerfull/dl", function(req, res, next) {
        statsController.getFullPlayersGameInformation(req.params.tid, function(err, tournament, playersInfo, playerTotals) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.send("Couldn't find that tournament");
            } else {
                // console.log(playerTotals);
                var linkTournamentName = tournament.tournament_name.replace(" ", "_").toLowerCase();
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme};
                res.render("full-players-simple", {playersInfo : playersInfo, tournament : tournamentData, playerTotals : playerTotals,
                    linkName : linkTournamentName});
            }
        });
    });

    app.get("/t/:tid/stats/roundreport", function(req, res, next) {
        statsController.getRoundReport(req.params.tid, function(err, tournament, roundsInfo) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.status(404).end();
            } else {
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID};
                res.render("round-report", {tournament : tournamentData, roundsInfo : roundsInfo});
            }
        });
    });

    app.get("/t/:tid/stats/roundreport/dl", function(req, res, next) {
        statsController.getRoundReport(req.params.tid, function(err, tournament, roundsInfo) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.status(404).end();
            } else {
                var linkTournamentName = tournament.tournament_name.replace(" ", "_").toLowerCase();
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID};
                res.render("round-report-simple", {tournament : tournamentData, roundsInfo : roundsInfo, linkName : linkTournamentName});
            }
        });
    });

    app.post('/t/:tid/stats/filter/teams', function(req, res) {
        var constraints = {};
        constraints.teams = req.body.teams;
        if (req.body.minround.length == 0) {
            constraints.minround = Number.NEGATIVE_INFINITY;
        } else {
            constraints.minround = req.body.minround;
        }
        if (req.body.maxround.length == 0) {
            constraints.maxround = Number.POSITIVE_INFINITY;
        } else {
            constraints.maxround = req.body.maxround;
        }
        statsController.getFilteredTeamsInformation(req.params.tid, constraints, function(err, tournament, teamInfo) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.send("Couldn't find that tournament");
            } else {
                // res.send({type : "team", teamInfo: teamInfo, tournament : tournament});
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme, divisions : tournament.divisions};
                res.render("quick-teams", {tournament : tournamentData, teamInfo : teamInfo, custom : true});
            }
        });
    });

    app.post("/t/:tid/stats/filter/players", function(req, res) {
        var constraints = {};
        constraints.teams = req.body.teams;
        if (req.body.minround.length == 0) {
            constraints.minround = Number.NEGATIVE_INFINITY;
        } else {
            constraints.minround = req.body.minround;
        }
        if (req.body.maxround.length == 0) {
            constraints.maxround = Number.POSITIVE_INFINITY;
        } else {
            constraints.maxround = req.body.maxround;
        }
        statsController.getFilteredPlayersInformation(req.params.tid, constraints, function(err, tournament, playersInfo) {
            if (err) {
                res.send(err);
            } else if (tournament == null) {
                res.send("Couldn't find that tournament");
            } else {
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme};
                res.render("quick-players", {tournament : tournamentData, playersInfo : playersInfo, custom : true});
            }
        });
    });

    app.get("/t/:tid/export/qbj", function(req, res) {
        statsController.convertToQuizbowlSchema(req.params.tid, function(err, json) {
            if (err) {
                res.status(500).end();
            } else if (!json) {
                res.status(404).end();
            } else {
                res.status(200).set("Content-Type", "application/vnd.quizbowl.qbj+json").send(json);
            }
        });
    });

    // app.get("/t/:tid/export/sqbs", function(req, res) {
    //     statsController.convertToSQBS(req.params.tid, function(err, sqbs) {
    //         if (err) {
    //             res.status(500).end();
    //         } else if (!sqbs) {
    //             res.status(404).end();
    //         } else {
    //             res.status(200).send(sqbs);
    //         }
    //     });
    // });

    app.get("/t/:tid/export/scoresheets", function(req, res) {
        statsController.exportScoresheets(req.params.tid, function(err, scoresheets) {
            if (err) {
                res.status(500).end();
            } else if (!scoresheets) {
                res.status(404).end();
            } else {
                res.status(200).send({scoresheets : scoresheets.rounds, pointScheme : scoresheets.pointScheme});
            }
        });
    });

    app.get("*", function(req, res, next) {
        res.status(404).render("not-found", {tournamentd : req.session.director, msg : "That page doesn't exist."});
    });
};
<commit_msg>search featured reverted for now<commit_after>var mongoose = require("mongoose");
var Tournament = mongoose.model("Tournament");
var statsController = require("../../app/controllers/stats-controller");

module.exports = function(app) {

    // app.get("/search", function(req, res) {
    //     res.render("search", {tournamentd : req.session.director});
    // });
    //
    // app.get("/search/submit", function(req, res) {
    //     statsController.findTournamentsByNameAndSet(req.query.t_name, req.query.t_qset, function(err, tournaments) {
    //         if (err) {
    //             res.status(500).end();
    //         } else {
    //             // res.send(tournaments);
    //             res.render("tournament-search-result", {tournaments : tournaments});
    //         }
    //     });
    // });

    app.get("/t/:tid/stats", function(req, res, next) {
        var tournament = req.params.tid;
        res.redirect("/t/" + tournament + "/stats/team");
    });

    app.get("/t/:tid/stats/team", function(req, res, next) {
        statsController.getTeamsInfo(req.params.tid, function(err, tournament, teamInfo) {
            if (err) {
                res.status(500).send(err);
            } else if (tournament == null) {
                // console.log(teamInfo);
                res.send("Couldn't find that tournament");
            } else {
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme, divisions : tournament.divisions};
                res.render("quick-teams", {tournament : tournamentData, teamInfo : teamInfo, custom : false});
            }
        });
    });

    app.get("/t/:tid/stats/team/dl", function(req, res, next) {
        // res.send("OK");
        statsController.getTeamsInfo(req.params.tid, function(err, tournament, teamInfo) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.send("Couldn't find that tournament");
            } else {
                var linkTournamentName = tournament.tournament_name.replace(" ", "_").toLowerCase();
                // console.log(linkTeamName);
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme, divisions : tournament.divisions};
                res.render("quick-teams-simple", {tournament : tournamentData, teamInfo : teamInfo, linkName : linkTournamentName});
            }
        });
    });

    app.get("/t/:tid/stats/player", function(req, res, next) {
        statsController.getPlayersInfo(req.params.tid, function(err, tournament, playersInfo) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.send("Couldn't find that tournament");
            } else {
                // console.log(playersInfo);
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme};
                res.render("quick-players", {tournament : tournamentData, playersInfo : playersInfo, custom : false});
            }
        });
    });

    app.get("/t/:tid/stats/player/dl", function(req, res, next) {
        statsController.getPlayersInfo(req.params.tid, function(err, tournament, playersInfo) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.send("Couldn't find that tournament");
            } else {
                var linkTournamentName = tournament.tournament_name.replace(" ", "_").toLowerCase();
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme};
                res.render("quick-players-simple", {tournament : tournamentData, playersInfo : playersInfo, linkName : linkTournamentName});
            }
        });
    });

    app.get("/t/:tid/stats/teamfull", function(req, res, next) {
        statsController.getFullTeamsGameInformation(req.params.tid, function(err, tournament, teamsGames, playersInfo, teamTotals) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.send("Couldn't find that tournament");
            } else {
                // console.log(teamTotals);
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme};
                res.render("full-teams", {tournament : tournamentData, teamsGames : teamsGames, playersInfo : playersInfo, teamTotals : teamTotals});
            }
        });
    });

    app.get("/t/:tid/stats/teamfull/dl", function(req, res, next) {
        statsController.getFullTeamsGameInformation(req.params.tid, function(err, tournament, teamsGames, playersInfo, teamTotals) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.send("Couldn't find that tournament");
            } else {
                // console.log(teamTotals);
                var linkTournamentName = tournament.tournament_name.replace(" ", "_").toLowerCase();
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme};
                res.render("full-team-simple", {tournament : tournamentData, teamsGames : teamsGames, playersInfo : playersInfo, teamTotals : teamTotals,
                    linkName : linkTournamentName});
            }
        });
    });

    app.get("/t/:tid/stats/playerfull", function(req, res, next) {
        statsController.getFullPlayersGameInformation(req.params.tid, function(err, tournament, playersInfo, playerTotals) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.send("Couldn't find that tournament");
            } else {
                // console.log(playerTotals);
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme};
                res.render("full-player", {playersInfo : playersInfo, tournament : tournamentData, playerTotals : playerTotals});
            }
        });
    });

    app.get("/t/:tid/stats/playerfull/dl", function(req, res, next) {
        statsController.getFullPlayersGameInformation(req.params.tid, function(err, tournament, playersInfo, playerTotals) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.send("Couldn't find that tournament");
            } else {
                // console.log(playerTotals);
                var linkTournamentName = tournament.tournament_name.replace(" ", "_").toLowerCase();
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme};
                res.render("full-players-simple", {playersInfo : playersInfo, tournament : tournamentData, playerTotals : playerTotals,
                    linkName : linkTournamentName});
            }
        });
    });

    app.get("/t/:tid/stats/roundreport", function(req, res, next) {
        statsController.getRoundReport(req.params.tid, function(err, tournament, roundsInfo) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.status(404).end();
            } else {
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID};
                res.render("round-report", {tournament : tournamentData, roundsInfo : roundsInfo});
            }
        });
    });

    app.get("/t/:tid/stats/roundreport/dl", function(req, res, next) {
        statsController.getRoundReport(req.params.tid, function(err, tournament, roundsInfo) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.status(404).end();
            } else {
                var linkTournamentName = tournament.tournament_name.replace(" ", "_").toLowerCase();
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID};
                res.render("round-report-simple", {tournament : tournamentData, roundsInfo : roundsInfo, linkName : linkTournamentName});
            }
        });
    });

    app.post('/t/:tid/stats/filter/teams', function(req, res) {
        var constraints = {};
        constraints.teams = req.body.teams;
        if (req.body.minround.length == 0) {
            constraints.minround = Number.NEGATIVE_INFINITY;
        } else {
            constraints.minround = req.body.minround;
        }
        if (req.body.maxround.length == 0) {
            constraints.maxround = Number.POSITIVE_INFINITY;
        } else {
            constraints.maxround = req.body.maxround;
        }
        statsController.getFilteredTeamsInformation(req.params.tid, constraints, function(err, tournament, teamInfo) {
            if (err) {
                res.status(500).end();
            } else if (tournament == null) {
                res.send("Couldn't find that tournament");
            } else {
                // res.send({type : "team", teamInfo: teamInfo, tournament : tournament});
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme, divisions : tournament.divisions};
                res.render("quick-teams", {tournament : tournamentData, teamInfo : teamInfo, custom : true});
            }
        });
    });

    app.post("/t/:tid/stats/filter/players", function(req, res) {
        var constraints = {};
        constraints.teams = req.body.teams;
        if (req.body.minround.length == 0) {
            constraints.minround = Number.NEGATIVE_INFINITY;
        } else {
            constraints.minround = req.body.minround;
        }
        if (req.body.maxround.length == 0) {
            constraints.maxround = Number.POSITIVE_INFINITY;
        } else {
            constraints.maxround = req.body.maxround;
        }
        statsController.getFilteredPlayersInformation(req.params.tid, constraints, function(err, tournament, playersInfo) {
            if (err) {
                res.send(err);
            } else if (tournament == null) {
                res.send("Couldn't find that tournament");
            } else {
                var tournamentData = {tournament_name : tournament.tournament_name, shortID : tournament.shortID,
                    pointScheme : tournament.pointScheme};
                res.render("quick-players", {tournament : tournamentData, playersInfo : playersInfo, custom : true});
            }
        });
    });

    app.get("/t/:tid/export/qbj", function(req, res) {
        statsController.convertToQuizbowlSchema(req.params.tid, function(err, json) {
            if (err) {
                res.status(500).end();
            } else if (!json) {
                res.status(404).end();
            } else {
                res.status(200).set("Content-Type", "application/vnd.quizbowl.qbj+json").send(json);
            }
        });
    });

    // app.get("/t/:tid/export/sqbs", function(req, res) {
    //     statsController.convertToSQBS(req.params.tid, function(err, sqbs) {
    //         if (err) {
    //             res.status(500).end();
    //         } else if (!sqbs) {
    //             res.status(404).end();
    //         } else {
    //             res.status(200).send(sqbs);
    //         }
    //     });
    // });

    app.get("/t/:tid/export/scoresheets", function(req, res) {
        statsController.exportScoresheets(req.params.tid, function(err, scoresheets) {
            if (err) {
                res.status(500).end();
            } else if (!scoresheets) {
                res.status(404).end();
            } else {
                res.status(200).send({scoresheets : scoresheets.rounds, pointScheme : scoresheets.pointScheme});
            }
        });
    });

    app.get("*", function(req, res, next) {
        res.status(404).render("not-found", {tournamentd : req.session.director, msg : "That page doesn't exist."});
    });
};
<|endoftext|>


<commit_before>var fs = require('fs');
var sources = require('editor-layer-index/imagery.json');
var imagery = [];

// ignore imagery more than 20 years old..
var cutoffDate = new Date();
cutoffDate.setFullYear(cutoffDate.getFullYear() - 20);

var blacklist = {
    'hike_n_bike': true,                  // 'Hike & Bike'
    'osm-mapnik-german_style': true,      // 'OpenStreetMap (German Style)'
    'osm-mapnik-black_and_white': true,   // 'OpenStreetMap (Standard Black & White)'
    'skobbler': true,                     // 'Skobbler'
    'openpt_map': true,                   // 'OpenPT Map (overlay)'
    'tf-cycle': true,                     // 'Thunderforest OpenCycleMap'
    'qa_no_address': true,                // 'QA No Address'

    'US-TIGER-Roads-2012': true,
    'US-TIGER-Roads-2014': true,

    'Waymarked_Trails-Cycling': true,
    'Waymarked_Trails-Hiking': true,
    'Waymarked_Trails-MTB': true,
    'Waymarked_Trails-Skating': true,
    'Waymarked_Trails-Winter_Sports': true,

    'OSM_Inspector-Addresses': true,
    'OSM_Inspector-Geometry': true,
    'OSM_Inspector-Highways': true,
    'OSM_Inspector-Multipolygon': true,
    'OSM_Inspector-Places': true,
    'OSM_Inspector-Routing': true,
    'OSM_Inspector-Tagging': true
};
var supportedWMSProjections = [
    'EPSG:3857',
    'EPSG:900913', // EPSG:3857 alternatives codes
    'EPSG:3587',
    'EPSG:54004',
    'EPSG:41001',
    'EPSG:102113',
    'EPSG:102100',
    'EPSG:3785'
];

var whitelist = [
    // Add custom sources here if needed.
];

sources.concat(whitelist).forEach(function(source) {
    if (source.type !== 'tms' && source.type !== 'wms' && source.type !== 'bing') return;
    if (source.id in blacklist) return;
    var supportedProjection = source.available_projections &&
        supportedWMSProjections.find(function(supportedProjection) {
            return source.available_projections.some(function(projection) {
                return supportedProjection === projection;
            })
        });
    if (source.type === 'wms' && supportedProjection === undefined) return;

    var im = {
        id: source.id,
        name: source.name,
        type: source.type,
        template: source.url
    };

    if (source.type === 'wms') {
        im.projection = supportedProjection;
    }

    var startDate, endDate, isValid;

    if (source.end_date) {
        endDate = new Date(source.end_date);
        isValid = !isNaN(endDate.getTime());
        if (isValid) {
            if (endDate <= cutoffDate) return;  // too old
            im.endDate = endDate;
        }
    }

    if (source.start_date) {
        startDate = new Date(source.start_date);
        isValid = !isNaN(startDate.getTime());
        if (isValid) {
            im.startDate = startDate;
        }
    }

    var extent = source.extent || {};
    if (extent.min_zoom || extent.max_zoom) {
        im.scaleExtent = [
            extent.min_zoom || 0,
            extent.max_zoom || 22
        ];
    }

    if (extent.polygon) {
        im.polygon = extent.polygon;
    } else if (extent.bbox) {
        im.polygon = [[
            [extent.bbox.min_lon, extent.bbox.min_lat],
            [extent.bbox.min_lon, extent.bbox.max_lat],
            [extent.bbox.max_lon, extent.bbox.max_lat],
            [extent.bbox.max_lon, extent.bbox.min_lat],
            [extent.bbox.min_lon, extent.bbox.min_lat]
        ]];
    }

    if (source.id === 'mapbox_locator_overlay') {
        im.overzoom = false;
    }

    var attribution = source.attribution || {};
    if (attribution.url) {
        im.terms_url = attribution.url;
    }
    if (attribution.text) {
        im.terms_text = attribution.text;
    }
    if (attribution.html) {
        im.terms_html = attribution.html;
    }

    ['best', 'default', 'description', 'icon', 'overlay'].forEach(function(a) {
        if (source[a]) {
            im[a] = source[a];
        }
    });

    imagery.push(im);
});

imagery.sort(function(a, b) {
    return a.name.localeCompare(b.name);
});

fs.writeFileSync('data/imagery.json', JSON.stringify({ dataImagery: imagery }, null, 4));
<commit_msg>Blacklist landsat wms layer (slow/offline, and low res)<commit_after>var fs = require('fs');
var sources = require('editor-layer-index/imagery.json');
var imagery = [];

// ignore imagery more than 20 years old..
var cutoffDate = new Date();
cutoffDate.setFullYear(cutoffDate.getFullYear() - 20);

var blacklist = {
    'hike_n_bike': true,                  // 'Hike & Bike'
    'osm-mapnik-german_style': true,      // 'OpenStreetMap (German Style)'
    'osm-mapnik-black_and_white': true,   // 'OpenStreetMap (Standard Black & White)'
    'skobbler': true,                     // 'Skobbler'
    'openpt_map': true,                   // 'OpenPT Map (overlay)'
    'tf-cycle': true,                     // 'Thunderforest OpenCycleMap'
    'qa_no_address': true,                // 'QA No Address'
    'landsat': true,                      // 'Landsat'

    'US-TIGER-Roads-2012': true,
    'US-TIGER-Roads-2014': true,

    'Waymarked_Trails-Cycling': true,
    'Waymarked_Trails-Hiking': true,
    'Waymarked_Trails-MTB': true,
    'Waymarked_Trails-Skating': true,
    'Waymarked_Trails-Winter_Sports': true,

    'OSM_Inspector-Addresses': true,
    'OSM_Inspector-Geometry': true,
    'OSM_Inspector-Highways': true,
    'OSM_Inspector-Multipolygon': true,
    'OSM_Inspector-Places': true,
    'OSM_Inspector-Routing': true,
    'OSM_Inspector-Tagging': true
};
var supportedWMSProjections = [
    'EPSG:3857',
    'EPSG:900913', // EPSG:3857 alternatives codes
    'EPSG:3587',
    'EPSG:54004',
    'EPSG:41001',
    'EPSG:102113',
    'EPSG:102100',
    'EPSG:3785'
];

var whitelist = [
    // Add custom sources here if needed.
];

sources.concat(whitelist).forEach(function(source) {
    if (source.type !== 'tms' && source.type !== 'wms' && source.type !== 'bing') return;
    if (source.id in blacklist) return;
    var supportedProjection = source.available_projections &&
        supportedWMSProjections.find(function(supportedProjection) {
            return source.available_projections.some(function(projection) {
                return supportedProjection === projection;
            })
        });
    if (source.type === 'wms' && supportedProjection === undefined) return;

    var im = {
        id: source.id,
        name: source.name,
        type: source.type,
        template: source.url
    };

    if (source.type === 'wms') {
        im.projection = supportedProjection;
    }

    var startDate, endDate, isValid;

    if (source.end_date) {
        endDate = new Date(source.end_date);
        isValid = !isNaN(endDate.getTime());
        if (isValid) {
            if (endDate <= cutoffDate) return;  // too old
            im.endDate = endDate;
        }
    }

    if (source.start_date) {
        startDate = new Date(source.start_date);
        isValid = !isNaN(startDate.getTime());
        if (isValid) {
            im.startDate = startDate;
        }
    }

    var extent = source.extent || {};
    if (extent.min_zoom || extent.max_zoom) {
        im.scaleExtent = [
            extent.min_zoom || 0,
            extent.max_zoom || 22
        ];
    }

    if (extent.polygon) {
        im.polygon = extent.polygon;
    } else if (extent.bbox) {
        im.polygon = [[
            [extent.bbox.min_lon, extent.bbox.min_lat],
            [extent.bbox.min_lon, extent.bbox.max_lat],
            [extent.bbox.max_lon, extent.bbox.max_lat],
            [extent.bbox.max_lon, extent.bbox.min_lat],
            [extent.bbox.min_lon, extent.bbox.min_lat]
        ]];
    }

    if (source.id === 'mapbox_locator_overlay') {
        im.overzoom = false;
    }

    var attribution = source.attribution || {};
    if (attribution.url) {
        im.terms_url = attribution.url;
    }
    if (attribution.text) {
        im.terms_text = attribution.text;
    }
    if (attribution.html) {
        im.terms_html = attribution.html;
    }

    ['best', 'default', 'description', 'icon', 'overlay'].forEach(function(a) {
        if (source[a]) {
            im[a] = source[a];
        }
    });

    imagery.push(im);
});

imagery.sort(function(a, b) {
    return a.name.localeCompare(b.name);
});

fs.writeFileSync('data/imagery.json', JSON.stringify({ dataImagery: imagery }, null, 4));
<|endoftext|>


<commit_before>import resolveNode from "./resolveNode";
import match from "./matchRedirect";
import {relative, dirname, extname} from "path";

export default function (t, {pathToMatch, pathToRemove, pathToReplace, replaceFn}, {toMatch, toRemove, toReplace, filename, wrapReplacementInPromise}, {opts: {root, extensions}}) {
	const requiredFilename = resolveNode(dirname(filename), pathToMatch.node.value, extensions);
	const matched = match(requiredFilename, toMatch, root, extensions);

	if(matched !== null) {
		const {redirect, redirected} = matched;

		// path has a corresponing redirect
		if(redirected !== null) {
			if(redirected.includes("/node_modules/")) {
				// resolveNode here only generates a warning when necessary
				resolveNode(dirname(filename), redirect, extensions);
				pathToMatch.replaceWith(t.stringLiteral(redirect));
				return;
			}

			let relativeRedirect = relative(dirname(filename), redirected);
			if(!/^\.\.?\//.test(relativeRedirect)) relativeRedirect = "./" + relativeRedirect;

			if(!extname(redirect)) {
				const ext = extname(relativeRedirect);
				if(ext) relativeRedirect = relativeRedirect.slice(0, -ext.length);
			}
			pathToMatch.replaceWith(t.stringLiteral(relativeRedirect));
		}
	// if can be removed
	} else if(pathToRemove) {
		if(toRemove.some(regexp => regexp.test(requiredFilename)) || toReplace.find(([regexp]) => regexp.test(requiredFilename))) {
			pathToRemove.remove();
		}

	// if can be replaced
	} else if(pathToReplace) {
		const replacement = toReplace.find(([regexp]) => regexp.test(requiredFilename));

		if(replacement) {
			replaceFn(t, replacement[1], pathToReplace, wrapReplacementInPromise);
		}
	}
}<commit_msg>fix(resolve): Correctly resolve to the node module pointed at from the root when a module with the s<commit_after>import resolveNode from "./resolveNode";
import match from "./matchRedirect";
import {relative, dirname, extname} from "path";

export default function (t, {pathToMatch, pathToRemove, pathToReplace, replaceFn}, {toMatch, toRemove, toReplace, filename, wrapReplacementInPromise}, {opts: {root, extensions}}) {
	const requiredFilename = resolveNode(dirname(filename), pathToMatch.node.value, extensions);
	const matched = match(requiredFilename, toMatch, root, extensions);

	if(matched !== null) {
		const {redirect, redirected} = matched;

		// path has a corresponing redirect
		if(redirected !== null) {
			if(redirected.includes("/node_modules/")) {
				const resolvedFromFile = resolveNode(dirname(filename), redirect, extensions);

				// require(redirect) resolves to the same path from filename as require(redirected)
				if(resolvedFromFile === redirected) {
					pathToMatch.replaceWith(t.stringLiteral(redirect));
					return;
				} else {
					const modulePath = redirected.match("^.*/node_modules/([^\/]+?)(?=/)");
					if(modulePath) {
						const [moduleDir, moduleName] = modulePath;
						// require(modulePath) resolves to the same file as require(modulePath/file/path)
						// thanks to package.json
						if(resolveNode(moduleDir, moduleName, extensions) === redirected) {
							pathToMatch.replaceWith(t.stringLiteral(relative(dirname(filename), moduleDir)));
							return;
						}
					}
				}
			}

			let relativeRedirect = relative(dirname(filename), redirected);
			if(!/^\.\.?\//.test(relativeRedirect)) relativeRedirect = "./" + relativeRedirect;

			if(!extname(redirect)) {
				const ext = extname(relativeRedirect);
				if(ext) relativeRedirect = relativeRedirect.slice(0, -ext.length);
			}
			pathToMatch.replaceWith(t.stringLiteral(relativeRedirect));
		}
	// if can be removed
	} else if(pathToRemove) {
		if(toRemove.some(regexp => regexp.test(requiredFilename)) || toReplace.find(([regexp]) => regexp.test(requiredFilename))) {
			pathToRemove.remove();
		}

	// if can be replaced
	} else if(pathToReplace) {
		const replacement = toReplace.find(([regexp]) => regexp.test(requiredFilename));

		if(replacement) {
			replaceFn(t, replacement[1], pathToReplace, wrapReplacementInPromise);
		}
	}
}<|endoftext|>


<commit_before>import { put, takeLatest, select, takeEvery, call, fork } from 'redux-saga/effects';
import { delay } from 'redux-saga';
import moment from 'moment';

import {
	REMOVE_HISTORY,
	SUBMIT_CONVERSION,
	SUBMIT_OPTION_FROM,
	SUBMIT_OPTION_TO,
	RECEIVE_RATES,
	UPDATE_HISTORY,
	UPDATE_OPTION_FROM,
	UPDATE_OPTION_TO,
} from '../constants/reduxConstants';
import currencyService from '../services/currencyService';

const getCurrency = state => state.currency;

function* removeHistory(action) {
	const { history }  = yield select(getCurrency);

	// Clone history object and add new conversion
	const newByIds = { ...history.byId };
	delete newByIds[action.id];
	// sort then reverse so newest is on top
	const newAllIds = Object.keys(newByIds).sort().reverse();

	// Construct new history from old history
	const newHistory = Object.assign({}, history, {
			byId: newByIds,
			allIds: newAllIds
		});

	yield put({ type: UPDATE_HISTORY, history: newHistory });
}

function* updateConversion(action) {
	const { optionFrom, optionTo, history }  = yield select(getCurrency);

	// Clone history object and add new conversion
	const newByIds = { ...history.byId };
	const timestamp = Date.now();
	const nextId = timestamp + optionFrom + optionTo; // Very simple hash
	newByIds[nextId] = {
		optionFrom,
		optionTo,
		timestamp,
		fromValue: action.fromValue,
		convertedValue: action.convertedValue,
	}
	// sort then reverse so newest is on top
	const newAllIds = Object.keys(newByIds).sort().reverse();

	// Construct new history from old history
	const newHistory = Object.assign({}, history, {
			byId: newByIds,
			allIds: newAllIds
		});

	yield put({ type: UPDATE_HISTORY, history: newHistory });
}

function* updateOptionFrom(action) {
	yield put({ type: UPDATE_OPTION_FROM, option: action.option });
}

function* updateOptionTo(action) {
	yield put({ type: UPDATE_OPTION_TO, option: action.option });
}

function* updateRates() {
	while (true) {
		const { optionFrom, optionTo }  = yield select(getCurrency);
		const rates = yield call(currencyService.fetchRates);

		if (rates) {
			// Set default options if haven't been selected
			if (!optionFrom || !optionTo) {
				yield put({ type: UPDATE_OPTION_FROM, option: rates.allIds[0] });
				yield put({ type: UPDATE_OPTION_TO, option: rates.allIds[0] });
			}
			yield put({ type: RECEIVE_RATES, rates: rates });
			yield delay(4 * 60 * 60 * 1000); // 4 hours
		} else {
			yield delay(1 * 60 * 1000); // 1min
		}
	}
}

export default function* currencySaga() {
	yield takeLatest(REMOVE_HISTORY, removeHistory);
	yield takeLatest(SUBMIT_OPTION_FROM, updateOptionFrom);
	yield takeLatest(SUBMIT_OPTION_TO, updateOptionTo);
	yield takeLatest(SUBMIT_CONVERSION, updateConversion);
	yield fork(updateRates);
}
<commit_msg>Change updateRates to only retry if failed<commit_after>import { put, takeLatest, select, takeEvery, call, fork } from 'redux-saga/effects';
import { delay } from 'redux-saga';
import moment from 'moment';

import {
	REMOVE_HISTORY,
	SUBMIT_CONVERSION,
	SUBMIT_OPTION_FROM,
	SUBMIT_OPTION_TO,
	RECEIVE_RATES,
	UPDATE_HISTORY,
	UPDATE_OPTION_FROM,
	UPDATE_OPTION_TO,
} from '../constants/reduxConstants';
import currencyService from '../services/currencyService';

const getCurrency = state => state.currency;

function* removeHistory(action) {
	const { history }  = yield select(getCurrency);

	// Clone history object and add new conversion
	const newByIds = { ...history.byId };
	delete newByIds[action.id];
	// sort then reverse so newest is on top
	const newAllIds = Object.keys(newByIds).sort().reverse();

	// Construct new history from old history
	const newHistory = Object.assign({}, history, {
			byId: newByIds,
			allIds: newAllIds
		});

	yield put({ type: UPDATE_HISTORY, history: newHistory });
}

function* updateConversion(action) {
	const { optionFrom, optionTo, history }  = yield select(getCurrency);

	// Clone history object and add new conversion
	const newByIds = { ...history.byId };
	const timestamp = Date.now();
	const nextId = timestamp + optionFrom + optionTo; // Very simple hash
	newByIds[nextId] = {
		optionFrom,
		optionTo,
		timestamp,
		fromValue: action.fromValue,
		convertedValue: action.convertedValue,
	}
	// sort then reverse so newest is on top
	const newAllIds = Object.keys(newByIds).sort().reverse();

	// Construct new history from old history
	const newHistory = Object.assign({}, history, {
			byId: newByIds,
			allIds: newAllIds
		});

	yield put({ type: UPDATE_HISTORY, history: newHistory });
}

function* updateOptionFrom(action) {
	yield put({ type: UPDATE_OPTION_FROM, option: action.option });
}

function* updateOptionTo(action) {
	yield put({ type: UPDATE_OPTION_TO, option: action.option });
}

function* updateRates() {
	while (true) {
		const { optionFrom, optionTo }  = yield select(getCurrency);
		const rates = yield call(currencyService.fetchRates);

		if (rates) {
			// Set default options if haven't been selected
			if (!optionFrom || !optionTo) {
				yield put({ type: UPDATE_OPTION_FROM, option: rates.allIds[0] });
				yield put({ type: UPDATE_OPTION_TO, option: rates.allIds[0] });
			}
			yield put({ type: RECEIVE_RATES, rates: rates });
			break;
		} else {
			// retry in 1 min
			yield delay(1 * 60 * 1000);
		}
	}
}

export default function* currencySaga() {
	yield takeLatest(REMOVE_HISTORY, removeHistory);
	yield takeLatest(SUBMIT_OPTION_FROM, updateOptionFrom);
	yield takeLatest(SUBMIT_OPTION_TO, updateOptionTo);
	yield takeLatest(SUBMIT_CONVERSION, updateConversion);
	yield call(updateRates);
}
<|endoftext|>


<commit_before>(function($){
  if (Drupal.settings.toolbar_hide.onload) {
    $(document).ready(
      function() {
        $('#toolbar').hide();
        $('body').addClass('tbr_menu_hidden');
    });
  }
  $(document.ready(
    function() {
      if ($.cookie('toolbar_hide_hidden')) {
        $('#toolbar').hide();
        $('body').addClass('tbr_menu_hidden');
      } else {
        $('#toolbar').show();
        $('body').removeClass('tbr_menu_hidden');
      }
    }
  ));
  $(document).keypress(function(e) {
    var unicode=e.keyCode? e.keyCode : e.charCode;
    if (String.fromCharCode(unicode)==Drupal.settings.toolbar_hide.key){
      $('#toolbar').slideToggle('fast');
      $('body').toggleClass('tbr_menu_hidden');
      if ($('body').hasClass('tbr_hide_hidden')) {
        $.cookie('toolbar_hide_hidden', 1);
      } else {
        $.cookie('toolbar_hide_hidden', 0);
      }
    }
  });
})(jQuery);
<commit_msg>Toolbar hide fix dev version in JS<commit_after>(function($){
  if (Drupal.settings.toolbar_hide.onload) {
    $(document).ready(
      function() {
        $('#toolbar').hide();
        $('body').addClass('tbr_menu_hidden');
    });
  }
  $(document).ready(
    function() {
      if ($.cookie('toolbar_hide_hidden')) {
        $('#toolbar').hide();
        $('body').addClass('tbr_menu_hidden');
      } else {
        $('#toolbar').show();
        $('body').removeClass('tbr_menu_hidden');
      }
    }
  );
  $(document).keypress(function(e) {
    var unicode=e.keyCode? e.keyCode : e.charCode;
    if (String.fromCharCode(unicode)==Drupal.settings.toolbar_hide.key){
      $('#toolbar').slideToggle('fast');
      $('body').toggleClass('tbr_menu_hidden');
      if ($('body').hasClass('tbr_hide_hidden')) {
        $.cookie('toolbar_hide_hidden', 1);
      } else {
        $.cookie('toolbar_hide_hidden', 0);
      }
    }
  });
})(jQuery);
<|endoftext|>