<commit_before>// Setting variables

console.log('Hello World! I\'m starting!')

const botConfig = require('./botconfig.json')
const Discord = require('discord.js')
const Wikia = require('node-wikia')
const Database = require('better-sqlite3')

const bot = new Discord.Client()
const fcpattern = new RegExp(/^(\d{4}-\d{4}-\d{4})$/g)

var wikia = new Wikia('animalcrossing')
var db = new Database('userInfo.db')

// Launching bot
bot.on('ready', async () => {
  console.log(`${bot.user.username} is ready!`)

  try {
    let link = await bot.generateInvite(['READ_MESSAGES', 'SEND_MESSAGES'])
    console.log(link)
  } catch (e) {
    console.log(e.stack)
  }
})

// on message

bot.on('message', async message => {
  // bot message or not start with prefix = return
  if (message.author.bot) return
  if (!message.content.startsWith(botConfig.prefix)) return

  let user = message.author
  let messageArray = message.content.trim().split(' ')
  let command = messageArray[0].replace(botConfig.prefix, '')
  let args = messageArray.slice(1)

  switch (command.toUpperCase()) {
    // !userinfo
    case 'USERINFO':
      let userinfo = new Discord.RichEmbed()
        .setColor(getRandomColor())
        .setAuthor(user.username)
        .setDescription(`#${user.discriminator}`)
        .addField('Created on: ', user.createdAt)
        .setThumbnail(user.avatarURL)
      message.channel.send({ embed: userinfo })
      break
    // !wiki
    case 'WIKI':
      if (args.length > 0) {
        wikia.getSearchList({'query': args.join(' ')}).then(function (data) {
          message.channel.send(data.items[0].url)
        })
        .fail(function (e) {
          message.channel.send('There isn\'t any wiki page about ' + args)
          console.log(e.stack)
        })
      } else {
        message.channel.send(botConfig.wiki)
      }
      break

    // !help
    // DONT FORGET TO ADD NEW COMMANDS HERE!

    case 'HELP':
      let help = new Discord.RichEmbed()
        .setColor(getRandomColor())
        .setTitle('Commands available')
        .addField('!help', 'Get a list of commands')
        .addField('!wiki [search]', 'Search the Wiki')
        .addField('!info (mention)', 'Get user info')
        .addField('!fc [code]', 'Add your Friend Code')
        .addField('!fc [mention]', 'Get someone elses Friend Code')
        .addField('!name [code]', 'Add your Name')
        .addField('!name [mention]', 'Get someone elses Name')
        .addField('!town [code]', 'Add your Town')
        .addField('!town [mention]', 'Get someone elses Town')
        .addField('!fruit [code]', 'Add your Native Fruit')
        .addField('!fruit [mention]', 'Get someone elses Native Fruit')
        .addField('!note [code]', 'Add your Note')
        .addField('!note [mention]', 'Get someone elses Note')
        .setFooter('This bot is made by <@237985610084777994> with help from <@189769721653100546> and GitHub Contributors!')
        .setThumbnail(message.guild.iconURL)
      message.channel.send({ embed: help })
      break

    // !fc

    case 'FC':
      if (args.length === 0) {
        var usr = user
        var usrinfo = getUserInfo(usr.id)
        if (usrinfo.FriendCode != null) {
          message.channel.send(usr.username + "'s Friend Code is: `" + usrinfo.FriendCode + '`')
        } else {
          message.channel.send(usr.username + ' has not set a Friend Code yet')
        }
      } else if (args.length === 1) {
        if (fcpattern.test(args[0])) {
          setUserInfo(user.id, { FriendCode: args[0] })
          message.channel.send('Your Friend Code is now `' + args[0] + '`')
        } else if (message.mentions.users.first() != null) {
          usr = message.mentions.users.first()
          usrinfo = getUserInfo(usr.id)
          if (usrinfo.FriendCode != null) {
            message.channel.send(usr.username + "'s Friend Code is: `" + usrinfo.FriendCode + '`')
          } else {
            message.channel.send(usr.username + ' has not set a Friend Code yet')
          }
        } else {
          message.channel.send('Invalid Friend Code or User')
        }
      } else {
        message.channel.send('Usage: `!fc [code]` or `!fc [mention]`')
      }
      break

    // !name

    case 'NAME':
      if (args.length === 0) {
        usr = user
        usrinfo = getUserInfo(usr.id)
        if (usrinfo.Name != null) {
          message.channel.send(usr.username + "'s Name is: `" + usrinfo.Name + '`')
        } else {
          message.channel.send(usr.username + ' has not set a Name yet')
        }
      } else if (args.length === 1) {
        if (message.mentions.users.first() != null) {
          usr = message.mentions.users.first()
          usrinfo = getUserInfo(usr.id)
          if (usrinfo.Name != null) {
            message.channel.send(usr.username + "'s Name is: `" + usrinfo.Name + '`')
          } else {
            message.channel.send(usr.username + ' has not set a Name yet')
          }
        } else {
          setUserInfo(user.id, { Name: args[0] })
          message.channel.send('Your Name is now `' + args[0] + '`')
        }
      } else {
        message.channel.send('Usage: `!name [name]` or `!name [mention]`')
      }
      break

    // !town

    case 'TOWN':
      if (args.length === 0) {
        usr = user
        usrinfo = getUserInfo(usr.id)
        if (usrinfo.Town != null) {
          message.channel.send(usr.username + "'s Town is: `" + usrinfo.Town + '`')
        } else {
          message.channel.send(usr.username + ' has not set a Town yet')
        }
      } else if (args.length === 1) {
        if (message.mentions.users.first() != null) {
          usr = message.mentions.users.first()
          usrinfo = getUserInfo(usr.id)
          if (usrinfo.Town != null) {
            message.channel.send(usr.username + "'s Town is: `" + usrinfo.Town + '`')
          } else {
            message.channel.send(usr.username + ' has not set a Town yet')
          }
        } else {
          setUserInfo(user.id, { Town: args[0] })
          message.channel.send('Your Town is now `' + args[0] + '`')
        }
      } else {
        message.channel.send('Usage: `!town [town]` or `!town [mention]`')
      }
      break

    // !fruit

    case 'FRUIT':
      if (args.length === 0) {
        usr = user
        usrinfo = getUserInfo(usr.id)
        if (usrinfo.Fruit != null) {
          message.channel.send(usr.username + "'s Fruit is: `" + usrinfo.Fruit + '`')
        } else {
          message.channel.send(usr.username + ' has not set a Fruit yet')
        }
      } else if (args.length === 1) {
        if (message.mentions.users.first() != null) {
          usr = message.mentions.users.first()
          usrinfo = getUserInfo(usr.id)
          if (usrinfo.Fruit != null) {
            message.channel.send(usr.username + "'s Fruit is: `" + usrinfo.Fruit + '`')
          } else {
            message.channel.send(usr.username + ' has not set a Fruit yet')
          }
        } else {
          switch (args[0].toUpperCase()) {
            case 'ALL':
              setUserInfo(user.id, { Fruit: 'All' })
              message.channel.send('Your Fruit is now `All`')
              break
            case 'PEACH':
              setUserInfo(user.id, { Fruit: 'Peach' })
              message.channel.send('Your Fruit is now `Peach`')
              break
            case 'PEAR':
              setUserInfo(user.id, { Fruit: 'Pear' })
              message.channel.send('Your Fruit is now `Pear`')
              break
            case 'APPLE':
              setUserInfo(user.id, { Fruit: 'Apple' })
              message.channel.send('Your Fruit is now `Apple`')
              break
            case 'ORANGE':
              setUserInfo(user.id, { Fruit: 'Orange' })
              message.channel.send('Your Fruit is now `Orange`')
              break
            case 'CHERRY':
              setUserInfo(user.id, { Fruit: 'Cherry' })
              message.channel.send('Your Fruit is now `Cherry`')
              break
            case 'PEACHES':
              setUserInfo(user.id, { Fruit: 'Peach' })
              message.channel.send('Your Fruit is now `Peach`')
              break
            case 'PEARS':
              setUserInfo(user.id, { Fruit: 'Pear' })
              message.channel.send('Your Fruit is now `Pear`')
              break
            case 'APPLES':
              setUserInfo(user.id, { Fruit: 'Apple' })
              message.channel.send('Your Fruit is now `Apple`')
              break
            case 'ORANGES':
              setUserInfo(user.id, { Fruit: 'Orange' })
              message.channel.send('Your Fruit is now `Orange`')
              break
            case 'CHERRIES':
              setUserInfo(user.id, { Fruit: 'Cherry' })
              message.channel.send('Your Fruit is now `Cherry`')
              break
            default:
              message.channel.send('Invalid Fruit')
              break
          }
        }
      } else {
        message.channel.send('Usage: `!fruit [fruit]` or `!fruit [mention]`')
      }
      break

    // !note

    case 'NOTE':
      if (args.length === 0) {
        usr = user
        usrinfo = getUserInfo(usr.id)
        if (usrinfo.Note !== null) {
          message.channel.send(usr.username + "'s Note is: `" + usrinfo.Note + '`')
        } else {
          message.channel.send(usr.username + ' has not set a Note yet')
        }
      } else if (message.mentions.users.first() === null && args.length > 0) {
        setUserInfo(user.id, { Note: args.join(' ') })
        message.channel.send('Your Note is now `' + args.join(' ') + '`')
      } else if (message.mentions.users.first() !== null && args.length === 1) {
        usr = message.mentions.users.first()
        usrinfo = getUserInfo(usr.id)
        if (usrinfo.Note !== null) {
          message.channel.send(usr.username + "'s Note is: `" + usrinfo.Note + '`')
        } else {
          message.channel.send(usr.username + ' has not set a Note yet')
        }
      } else {
        message.channel.send('Usage: `!note [note]` or `!note [mention]`')
      }
      break

    // !info

    case 'INFO':
      if (args.length === 1) {
        if (message.mentions.users.first() != null) {
          usr = message.mentions.users.first()
          usrinfo = getUserInfo(usr.id)

          //  IF User havent set any info
          if (usrinfo.FriendCode === undefined) {
            message.channel.send('This user haven\'t set their details yet! Notify the user so that they will enter the details!')
            console.log('!info undefined friendcode')
            return
          }
          console.log(usrinfo)
          if (usrinfo.FriendCode !== null) {
            message.channel.send(usr.username + "'s info is: \n Friend Code: `" + usrinfo.FriendCode + '` \n Name: `' + usrinfo.Name + '` \n Town: `' + usrinfo.Town + '` \n Fruit: `' + usrinfo.Fruit + '` \n Note: `' + usrinfo.Note + '`')
          } else {
            message.channel.send(usr.username + ' has not set a Friend Code yet')
          }
        } else {
          message.channel.send('Usage: `!info [mention]`')
        }
      } else if (args.length === 0) {
        usr = user
        usrinfo = getUserInfo(usr.id)
        if (usrinfo.FriendCode != null) {
          message.channel.send(usr.username + "'s info is: \n Friend Code: `" + usrinfo.FriendCode + '` \n Name: `' + usrinfo.Name + '` \n Town: `' + usrinfo.Town + '` \n Fruit: `' + usrinfo.Fruit + '` \n Note: `' + usrinfo.Note + '`')
        } else {
          message.channel.send(usr.username + ' has not set a Friend Code yet')
        }
      } else {
        message.channel.send('Usage: `!info [mention]`')
      }
      break

    // if prefix + not valid command

    default:
      message.channel.send('The command is invalid! Do `!help` if you need help.')
      break
  }
})

// FUNCTIONS!

function getUserInfo (userID) {
  return db.prepare(`SELECT * FROM USERINFO WHERE UserID=?`).get(userID)
}

function setUserInfo (userID, info) {
  var row = db.prepare(`SELECT * FROM USERINFO WHERE UserID=?`).get(userID)

  if (row === null) {
    db.prepare(`INSERT INTO USERINFO (UserID) VALUES (?)`).run(userID)
    row = db.prepare(`SELECT * FROM USERINFO WHERE UserID=?`).get(userID)
  }
  if (info.FriendCode !== null) { row.FriendCode = info.FriendCode.trim() }
  if (info.Name !== null) { row.Name = info.Name.trim() }
  if (info.Town !== null) { row.Town = info.Town.trim() }
  if (info.Fruit !== null) { row.Fruit = info.Fruit.trim() }
  if (info.Note !== null) { row.Note = info.Note.trim() }

  db.prepare(`UPDATE USERINFO SET FriendCode = @FriendCode, Name = @Name, Town = @Town, Fruit = @Fruit, Note = @Note WHERE UserID=?`).run(userID, row)
}

function getRandomColor () {
  var letters = '0123456789ABCDEF'
  var color = '#'
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)]
  }
  return color
}

bot.login(botConfig.token)
<commit_msg>new method<commit_after>// Setting variables

console.log('Hello World! I\'m starting!')

const botConfig = require('./botconfig.json')
const Discord = require('discord.js')
const Wikia = require('node-wikia')
const Database = require('better-sqlite3')

const bot = new Discord.Client()
const fcpattern = new RegExp(/^(\d{4}-\d{4}-\d{4})$/g)

var wikia = new Wikia('animalcrossing')
var db = new Database('userInfo.db')

// Launching bot
bot.on('ready', async () => {
  console.log(`${bot.user.username} is ready!`)

  try {
    let link = await bot.generateInvite(['READ_MESSAGES', 'SEND_MESSAGES'])
    console.log(link)
  } catch (e) {
    console.log(e.stack)
  }
})

// on message

bot.on('message', async message => {
  // bot message or not start with prefix = return
  if (message.author.bot) return
  if (!message.content.startsWith(botConfig.prefix)) return

  let user = message.author
  let messageArray = message.content.trim().split(' ')
  let command = messageArray[0].replace(botConfig.prefix, '')
  let args = messageArray.slice(1)

  switch (command.toUpperCase()) {
    // !userinfo
    case 'USERINFO':
      let userinfo = new Discord.RichEmbed()
        .setColor(getRandomColor())
        .setAuthor(user.username)
        .setDescription(`#${user.discriminator}`)
        .addField('Created on: ', user.createdAt)
        .setThumbnail(user.avatarURL)
      message.channel.send({ embed: userinfo })
      break
    // !wiki
    case 'WIKI':
      if (args.length > 0) {
        wikia.getSearchList({'query': args.join(' ')}).then(function (data) {
          message.channel.send(data.items[0].url)
        })
        .fail(function (e) {
          message.channel.send('There isn\'t any wiki page about `' + args + '`')
          console.log(e.stack)
        })
      } else {
        message.channel.send(botConfig.wiki)
      }
      break

    // !help
    // DONT FORGET TO ADD NEW COMMANDS HERE!

    case 'HELP':
      let help = new Discord.RichEmbed()
        .setColor(getRandomColor())
        .setTitle('Commands available')
        .addField('!help', 'Get a list of commands')
        .addField('!wiki [search]', 'Search the Wiki')
        .addField('!info (mention)', 'Get user info')
        .addField('!fc [code]', 'Add your Friend Code')
        .addField('!fc [mention]', 'Get someone elses Friend Code')
        .addField('!name [code]', 'Add your Name')
        .addField('!name [mention]', 'Get someone elses Name')
        .addField('!town [code]', 'Add your Town')
        .addField('!town [mention]', 'Get someone elses Town')
        .addField('!fruit [code]', 'Add your Native Fruit')
        .addField('!fruit [mention]', 'Get someone elses Native Fruit')
        .addField('!note [code]', 'Add your Note')
        .addField('!note [mention]', 'Get someone elses Note')
        .addField('Author', 'This bot is made by <@237985610084777994> with help from <@189769721653100546> and GitHub Contributors!')
        .setThumbnail(message.guild.iconURL)
      message.channel.send({ embed: help })
      break

    // !fc

    case 'FC':
      if (args.length === 0) {
        var usr = user
        var usrinfo = getUserInfo(usr.id)
        if (usrinfo.FriendCode != null) {
          message.channel.send(usr.username + "'s Friend Code is: `" + usrinfo.FriendCode + '`')
        } else {
          message.channel.send(usr.username + ' has not set a Friend Code yet')
        }
      } else if (args.length === 1) {
        if (fcpattern.test(args[0])) {
          setUserInfo(user.id, { FriendCode: args[0] })
          message.channel.send('Your Friend Code is now `' + args[0] + '`')
        } else if (message.mentions.users.first() != null) {
          usr = message.mentions.users.first()
          usrinfo = getUserInfo(usr.id)
          if (usrinfo.FriendCode != null) {
            message.channel.send(usr.username + "'s Friend Code is: `" + usrinfo.FriendCode + '`')
          } else {
            message.channel.send(usr.username + ' has not set a Friend Code yet')
          }
        } else {
          message.channel.send('Invalid Friend Code or User')
        }
      } else {
        message.channel.send('Usage: `!fc [code]` or `!fc [mention]`')
      }
      break

    // !name

    case 'NAME':
      if (args.length === 0) {
        usr = user
        usrinfo = getUserInfo(usr.id)
        if (usrinfo.Name != null) {
          message.channel.send(usr.username + "'s Name is: `" + usrinfo.Name + '`')
        } else {
          message.channel.send(usr.username + ' has not set a Name yet')
        }
      } else if (args.length === 1) {
        if (message.mentions.users.first() != null) {
          usr = message.mentions.users.first()
          usrinfo = getUserInfo(usr.id)
          if (usrinfo.Name != null) {
            message.channel.send(usr.username + "'s Name is: `" + usrinfo.Name + '`')
          } else {
            message.channel.send(usr.username + ' has not set a Name yet')
          }
        } else {
          setUserInfo(user.id, { Name: args[0] })
          message.channel.send('Your Name is now `' + args[0] + '`')
        }
      } else {
        message.channel.send('Usage: `!name [name]` or `!name [mention]`')
      }
      break

    // !town

    case 'TOWN':
      if (args.length === 0) {
        usr = user
        usrinfo = getUserInfo(usr.id)
        if (usrinfo.Town != null) {
          message.channel.send(usr.username + "'s Town is: `" + usrinfo.Town + '`')
        } else {
          message.channel.send(usr.username + ' has not set a Town yet')
        }
      } else if (args.length === 1) {
        if (message.mentions.users.first() != null) {
          usr = message.mentions.users.first()
          usrinfo = getUserInfo(usr.id)
          if (usrinfo.Town != null) {
            message.channel.send(usr.username + "'s Town is: `" + usrinfo.Town + '`')
          } else {
            message.channel.send(usr.username + ' has not set a Town yet')
          }
        } else {
          setUserInfo(user.id, { Town: args[0] })
          message.channel.send('Your Town is now `' + args[0] + '`')
        }
      } else {
        message.channel.send('Usage: `!town [town]` or `!town [mention]`')
      }
      break

    // !fruit

    case 'FRUIT':
      if (args.length === 0) {
        usr = user
        usrinfo = getUserInfo(usr.id)
        if (usrinfo.Fruit != null) {
          message.channel.send(usr.username + "'s Fruit is: `" + usrinfo.Fruit + '`')
        } else {
          message.channel.send(usr.username + ' has not set a Fruit yet')
        }
      } else if (args.length === 1) {
        if (message.mentions.users.first() != null) {
          usr = message.mentions.users.first()
          usrinfo = getUserInfo(usr.id)
          if (usrinfo.Fruit != null) {
            message.channel.send(usr.username + "'s Fruit is: `" + usrinfo.Fruit + '`')
          } else {
            message.channel.send(usr.username + ' has not set a Fruit yet')
          }
        } else {
          switch (args[0].toUpperCase()) {
            case 'ALL':
              setUserInfo(user.id, { Fruit: 'All' })
              message.channel.send('Your Fruit is now `All`')
              break
            case 'PEACH':
              setUserInfo(user.id, { Fruit: 'Peach' })
              message.channel.send('Your Fruit is now `Peach`')
              break
            case 'PEAR':
              setUserInfo(user.id, { Fruit: 'Pear' })
              message.channel.send('Your Fruit is now `Pear`')
              break
            case 'APPLE':
              setUserInfo(user.id, { Fruit: 'Apple' })
              message.channel.send('Your Fruit is now `Apple`')
              break
            case 'ORANGE':
              setUserInfo(user.id, { Fruit: 'Orange' })
              message.channel.send('Your Fruit is now `Orange`')
              break
            case 'CHERRY':
              setUserInfo(user.id, { Fruit: 'Cherry' })
              message.channel.send('Your Fruit is now `Cherry`')
              break
            case 'PEACHES':
              setUserInfo(user.id, { Fruit: 'Peach' })
              message.channel.send('Your Fruit is now `Peach`')
              break
            case 'PEARS':
              setUserInfo(user.id, { Fruit: 'Pear' })
              message.channel.send('Your Fruit is now `Pear`')
              break
            case 'APPLES':
              setUserInfo(user.id, { Fruit: 'Apple' })
              message.channel.send('Your Fruit is now `Apple`')
              break
            case 'ORANGES':
              setUserInfo(user.id, { Fruit: 'Orange' })
              message.channel.send('Your Fruit is now `Orange`')
              break
            case 'CHERRIES':
              setUserInfo(user.id, { Fruit: 'Cherry' })
              message.channel.send('Your Fruit is now `Cherry`')
              break
            default:
              message.channel.send('Invalid Fruit')
              break
          }
        }
      } else {
        message.channel.send('Usage: `!fruit [fruit]` or `!fruit [mention]`')
      }
      break

    // !note

    case 'NOTE':
      if (args.length === 0) {
        usr = user
        usrinfo = getUserInfo(usr.id)
        if (usrinfo.Note !== null) {
          message.channel.send(usr.username + "'s Note is: `" + usrinfo.Note + '`')
        } else {
          message.channel.send(usr.username + ' has not set a Note yet')
        }
      } else if (message.mentions.users.first() === null && args.length > 0) {
        setUserInfo(user.id, { Note: args.join(' ') })
        message.channel.send('Your Note is now `' + args.join(' ') + '`')
      } else if (message.mentions.users.first() !== null && args.length === 1) {
        usr = message.mentions.users.first()
        usrinfo = getUserInfo(usr.id)
        if (usrinfo.Note !== null) {
          message.channel.send(usr.username + "'s Note is: `" + usrinfo.Note + '`')
        } else {
          message.channel.send(usr.username + ' has not set a Note yet')
        }
      } else {
        message.channel.send('Usage: `!note [note]` or `!note [mention]`')
      }
      break

    /* !info
    Lazy Programming. Just use try and catch */

    case 'INFO':
      try {
        if (args.length === 1) {
          if (message.mentions.users.first() != null) {
            usr = message.mentions.users.first()
            usrinfo = getUserInfo(usr.id)
            console.log(usrinfo)
            if (usrinfo.FriendCode !== null) {
              message.channel.send(usr.username + "'s info is: \n Friend Code: `" + usrinfo.FriendCode + '` \n Name: `' + usrinfo.Name + '` \n Town: `' + usrinfo.Town + '` \n Fruit: `' + usrinfo.Fruit + '` \n Note: `' + usrinfo.Note + '`')
            } else {
              message.channel.send(usr.username + ' has not set a Friend Code yet')
            }
          } else {
            message.channel.send('Usage: `!info [mention]`')
          }
        } else if (args.length === 0) {
          usr = user
          usrinfo = getUserInfo(usr.id)
          if (usrinfo.FriendCode != null) {
            message.channel.send(usr.username + "'s info is: \n Friend Code: `" + usrinfo.FriendCode + '` \n Name: `' + usrinfo.Name + '` \n Town: `' + usrinfo.Town + '` \n Fruit: `' + usrinfo.Fruit + '` \n Note: `' + usrinfo.Note + '`')
          } else {
            message.channel.send(usr.username + ' has not set a Friend Code yet')
          }
        } else {
          message.channel.send('Usage: `!info [mention]`')
        }
      } catch (e) { message.channel.send('The user haven\'t give any information to the bot!') }

      break

    // if prefix + not valid command

    default:
      message.channel.send('The command is invalid! Do `!help` if you need help.')
      break
  }
})

// FUNCTIONS!

function getUserInfo (userID) {
  return db.prepare(`SELECT * FROM USERINFO WHERE UserID=?`).get(userID)
}

function setUserInfo (userID, info) {
  var row = db.prepare(`SELECT * FROM USERINFO WHERE UserID=?`).get(userID)

  if (row === null) {
    db.prepare(`INSERT INTO USERINFO (UserID) VALUES (?)`).run(userID)
    row = db.prepare(`SELECT * FROM USERINFO WHERE UserID=?`).get(userID)
  }
  if (info.FriendCode !== null) { row.FriendCode = info.FriendCode.trim() }
  if (info.Name !== null) { row.Name = info.Name.trim() }
  if (info.Town !== null) { row.Town = info.Town.trim() }
  if (info.Fruit !== null) { row.Fruit = info.Fruit.trim() }
  if (info.Note !== null) { row.Note = info.Note.trim() }

  db.prepare(`UPDATE USERINFO SET FriendCode = @FriendCode, Name = @Name, Town = @Town, Fruit = @Fruit, Note = @Note WHERE UserID=?`).run(userID, row)
}

function getRandomColor () {
  var letters = '0123456789ABCDEF'
  var color = '#'
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)]
  }
  return color
}

bot.login(botConfig.token)
<|endoftext|>


<commit_before>
<commit_msg>Updated to new button IDs<commit_after>
<|endoftext|>


<commit_before>let errorMargin = 0.0001;

let hackOn = false;
window.addEventListener('keypress', e => {
  if (e.which === 49) {
    hackOn = !hackOn;
  }
});

export default function stepper(frameRate, x, v, destX, k, b) {
  // Spring stiffness, in kg / s^2

  // for animations, destX is really spring length (spring at rest). initial
  // position is considered as the stretched/compressed posiiton of a spring
  let Fspring = -k * (x - destX);

  // Damping constant, in kg / s
  let Fdamper = -b * v;

  // usually we put mass here, but for animation purposes, specifying mass is a
  // bit redundant. you could simply adjust k and b accordingly
  // let a = (Fspring + Fdamper) / mass;
  let a = Fspring + Fdamper;

  let newX = x + v * (hackOn ? 1 / 1000 : frameRate);
  let newV = v + a * (hackOn ? 1 / 1000 : frameRate);

  if (Math.abs(newV - v) < errorMargin && Math.abs(newX - x) < errorMargin) {
    return [destX, 0];
  }

  return [newX, newV];
}
<commit_msg>Fix typo<commit_after>let errorMargin = 0.0001;

let hackOn = false;
window.addEventListener('keypress', e => {
  if (e.which === 49) {
    hackOn = !hackOn;
  }
});

export default function stepper(frameRate, x, v, destX, k, b) {
  // Spring stiffness, in kg / s^2

  // for animations, destX is really spring length (spring at rest). initial
  // position is considered as the stretched/compressed position of a spring
  let Fspring = -k * (x - destX);

  // Damping constant, in kg / s
  let Fdamper = -b * v;

  // usually we put mass here, but for animation purposes, specifying mass is a
  // bit redundant. you could simply adjust k and b accordingly
  // let a = (Fspring + Fdamper) / mass;
  let a = Fspring + Fdamper;

  let newX = x + v * (hackOn ? 1 / 1000 : frameRate);
  let newV = v + a * (hackOn ? 1 / 1000 : frameRate);

  if (Math.abs(newV - v) < errorMargin && Math.abs(newX - x) < errorMargin) {
    return [destX, 0];
  }

  return [newX, newV];
}
<|endoftext|>


<commit_before>'use strict'
/* @flow */

import Base from "../base-component"
import Render from "./chat-render"

export default class Chat extends Base {
  constructor (props) {
    super(props)
  }
  render () {
    return Render.apply(this)
  }

  static parseRoute (store, currentPath, nextPath) {
    return {
      componentAtTop: {
        component: Chat,
        title: 'Chat'
      },
      parseNextRoute: null
    }
  }
}
<commit_msg>Consistent component naming<commit_after>'use strict'
/* @flow */

import BaseComponent from "../base-component"
import Render from "./chat-render"

export default class Chat extends BaseComponent {
  constructor (props) {
    super(props)
  }
  render () {
    return Render.apply(this)
  }

  static parseRoute (store, currentPath, nextPath) {
    return {
      componentAtTop: {
        component: Chat,
        title: 'Chat'
      },
      parseNextRoute: null
    }
  }
}
<|endoftext|>


<commit_before>var query = (year, month, day) => {
  return {
    where: {
      createdAt: {
        between: [year + '-' + month + '-' + day + ' 00:00:00', year + '-' + month + '-' + day + ' 23:59:59']
      }
    }
  }
}

module.exports = function(sequelize, User) {
  var Gratitude = require('./../journals/journeys/gratitude')(sequelize);
  var Outlook = require('./../journals/journeys/outlook')(sequelize);
  var Affirmation = require('./../journals/journeys/affirmation')(sequelize);
  var Amazing = require('./../journals/journeys/amazing')(sequelize);
  var Reflection = require('./../journals/journeys/reflection')(sequelize);

  var getEntriesOnDate = (req, res, next, userId, month, day, year) => {
    var localQuery = query(year, month, day);
    var results = []
    User.find({
      where: {
        id: userId
      }
    })
    .then(user => {
      user.getAffirmations(localQuery)
      .then((affirmation) => {
        results.push(affirmation)
        console.log('made it yo')
        user.getAmazings(localQuery)
        .then((amazing) => {
          results.push(amazing)
          user.getGratitudes(localQuery)
          .then((gratitude) => {
            results.push(gratitude)
            user.getOutlooks(localQuery)
            .then((outlook) => {
              results.push(outlook)
              user.getReflections(localQuery)
              .then(reflection => {
                results.push(reflection)
                res.send(results);
              })
            })
          })
        })
      })
    })
  }

  var postEntry = (req, res, next) => {
    console.log(req.body)
    User.find({
      where: {
        id: req.body.id
      }
    })
    .then(user => {
      if (req.body.affirmation) {
        Affirmation.create({
          entry: req.body.affirmation,
          interface: req.body.interface
        })
        .then(affirmation => {
          user.setAffirmations(affirmation)
        })
      }
      if (req.body.amazing) {
        Amazing.create({
          entry: req.body.amazing,
          interface: req.body.interface
        })
        .then(amazing => {
          user.setAmazings(amazing)
        })
      }
      if (req.body.gratitude) {
        Gratitude.create({
          entry: req.body.gratitude,
          interface: req.body.interface
        })
        .then(gratitude => {
          user.setGratitudes(gratitude)
        })
      }
      Outlook.create({
        entry: req.body.outlook,
        interface: req.body.interface
      })
      .then(outlook => {
        user.setOutlooks(outlook)
      })
      Reflection.create({
        entry: req.body.reflection,
        interface: req.body.interface
      })
      .then(reflection => {
        user.setReflections(reflection)
      })
      res.send(user);
    })
  }

  // var editEntry = (req, res, next, id, year, month, day) => {
  //   User.find({
  //     where: {
  //       id: req.body.id
  //     }
  //   })
  //   .then(user => {
  //     if (req.body.affirmation) {

  //     }
  //     if (req.body.amazing)
  //     if (req.body.gratitude)
  //     if (req.body.outlook)
  //     if (req.body.reflection)
  //   })
  // }

  return {
    getEntriesOnDate: getEntriesOnDate,
    postEntry: postEntry,
    //editEntry: editEntry
  }
}<commit_msg>Server refactor, not working<commit_after>var query = (year, month, day) => {
  return {
    where: {
      createdAt: {
        between: [year + '-' + month + '-' + day + ' 00:00:00', year + '-' + month + '-' + day + ' 23:59:59']
      }
    }
  }
}

module.exports = function(sequelize, User) {
  var Gratitude = require('./../journals/journeys/gratitude')(sequelize);
  var Outlook = require('./../journals/journeys/outlook')(sequelize);
  var Affirmation = require('./../journals/journeys/affirmation')(sequelize);
  var Amazing = require('./../journals/journeys/amazing')(sequelize);
  var Reflection = require('./../journals/journeys/reflection')(sequelize);

  var getEntriesOnDate = (req, res, next, userId, month, day, year) => {
    var localQuery = query(year, month, day);
    var results = []
    User.find({
      where: {
        id: userId
      }
    })
    .then(user => {
      user.getAffirmations(localQuery)
      .then((affirmation) => {
        results.push(affirmation)
        user.getAmazings(localQuery)
        .then((amazing) => {
          results.push(amazing)
          user.getGratitudes(localQuery)
          .then((gratitude) => {
            results.push(gratitude)
            user.getOutlooks(localQuery)
            .then((outlook) => {
              results.push(outlook)
              user.getReflections(localQuery)
              .then(reflection => {
                results.push(reflection)
                res.send(results);
              })
            })
          })
        })
      })
    })
  }

  var postEntry = (req, res, next) => {
    console.log(req.body)
    User.find({
      where: {
        id: req.body.id
      }
    })
    .then(user => {
      if (req.body.affirmation) {
        Affirmation.create({
          entry: req.body.affirmation,
          interface: req.body.interface
        })
        .then(affirmation => {
          user.setAffirmations(affirmation)
        })
      }
      if (req.body.amazing) {
        Amazing.create({
          entry: req.body.amazing,
          interface: req.body.interface
        })
        .then(amazing => {
          user.setAmazings(amazing)
        })
      }
      if (req.body.gratitude) {
        Gratitude.create({
          entry: req.body.gratitude,
          interface: req.body.interface
        })
        .then(gratitude => {
          user.setGratitudes(gratitude)
        })
      }
      Outlook.create({
        entry: req.body.outlook,
        interface: req.body.interface
      })
      .then(outlook => {
        user.setOutlooks(outlook)
      })
      Reflection.create({
        entry: req.body.reflection,
        interface: req.body.interface
      })
      .then(reflection => {
        user.setReflections(reflection)
      })
      res.send(user);
    })
  }

  // var editEntry = (req, res, next, id, year, month, day) => {
  //   User.find({
  //     where: {
  //       id: req.body.id
  //     }
  //   })
  //   .then(user => {
  //     if (req.body.affirmation) {

  //     }
  //     if (req.body.amazing)
  //     if (req.body.gratitude)
  //     if (req.body.outlook)
  //     if (req.body.reflection)
  //   })
  // }

  return {
    getEntriesOnDate: getEntriesOnDate,
    postEntry: postEntry,
    //editEntry: editEntry
  }
}<|endoftext|>


<commit_before>// REPLACE SUB TASK
// replace is called at the install task time, but you can also call it in an already
// created project if you want to recopy the placeholder files.
// - replace goes to each server of the project and looks at all the placholder files
// for each template.
// Placeholder files are matched via the _p_ prefix in their file name.
// In these files all the $[] instances are replaced with values from this teleport object.
// You can check more precisely how the formatString function works in the ../utils/index.js.
// Note also that the replace method will for each _p_<file_name> placeholder file
// create one file per type (localhost, staging and production in the common case).
// Meaning that you will have localhost_<file_name>, staging_<file_name>,
// production_<file_name> created.
// - replace goes to your bundler folder and does the same thing, except
// that it is not going to create one file per type, just only one.

import fs from 'fs'
import glob from 'glob'
import mkdirp from 'mkdirp'
import path from 'path'

import { formatString } from '../utils'

const dockerPlaceholderfiles = [
  'build.sh',
  'controller.yaml',
  'Dockerfile',
  'service.yaml'
]

const deployPlaceholderfiles = [
  'build.sh',
  'controller.yaml',
  'deploy.sh',
  'push.sh',
  'run.sh',
  'service.yaml'
]

const notLocalhostPlaceholderFiles = [
  /.*push.sh$/,
  /.*controller.sh$/,
  /.*build.sh$/,
  /.*controller.yaml$/,
  /.*deploy.sh$/,
  /.*Dockerfile$/,
  /.*push.sh$/,
  /.*Procfile$/,
  /.*run.sh$/,
  /.*service.yaml$/
]
const templatePrefix = '_p_'

export function replace () {
  const { program, project } = this
  // boilerplate
  program.method = 'replaceServerPlaceholderFiles'
  program.methods = null
  this.mapInTypesAndServers()
  // boilerplate
  this.replaceBundlerPlaceholderFiles()
  // info
  this.consoleInfo(`Your ${project.package.name} project was successfully replaced!`)
}

export function replaceServerPlaceholderFiles () {
  // unpack
  const { backend, project, program, type, run, server } = this
  // connect if no port was set here
  if (type.name !== 'localhost' && typeof run.port === 'undefined') {
    this.connect()
  }
  // add types
  project.typeNames = Object.keys(project.config.typesByName)
  // prepare the extraConfig
  const extraConfig = Object.assign(
    {
      'SITE_NAME': backend.siteName,
      'TYPE': type.name,
      'WEB': 'on'
    },
    backend.dockerEnv,
    server.dockerEnv
  )
  // specify the port if it is already set
  if (server.runsByTypeName[type.name] && server.runsByTypeName[type.name].port) {
    run.port = server.runsByTypeName[type.name].port
  }
  if (run.port) {
    extraConfig.PORT = run.port
  }
  this.dockerExtraConfig = Object.keys(extraConfig)
    .map(key => `ENV ${key} ${extraConfig[key]}`).join('\n')
  this.manageExtraConfig = Object.keys(extraConfig)
    .map(key => `export ${key}=${extraConfig[key]}`).join(' && ')
  if (this.manageExtraConfig.length > 0) {
    this.manageExtraConfig = `${this.manageExtraConfig} &&`
  }
  // for each template replace
  this.getAllTemplateNames().forEach(templateName => {
    const templateDir = path.join(project.nodeModulesDir, templateName)
    // replace at the server scope
    const templateServerDir = path.join(templateDir, 'backend/servers', server.name)
    const templateFileDirs = glob.sync(path.join(templateServerDir, `**/${templatePrefix}*`))
    templateFileDirs.forEach(templateFileDir => {
      const dirChunks = templateFileDir.split('/')
      let installedFileName = dirChunks.slice(-1)[0]
                                       .replace(templatePrefix, '')
      // we know that there are some script and config files dedicated to the deploy step
      // so we don't have actually to write them for the localhost type case
      if (type.name === 'localhost') {
        if (notLocalhostPlaceholderFiles.find(notLocalhostPlaceholderFile => {
          return notLocalhostPlaceholderFile.test(installedFileName)
        })) {
          return
        }
      } else if (installedFileName.split('_')[0] === 'localhost') {
        // also we have some specific placeholder files dedicated to localhost
        // so if we are not to the localhost case we have to leave
        return
      }
      // if we are not in the case of a docker deploy file
      // we can escape
      if (typeof backend.helpersByName.docker === 'undefined' &&
        dockerPlaceholderfiles.includes(installedFileName)) {
        return
      }
      const installedParams = installedFileName.split('_')
      if (
        installedParams.length === 2 && installedParams[0] !== type.name ||
        // NOTE HERE A QUICK WORKAROUND SOLUTION
        // we hardcode the special case of Procfile where we need to make it pass
        // through the replace, but actually not making it specified
        // with the type prefix
        installedParams.length === 1 && installedFileName !== 'Procfile'
      ) {
        installedFileName = `${type.name}_${installedFileName}`
      }
      const installedFolderDir = path.join(project.dir, 'backend', dirChunks.slice(0, -1)
                                  .join('/')
                                  .split('backend')
                                  .slice(-1)[0])
      const installedFileDir = path.join(installedFolderDir, installedFileName)
      if (fs.existsSync(installedFileDir) &&
        // we need to have specified force to true to do the replace
        program.force !== 'true'
      ) {
        return
      }
      // make sure that the folder system to this file already exists
      mkdirp.sync(installedFolderDir)
      const templateFile = fs.readFileSync(templateFileDir, 'utf-8')
      // then write inside
      fs.writeFileSync(installedFileDir, formatString(templateFile, this))
    })
  })
}

export function replaceBundlerPlaceholderFiles () {
  const { project } = this
  this.getAllTemplateNames().forEach(templateName => {
    const templateDir = path.join(project.nodeModulesDir, templateName)
    // replace at the server scope
    const templateBundlerDir = path.join(templateDir, 'bundler')
    if (fs.existsSync(templateBundlerDir)) {
      const templateFileDirs = glob.sync(path.join(templateBundlerDir, `**/${templatePrefix}*`))
      templateFileDirs.forEach(templateFileDir => {
        const dirChunks = templateFileDir.split('/')
        let installedFileName = dirChunks.slice(-1)[0]
                                         .replace(templatePrefix, '')
        const installedFolderDir = path.join(project.dir, 'bundler')
        const installedFileDir = path.join(installedFolderDir, installedFileName)
        const templateFile = fs.readFileSync(templateFileDir, 'utf-8')
        mkdirp.sync(installedFolderDir)
        fs.writeFileSync(installedFileDir, formatString(templateFile, this))
      })
    }
  })
}
<commit_msg>minor copy tweak in replace method file<commit_after>// REPLACE SUB TASK
// replace is called at the install task time, but you can also call it in an already
// created project if you want to recopy the placeholder files.
// - replace goes to each server of the project and looks at all the placholder files
// for each template.
// Placeholder files are matched via the _p_ prefix in their file name.
// In these files all the $[] instances are replaced with values from this teleport object.
// You can check more precisely how the formatString function works in the ../utils/index.js.
// Note also that the replace method will for each _p_<file_name> placeholder file
// create one file per type (localhost, staging and production in the common case).
// Meaning that you will have localhost_<file_name>, staging_<file_name>,
// production_<file_name> created.
// - replace goes to your bundler folder and does the same thing, except
// that it is not going to create one file per type, just only one.

import fs from 'fs'
import glob from 'glob'
import mkdirp from 'mkdirp'
import path from 'path'

import { formatString } from '../utils'

const dockerPlaceholderfiles = [
  'build.sh',
  'controller.yaml',
  'Dockerfile',
  'service.yaml'
]

const deployPlaceholderfiles = [
  'build.sh',
  'controller.yaml',
  'deploy.sh',
  'push.sh',
  'run.sh',
  'service.yaml'
]

const notLocalhostPlaceholderFiles = [
  /.*push.sh$/,
  /.*controller.sh$/,
  /.*build.sh$/,
  /.*controller.yaml$/,
  /.*deploy.sh$/,
  /.*Dockerfile$/,
  /.*push.sh$/,
  /.*Procfile$/,
  /.*run.sh$/,
  /.*service.yaml$/
]
const templatePrefix = '_p_'

export function replace () {
  const { program, project } = this
  // boilerplate
  program.method = 'replaceServerPlaceholderFiles'
  program.methods = null
  this.mapInTypesAndServers()
  // boilerplate
  this.replaceBundlerPlaceholderFiles()
  // info
  this.consoleInfo(`Your ${project.package.name} project was successfully replaced!`)
}

export function replaceServerPlaceholderFiles () {
  // unpack
  const { backend, project, program, type, run, server } = this
  // connect if no port was set here
  if (type.name !== 'localhost' && typeof run.port === 'undefined') {
    this.connect()
  }
  // add types
  project.typeNames = Object.keys(project.config.typesByName)
  // prepare the extraConfig
  const extraConfig = Object.assign(
    {
      'SITE_NAME': backend.siteName,
      'TYPE': type.name,
      'WEB': 'on'
    },
    backend.dockerEnv,
    server.dockerEnv
  )
  // specify the port if it is available
  if (server.runsByTypeName[type.name] && server.runsByTypeName[type.name].port) {
    run.port = server.runsByTypeName[type.name].port
  }
  if (run.port) {
    extraConfig.PORT = run.port
  }
  this.dockerExtraConfig = Object.keys(extraConfig)
    .map(key => `ENV ${key} ${extraConfig[key]}`).join('\n')
  this.manageExtraConfig = Object.keys(extraConfig)
    .map(key => `export ${key}=${extraConfig[key]}`).join(' && ')
  if (this.manageExtraConfig.length > 0) {
    this.manageExtraConfig = `${this.manageExtraConfig} &&`
  }
  // for each template replace
  this.getAllTemplateNames().forEach(templateName => {
    const templateDir = path.join(project.nodeModulesDir, templateName)
    // replace at the server scope
    const templateServerDir = path.join(templateDir, 'backend/servers', server.name)
    const templateFileDirs = glob.sync(path.join(templateServerDir, `**/${templatePrefix}*`))
    templateFileDirs.forEach(templateFileDir => {
      const dirChunks = templateFileDir.split('/')
      let installedFileName = dirChunks.slice(-1)[0]
                                       .replace(templatePrefix, '')
      // we know that there are some script and config files dedicated to the deploy step
      // so we don't have actually to write them for the localhost type case
      if (type.name === 'localhost') {
        if (notLocalhostPlaceholderFiles.find(notLocalhostPlaceholderFile => {
          return notLocalhostPlaceholderFile.test(installedFileName)
        })) {
          return
        }
      } else if (installedFileName.split('_')[0] === 'localhost') {
        // also we have some specific placeholder files dedicated to localhost
        // so if we are not to the localhost case we have to leave
        return
      }
      // if we are not in the case of a docker deploy file
      // we can escape
      if (typeof backend.helpersByName.docker === 'undefined' &&
        dockerPlaceholderfiles.includes(installedFileName)) {
        return
      }
      const installedParams = installedFileName.split('_')
      if (
        installedParams.length === 2 && installedParams[0] !== type.name ||
        // NOTE HERE A QUICK WORKAROUND SOLUTION
        // we hardcode the special case of Procfile where we need to make it pass
        // through the replace, but actually not making it specified
        // with the type prefix
        installedParams.length === 1 && installedFileName !== 'Procfile'
      ) {
        installedFileName = `${type.name}_${installedFileName}`
      }
      const installedFolderDir = path.join(project.dir, 'backend', dirChunks.slice(0, -1)
                                  .join('/')
                                  .split('backend')
                                  .slice(-1)[0])
      const installedFileDir = path.join(installedFolderDir, installedFileName)
      if (fs.existsSync(installedFileDir) &&
        // we need to have specified force to true to do the replace
        program.force !== 'true'
      ) {
        return
      }
      // make sure that the folder system to this file already exists
      mkdirp.sync(installedFolderDir)
      const templateFile = fs.readFileSync(templateFileDir, 'utf-8')
      // then write inside
      fs.writeFileSync(installedFileDir, formatString(templateFile, this))
    })
  })
}

export function replaceBundlerPlaceholderFiles () {
  const { project } = this
  this.getAllTemplateNames().forEach(templateName => {
    const templateDir = path.join(project.nodeModulesDir, templateName)
    // replace at the server scope
    const templateBundlerDir = path.join(templateDir, 'bundler')
    if (fs.existsSync(templateBundlerDir)) {
      const templateFileDirs = glob.sync(path.join(templateBundlerDir, `**/${templatePrefix}*`))
      templateFileDirs.forEach(templateFileDir => {
        const dirChunks = templateFileDir.split('/')
        let installedFileName = dirChunks.slice(-1)[0]
                                         .replace(templatePrefix, '')
        const installedFolderDir = path.join(project.dir, 'bundler')
        const installedFileDir = path.join(installedFolderDir, installedFileName)
        const templateFile = fs.readFileSync(templateFileDir, 'utf-8')
        mkdirp.sync(installedFolderDir)
        fs.writeFileSync(installedFileDir, formatString(templateFile, this))
      })
    }
  })
}
<|endoftext|>


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

    global.setupEventPersonsList = function setupEventPersonsList() {
        enableIfChecked('#persons-list', '.select-row:visible', '#persons-list .js-requires-selected-row');
        $('#persons-list [data-toggle=dropdown]').closest('.group').dropdown();

        $('#persons-list [data-filter]').on('click', function() {
            var personRows = $('#persons-list tr[data-person-roles]');
            var filters = $('#persons-list [data-filter]:checked').map(function() {
                return $(this).data('filter');
            }).get();

            var visibleEntries = personRows.filter(function() {
                var $this = $(this);

                return _.any(filters, function(filterName) {
                    return $this.data('person-roles')[filterName];
                });
            });

            personRows.hide();
            visibleEntries.show();
            $('#persons-list').trigger('indico:syncEnableIfChecked');
        });

        $('#persons-list td').on('mouseenter', function() {
            var $this = $(this);
            if (this.offsetWidth < this.scrollWidth && !$this.attr('title')) {
                $this.attr('title', $this.text());
            }
        });

        $('#persons-list .tablesorter').tablesorter({
            cssAsc: 'header-sort-asc',
            cssDesc: 'header-sort-desc',
            headerTemplate: '',
            sortList: [[1, 0]]
        });

        $('#persons-list .js-count-label:not(.no-role)').qbubble({
            show: {
                event: 'mouseover'
            },
            hide: {
                fixed: true,
                delay: 100,
                event: 'mouseleave'
            },
            position: {
                my: 'left center',
                at: 'right center'
            },
            content: {
                text: function() {
                    var items = $(this).data('items');
                    var html = $('
');

                    $.each(items, function() {
                        var item = $('
');
                        if (this.url) {
                            item.append($('', {text: this.title, 'href': this.url}));
                        } else {
                            item.text(this.title);
                        }
                        html.append(item);
                    });

                    return html;
                }
            }
        });
    };

    global.showUndoWarning = function showUndoWarning(message, feedbackMessage, actionCallback) {
        cornerMessage({
            message: message,
            progressMessage: $T.gettext("Undoing previous operation..."),
            feedbackMessage: feedbackMessage,
            actionLabel: $T.gettext('Undo'),
            actionCallback: actionCallback,
            duration: 10000,
            feedbackDuration: 4000,
            class: 'warning'
        });
    };
})(window);
<commit_msg>Allow person filters to be explicitly refreshed<commit_after>(function(global) {
    'use strict';

    global.refreshPersonFilters = function refreshPersonFilters() {
        var personRows = $('#persons-list tr[data-person-roles]');
        var filters = $('#persons-list [data-filter]:checked').map(function() {
            return $(this).data('filter');
        }).get();

        var visibleEntries = personRows.filter(function() {
            var $this = $(this);

            return _.any(filters, function(filterName) {
                return $this.data('person-roles')[filterName];
            });
        });

        personRows.hide();
        visibleEntries.show();
        $('#persons-list').trigger('indico:syncEnableIfChecked');
    };

    global.setupEventPersonsList = function setupEventPersonsList() {
        enableIfChecked('#persons-list', '.select-row:visible', '#persons-list .js-requires-selected-row');
        $('#persons-list [data-toggle=dropdown]').closest('.group').dropdown();
        $('#persons-list [data-filter]').on('click', refreshPersonFilters);

        $('#persons-list td').on('mouseenter', function() {
            var $this = $(this);
            if (this.offsetWidth < this.scrollWidth && !$this.attr('title')) {
                $this.attr('title', $this.text());
            }
        });

        $('#persons-list .tablesorter').tablesorter({
            cssAsc: 'header-sort-asc',
            cssDesc: 'header-sort-desc',
            headerTemplate: '',
            sortList: [[1, 0]]
        });

        $('#persons-list .js-count-label:not(.no-role)').qbubble({
            show: {
                event: 'mouseover'
            },
            hide: {
                fixed: true,
                delay: 100,
                event: 'mouseleave'
            },
            position: {
                my: 'left center',
                at: 'right center'
            },
            content: {
                text: function() {
                    var items = $(this).data('items');
                    var html = $('
');

                    $.each(items, function() {
                        var item = $('
');
                        if (this.url) {
                            item.append($('', {text: this.title, 'href': this.url}));
                        } else {
                            item.text(this.title);
                        }
                        html.append(item);
                    });

                    return html;
                }
            }
        });
    };

    global.showUndoWarning = function showUndoWarning(message, feedbackMessage, actionCallback) {
        cornerMessage({
            message: message,
            progressMessage: $T.gettext("Undoing previous operation..."),
            feedbackMessage: feedbackMessage,
            actionLabel: $T.gettext('Undo'),
            actionCallback: actionCallback,
            duration: 10000,
            feedbackDuration: 4000,
            class: 'warning'
        });
    };
})(window);
<|endoftext|>


<commit_before>'use strict'

var Atomic = require('./component')
var utils = require('../utils')

var DEFAULT_FONT_SIZE = 32

// attr
//  - value: text content.
//  - lines: maximum lines of the text.
function Text (data) {
  Atomic.call(this, data)
}

Text.prototype = Object.create(Atomic.prototype)

Text.prototype.create = function () {
  var node = document.createElement('div')
  node.classList.add('weex-container')
  node.style.fontSize = DEFAULT_FONT_SIZE * this.data.scale + 'px'
  this.textNode = document.createElement('span')
  // Give the developers the ability to control space
  // and line-breakers.
  this.textNode.style.whiteSpace = 'pre-wrap'
  this.textNode.style.display = '-webkit-box'
  this.textNode.style.webkitBoxOrient = 'vertical'
  this.style.lines.call(this, this.data.style.lines)
  node.appendChild(this.textNode)
  return node
}

Text.prototype.attr = {
  value: function (value) {
    var span = this.node.firstChild
    span.innerHTML = ''
    if (!value) {
      return
    }
    span.textContent = value
    /**
     * Developers are supposed to have the ability to break text
     * lines manually. Using `` `` to replace text space is
     * not compatible with the ``-webkit-line-clamp``. Therefor
     * we use ``white-space: no-wrap`` instead (instead of the
     * code bellow).

      var frag = document.createDocumentFragment()
        text.split(' ').forEach(function(str) {
          var textNode = document.createTextNode(str)
          var space = document.createElement('i')
          space.innerHTML = ' '
          frag.appendChild(space)
          frag.appendChild(textNode)
        })
        frag.removeChild(frag.firstChild)
        span.appendChild(document.createElement('br'))
        span.appendChild(frag)
      })
      span.removeChild(span.firstChild)
     */
  }
}

Text.prototype.clearAttr = function () {
  this.node.firstChild.textContent = ''
}

Text.prototype.style = utils.extend(Object.create(Atomic.prototype.style), {

  lines: function (val) {
    val = parseInt(val)
    if (val !== val) { // NaN
      return
    }
    if (val <= 0) {
      this.textNode.style.textOverflow = ''
      this.textNode.style.overflow = 'visible'
      this.textNode.style.webkitLineClamp = ''
    } else {
      this.textNode.style.overflow = 'hidden'
      this.textNode.style.textOverflow = 'ellipsis'
      this.textNode.style.webkitLineClamp = val
    }
  }

})

module.exports = Text
<commit_msg>* [html5] add text-overflow<commit_after>'use strict'

var Atomic = require('./component')
var utils = require('../utils')

var DEFAULT_FONT_SIZE = 32
var DEFAULT_TEXT_OVERFLOW = 'ellipsis'

// attr
//  - value: text content.
//  - lines: maximum lines of the text.
function Text (data) {
  Atomic.call(this, data)
}

Text.prototype = Object.create(Atomic.prototype)

Text.prototype.create = function () {
  var node = document.createElement('div')
  node.classList.add('weex-container')
  node.style.fontSize = DEFAULT_FONT_SIZE * this.data.scale + 'px'
  this.textNode = document.createElement('span')
  // Give the developers the ability to control space
  // and line-breakers.
  this.textNode.style.whiteSpace = 'pre-wrap'
  this.textNode.style.display = '-webkit-box'
  this.textNode.style.webkitBoxOrient = 'vertical'
  this.style.lines.call(this, this.data.style.lines)
  node.appendChild(this.textNode)
  return node
}

Text.prototype.attr = {
  value: function (value) {
    var span = this.node.firstChild
    span.innerHTML = ''
    if (!value) {
      return
    }
    span.textContent = value
    /**
     * Developers are supposed to have the ability to break text
     * lines manually. Using `` `` to replace text space is
     * not compatible with the ``-webkit-line-clamp``. Therefor
     * we use ``white-space: no-wrap`` instead (instead of the
     * code bellow).

      var frag = document.createDocumentFragment()
        text.split(' ').forEach(function(str) {
          var textNode = document.createTextNode(str)
          var space = document.createElement('i')
          space.innerHTML = ' '
          frag.appendChild(space)
          frag.appendChild(textNode)
        })
        frag.removeChild(frag.firstChild)
        span.appendChild(document.createElement('br'))
        span.appendChild(frag)
      })
      span.removeChild(span.firstChild)
     */
  }
}

Text.prototype.clearAttr = function () {
  this.node.firstChild.textContent = ''
}

Text.prototype.style = utils.extend(Object.create(Atomic.prototype.style), {

  lines: function (val) {
    val = parseInt(val)
    if (val !== val) { // NaN
      return
    }
    if (val <= 0) {
      this.textNode.style.textOverflow = ''
      this.textNode.style.overflow = 'visible'
      this.textNode.style.webkitLineClamp = ''
    } else {
      var style = this.data ? this.data.style : null
      this.textNode.style.overflow = 'hidden'
      this.textNode.style.textOverflow = style ? style.textOverflow : DEFAULT_TEXT_OVERFLOW
      this.textNode.style.webkitLineClamp = val
    }
  },

  textOverflow: function (val) {
    this.textNode.style.textOverflow = val
  }

})

module.exports = Text
<|endoftext|>


<commit_before>import Vue from 'vue'
import VueRouter from 'vue-router'
import originalCreateStore from '~/store'
import { merge } from 'lodash'
import { RouterLinkStub as NuxtLink } from '@vue/test-utils'
import axiosMock from './axios-mock'
import fixtures from './fixtures'

beforeEach(() => {
  Vue.prototype.$toast = {
    error: jest.fn(),
    success: jest.fn()
  }
})

function createStore() {
  const store = originalCreateStore()
  store.replaceState({
    auth: {
      loggedIn: false,
      user: null
    }
  })
  return store
}

const authedUserCreateStore = () => {
  const store = createStore()
  store.replaceState({
    auth: {
      loggedIn: true,
      user: {
        data: {
          user: {
            username: 'foo',
            id: '1'
          },
          storage: {
            available: 1
          }
        }
      }
    }
  })
  return store
}

const baseMountOpts = (...overrides) =>
  merge(
    {},
    {
      stubs: {
        NuxtLink
      }
    },
    ...overrides
  )

export {
  createStore,
  VueRouter,
  authedUserCreateStore,
  baseMountOpts,
  axiosMock,
  fixtures
}

export * from '@vue/test-utils'
<commit_msg>Add $auth mock<commit_after>import Vue from 'vue'
import VueRouter from 'vue-router'
import originalCreateStore from '~/store'
import { merge } from 'lodash'
import { RouterLinkStub as NuxtLink } from '@vue/test-utils'
import axiosMock from './axios-mock'
import fixtures from './fixtures'

beforeEach(() => {
  Vue.prototype.$toast = {
    error: jest.fn(),
    success: jest.fn()
  }
  Vue.prototype.$auth = {
    loginWith: jest.fn(),
    logout: jest.fn()
  }
})

function createStore() {
  const store = originalCreateStore()
  store.replaceState({
    auth: {
      loggedIn: false,
      user: null
    }
  })
  return store
}

const authedUserCreateStore = () => {
  const store = createStore()
  store.replaceState({
    auth: {
      loggedIn: true,
      user: {
        data: {
          user: {
            username: 'foo',
            id: '1'
          },
          storage: {
            available: 1
          }
        }
      }
    }
  })
  return store
}

const baseMountOpts = (...overrides) =>
  merge(
    {},
    {
      stubs: {
        NuxtLink
      }
    },
    ...overrides
  )

export {
  createStore,
  VueRouter,
  authedUserCreateStore,
  baseMountOpts,
  axiosMock,
  fixtures
}

export * from '@vue/test-utils'
<|endoftext|>


<commit_before>mi2JS.comp.add('base/MultiCheck', 'base/InputBase', '',

// component initializer function that defines constructor and adds methods to the prototype
function(proto, superProto, comp, superComp){

	var mi2 = mi2JS;

	mi2.mixin(comp,mi2.NWGroup);

	proto.itemTpl = {tag:'B'};

	proto.construct = function(el, tpl, parent){
		this.items = {};
		superProto.construct.call(this, el, tpl, parent);

		this.listen(el,'click');
		this.mapItems(el.children);
		if(this.isReadOnly()) this.setReadOnly(true);
	};

	proto.mapItems = function(it){
		var id, nw;
		for(var i=0; i<it.length; i++){
			nw = this.findRef(it[i]);
			id = nw.data('id');
			if(id !== null) this.items[id] = nw;
		}
	};

	proto.setReadOnly = function(v){
		superProto.setReadOnly.call(this,v);
		this.callFunc('attr',['readonly',v ? '':null]);
	};

	proto.on_click = function(evt){
		if(this.isReadOnly() || !this.isEnabled()) return;

		var target = this.item(evt.target);
		if(target){
			if(this.attr('single-value')){
				this.selectedIs(target.data('id'));
			}else{
				target.setSelected(!target.isSelected());
			}
			this.fireIfChanged();
		}
	};

	proto.setConfig = function(data){
		// NodeWrapper is cheap, so we discard the old ones
		this.innerHTML = '';
		this.items = {};
		// allow key:value object or array of {id:'',text:''} objects
		var isArray = data instanceof Array;
		for(var p in data){
			var id = isArray ? data[p].id : p;
			var item = mi2.add(this.el, this.itemTpl);
			item.data('id', id);
			item.setText(   isArray ? data[p].text  : data[p]);
			this.items[id] = item;
		}
	};

	proto.setRawValue = function(value){
		this.selectedIs( value );
	};

	proto.getRawValue = function(value){
		var ret = this.forEachGetArray(function(item){
			if(item.isSelected()) return item.data('id');
		});

		if(this.attr('single-value')) ret = ret[0];

		return ret;
	};

});
<commit_msg>bugfix<commit_after>mi2JS.comp.add('base/MultiCheck', 'base/InputBase', '',

// component initializer function that defines constructor and adds methods to the prototype
function(proto, superProto, comp, superComp){

	var mi2 = mi2JS;

	mi2.mixin(comp,mi2.NWGroup);

	proto.itemTpl = {tag:'B'};

	proto.construct = function(el, tpl, parent){
		this.items = {};
		superProto.construct.call(this, el, tpl, parent);

		this.listen(el,'click');
		this.mapItems(el.children);
		if(this.isReadOnly()) this.setReadOnly(true);
	};

	proto.mapItems = function(it){
		var id, nw;
		for(var i=0; i<it.length; i++){
			nw = this.findRef(it[i]);
			id = nw.data('id');
			if(id !== null) this.items[id] = nw;
		}
	};

	proto.setReadOnly = function(v){
		superProto.setReadOnly.call(this,v);
		this.callFunc('attr',['readonly',v ? '':null]);
	};

	proto.on_click = function(evt){
		if(this.isReadOnly() || !this.isEnabled()) return;

		var target = this.item(evt.target);
		if(target){
			if(this.attr('single-value')){
				this.selectedIs(target.data('id'));
			}else{
				target.setSelected(!target.isSelected());
			}
			this.fireIfChanged();
		}
	};

	proto.setConfig = function(data){
		// NodeWrapper is cheap, so we discard the old ones
		this.el.innerHTML = '';
		this.items = {};
		// allow key:value object or array of {id:'',text:''} objects
		var isArray = data instanceof Array;
		for(var p in data){
			var id = isArray ? data[p].id : p;
			var item = mi2.add(this.el, this.itemTpl);
			item.data('id', id);
			item.setText(   isArray ? data[p].text  : data[p]);
			this.items[id] = item;
		}
	};

	proto.setRawValue = function(value){
		this.selectedIs( value );
	};

	proto.getRawValue = function(value){
		var ret = this.forEachGetArray(function(item){
			if(item.isSelected()) return item.data('id');
		});

		if(this.attr('single-value')) ret = ret[0];

		return ret;
	};

});
<|endoftext|>


<commit_before>var widgetModule = angular.module('widget', ['ngCookies']);

widgetModule.controller('widgetCtrl', function ($scope, $timeout, widgetService, mixpanelService, paramsService, dbService) {

    var hpcloud = 'HP';
    var softlayer = 'SOFTLAYER';
    var play = 'RUNNING';
    var stop = 'STOPPED';

    $scope.widgetStatus = {};

    function _getAdvanced(){
        return $scope.advancedParams[$scope.cloudType];
    }

    $scope.advancedParams = {};
    $scope.advancedParams[hpcloud] = {'type':'hpcloud-compute','params':{'project':null, 'key':null, 'secretKey':null}};
    $scope.advancedParams[softlayer] = {'type':'softlayer', 'params' : {'username':null, 'apiKey':null} };

    $scope.poweredByUrl = {};
    $scope.poweredByUrl[hpcloud] = "http://hpcloud.com";
    $scope.poweredByUrl[softlayer] = "http://softlayer.com";

    function _hasAdvanced(){
        var aData = _getAdvanced();
        var params = aData.params;
        for ( var i in params ){
            if ( params.hasOwnProperty(i) && !params[i] ){
                return false;
            }
        }
        return true;
    }

    function resetWidgetStatus( msg ){
        $scope.widgetStatus = {
            'state' : stop,
            'reset':true
        };

        if ( !!msg ){
            $scope.widgetStatus.message = msg;
        }
        ellipsisIndex = 0;
    }

    var ellipsisIndex = 0;
    var ellipsis='......';

    function _scrollLog() {
        var log = $('#log')[0];
        log.scrollTop = log.scrollHeight;
    }

    function handleStatus( status, myTimeout ){

        console.log(['got status', status]);
        dbService.saveWidgetStatus( status );
        $scope.ellipsis = ellipsis.substring(ellipsis.length - ellipsisIndex % ellipsis.length);
        ellipsisIndex = ellipsisIndex +1;
        $scope.widgetStatus = status;
        $timeout(pollStatus, myTimeout || 3000) ;
        _scrollLog();

    }

    function pollStatus( myTimeout){

        if ( $scope.widgetStatus.state !== stop ){ // keep polling until widget stops ==> mainly for timeleft..
            widgetService.getStatus( $scope.widgetStatus.instanceId, $scope.params.apiKey ).then( function( result ){
                if ( !result ){
                    return ;
                }
                handleStatus( result.status, myTimeout );
            },function(result){
                    console.log(['status error',result]);
                });
        }else{
            console.log("removing widget status");
            dbService.remove();
        }
    }

    $scope.isCompleted = function(){
        return $scope.widgetStatus.state === stop && !$scope.widgetStatus.instanceId && !$scope.widgetStatus.message && $scope.widgetStatus.timeleftMillis === 0;
    };
    $scope.pendingOutput = function(){
        return $scope.widgetStatus.state == play && !$scope.widgetStatus.output;
    };

    $scope.play = function(){
        resetWidgetStatus();
        $scope.widgetStatus.state = play;
        widgetService.play(  $scope.params.apiKey,  _hasAdvanced() ? _getAdvanced() : null )
            .then(function( result ){
                console.log(['play result', result]);
                $scope.widgetStatus = result.status;

                pollStatus(1);
        }, function( result ){
                console.log(['play error', result]);
                resetWidgetStatus("unknown error");
            });
//        success: function (data, textStatus, jqXHR) {
//            var state = data.status.state.toLowerCase();
//            if (state == "error" || state == "stopped") {
//                widgetState.showPlayButton();
//                widgetLog.error(data.status.message);
//                return;
//            }
//            if (data.status.instanceId) {
//                widgetState.instanceId(data.status.instanceId);
//            }
//
//            if ( advancedDataAvailable( advancedData ) ){
//                if (advancedData.project == advancedCookie.project() &&
//                    advancedData.key == advancedCookie.key() &&
//                    advancedData.secretKey == advancedCookie.secretKey()) {
//
//                    advancedCookie.prolong();
//
//                } else {
//                    $(".remember_creds").show();
//                }
//            }
//
//            setTimeoutForUpdateStatus(1);
//        },
//        error: function (data) {
//            var displayMessage = data.getResponseHeader("display-message");
//            if (displayMessage) {
//                var displayMessageObj = JSON.parse(displayMessage);
//                widgetLog.error(displayMessageObj.msg);
//            }
//        }
    };

    $scope.stop = function(){
        $scope.widgetStatus.state = stop;
        resetWidgetStatus();
    };

    $scope.getTimeLeft = function(){
        if ( !$scope.widgetStatus || !$scope.widgetStatus.timeleftMillis ){
            return "";
        }
        var timeLeft = $scope.widgetStatus.timeleftMillis;
        if ( !!timeLeft ){
            timeLeft = timeLeft / 1000;
            return (parseInt(timeLeft /60 ) + 1 )+ " minutes";
        }
        return "";
    };

    $scope.showPlay = function(){
        return $scope.widgetStatus.state === stop;
    };

    $scope.showStop = function(){
        return $scope.widgetStatus.state === play;
    };

    $scope.submitAdvancedData = function(){
        console.log("submitting advanced");
        $scope.play();
    };

    var savedStatus = dbService.getWidgetStatus();

    if ( !!savedStatus ){
        handleStatus( savedStatus,1 );
    }else{
        resetWidgetStatus();
    }

    console.log(["saved status", savedStatus]);
    // place params on scope
    $scope.params = paramsService.params;
    $scope.cloudType = myConf.cloudProvider;

    $scope.isShowAdvanced = function () {
        console.log(["showadvanced param is ", $scope.params.showAdvanced, $scope.params.showAdvanced == "true"]);
        try {
            return $scope.params.showAdvanced == "true";
        } catch (e) {
            return true;
        }
    };

    var apiKey = $scope.params.apiKey;
    var shareUrl= encodeURI("http://bluforcloud.com");

    var msg =  encodeURI("Launch on the cloud in a single click using the Cloudify widget");
    var twitterMsg = encodeURIComponent( $scope.params.title + " on any cloud with a single click with #cloudifysource");

    $("#facebook_share_link").attr("href", "http://www.facebook.com/sharer/sharer.php?u=" + shareUrl).click(function(){
        window.open('http://www.facebook.com/sharer/sharer.php?u=' + shareUrl, 'facebook_share', 'height=320, width=640, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no');
        return false;
    });
    $("#google_plus_share_link").attr("href", "https://plus.google.com/share?url=" + shareUrl);
    $("#twitter_share_link").attr("href", "https://twitter.com/share?url=" + encodeURIComponent($scope.params.origin_page_url) + "&text=" + twitterMsg);

});

// encrypt decrypt service
widgetModule.service('encryptDecrypt', function ($http) {
    this.encrypt = function (data) {
        return $http.post('/encrypt', {data: data });
    };

    this.decrypt = function (data) {
        return $http.post('/decrypt', {data: data})
    };
});

widgetModule.service('paramsService', function(){
    // read params from URL;
    function get_params() {
        var params = {};
        var hash;
        var hashes = window.location.search.substring(1).split('&');
        console.log(["using search tearm", hashes ]);
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            if ($.trim(hash[1]) != ""){
                params[hash[0]] = decodeURIComponent(hash[1]);
            }
        }
        console.log(["params are",params]);
        return params;
    }

    this.params = get_params();
});

widgetModule.service('dbService', function( $cookieStore, paramsService ){

    var params = paramsService.params;

    function getCookieName(){
        return "widgetCookie" + params.origin_page_url + params.apiKey;
    }

    this.remove = function(){
        this.saveWidgetStatus(null);
    };

    this.saveWidgetStatus = function(status){
        if ( !status ){
           $cookieStore.remove( getCookieName() );
        }else{
            $cookieStore.put( getCookieName() , status);
        }
    };

    this.getWidgetStatus = function(){
        return $cookieStore.get( getCookieName() );
    }
});

widgetModule.service('advancedData', function (encryptDecrypt) {
    var cookieName = "ADVANCED_DATA";
    this.save = function (data) {
        encryptDecrypt.encrypt(data).then(function (result) {
            $.cookie(cookieName, JSON.stringify(data), {"path": "/", expires: 10000 });
        });
    };

    this.load = function () {

        encryptDecrypt.decrypt($.cookie(cookieName)).then(function (result) {
            return result.data
        });
    }
});

widgetModule.service('widgetService', function( $http, mixpanelService, paramsService ){
    var origin_page_url = paramsService.params.origin_page_url;
    this.getStatus = function( instanceId , apiKey ){
        return $http.get( "/widget/"+ instanceId + "/status?apiKey=" + apiKey).then( function( data ){
            $.postMessage( JSON.stringify({name:"widget_status", data:data.data}), origin_page_url , parent );
            return data.data;
        });
    };

    this.play = function( apiKey, advancedData ){
        $.postMessage( JSON.stringify({name:"play_widget"}), origin_page_url , parent );
        if ( !advancedData ){
            return $http.post( '/widget/start?apiKey=' + encodeURI(apiKey)).then(function(result){ return result.data; });
        }else{
            return $http.post( '/widget/start?apiKey=' + encodeURI(apiKey),advancedData).then(function(result){ return result.data});
        }

    };

    this.stop = function(){
        if (!confirm("Are you sure you want to stop the instance?")) {
            return;
        }
        mixpanelService.stopWidget();
        $.postMessage( JSON.stringify({name:"stop_widget"}), origin_page_url , parent );
        widgetState.showPlayButton();
        if ( widgetState.instanceId()) {
            $.post("/widget/"+ widgetState.instanceId() + "/stop?apiKey=" + params["apiKey"], {}, function (data) {
                if (data && data.status && data.status.state == "error") {
                    widgetState.showPlayButton();
                    widgetLog.error(data.status.message );
                    return;
                }
                stop_instance();
            });
        }
    }
});

widgetModule.service('mixpanelService', function( paramsService){
    var params = paramsService.params;
      this.stopWidget = function(){
            mixpanel.track("Stop Widget",{'page name' : params.title, 'url' : params.origin_page_url });
      };
});

<commit_msg>fixing social links.<commit_after>var widgetModule = angular.module('widget', ['ngCookies']);

widgetModule.controller('widgetCtrl', function ($scope, $timeout, widgetService, mixpanelService, paramsService, dbService) {

    var hpcloud = 'HP';
    var softlayer = 'SOFTLAYER';
    var play = 'RUNNING';
    var stop = 'STOPPED';

    $scope.widgetStatus = {};

    function _getAdvanced(){
        return $scope.advancedParams[$scope.cloudType];
    }

    $scope.advancedParams = {};
    $scope.advancedParams[hpcloud] = {'type':'hpcloud-compute','params':{'project':null, 'key':null, 'secretKey':null}};
    $scope.advancedParams[softlayer] = {'type':'softlayer', 'params' : {'username':null, 'apiKey':null} };

    $scope.poweredByUrl = {};
    $scope.poweredByUrl[hpcloud] = "http://hpcloud.com";
    $scope.poweredByUrl[softlayer] = "http://softlayer.com";

    function _hasAdvanced(){
        var aData = _getAdvanced();
        var params = aData.params;
        for ( var i in params ){
            if ( params.hasOwnProperty(i) && !params[i] ){
                return false;
            }
        }
        return true;
    }

    function resetWidgetStatus( msg ){
        $scope.widgetStatus = {
            'state' : stop,
            'reset':true
        };

        if ( !!msg ){
            $scope.widgetStatus.message = msg;
        }
        ellipsisIndex = 0;
    }

    var ellipsisIndex = 0;
    var ellipsis='......';

    function _scrollLog() {
        var log = $('#log')[0];
        log.scrollTop = log.scrollHeight;
    }

    function handleStatus( status, myTimeout ){

        console.log(['got status', status]);
        dbService.saveWidgetStatus( status );
        $scope.ellipsis = ellipsis.substring(ellipsis.length - ellipsisIndex % ellipsis.length);
        ellipsisIndex = ellipsisIndex +1;
        $scope.widgetStatus = status;
        $timeout(pollStatus, myTimeout || 3000) ;
        _scrollLog();

    }

    function pollStatus( myTimeout){

        if ( $scope.widgetStatus.state !== stop ){ // keep polling until widget stops ==> mainly for timeleft..
            widgetService.getStatus( $scope.widgetStatus.instanceId, $scope.params.apiKey ).then( function( result ){
                if ( !result ){
                    return ;
                }
                handleStatus( result.status, myTimeout );
            },function(result){
                    console.log(['status error',result]);
                });
        }else{
            console.log("removing widget status");
            dbService.remove();
        }
    }

    $scope.isCompleted = function(){
        return $scope.widgetStatus.state === stop && !$scope.widgetStatus.instanceId && !$scope.widgetStatus.message && $scope.widgetStatus.timeleftMillis === 0;
    };
    $scope.pendingOutput = function(){
        return $scope.widgetStatus.state == play && !$scope.widgetStatus.output;
    };

    $scope.play = function(){
        resetWidgetStatus();
        $scope.widgetStatus.state = play;
        widgetService.play(  $scope.params.apiKey,  _hasAdvanced() ? _getAdvanced() : null )
            .then(function( result ){
                console.log(['play result', result]);
                $scope.widgetStatus = result.status;

                pollStatus(1);
        }, function( result ){
                console.log(['play error', result]);
                resetWidgetStatus("unknown error");
            });
//        success: function (data, textStatus, jqXHR) {
//            var state = data.status.state.toLowerCase();
//            if (state == "error" || state == "stopped") {
//                widgetState.showPlayButton();
//                widgetLog.error(data.status.message);
//                return;
//            }
//            if (data.status.instanceId) {
//                widgetState.instanceId(data.status.instanceId);
//            }
//
//            if ( advancedDataAvailable( advancedData ) ){
//                if (advancedData.project == advancedCookie.project() &&
//                    advancedData.key == advancedCookie.key() &&
//                    advancedData.secretKey == advancedCookie.secretKey()) {
//
//                    advancedCookie.prolong();
//
//                } else {
//                    $(".remember_creds").show();
//                }
//            }
//
//            setTimeoutForUpdateStatus(1);
//        },
//        error: function (data) {
//            var displayMessage = data.getResponseHeader("display-message");
//            if (displayMessage) {
//                var displayMessageObj = JSON.parse(displayMessage);
//                widgetLog.error(displayMessageObj.msg);
//            }
//        }
    };

    $scope.stop = function(){
        $scope.widgetStatus.state = stop;
        resetWidgetStatus();
    };

    $scope.getTimeLeft = function(){
        if ( !$scope.widgetStatus || !$scope.widgetStatus.timeleftMillis ){
            return "";
        }
        var timeLeft = $scope.widgetStatus.timeleftMillis;
        if ( !!timeLeft ){
            timeLeft = timeLeft / 1000;
            return (parseInt(timeLeft /60 ) + 1 )+ " minutes";
        }
        return "";
    };

    $scope.showPlay = function(){
        return $scope.widgetStatus.state === stop;
    };

    $scope.showStop = function(){
        return $scope.widgetStatus.state === play;
    };

    $scope.submitAdvancedData = function(){
        console.log("submitting advanced");
        $scope.play();
    };

    var savedStatus = dbService.getWidgetStatus();

    if ( !!savedStatus ){
        handleStatus( savedStatus,1 );
    }else{
        resetWidgetStatus();
    }

    console.log(["saved status", savedStatus]);
    // place params on scope
    $scope.params = paramsService.params;
    $scope.cloudType = myConf.cloudProvider;

    $scope.isShowAdvanced = function () {
        console.log(["showadvanced param is ", $scope.params.showAdvanced, $scope.params.showAdvanced == "true"]);
        try {
            return $scope.params.showAdvanced == "true";
        } catch (e) {
            return true;
        }
    };

    var apiKey = $scope.params.apiKey;
    var shareUrl= encodeURI("http://bluforcloud.com/plans/play");

    var msg =  encodeURI("Launch on the cloud in a single click using the Cloudify widget");
    var twitterMsg = encodeURIComponent( "I just installed #bluforcloud with a single click on http://bluforcloud.com/plans/play");

    $("#facebook_share_link").attr("href", "http://www.facebook.com/sharer/sharer.php?u=" + shareUrl).click(function(){
        window.open('http://www.facebook.com/sharer/sharer.php?u=' + shareUrl, 'facebook_share', 'height=320, width=640, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no');
        return false;
    });
    $("#google_plus_share_link").attr("href", "https://plus.google.com/share?url=" + shareUrl).click(function(){
        window.open("https://plus.google.com/share?url=" + shareUrl, 'height=320, width=640, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no');
    });
    $("#twitter_share_link").attr("href", "https://twitter.com/share?url=" + encodeURIComponent($scope.params.origin_page_url) + "&text=" + twitterMsg).click(function(){
        window.open("https://twitter.com/share?url=" + encodeURIComponent($scope.params.origin_page_url) + "&text=" + twitterMsg, 'height=320, width=640, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no');
    });

});

// encrypt decrypt service
widgetModule.service('encryptDecrypt', function ($http) {
    this.encrypt = function (data) {
        return $http.post('/encrypt', {data: data });
    };

    this.decrypt = function (data) {
        return $http.post('/decrypt', {data: data})
    };
});

widgetModule.service('paramsService', function(){
    // read params from URL;
    function get_params() {
        var params = {};
        var hash;
        var hashes = window.location.search.substring(1).split('&');
        console.log(["using search tearm", hashes ]);
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            if ($.trim(hash[1]) != ""){
                params[hash[0]] = decodeURIComponent(hash[1]);
            }
        }
        console.log(["params are",params]);
        return params;
    }

    this.params = get_params();
});

widgetModule.service('dbService', function( $cookieStore, paramsService ){

    var params = paramsService.params;

    function getCookieName(){
        return "widgetCookie" + params.origin_page_url + params.apiKey;
    }

    this.remove = function(){
        this.saveWidgetStatus(null);
    };

    this.saveWidgetStatus = function(status){
        if ( !status ){
           $cookieStore.remove( getCookieName() );
        }else{
            $cookieStore.put( getCookieName() , status);
        }
    };

    this.getWidgetStatus = function(){
        return $cookieStore.get( getCookieName() );
    }
});

widgetModule.service('advancedData', function (encryptDecrypt) {
    var cookieName = "ADVANCED_DATA";
    this.save = function (data) {
        encryptDecrypt.encrypt(data).then(function (result) {
            $.cookie(cookieName, JSON.stringify(data), {"path": "/", expires: 10000 });
        });
    };

    this.load = function () {

        encryptDecrypt.decrypt($.cookie(cookieName)).then(function (result) {
            return result.data
        });
    }
});

widgetModule.service('widgetService', function( $http, mixpanelService, paramsService ){
    var origin_page_url = paramsService.params.origin_page_url;
    this.getStatus = function( instanceId , apiKey ){
        return $http.get( "/widget/"+ instanceId + "/status?apiKey=" + apiKey).then( function( data ){
            $.postMessage( JSON.stringify({name:"widget_status", data:data.data}), origin_page_url , parent );
            return data.data;
        });
    };

    this.play = function( apiKey, advancedData ){
        $.postMessage( JSON.stringify({name:"play_widget"}), origin_page_url , parent );
        if ( !advancedData ){
            return $http.post( '/widget/start?apiKey=' + encodeURI(apiKey)).then(function(result){ return result.data; });
        }else{
            return $http.post( '/widget/start?apiKey=' + encodeURI(apiKey),advancedData).then(function(result){ return result.data});
        }

    };

    this.stop = function(){
        if (!confirm("Are you sure you want to stop the instance?")) {
            return;
        }
        mixpanelService.stopWidget();
        $.postMessage( JSON.stringify({name:"stop_widget"}), origin_page_url , parent );
        widgetState.showPlayButton();
        if ( widgetState.instanceId()) {
            $.post("/widget/"+ widgetState.instanceId() + "/stop?apiKey=" + params["apiKey"], {}, function (data) {
                if (data && data.status && data.status.state == "error") {
                    widgetState.showPlayButton();
                    widgetLog.error(data.status.message );
                    return;
                }
                stop_instance();
            });
        }
    }
});

widgetModule.service('mixpanelService', function( paramsService){
    var params = paramsService.params;
      this.stopWidget = function(){
            mixpanel.track("Stop Widget",{'page name' : params.title, 'url' : params.origin_page_url });
      };
});

<|endoftext|>


<commit_before>var page = require('webpage').create();
var letters = [
	"a", "b", "c", "d",	"e", "f", "g",
	"h", "i", "j", "k",	"l", "m", "n",
	"o", "p", "q", "r",	"s", "t", "u",
	"v", "w", "x", "y", "z", "0", "1",
	"2", "3", "4", "5",	"6", "7", "8",
	"9"
];

var domain = [
	".com",
	".org",
	".net",
	".gov",
	".mil",
	".edu"
];

for (i=0;i<letters.length;i++) {
	for (d=0;d<domain.length;d++){
		var url = 'http://www.'+letters[i]+domain[d];
		console.log(url);
		page.open(url, function() {
  		page.render('example.png');
  		phantom.exit();
		});

	};
};

<commit_msg>updated to latest attempt<commit_after>var page = require('webpage').create();
var array_position = 0;

var arrayProdsites = [
        "cobnks.com",
        "aertsonmidtown.com",
        "hillcrestbank.com",
        "nbhbank.com",
        "foodwinerum.com",
        "visitbarbados.org",
        "bradentongulfislands.com",
        "visitcabarrus.com",
        "paradisebymarriott.com",
        "admin.paradisebymarriott.com",
        "thevenetianroom.com",
        "casadecampo.com.do",
        "cityway.com",
        "clubquarters.com",
        "davenporthotelcollection.com",
        "dmomojo.com",
        "dolcehotels.es",
        "ironworkshotel.com",
        "ironworksindy.com",
        "kerzner.com",
        "fortmyers-sanibel.com",
        "fortmyers-sanibel.com/island-hopper/",
        "marcam-images.com/",
        "mmgyglobal.com",
        "mortgagelendersofamerica.com",
        "nationalgeographicexpeditions.com",
        "newmexico.org",
        "newmexico.org/trails/",
        "thehomestead.com",
        "rancholaspalmas.com",
        "lacosta.com",
        "montelucia.com",
        "outerbanks.org",
        "rancholaspalmas.com",
        "kcrestaurantweek.com",
        "bankmw.com"
        ];

var scheme = 'http://www.'

function open_website(){
    // Open website
    console.log('Opening: ' + scheme  + arrayProdsites[array_position]);
    page.open(scheme + arrayProdsites[array_position], function(status){
        console.log(status);
        // Render
        if(status === "success") {
            console.log(" Status: " + status);
            console.log('');
            //page.render(array_position + '_example.png');
        } else {
            console.log(' Status: Failed');
            console.log('');
        }

        // Increment
        array_position++;
        page.close();

        // Go to the next or exit
        if(arrayProdsites.length !== array_position){
            open_website();
        } else {
            phantom.exit();
        }
    }).onError;
}

open_website();

<|endoftext|>