<commit_before>const got = require('got');
const cheerio = require('cheerio');

const QUERY_STRING_SETTINGS = [
    'client=chrome',
    'rls=en',
    'ie=UTF-8',
    'oe=UTF-8'
].join('&');

function getText(children) {
    if (children.children) return getText(children.children);
    return children.map(c => {
        return c.children ? getText(c.children) : c.data;
    }).join('');
}

exports.run = async (bot, msg, args) => {
    if (args.length < 1) {
        message.channel.send('You must enter something to search for!');
    }

    await msg.edit(':arrows_counterclockwise: Searching...');

    const res = await got(`https://google.com/search?${QUERY_STRING_SETTINGS}&q=${encodeURIComponent(args.join(' '))}`);
    if (res.statusCode !== 200) {
        return msg.reply(`:no_entry_sign: Error! (${res.statusCode}): ${res.statusMessage}`);
    }

    let $ = cheerio.load(res.body);
    let results = [];

    $('.g').each((i) => {
        results[i] = {};
    });

    $('.g>.r>a').each((i, e) => {
        let raw = e.attribs['href'];
        results[i]['link'] = decodeURIComponent(raw.substr(7, raw.indexOf('&sa=U') - 7));
    });

    $('.g>.s>.st').each((i, e) => {
        results[i]['description'] = getText(e);
    });

    let output = results.filter(r => r.link && r.description)
        .slice(0, 5)
        .map(r => `${r.link}\n\t${r.description}\n`)
        .join('\n');

        msg.reply(`Search results for: \n \`${args.join(' ')}\` is ${output})
};

<commit_msg>Update google.js<commit_after>const got = require('got');
const cheerio = require('cheerio');

const QUERY_STRING_SETTINGS = [
    'client=chrome',
    'rls=en',
    'ie=UTF-8',
    'oe=UTF-8'
].join('&');

function getText(children) {
    if (children.children) return getText(children.children);
    return children.map(c => {
        return c.children ? getText(c.children) : c.data;
    }).join('');
}

exports.run = async (bot, msg, args) => {
    if (args.length < 1) {
        message.channel.send('You must enter something to search for!');
    }

    await msg.edit(':arrows_counterclockwise: Searching...');

    const res = await got(`https://google.com/search?${QUERY_STRING_SETTINGS}&q=${encodeURIComponent(args.join(' '))}`);
    if (res.statusCode !== 200) {
        return msg.reply(`:no_entry_sign: Error! (${res.statusCode}): ${res.statusMessage}`);
    }

    let $ = cheerio.load(res.body);
    let results = [];

    $('.g').each((i) => {
        results[i] = {};
    });

    $('.g>.r>a').each((i, e) => {
        let raw = e.attribs['href'];
        results[i]['link'] = decodeURIComponent(raw.substr(7, raw.indexOf('&sa=U') - 7));
    });

    $('.g>.s>.st').each((i, e) => {
        results[i]['description'] = getText(e);
    });

    let output = results.filter(r => r.link && r.description)
        .slice(0, 5)
        .map(r => `${r.link}\n\t${r.description}\n`)
        .join('\n');

        msg.reply(`Search results for: \n \`${args.join(' ')}\` is ${output}`)
};

<|endoftext|>


<commit_before>const Discord = require('discord.js');
exports.run = (client, message) => {
    const modlog = client.channels.find('name', 'pie-log');
    const user = message.mentions.users.first();
if (message.mentions.users.size < 1) return message.reply('You must mention someone to insult them.').catch(console.error);
message.delete()
var roll = Math.floor(Math.random() * 10) + 1
if (roll = 1) {
  message.channel.send({embed: {
    color: 0xff0000,
    title: "GET REKT KID",
    description: (``),
    footer: ("hahahahahahaha"),
fields: [{
  name: "Insult:",
  value: `${user} is a failed abortion whose birth certificate is an apology from the condom factory.`
}],
  }})
} else {
if (roll = 2) {
    message.channel.send({embed: {
      color: 0xff0000,
      title: "GET REKT KID",
      description: (``),
      footer: ("hahahahahahaha"),
  fields: [{
    name: "Insult:",
    value: `${user} must have been born on a highway, because that's where most accidents happen.`
  }],
    }})
  } else {
if (roll = 3) {
        message.channel.send({embed: {
          color: 0xff0000,
          title: "GET REKT KID",
          description: (``),
          footer: ("hahahahahahaha"),
      fields: [{
        name: "Insult:",
        value: `${user} is so ugly that when your mama dropped you off at school she got a fine for littering.`
      }],
        }})
      }
      else {
        if (roll = 4) {
          message.channel.send({embed: {
            color: 0xff0000,
            title: "GET REKT KID",
            description: (``),
            footer: ("hahahahahahaha"),
        fields: [{
          name: "Insult:",
          value: `${user} Dumbass.`
        }],
          }})
          } else {
            if (roll = 5) {

                message.channel.send({embed: {
                  color: 0xff0000,
                  title: "GET REKT KID",
                  description: (``),
                  footer: ("hahahahahahaha"),
              fields: [{
                name: "Insult:",
                value: `Roses are red, violets are blue, I have 5 fingers, the 3rd ones for ${user}.`
              }],
                }})
              } else {
                if (roll = 6) {
                    message.channel.send({embed: {
                      color: 0xff0000,
                      title: "GET REKT KID",
                      description: (``),
                      footer: ("hahahahahahaha"),
                  fields: [{
                    name: "Insult:",
                    value: `${user} bring everyone a lot of joy, when ${user} leaves the room.`
                  }],
                    }})
                  }
                  else {
                    if (roll = 7) {

                        message.channel.send({embed: {
                          color: 0xff0000,
                          title: "GET REKT KID",
                          description: (``),
                          footer: ("hahahahahahaha"),
                      fields: [{
                        name: "Insult:",
                        value: `I wasn't born with enough middle fingers to let you know how I feel about ${user}.`
                      }],
                        }})
                      }else {
                        if (roll = 8) {
                            message.channel.send({embed: {
                              color: 0xff0000,
                              title: "GET REKT KID",
                              description: (``),
                              footer: ("hahahahahahaha"),
                          fields: [{
                            name: "Insult:",
                            value: `I'm jealous of all the people that haven't met ${user}!`
                          }],
                            }})
                          }else {
                            if (roll = 9) {
                                message.channel.send({embed: {
                                  color: 0xff0000,
                                  title: "GET REKT KID",
                                  description: (``),
                                  footer: ("hahahahahahaha"),
                              fields: [{
                                name: "Insult:",
                                value: `${user} shouldn't play hide and seek, no one would look for ${user}.`
                              }],
                                }})
                              }else {
                                if (roll = 10) {
                                  message.channel.send({embed: {
                                    color: 0xff0000,
                                    title: "KARMA BITCH",
                                    description: (``),
                                    footer: ("God is respectful hahahahahaha"),
                                fields: [{
                                  name: "Insult:",
                                  value: `${message.author} Well, the tables have turned. You're an idiot to trust a bot like me. KARMA.`
                                }],
                                  }})
                                  }
    }
  }
}
                  }
                }
              }
            }
          }
        }

client.channels.get(modlog.id).send({embed: {
    color: 0x0000FF,
    title: "Command input",
    description: `\n\n**Username:** \n${message.author.username} <${message.author}>\n**Command:** ;insult ${user}`,
    timestamp: new Date(),
    footer: {
      icon_url: `${message.author.avatarURL}`,
      text: `User: ${message.author.username}`
    }
  }
})
};

exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: 0
};

exports.help = {
name: 'insult',
description: 'To make the bot insult someone.',
usage: 'insult [mention]'
};
<commit_msg>Update insult.js<commit_after>const Discord = require('discord.js');
exports.run = (client, message) => {
    const modlog = client.channels.find('name', 'pie-log');
    const user = message.mentions.users.first();
if (message.mentions.users.size < 1) return message.reply('You must mention someone to insult them.').catch(console.error);
message.delete()
var roll = Math.floor(Math.random() * 10) + 1
if (roll = 1) {
  message.channel.send({embed: {
    color: 0xff0000,
    title: "GET REKT KID",
    description: (``),
    footer: {text = "hahahahahahaha"},
fields: [{
  name: "Insult:",
  value: `${user} is a failed abortion whose birth certificate is an apology from the condom factory.`
}],
  }})
} else {
if (roll = 2) {
    message.channel.send({embed: {
      color: 0xff0000,
      title: "GET REKT KID",
      description: (``),
      footer: {text = "hahahahahahaha"},
  fields: [{
    name: "Insult:",
    value: `${user} must have been born on a highway, because that's where most accidents happen.`
  }],
    }})
  } else {
if (roll = 3) {
        message.channel.send({embed: {
          color: 0xff0000,
          title: "GET REKT KID",
          description: (``),
          footer: {text = "hahahahahahaha"},
      fields: [{
        name: "Insult:",
        value: `${user} is so ugly that when your mama dropped you off at school she got a fine for littering.`
      }],
        }})
      }
      else {
        if (roll = 4) {
          message.channel.send({embed: {
            color: 0xff0000,
            title: "GET REKT KID",
            description: (``),
            footer: {text = "hahahahahahaha"},
        fields: [{
          name: "Insult:",
          value: `${user} Dumbass.`
        }],
          }})
          } else {
            if (roll = 5) {

                message.channel.send({embed: {
                  color: 0xff0000,
                  title: "GET REKT KID",
                  description: (``),
                  footer: {text = "hahahahahahaha"},
              fields: [{
                name: "Insult:",
                value: `Roses are red, violets are blue, I have 5 fingers, the 3rd ones for ${user}.`
              }],
                }})
              } else {
                if (roll = 6) {
                    message.channel.send({embed: {
                      color: 0xff0000,
                      title: "GET REKT KID",
                      description: (``),
                      footer: {text = "hahahahahahaha"},
                  fields: [{
                    name: "Insult:",
                    value: `${user} bring everyone a lot of joy, when ${user} leaves the room.`
                  }],
                    }})
                  }
                  else {
                    if (roll = 7) {

                        message.channel.send({embed: {
                          color: 0xff0000,
                          title: "GET REKT KID",
                          description: (``),
                          footer: {text = "hahahahahahaha"},
                      fields: [{
                        name: "Insult:",
                        value: `I wasn't born with enough middle fingers to let you know how I feel about ${user}.`
                      }],
                        }})
                      }else {
                        if (roll = 8) {
                            message.channel.send({embed: {
                              color: 0xff0000,
                              title: "GET REKT KID",
                              description: (``),
                              footer: {text = "hahahahahahaha"},
                          fields: [{
                            name: "Insult:",
                            value: `I'm jealous of all the people that haven't met ${user}!`
                          }],
                            }})
                          }else {
                            if (roll = 9) {
                                message.channel.send({embed: {
                                  color: 0xff0000,
                                  title: "GET REKT KID",
                                  description: (``),
                                  footer: {text = "hahahahahahaha"},
                              fields: [{
                                name: "Insult:",
                                value: `${user} shouldn't play hide and seek, no one would look for ${user}.`
                              }],
                                }})
                              }else {
                                if (roll = 10) {
                                  message.channel.send({embed: {
                                    color: 0xff0000,
                                    title: "KARMA BITCH",
                                    description: (``),
                                    footer: {text = "God is respectful hahahahahahaha"},
                                fields: [{
                                  name: "Insult:",
                                  value: `${message.author} Well, the tables have turned. You're an idiot to trust a bot like me. KARMA.`
                                }],
                                  }})
                                  }
    }
  }
}
                  }
                }
              }
            }
          }
        }

client.channels.get(modlog.id).send({embed: {
    color: 0x0000FF,
    title: "Command input",
    description: `\n\n**Username:** \n${message.author.username} <${message.author}>\n**Command:** ;insult ${user}`,
    timestamp: new Date(),
    footer: {
      icon_url: `${message.author.avatarURL}`,
      text: `User: ${message.author.username}`
    }
  }
})
};

exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: 0
};

exports.help = {
name: 'insult',
description: 'To make the bot insult someone.',
usage: 'insult [mention]'
};
<|endoftext|>


<commit_before>const Discord = require('discord.js');
exports.run = (client, message) => {
  const modlog = client.channels.find('name', 'pie-log');
  const anno2 = client.channels.find('name', 'reports');
const guildmember = message.content.split(" ").join(" ").slice(8)
const say = args.slice(1).join(' ');
if (say.length < 1) return message.reply('Please specify on the reason for reporting.').catch(console.error);
message.delete()

client.channels.get(anno2.id).send({embed: {
  color: 0xffff00,
  title: `Report filed`,
  description: ``,
  fields: [{
    name: "ROBLOX Username:",
    value: `${guildmember}`
  },{
  name: "Report reason:",
  value: `${say}`
  }]
    }
    })
};

message.author.sendMessage({embed: {
  color: 0xff0000,
  title: "Report Filed",
  description: (`\n**You have filed a report**\n`),
fields: [{
name: "You filed a report against this ROBLOX player:",
value: `${guildmember}`
},{
name: "Reason:",
value: `${say}`
},{
name: "If you believe that this was an error, please contact a high rank immediately, false report may get you warned!",
value: "Otherwise, your report will be dealt with. You may also head over to the mainframe to file one: https://www.roblox.com/games/1191242893/Mainframe"
}]
    }})
exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: 0
};

exports.help = {
name: 'report',
description: 'Files a report to the high ranks.',
usage: 'report (ROBLOX USERNAME) message'
};
<commit_msg>Update report.js<commit_after>const Discord = require('discord.js');
exports.run = (client, message) => {
  const modlog = client.channels.find('name', 'pie-log');
  const anno2 = client.channels.find('name', 'reports');
const guildmember = message.content.split(" ").join(" ").slice(8)
const say = args.slice(1).join(' ');
if (say.length < 1) return message.reply('Please specify on the reason for reporting.').catch(console.error);
message.delete()

client.channels.get(anno2.id).send({embed: {
  color: 0xffff00,
  title: `Report filed`,
  description: ``,
  fields: [{
    name: "ROBLOX Username:",
    value: `${guildmember}`
  },{
  name: "Report reason:",
  value: `${say}`
  }]
    }
    })
};

message.guild.member(message.author).sendMessage({embed: {
  color: 0xff0000,
  title: "Report Filed",
  description: (`\n**You have filed a report**\n`),
fields: [{
name: "You filed a report against this ROBLOX player:",
value: `${guildmember}`
},{
name: "Reason:",
value: `${say}`
},{
name: "If you believe that this was an error, please contact a high rank immediately, false report may get you warned!",
value: "Otherwise, your report will be dealt with. You may also head over to the mainframe to file one: https://www.roblox.com/games/1191242893/Mainframe"
}]
    }})
exports.conf = {
enabled: true,
guildOnly: false,
aliases: [],
permLevel: 0
};

exports.help = {
name: 'report',
description: 'Files a report to the high ranks.',
usage: 'report (ROBLOX USERNAME) message'
};
<|endoftext|>


<commit_before>const Command = require('../base/Command');

class Squads extends Command {
    constructor(client) {
        super(client, {
            name: 'squads',
            aliases: ['sq', 'squad', 'raid', 'raidteam'],
            category: 'Star Wars'
        });
    }

    async run(client, message, [user, list, phase]) {
        const squadList = client.squads;

        const lang = message.guildSettings.swgoghLanguage;
        const allyCodes = await client.getAllyCode(message, user);
        let player = null;
        if (!allyCodes.length || allyCodes.length > 1) {
            phase = list;
            list = user;
        } else {
            try {
                player = await client.swgohAPI.player(allyCodes[0], lang);
            } catch (e) {
                console.log('Broke getting player in squads: ' + e);
            }
        }
        // console.log(player.roster.filter(c => c.name.includes('Anakin')));

        const lists = Object.keys(squadList).filter(l => !['psummary', 'gsummary'].includes(l));

        if (!list) {
            // No list, show em the possible ones
            return message.channel.send(message.language.get('COMMAND_SQUADS_NO_LIST', lists.join(', ')));
        } else {
            list = list.toLowerCase();
        }
        if (lists.includes(list)) {
            if (!phase) {
                // They've chosen a list, show em the phase list
                const outList = squadList[list].phase.map((p, ix) =>
                    '`' + (ix + 1) + '`'+ ": " + p.name.replace('&', '&').toProperCase().replace(/aat/gi, 'AAT')
                ).join('\n');
                return message.channel.send(message.language.get('COMMAND_SQUADS_SHOW_LIST', list.toProperCase().replace(/aat/gi, 'AAT'), outList));
            } else if (phase > 0 && phase <= squadList[list].phase.length) {
                phase = phase - 1;
                const sqArray = [];
                squadList[list].phase[phase].name = squadList[list].phase[phase].name.replace('&', '&').toProperCase().replace(/aat/gi, 'AAT');
                squadList[list].phase[phase].squads.forEach(s => {
                    let outStr = s.name ? `**${s.name}**\n` : '';

                    outStr += charCheck(s.team, {
                        level : squadList[list].level,
                        stars : squadList[list].rarity,
                        gear  : squadList[list].gear
                    }, player);
                    sqArray.push(outStr);
                });

                const fields = [];
                const outArr = client.msgArray(sqArray, '\n', 1000);
                outArr.forEach((sq, ix) => {
                    fields.push({
                        name: message.language.get('COMMAND_SQUADS_FIELD_HEADER') + (ix === 0 ? '' : ' ' + message.language.get('BASE_CONT_STRING')),
                        value: sq
                    });
                });
                return message.channel.send({embed: {
                    author: {
                        name: squadList[list].name.toProperCase().replace(/aat/gi, 'AAT')
                    },
                    description: `**${squadList[list].phase[phase].name}**\n${squadList[list].rarity}* | g${squadList[list].gear} | lvl${squadList[list].level}`,
                    fields: fields,
                    color: 0x00FF00
                }});
            } else {
                const outList = squadList[list].phase.map((p, ix) => '`' + (ix + 1) + '`'+ ": " + p.name.replace('&', '&').toProperCase().replace(/aat/gi, 'AAT')).join('\n');
                return message.channel.send(message.language.get('COMMAND_SQUAD_INVALID_PHASE', outList));
            }
        } else {
            // Unknown list/ category
            return message.channel.send(`Invalid category, please select one of the following: \n\`${lists.join(', ')}\``);
        }

        function charCheck(characters, stats, player=null) {
            const {level, stars, gear} = stats;
            let outStr = '';
            if (!player) {
                characters.forEach(c => {
                    try {
                        outStr += client.characters.filter(char => char.uniqueName === c.split(':')[0])[0].name + '\n';
                    } catch (e) {
                        console.log(c + ': ' + e);
                    }
                });
            } else {
                characters.forEach(c => {
                    try {
                        const ch = player.roster.filter(char => char.defId === c.split(':')[0])[0];
                        if (!ch) {
                            outStr += '`✗|✗|✗` ' + client.characters.filter(char => char.uniqueName === c.split(':')[0])[0].name + '\n';
                        } else if (ch.rarity >= stars && ch.gear >= gear && ch.level >= level) {
                            outStr += '`✓|✓|✓` **' + ch.name + '**\n';
                        } else {
                            outStr += ch.rarity >= stars ? '`✓|' : '`✗|';
                            outStr += ch.gear   >= gear  ? '✓|' : '✗|';
                            outStr += ch.level  >= level ? '✓` ' : '✗` ';
                            outStr += ch.name + '\n';
                        }
                    } catch (e) {
                        console.log(c + ': ' + e);
                    }
                });
            }
            return outStr;
        }
    }
}

module.exports = Squads;

<commit_msg>Fixed some issues with looking at ship based teams<commit_after>const Command = require('../base/Command');

class Squads extends Command {
    constructor(client) {
        super(client, {
            name: 'squads',
            aliases: ['sq', 'squad', 'raid', 'raidteam'],
            category: 'Star Wars'
        });
    }

    async run(client, message, [user, list, phase]) {
        const squadList = client.squads;
        const lists = Object.keys(squadList).filter(l => !['psummary', 'gsummary'].includes(l));
        let shipEv = false;

        if (!user) {
            return message.channel.send(message.language.get('COMMAND_SQUADS_NO_LIST', lists.join(', ')));
        }

        const lang = message.guildSettings.swgoghLanguage;
        let allyCodes;
        if (user === "me" || client.isUserID(user) || client.isAllyCode(user)) {
            allyCodes = await client.getAllyCode(message, user);
        }
        let player = null;
        if (!allyCodes || !allyCodes.length || allyCodes.length > 1) {
            phase = list;
            list = user;
        } else {
            try {
                player = await client.swgohAPI.player(allyCodes[0], lang);
            } catch (e) {
                console.log('Broke getting player in squads: ' + e);
            }
        }
        // console.log(player.roster.filter(c => c.name.includes('Anakin')));

        if (!list) {
            // No list, show em the possible ones
            return message.channel.send(message.language.get('COMMAND_SQUADS_NO_LIST', lists.join(', ')));
        } else {
            list = list.toLowerCase();
        }
        if (lists.includes(list)) {
            if (!phase) {
                // They've chosen a list, show em the phase list
                const outList = squadList[list].phase.map((p, ix) =>
                    '`' + (ix + 1) + '`'+ ": " + p.name.replace('&', '&').toProperCase().replace(/aat/gi, 'AAT')
                ).join('\n');
                return message.channel.send(message.language.get('COMMAND_SQUADS_SHOW_LIST', list.toProperCase().replace(/aat/gi, 'AAT'), outList));
            } else if (phase > 0 && phase <= squadList[list].phase.length) {
                phase = phase - 1;
                const sqArray = [];
                squadList[list].phase[phase].name = squadList[list].phase[phase].name.replace('&', '&').toProperCase().replace(/aat/gi, 'AAT');
                squadList[list].phase[phase].squads.forEach(s => {
                    let outStr = s.name ? `**${s.name}**\n` : '';

                    outStr += charCheck(s.team, {
                        level : squadList[list].level,
                        stars : squadList[list].rarity,
                        gear  : squadList[list].gear
                    }, player, s.ships);
                    if (s.ships) shipEv = true;
                    sqArray.push(outStr);
                });

                const fields = [];
                const outArr = client.msgArray(sqArray, '\n', 1000);
                outArr.forEach((sq, ix) => {
                    fields.push({
                        name: message.language.get('COMMAND_SQUADS_FIELD_HEADER') + (ix === 0 ? '' : ' ' + message.language.get('BASE_CONT_STRING')),
                        value: sq
                    });
                });
                return message.channel.send({embed: {
                    author: {
                        name: squadList[list].name.toProperCase().replace(/aat/gi, 'AAT')
                    },
                    description: `**${squadList[list].phase[phase].name}**\n${squadList[list].rarity}* ${shipEv ? '' : `| g${squadList[list].gear}`} | lvl${squadList[list].level}`,
                    fields: fields,
                    color: 0x00FF00
                }});
            } else {
                const outList = squadList[list].phase.map((p, ix) => '`' + (ix + 1) + '`'+ ": " + p.name.replace('&', '&').toProperCase().replace(/aat/gi, 'AAT')).join('\n');
                return message.channel.send(message.language.get('COMMAND_SQUAD_INVALID_PHASE', outList));
            }
        } else {
            // Unknown list/ category
            return message.channel.send(`Invalid category, please select one of the following: \n\`${lists.join(', ')}\``);
        }

        function charCheck(characters, stats, player=null, ships=null) {
            const {level, stars, gear} = stats;
            let outStr = '';
            if (!player) {
                characters.forEach(c => {
                    try {
                        if (!ships) {
                            outStr += client.characters.filter(char => char.uniqueName === c.split(':')[0])[0].name + '\n';
                        } else {
                            outStr += client.ships.filter(ship => ship.uniqueName === c.split(':')[0])[0].name + '\n';
                            if (!outStr.length) console.log(c);
                        }
                    } catch (e) {
                        console.log(c + ': ' + e);
                    }
                });
            } else {
                characters.forEach(c => {
                    try {
                        const ch = player.roster.filter(char => char.defId === c.split(':')[0])[0];
                        if (!ch) {
                            if (!ships) {
                                outStr += '`✗|✗|✗` ' + client.characters.filter(char => char.uniqueName === c.split(':')[0])[0].name + '\n';
                            } else {
                                outStr += '`✗|✗` ' + client.characters.filter(char => char.uniqueName === c.split(':')[0])[0].name + '\n';
                            }
                        } else if (ch.rarity >= stars && ch.gear >= gear && ch.level >= level) {
                            if (!ships) {
                                outStr += '`✓|✓|✓` **' + ch.name + '**\n';
                            } else {
                                outStr += '`✓|✓` **' + ch.name + '**\n';
                            }
                        } else {
                            outStr += ch.rarity >= stars ? '`✓|' : '`✗|';
                            if (!ships) {
                                outStr += ch.gear   >= gear  ? '✓|' : '✗|';
                            }
                            outStr += ch.level  >= level ? '✓` ' : '✗` ';
                            outStr += ch.name + '\n';
                        }
                    } catch (e) {
                        console.log(c + ': ' + e);
                    }
                });
            }
            return outStr;
        }
    }
}

module.exports = Squads;

<|endoftext|>


<commit_before>ChatbotLayout.config(
    {
        sampleLink: "sfid/static/samples.json",
        textStartingConversation: 'Type a question or choose one of our samples.',
        submitFunction: submit
    }
);

function submit(input) {
    var data = {"input": removePunctuation(input).toLowerCase()};
    var url = "/sfid";
    $.ajax({
        type: "POST",
        url: url,
        contentType: 'application/json',
        data: JSON.stringify(data, null, '\t'),
        success: function (data) {
            labels = data['labels'];
            intent = data['intent'];
            var formatedAnswer = formatAnswer(input, removePunctuation(input).toLowerCase(), labels, intent);
            ChatbotLayout.pushMessage(formatedAnswer, 'bot');

        }
    });
}

function removePunctuation(input) {
    return input.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()@\+\?><\[\]\+]/g, '');
}

function formatAnswer(original, original_no_punctuation, labels, intent) {
    var formattedAnswer = '';

    labels_model = [labels];
    //labels_model = labels.split(" | ");

    for (var l in labels_model) {
        l = labels_model[l].split(" ");
        var original_splitted = original.split(" ");
        var original_splitted_np = original_no_punctuation.split(" ");
        var mainText = '';
        if (intent === 'restaurant') {
            intent = 'restaurants and food';
        }
        else if (intent === 'movie') {
            intent = 'movies';
        }
        else {
            intent = 'flights';
        }
        mainText = decorateMainText(intent);
        var json_like = '';
        for (i = 0; i < l.length; i++) {
            if (l[i] !== "O") {
                if (l[i].toLowerCase().substring(0, 1) == 'b') {
                    json_like += '

' + l[i].toLowerCase().substring(2, l[i].length) + ': ' + ' ' + original_splitted_np[i] + ' ';
                }
                else {
                    json_like += '' + original_splitted_np[i] + ' ';
                }
            }
        }
        if (json_like !== '') {
            return mainText + decorateInfo(json_like);
        } else {
            return mainText;
        }
    }
}

function decorateMainText(intent) {
    var markupHighlightedIntent = '' + intent + '';
    var answerList = [
        'Did you know that answering ' + markupHighlightedIntent + ' questions is my specialty? ;-)',
        'I love your question about ' + markupHighlightedIntent + ' ... :-)',
        'This is like the zillion-th question you ask me about ' + markupHighlightedIntent + ' ...',
        'Huh... this is the strangest question about ' + markupHighlightedIntent + ' I have ever been asked ...'
    ];
    var randomNumber = Math.ceil(Math.random() * (answerList.length - 1));
    return ('
' + answerList[randomNumber] + '
');
}

function decorateInfo(data) {
    return '

I will make an API call with this detected information' + data + '
'
}
<commit_msg>adding missing full stop<commit_after>ChatbotLayout.config(
    {
        sampleLink: "sfid/static/samples.json",
        textStartingConversation: 'Type a question or choose one of our samples.',
        submitFunction: submit
    }
);

function submit(input) {
    var data = {"input": removePunctuation(input).toLowerCase()};
    var url = "/sfid";
    $.ajax({
        type: "POST",
        url: url,
        contentType: 'application/json',
        data: JSON.stringify(data, null, '\t'),
        success: function (data) {
            labels = data['labels'];
            intent = data['intent'];
            var formatedAnswer = formatAnswer(input, removePunctuation(input).toLowerCase(), labels, intent);
            ChatbotLayout.pushMessage(formatedAnswer, 'bot');

        }
    });
}

function removePunctuation(input) {
    return input.replace(/[\.,-\/#!$%\^&\*;:{}=\-_`~()@\+\?><\[\]\+]/g, '');
}

function formatAnswer(original, original_no_punctuation, labels, intent) {
    var formattedAnswer = '';

    labels_model = [labels];
    //labels_model = labels.split(" | ");

    for (var l in labels_model) {
        l = labels_model[l].split(" ");
        var original_splitted = original.split(" ");
        var original_splitted_np = original_no_punctuation.split(" ");
        var mainText = '';
        if (intent === 'restaurant') {
            intent = 'restaurants and food';
        }
        else if (intent === 'movie') {
            intent = 'movies';
        }
        else {
            intent = 'flights';
        }
        mainText = decorateMainText(intent);
        var json_like = '';
        for (i = 0; i < l.length; i++) {
            if (l[i] !== "O") {
                if (l[i].toLowerCase().substring(0, 1) == 'b') {
                    json_like += '

' + l[i].toLowerCase().substring(2, l[i].length) + ': ' + ' ' + original_splitted_np[i] + ' ';
                }
                else {
                    json_like += '' + original_splitted_np[i] + ' ';
                }
            }
        }
        if (json_like !== '') {
            return mainText + decorateInfo(json_like);
        } else {
            return mainText;
        }
    }
}

function decorateMainText(intent) {
    var markupHighlightedIntent = '' + intent + '';
    var answerList = [
        'Did you know that answering ' + markupHighlightedIntent + ' questions is my specialty? ;-)',
        'I love your question about ' + markupHighlightedIntent + ' ... :-)',
        'This is like the zillion-th question you ask me about ' + markupHighlightedIntent + ' ...',
        'Huh... this is the strangest question about ' + markupHighlightedIntent + ' I have ever been asked ...'
    ];
    var randomNumber = Math.ceil(Math.random() * (answerList.length - 1));
    return ('
' + answerList[randomNumber] + '
');
}

function decorateInfo(data) {
    return '

I will make an API call with this detected information.' + data + '
'
}
<|endoftext|>


<commit_before>const isString = val => typeof val === 'string';
const isBlob = val => val instanceof Blob;
const isObject = val => val != null && typeof val == 'object';

polyfill.call(typeof window === 'object' ? window : this);

function polyfill() {
  if (isSupported.call(this)) return;

  if (!('navigator' in this)) this.navigator = {};
  this.navigator.sendBeacon = sendBeacon.bind(this);
};

function sendBeacon(url, data) {
  const event = this.event && this.event.type;
  const sync = event === 'unload' || event === 'beforeunload';

  const xhr = ('XMLHttpRequest' in this) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
  xhr.open('POST', url, !sync);
  xhr.withCredentials = true;
  xhr.setRequestHeader('Accept', '*/*');

  if (isString(data)) {
    xhr.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8');
    xhr.responseType = 'text/plain';
  } else if (isBlob(data) && data.type) {
    xhr.setRequestHeader('Content-Type', data.type);
  }

  try {
    xhr.send(data);
  } catch (error) {
    return false;
  }

  return true;
}

function isSupported() {
  return ('navigator' in this) && ('sendBeacon' in this.navigator);
}
<commit_msg>fix: use isObject<commit_after>const isString = val => typeof val === 'string';
const isBlob = val => val instanceof Blob;
const isObject = val => val != null && typeof val == 'object';

polyfill.call(isObject(window) ? window : this);

function polyfill() {
  if (isSupported.call(this)) return;

  if (!('navigator' in this)) this.navigator = {};
  this.navigator.sendBeacon = sendBeacon.bind(this);
};

function sendBeacon(url, data) {
  const event = this.event && this.event.type;
  const sync = event === 'unload' || event === 'beforeunload';

  const xhr = ('XMLHttpRequest' in this) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
  xhr.open('POST', url, !sync);
  xhr.withCredentials = true;
  xhr.setRequestHeader('Accept', '*/*');

  if (isString(data)) {
    xhr.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8');
    xhr.responseType = 'text/plain';
  } else if (isBlob(data) && data.type) {
    xhr.setRequestHeader('Content-Type', data.type);
  }

  try {
    xhr.send(data);
  } catch (error) {
    return false;
  }

  return true;
}

function isSupported() {
  return ('navigator' in this) && ('sendBeacon' in this.navigator);
}
<|endoftext|>


<commit_before>/**
 * Created by tungtouch on 2/5/15.
 */

/*
* Listen UDP from Device: 128.199.126.250
* */

var dgram = require("dgram");
var colors = require('colors');
var async = require('async');
var redis = require("redis");
var rClient = redis.createClient();

//var ports = [4000, 4001, 4002, 3333, 4003, 4004, 4005, 4006, 4007, 4008, 4009, 4010, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, 3009, 3010, 3011];
var ports = [4444];
var r = 0;

var client = dgram.createSocket('udp4');

function saveData(index, data){
    rClient.hset("raw", "data"+index, data);
}

rClient.on("error", function (err) {
    console.log("Error " + err);
});

var q = async.queue(function (data, callback) {
    r++;
    console.log
    ("Success: ",
        (" |Record: "+ r +"|").blue,
        (" |Data: " + data.data + '|').red ,
        (' |Process: ' + q.length()).yellow
    );
    saveData(r, data);
    callback();
}, 50);

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

    console.log("Start listen port ",i,":", ports[i]);

    client.on("error", function (err) {
        console.log("Server error:\n".red + err.stack);
        client.close();
    });

    client.on("message", function (data, rinfo) {

        q.push({data: data}, function (err) {
            if(err){
                console.log("Error queue: ", err);
            }
        });
        //console.log("Number process: ", q.length());
        //console.log("Server got: ".yellow + " IP: " +
        //rinfo.address + " - Port:" + rinfo.port);
    });

    client.bind(ports[i]);
}
<commit_msg>Update UDPefef<commit_after>/**
 * Created by tungtouch on 2/5/15.
 */

/*
* Listen UDP from Device: 128.199.126.250
* */

var dgram = require("dgram");
var colors = require('colors');
var async = require('async');
var redis = require("redis");
var rClient = redis.createClient();

//var ports = [4000, 4001, 4002, 3333, 4003, 4004, 4005, 4006, 4007, 4008, 4009, 4010, 3001, 3002, 3003, 3004, 3005, 3006, 3007, 3008, 3009, 3010, 3011];
var ports = [4444];
var r = 0;

var client = dgram.createSocket('udp4');

function saveData(index, data){
    rClient.hset("raw", "data"+index, data);
}

rClient.on("error", function (err) {
    console.log("Error " + err);
});

var q = async.queue(function (data, callback) {
    r++;
    console.log
    ("Success:",
        (" |Record: "+ r).blue,
        (' |Process: ' + q.length()).yellow,
        (" |Data: " + data.data).red
    );
    saveData(r, data);
    callback();
}, 50);

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

    console.log("Start listen port ",i,":", ports[i]);

    client.on("error", function (err) {
        console.log("Server error:\n".red + err.stack);
        client.close();
    });

    client.on("message", function (data, rinfo) {

        q.push({data: data}, function (err) {
            if(err){
                console.log("Error queue: ", err);
            }
        });
        //console.log("Number process: ", q.length());
        //console.log("Server got: ".yellow + " IP: " +
        //rinfo.address + " - Port:" + rinfo.port);
    });

    client.bind(ports[i]);
}
<|endoftext|>


<commit_before>var original = require('original')
  , parse = require('url').parse
  , events = require('events')
  , https = require('https')
  , http = require('http')
  , util = require('util');

function isPlainObject(obj) {
  return Object.getPrototypeOf(obj) === Object.prototype;
}

/**
 * Creates a new EventSource object
 *
 * @param {String} url the URL to which to connect
 * @param {Object} eventSourceInitDict extra init params. See README for details.
 * @api public
 **/
function EventSource(url, eventSourceInitDict) {
  var readyState = EventSource.CONNECTING;
  Object.defineProperty(this, 'readyState', {
    get: function () {
      return readyState;
    }
  });

  Object.defineProperty(this, 'url', {
    get: function () {
      return url;
    }
  });

  var self = this;
  self.reconnectInterval = 1000;
  var connectPending = false;

  function onConnectionClosed() {
    if (connectPending || readyState === EventSource.CLOSED) return;
    connectPending = true;
    readyState = EventSource.CONNECTING;
    _emit('error', new Event('error'));

    // The url may have been changed by a temporary
    // redirect. If that's the case, revert it now.
    if (reconnectUrl) {
      url = reconnectUrl;
      reconnectUrl = null;
    }
    setTimeout(function () {
      if (readyState !== EventSource.CONNECTING) {
        return;
      }
      connect();
    }, self.reconnectInterval);
  }

  var req;
  var lastEventId = '';
  if (eventSourceInitDict && eventSourceInitDict.headers && isPlainObject(eventSourceInitDict.headers) && eventSourceInitDict.headers['Last-Event-ID']) {
    lastEventId = eventSourceInitDict.headers['Last-Event-ID'];
    delete eventSourceInitDict.headers['Last-Event-ID'];
  }

  var discardTrailingNewline = false
    , data = ''
    , eventName = '';

  var reconnectUrl = null;

  function connect() {
    connectPending = false;

    var options = parse(url);
    var isSecure = options.protocol == 'https:';
    options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' };
    if (lastEventId) options.headers['Last-Event-ID'] = lastEventId;
    if (eventSourceInitDict && eventSourceInitDict.headers && isPlainObject(eventSourceInitDict.headers)) {
      for (var i in eventSourceInitDict.headers) {
        var header = eventSourceInitDict.headers[i];
        if (header) {
          options.headers[i] = header;
        }
      }
    }

    options.rejectUnauthorized = !(eventSourceInitDict && eventSourceInitDict.rejectUnauthorized == false);

    req = (isSecure ? https : http).request(options, function (res) {
      // Handle HTTP redirects
      if (res.statusCode == 301 || res.statusCode == 307) {
        if (!res.headers.location) {
          // Server sent redirect response without Location header.
          _emit('error', new Event('error', {status: res.statusCode}));
          return;
        }
        if (res.statusCode == 307) reconnectUrl = url;
        url = res.headers.location;
        process.nextTick(connect);
        return;
      }

      if (res.statusCode !== 200) {
        _emit('error', new Event('error', {status: res.statusCode}));
        return self.close();
      }

      readyState = EventSource.OPEN;
      res.on('close', onConnectionClosed);
      res.on('end', onConnectionClosed);
      _emit('open', new Event('open'));

      // text/event-stream parser adapted from webkit's
      // Source/WebCore/page/EventSource.cpp
      var buf = '';
      res.on('data', function (chunk) {
        buf += chunk;

        var pos = 0
          , length = buf.length;
        while (pos < length) {
          if (discardTrailingNewline) {
            if (buf[pos] === '\n') {
              ++pos;
            }
            discardTrailingNewline = false;
          }

          var lineLength = -1
            , fieldLength = -1
            , c;

          for (var i = pos; lineLength < 0 && i < length; ++i) {
            c = buf[i];
            if (c === ':') {
              if (fieldLength < 0) {
                fieldLength = i - pos;
              }
            } else if (c === '\r') {
              discardTrailingNewline = true;
              lineLength = i - pos;
            } else if (c === '\n') {
              lineLength = i - pos;
            }
          }

          if (lineLength < 0) {
            break;
          }

          parseEventStreamLine(buf, pos, fieldLength, lineLength);

          pos += lineLength + 1;
        }

        if (pos === length) {
          buf = '';
        } else if (pos > 0) {
          buf = buf.slice(pos);
        }
      });
    });

    req.on('error', onConnectionClosed);
    if (req.setNoDelay) req.setNoDelay(true);
    req.end();
  }

  connect();

  function _emit() {
    if (self.listeners(arguments[0]).length > 0) {
      self.emit.apply(self, arguments);
    }
  }

  this.close = function () {
    if (readyState == EventSource.CLOSED) return;
    readyState = EventSource.CLOSED;
    if (req.abort) req.abort();
  };

  function parseEventStreamLine(buf, pos, fieldLength, lineLength) {
    if (lineLength === 0) {
      if (data.length > 0) {
        var type = eventName || 'message';
        _emit(type, new MessageEvent(type, {
          data: data.slice(0, -1), // remove trailing newline
          lastEventId: lastEventId,
          origin: original(url)
        }));
        data = '';
      }
      eventName = void 0;
    } else if (fieldLength > 0) {
      var noValue = fieldLength < 0
        , step = 0
        , field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength));

      if (noValue) {
        step = lineLength;
      } else if (buf[pos + fieldLength + 1] !== ' ') {
        step = fieldLength + 1;
      } else {
        step = fieldLength + 2;
      }
      pos += step;
      var valueLength = lineLength - step
        , value = buf.slice(pos, pos + valueLength);

      if (field === 'data') {
        data += value + '\n';
      } else if (field === 'event') {
        eventName = value;
      } else if (field === 'id') {
        lastEventId = value;
      } else if (field === 'retry') {
        var retry = parseInt(value, 10);
        if (!Number.isNaN(retry)) {
          self.reconnectInterval = retry;
        }
      }
    }
  }
}

module.exports = EventSource;

util.inherits(EventSource, events.EventEmitter);
EventSource.prototype.constructor = EventSource; // make stacktraces readable

['open', 'error', 'message'].forEach(function (method) {
  Object.defineProperty(EventSource.prototype, 'on' + method, {
    /**
     * Returns the current listener
     *
     * @return {Mixed} the set function or undefined
     * @api private
     */
    get: function get() {
      var listener = this.listeners(method)[0];
      return listener ? (listener._listener ? listener._listener : listener) : undefined;
    },

    /**
     * Start listening for events
     *
     * @param {Function} listener the listener
     * @return {Mixed} the set function or undefined
     * @api private
     */
    set: function set(listener) {
      this.removeAllListeners(method);
      this.addEventListener(method, listener);
    }
  });
});

/**
 * Ready states
 */
Object.defineProperty(EventSource, 'CONNECTING', { enumerable: true, value: 0});
Object.defineProperty(EventSource, 'OPEN', { enumerable: true, value: 1});
Object.defineProperty(EventSource, 'CLOSED', { enumerable: true, value: 2});

/**
 * Emulates the W3C Browser based WebSocket interface using addEventListener.
 *
 * @param {String} method Listen for an event
 * @param {Function} listener callback
 * @see https://developer.mozilla.org/en/DOM/element.addEventListener
 * @see http://dev.w3.org/html5/websockets/#the-websocket-interface
 * @api public
 */
EventSource.prototype.addEventListener = function addEventListener(method, listener) {
  if (typeof listener === 'function') {
    // store a reference so we can return the original function again
    listener._listener = listener;
    this.on(method, listener);
  }
};

/**
 * W3C Event
 *
 * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event
 * @api private
 */
function Event(type, optionalProperties) {
  Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true });
  if (optionalProperties) {
    for (var f in optionalProperties) {
      if (optionalProperties.hasOwnProperty(f)) {
        Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true });
      }
    }
  }
}

/**
 * W3C MessageEvent
 *
 * @see http://www.w3.org/TR/webmessaging/#event-definitions
 * @api private
 */
function MessageEvent(type, eventInitDict) {
  Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true });
  for (var f in eventInitDict) {
    if (eventInitDict.hasOwnProperty(f)) {
      Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true });
    }
  }
}
<commit_msg>Flag eventSourceInitDict as optional in JSDoc<commit_after>var original = require('original')
  , parse = require('url').parse
  , events = require('events')
  , https = require('https')
  , http = require('http')
  , util = require('util');

function isPlainObject(obj) {
  return Object.getPrototypeOf(obj) === Object.prototype;
}

/**
 * Creates a new EventSource object
 *
 * @param {String} url the URL to which to connect
 * @param {Object} [eventSourceInitDict] extra init params. See README for details.
 * @api public
 **/
function EventSource(url, eventSourceInitDict) {
  var readyState = EventSource.CONNECTING;
  Object.defineProperty(this, 'readyState', {
    get: function () {
      return readyState;
    }
  });

  Object.defineProperty(this, 'url', {
    get: function () {
      return url;
    }
  });

  var self = this;
  self.reconnectInterval = 1000;
  var connectPending = false;

  function onConnectionClosed() {
    if (connectPending || readyState === EventSource.CLOSED) return;
    connectPending = true;
    readyState = EventSource.CONNECTING;
    _emit('error', new Event('error'));

    // The url may have been changed by a temporary
    // redirect. If that's the case, revert it now.
    if (reconnectUrl) {
      url = reconnectUrl;
      reconnectUrl = null;
    }
    setTimeout(function () {
      if (readyState !== EventSource.CONNECTING) {
        return;
      }
      connect();
    }, self.reconnectInterval);
  }

  var req;
  var lastEventId = '';
  if (eventSourceInitDict && eventSourceInitDict.headers && isPlainObject(eventSourceInitDict.headers) && eventSourceInitDict.headers['Last-Event-ID']) {
    lastEventId = eventSourceInitDict.headers['Last-Event-ID'];
    delete eventSourceInitDict.headers['Last-Event-ID'];
  }

  var discardTrailingNewline = false
    , data = ''
    , eventName = '';

  var reconnectUrl = null;

  function connect() {
    connectPending = false;

    var options = parse(url);
    var isSecure = options.protocol == 'https:';
    options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' };
    if (lastEventId) options.headers['Last-Event-ID'] = lastEventId;
    if (eventSourceInitDict && eventSourceInitDict.headers && isPlainObject(eventSourceInitDict.headers)) {
      for (var i in eventSourceInitDict.headers) {
        var header = eventSourceInitDict.headers[i];
        if (header) {
          options.headers[i] = header;
        }
      }
    }

    options.rejectUnauthorized = !(eventSourceInitDict && eventSourceInitDict.rejectUnauthorized == false);

    req = (isSecure ? https : http).request(options, function (res) {
      // Handle HTTP redirects
      if (res.statusCode == 301 || res.statusCode == 307) {
        if (!res.headers.location) {
          // Server sent redirect response without Location header.
          _emit('error', new Event('error', {status: res.statusCode}));
          return;
        }
        if (res.statusCode == 307) reconnectUrl = url;
        url = res.headers.location;
        process.nextTick(connect);
        return;
      }

      if (res.statusCode !== 200) {
        _emit('error', new Event('error', {status: res.statusCode}));
        return self.close();
      }

      readyState = EventSource.OPEN;
      res.on('close', onConnectionClosed);
      res.on('end', onConnectionClosed);
      _emit('open', new Event('open'));

      // text/event-stream parser adapted from webkit's
      // Source/WebCore/page/EventSource.cpp
      var buf = '';
      res.on('data', function (chunk) {
        buf += chunk;

        var pos = 0
          , length = buf.length;
        while (pos < length) {
          if (discardTrailingNewline) {
            if (buf[pos] === '\n') {
              ++pos;
            }
            discardTrailingNewline = false;
          }

          var lineLength = -1
            , fieldLength = -1
            , c;

          for (var i = pos; lineLength < 0 && i < length; ++i) {
            c = buf[i];
            if (c === ':') {
              if (fieldLength < 0) {
                fieldLength = i - pos;
              }
            } else if (c === '\r') {
              discardTrailingNewline = true;
              lineLength = i - pos;
            } else if (c === '\n') {
              lineLength = i - pos;
            }
          }

          if (lineLength < 0) {
            break;
          }

          parseEventStreamLine(buf, pos, fieldLength, lineLength);

          pos += lineLength + 1;
        }

        if (pos === length) {
          buf = '';
        } else if (pos > 0) {
          buf = buf.slice(pos);
        }
      });
    });

    req.on('error', onConnectionClosed);
    if (req.setNoDelay) req.setNoDelay(true);
    req.end();
  }

  connect();

  function _emit() {
    if (self.listeners(arguments[0]).length > 0) {
      self.emit.apply(self, arguments);
    }
  }

  this.close = function () {
    if (readyState == EventSource.CLOSED) return;
    readyState = EventSource.CLOSED;
    if (req.abort) req.abort();
  };

  function parseEventStreamLine(buf, pos, fieldLength, lineLength) {
    if (lineLength === 0) {
      if (data.length > 0) {
        var type = eventName || 'message';
        _emit(type, new MessageEvent(type, {
          data: data.slice(0, -1), // remove trailing newline
          lastEventId: lastEventId,
          origin: original(url)
        }));
        data = '';
      }
      eventName = void 0;
    } else if (fieldLength > 0) {
      var noValue = fieldLength < 0
        , step = 0
        , field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength));

      if (noValue) {
        step = lineLength;
      } else if (buf[pos + fieldLength + 1] !== ' ') {
        step = fieldLength + 1;
      } else {
        step = fieldLength + 2;
      }
      pos += step;
      var valueLength = lineLength - step
        , value = buf.slice(pos, pos + valueLength);

      if (field === 'data') {
        data += value + '\n';
      } else if (field === 'event') {
        eventName = value;
      } else if (field === 'id') {
        lastEventId = value;
      } else if (field === 'retry') {
        var retry = parseInt(value, 10);
        if (!Number.isNaN(retry)) {
          self.reconnectInterval = retry;
        }
      }
    }
  }
}

module.exports = EventSource;

util.inherits(EventSource, events.EventEmitter);
EventSource.prototype.constructor = EventSource; // make stacktraces readable

['open', 'error', 'message'].forEach(function (method) {
  Object.defineProperty(EventSource.prototype, 'on' + method, {
    /**
     * Returns the current listener
     *
     * @return {Mixed} the set function or undefined
     * @api private
     */
    get: function get() {
      var listener = this.listeners(method)[0];
      return listener ? (listener._listener ? listener._listener : listener) : undefined;
    },

    /**
     * Start listening for events
     *
     * @param {Function} listener the listener
     * @return {Mixed} the set function or undefined
     * @api private
     */
    set: function set(listener) {
      this.removeAllListeners(method);
      this.addEventListener(method, listener);
    }
  });
});

/**
 * Ready states
 */
Object.defineProperty(EventSource, 'CONNECTING', { enumerable: true, value: 0});
Object.defineProperty(EventSource, 'OPEN', { enumerable: true, value: 1});
Object.defineProperty(EventSource, 'CLOSED', { enumerable: true, value: 2});

/**
 * Emulates the W3C Browser based WebSocket interface using addEventListener.
 *
 * @param {String} method Listen for an event
 * @param {Function} listener callback
 * @see https://developer.mozilla.org/en/DOM/element.addEventListener
 * @see http://dev.w3.org/html5/websockets/#the-websocket-interface
 * @api public
 */
EventSource.prototype.addEventListener = function addEventListener(method, listener) {
  if (typeof listener === 'function') {
    // store a reference so we can return the original function again
    listener._listener = listener;
    this.on(method, listener);
  }
};

/**
 * W3C Event
 *
 * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event
 * @api private
 */
function Event(type, optionalProperties) {
  Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true });
  if (optionalProperties) {
    for (var f in optionalProperties) {
      if (optionalProperties.hasOwnProperty(f)) {
        Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true });
      }
    }
  }
}

/**
 * W3C MessageEvent
 *
 * @see http://www.w3.org/TR/webmessaging/#event-definitions
 * @api private
 */
function MessageEvent(type, eventInitDict) {
  Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true });
  for (var f in eventInitDict) {
    if (eventInitDict.hasOwnProperty(f)) {
      Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true });
    }
  }
}
<|endoftext|>


<commit_before>//var redis = require("redis");
//var rClient = redis.createClient();
var dgram = require("dgram");

var d = require('dequeue');
var FIFO = new d();

// Defined variables
var port = 4343;

// Call function init() loop
setInterval(init, 1);

// Start server listenning UDP
var udpServer = dgram.createSocket("udp4");
var index = 0;
udpServer.on("message",
    function (msg, rinfo) {
        index++;
        FIFO.push(msg.toString(), index);
    }
);

udpServer.on('error', function (err) {
    console.log("Error server UDP: ", err);
});

udpServer.bind(port);
console.log("Running server: ", port);
// End listen UDP

// Function init listen process performance UDP

function init() {
    while (FIFO.length > 0) {
        console("Data:", FIFO);
        var msg = FIFO.shift();

    }
}<commit_msg>Update UDPefef<commit_after>//var redis = require("redis");
//var rClient = redis.createClient();
var dgram = require("dgram");

var d = require('dequeue');
var FIFO = new d();

// Defined variables
var port = 4343;

// Call function init() loop
setInterval(init, 1);

// Start server listenning UDP
var udpServer = dgram.createSocket("udp4");
var index = 0;
udpServer.on("message",
    function (msg, rinfo) {
        index++;
        FIFO.push(msg.toString(), index);
    }
);

udpServer.on('error', function (err) {
    console.log("Error server UDP: ", err);
});

udpServer.bind(port);
console.log("Running server: ", port);
// End listen UDP

// Function init listen process performance UDP

function init() {
    while (FIFO.length > 0) {

        var msg = FIFO.shift();
        console("Data:", msg);
    }
}<|endoftext|>


<commit_before>var original = require('original')
  , parse = require('url').parse
  , events = require('events')
  , https = require('https')
  , http = require('http')
  , util = require('util');

function isPlainObject(obj) {
  return Object.getPrototypeOf(obj) === Object.prototype;
}

/**
 * Creates a new EventSource object
 *
 * @param {String} url the URL to which to connect
 * @param {Object} [eventSourceInitDict] extra init params. See README for details.
 * @api public
 **/
function EventSource(url, eventSourceInitDict) {
  var readyState = EventSource.CONNECTING;
  Object.defineProperty(this, 'readyState', {
    get: function () {
      return readyState;
    }
  });

  Object.defineProperty(this, 'url', {
    get: function () {
      return url;
    }
  });

  var self = this;
  self.reconnectInterval = 1000;

  function onConnectionClosed() {
    if (readyState === EventSource.CLOSED) return;
    readyState = EventSource.CONNECTING;
    _emit('error', new Event('error'));

    // The url may have been changed by a temporary
    // redirect. If that's the case, revert it now.
    if (reconnectUrl) {
      url = reconnectUrl;
      reconnectUrl = null;
    }
    setTimeout(function () {
      if (readyState !== EventSource.CONNECTING) {
        return;
      }
      connect();
    }, self.reconnectInterval);
  }

  var req;
  var lastEventId = '';
  if (eventSourceInitDict && eventSourceInitDict.headers && isPlainObject(eventSourceInitDict.headers) && eventSourceInitDict.headers['Last-Event-ID']) {
    lastEventId = eventSourceInitDict.headers['Last-Event-ID'];
    delete eventSourceInitDict.headers['Last-Event-ID'];
  }

  var discardTrailingNewline = false
    , data = ''
    , eventName = '';

  var reconnectUrl = null;

  function connect() {

    var options = parse(url);
    var isSecure = options.protocol == 'https:';
    options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' };
    if (lastEventId) options.headers['Last-Event-ID'] = lastEventId;
    if (eventSourceInitDict && eventSourceInitDict.headers && isPlainObject(eventSourceInitDict.headers)) {
      for (var i in eventSourceInitDict.headers) {
        var header = eventSourceInitDict.headers[i];
        if (header) {
          options.headers[i] = header;
        }
      }
    }

    options.rejectUnauthorized = !(eventSourceInitDict && eventSourceInitDict.rejectUnauthorized == false);

    // If specify http proxy, make the request to sent to the proxy server,
    // and include the original url in path and Host headers
    if (eventSourceInitDict && eventSourceInitDict.proxy) {
        var proxy = parse(eventSourceInitDict.proxy);
        options.path = url;
        options.headers.Host = options.host;
        options.hostname = proxy.hostname;
        options.host = proxy.host;
        options.port = proxy.port;
    }

    req = (isSecure ? https : http).request(options, function (res) {
      // Handle HTTP redirects
      if (res.statusCode == 301 || res.statusCode == 307) {
        if (!res.headers.location) {
          // Server sent redirect response without Location header.
          _emit('error', new Event('error', {status: res.statusCode}));
          return;
        }
        if (res.statusCode == 307) reconnectUrl = url;
        url = res.headers.location;
        process.nextTick(connect);
        return;
      }

      if (res.statusCode !== 200) {
        _emit('error', new Event('error', {status: res.statusCode}));
        if (res.statusCode == 204) return self.close();
        return
      }

      readyState = EventSource.OPEN;
      res.on('close', onConnectionClosed);
      res.on('end', onConnectionClosed);
      _emit('open', new Event('open'));

      // text/event-stream parser adapted from webkit's
      // Source/WebCore/page/EventSource.cpp
      var buf = '';
      res.on('data', function (chunk) {
        buf += chunk;

        var pos = 0
          , length = buf.length;
        while (pos < length) {
          if (discardTrailingNewline) {
            if (buf[pos] === '\n') {
              ++pos;
            }
            discardTrailingNewline = false;
          }

          var lineLength = -1
            , fieldLength = -1
            , c;

          for (var i = pos; lineLength < 0 && i < length; ++i) {
            c = buf[i];
            if (c === ':') {
              if (fieldLength < 0) {
                fieldLength = i - pos;
              }
            } else if (c === '\r') {
              discardTrailingNewline = true;
              lineLength = i - pos;
            } else if (c === '\n') {
              lineLength = i - pos;
            }
          }

          if (lineLength < 0) {
            break;
          }

          parseEventStreamLine(buf, pos, fieldLength, lineLength);

          pos += lineLength + 1;
        }

        if (pos === length) {
          buf = '';
        } else if (pos > 0) {
          buf = buf.slice(pos);
        }
      });
    });

    req.on('error', onConnectionClosed);
    if (req.setNoDelay) req.setNoDelay(true);
    req.end();
  }

  connect();

  function _emit() {
    if (self.listeners(arguments[0]).length > 0) {
      self.emit.apply(self, arguments);
    }
  }

  this.close = function () {
    if (readyState == EventSource.CLOSED) return;
    readyState = EventSource.CLOSED;
    if (req.abort) req.abort();
    if (req.xhr && req.xhr.abort) req.xhr.abort();
  };

  function parseEventStreamLine(buf, pos, fieldLength, lineLength) {
    if (lineLength === 0) {
      if (data.length > 0) {
        var type = eventName || 'message';
        _emit(type, new MessageEvent(type, {
          data: data.slice(0, -1), // remove trailing newline
          lastEventId: lastEventId,
          origin: original(url)
        }));
        data = '';
      }
      eventName = void 0;
    } else if (fieldLength > 0) {
      var noValue = fieldLength < 0
        , step = 0
        , field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength));

      if (noValue) {
        step = lineLength;
      } else if (buf[pos + fieldLength + 1] !== ' ') {
        step = fieldLength + 1;
      } else {
        step = fieldLength + 2;
      }
      pos += step;
      var valueLength = lineLength - step
        , value = buf.slice(pos, pos + valueLength);

      if (field === 'data') {
        data += value + '\n';
      } else if (field === 'event') {
        eventName = value;
      } else if (field === 'id') {
        lastEventId = value;
      } else if (field === 'retry') {
        var retry = parseInt(value, 10);
        if (!Number.isNaN(retry)) {
          self.reconnectInterval = retry;
        }
      }
    }
  }
}

module.exports = EventSource;

util.inherits(EventSource, events.EventEmitter);
EventSource.prototype.constructor = EventSource; // make stacktraces readable

['open', 'error', 'message'].forEach(function (method) {
  Object.defineProperty(EventSource.prototype, 'on' + method, {
    /**
     * Returns the current listener
     *
     * @return {Mixed} the set function or undefined
     * @api private
     */
    get: function get() {
      var listener = this.listeners(method)[0];
      return listener ? (listener._listener ? listener._listener : listener) : undefined;
    },

    /**
     * Start listening for events
     *
     * @param {Function} listener the listener
     * @return {Mixed} the set function or undefined
     * @api private
     */
    set: function set(listener) {
      this.removeAllListeners(method);
      this.addEventListener(method, listener);
    }
  });
});

/**
 * Ready states
 */
Object.defineProperty(EventSource, 'CONNECTING', { enumerable: true, value: 0});
Object.defineProperty(EventSource, 'OPEN', { enumerable: true, value: 1});
Object.defineProperty(EventSource, 'CLOSED', { enumerable: true, value: 2});

/**
 * Emulates the W3C Browser based WebSocket interface using addEventListener.
 *
 * @param {String} method Listen for an event
 * @param {Function} listener callback
 * @see https://developer.mozilla.org/en/DOM/element.addEventListener
 * @see http://dev.w3.org/html5/websockets/#the-websocket-interface
 * @api public
 */
EventSource.prototype.addEventListener = function addEventListener(method, listener) {
  if (typeof listener === 'function') {
    // store a reference so we can return the original function again
    listener._listener = listener;
    this.on(method, listener);
  }
};

/**
 * W3C Event
 *
 * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event
 * @api private
 */
function Event(type, optionalProperties) {
  Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true });
  if (optionalProperties) {
    for (var f in optionalProperties) {
      if (optionalProperties.hasOwnProperty(f)) {
        Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true });
      }
    }
  }
}

/**
 * W3C MessageEvent
 *
 * @see http://www.w3.org/TR/webmessaging/#event-definitions
 * @api private
 */
function MessageEvent(type, eventInitDict) {
  Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true });
  for (var f in eventInitDict) {
    if (eventInitDict.hasOwnProperty(f)) {
      Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true });
    }
  }
}
<commit_msg>better fix for multi connects<commit_after>var original = require('original')
  , parse = require('url').parse
  , events = require('events')
  , https = require('https')
  , http = require('http')
  , util = require('util');

function isPlainObject(obj) {
  return Object.getPrototypeOf(obj) === Object.prototype;
}

/**
 * Creates a new EventSource object
 *
 * @param {String} url the URL to which to connect
 * @param {Object} [eventSourceInitDict] extra init params. See README for details.
 * @api public
 **/
function EventSource(url, eventSourceInitDict) {
  var readyState = EventSource.CONNECTING;
  Object.defineProperty(this, 'readyState', {
    get: function () {
      return readyState;
    }
  });

  Object.defineProperty(this, 'url', {
    get: function () {
      return url;
    }
  });

  var self = this;
  self.reconnectInterval = 1000;

  function onConnectionClosed() {
    if (readyState === EventSource.CLOSED) return;
    readyState = EventSource.CONNECTING;
    _emit('error', new Event('error'));

    // The url may have been changed by a temporary
    // redirect. If that's the case, revert it now.
    if (reconnectUrl) {
      url = reconnectUrl;
      reconnectUrl = null;
    }
    setTimeout(function () {
      if (readyState !== EventSource.CONNECTING) {
        return;
      }
      connect();
    }, self.reconnectInterval);
  }

  var req;
  var lastEventId = '';
  if (eventSourceInitDict && eventSourceInitDict.headers && isPlainObject(eventSourceInitDict.headers) && eventSourceInitDict.headers['Last-Event-ID']) {
    lastEventId = eventSourceInitDict.headers['Last-Event-ID'];
    delete eventSourceInitDict.headers['Last-Event-ID'];
  }

  var discardTrailingNewline = false
    , data = ''
    , eventName = '';

  var reconnectUrl = null;

  function connect() {

    var options = parse(url);
    var isSecure = options.protocol == 'https:';
    options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' };
    if (lastEventId) options.headers['Last-Event-ID'] = lastEventId;
    if (eventSourceInitDict && eventSourceInitDict.headers && isPlainObject(eventSourceInitDict.headers)) {
      for (var i in eventSourceInitDict.headers) {
        var header = eventSourceInitDict.headers[i];
        if (header) {
          options.headers[i] = header;
        }
      }
    }

    options.rejectUnauthorized = !(eventSourceInitDict && eventSourceInitDict.rejectUnauthorized == false);

    // If specify http proxy, make the request to sent to the proxy server,
    // and include the original url in path and Host headers
    if (eventSourceInitDict && eventSourceInitDict.proxy) {
        var proxy = parse(eventSourceInitDict.proxy);
        options.path = url;
        options.headers.Host = options.host;
        options.hostname = proxy.hostname;
        options.host = proxy.host;
        options.port = proxy.port;
    }

    req = (isSecure ? https : http).request(options, function (res) {
      // Handle HTTP redirects
      if (res.statusCode == 301 || res.statusCode == 307) {
        if (!res.headers.location) {
          // Server sent redirect response without Location header.
          _emit('error', new Event('error', {status: res.statusCode}));
          return;
        }
        if (res.statusCode == 307) reconnectUrl = url;
        url = res.headers.location;
        process.nextTick(connect);
        return;
      }

      if (res.statusCode !== 200) {
        _emit('error', new Event('error', {status: res.statusCode}));
        if (res.statusCode == 204) return self.close();
        return
      }

      readyState = EventSource.OPEN;
      res.on('close', function() {
        res.removeAllListeners('close');
        res.removeAllListeners('end');
        onConnectionClosed()
      });

      res.on('end', function() {
        res.removeAllListeners('close');
        res.removeAllListeners('end');
        onConnectionClosed()
      });
      _emit('open', new Event('open'));

      // text/event-stream parser adapted from webkit's
      // Source/WebCore/page/EventSource.cpp
      var buf = '';
      res.on('data', function (chunk) {
        buf += chunk;

        var pos = 0
          , length = buf.length;
        while (pos < length) {
          if (discardTrailingNewline) {
            if (buf[pos] === '\n') {
              ++pos;
            }
            discardTrailingNewline = false;
          }

          var lineLength = -1
            , fieldLength = -1
            , c;

          for (var i = pos; lineLength < 0 && i < length; ++i) {
            c = buf[i];
            if (c === ':') {
              if (fieldLength < 0) {
                fieldLength = i - pos;
              }
            } else if (c === '\r') {
              discardTrailingNewline = true;
              lineLength = i - pos;
            } else if (c === '\n') {
              lineLength = i - pos;
            }
          }

          if (lineLength < 0) {
            break;
          }

          parseEventStreamLine(buf, pos, fieldLength, lineLength);

          pos += lineLength + 1;
        }

        if (pos === length) {
          buf = '';
        } else if (pos > 0) {
          buf = buf.slice(pos);
        }
      });
    });

    req.on('error', onConnectionClosed);
    if (req.setNoDelay) req.setNoDelay(true);
    req.end();
  }

  connect();

  function _emit() {
    if (self.listeners(arguments[0]).length > 0) {
      self.emit.apply(self, arguments);
    }
  }

  this.close = function () {
    if (readyState == EventSource.CLOSED) return;
    readyState = EventSource.CLOSED;
    if (req.abort) req.abort();
    if (req.xhr && req.xhr.abort) req.xhr.abort();
  };

  function parseEventStreamLine(buf, pos, fieldLength, lineLength) {
    if (lineLength === 0) {
      if (data.length > 0) {
        var type = eventName || 'message';
        _emit(type, new MessageEvent(type, {
          data: data.slice(0, -1), // remove trailing newline
          lastEventId: lastEventId,
          origin: original(url)
        }));
        data = '';
      }
      eventName = void 0;
    } else if (fieldLength > 0) {
      var noValue = fieldLength < 0
        , step = 0
        , field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength));

      if (noValue) {
        step = lineLength;
      } else if (buf[pos + fieldLength + 1] !== ' ') {
        step = fieldLength + 1;
      } else {
        step = fieldLength + 2;
      }
      pos += step;
      var valueLength = lineLength - step
        , value = buf.slice(pos, pos + valueLength);

      if (field === 'data') {
        data += value + '\n';
      } else if (field === 'event') {
        eventName = value;
      } else if (field === 'id') {
        lastEventId = value;
      } else if (field === 'retry') {
        var retry = parseInt(value, 10);
        if (!Number.isNaN(retry)) {
          self.reconnectInterval = retry;
        }
      }
    }
  }
}

module.exports = EventSource;

util.inherits(EventSource, events.EventEmitter);
EventSource.prototype.constructor = EventSource; // make stacktraces readable

['open', 'error', 'message'].forEach(function (method) {
  Object.defineProperty(EventSource.prototype, 'on' + method, {
    /**
     * Returns the current listener
     *
     * @return {Mixed} the set function or undefined
     * @api private
     */
    get: function get() {
      var listener = this.listeners(method)[0];
      return listener ? (listener._listener ? listener._listener : listener) : undefined;
    },

    /**
     * Start listening for events
     *
     * @param {Function} listener the listener
     * @return {Mixed} the set function or undefined
     * @api private
     */
    set: function set(listener) {
      this.removeAllListeners(method);
      this.addEventListener(method, listener);
    }
  });
});

/**
 * Ready states
 */
Object.defineProperty(EventSource, 'CONNECTING', { enumerable: true, value: 0});
Object.defineProperty(EventSource, 'OPEN', { enumerable: true, value: 1});
Object.defineProperty(EventSource, 'CLOSED', { enumerable: true, value: 2});

/**
 * Emulates the W3C Browser based WebSocket interface using addEventListener.
 *
 * @param {String} method Listen for an event
 * @param {Function} listener callback
 * @see https://developer.mozilla.org/en/DOM/element.addEventListener
 * @see http://dev.w3.org/html5/websockets/#the-websocket-interface
 * @api public
 */
EventSource.prototype.addEventListener = function addEventListener(method, listener) {
  if (typeof listener === 'function') {
    // store a reference so we can return the original function again
    listener._listener = listener;
    this.on(method, listener);
  }
};

/**
 * W3C Event
 *
 * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event
 * @api private
 */
function Event(type, optionalProperties) {
  Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true });
  if (optionalProperties) {
    for (var f in optionalProperties) {
      if (optionalProperties.hasOwnProperty(f)) {
        Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true });
      }
    }
  }
}

/**
 * W3C MessageEvent
 *
 * @see http://www.w3.org/TR/webmessaging/#event-definitions
 * @api private
 */
function MessageEvent(type, eventInitDict) {
  Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true });
  for (var f in eventInitDict) {
    if (eventInitDict.hasOwnProperty(f)) {
      Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true });
    }
  }
}
<|endoftext|>


<commit_before>const querystring = require('querystring');
const https = require('https');
const zlib = require('zlib');
const Agent = require('agentkeepalive').HttpsAgent;

const cache = require('./cache');

function getCurrentMemoryUsage() {
  const memoryUsage = process.memoryUsage();
  return memoryUsage.rss;
}

const keepAliveAgent = new Agent({
});

module.exports = function (req, res) {
  // This allows users to cache bust, this is useful when live logging. It stores the result in the regular (uncachebusted) spot so that future requests for the regular request are also updated.
  let cacheBust = false;
  if (req.query._) {
    console.log('Cache busting...');
    cacheBust = true;
    delete req.query._;
  }

  // Set header already so that all request, good or bad, have it
  res.setHeader('Access-Control-Allow-Origin', '*');

  const requestUrl = `${req.params[0]}?${querystring.stringify(req.query)}`;
  const jsonString = !cacheBust && cache.get(requestUrl);
  if (jsonString) {
    console.log('++++++cache hit', requestUrl);
    res.setHeader('Content-Type', 'application/json; charset=utf-8');
    res.send(jsonString);
  } else {
    console.log('------cache miss', requestUrl);
    const query = Object.assign({}, req.query, {
      // Allow users to provide their own API key. This is required during development so that other developers don't lock out the production in case they mess something up.
      api_key: req.query.api_key || '97c84db1a100b32a6d5abb763711244e',
    });

    const options = {
      host: 'www.warcraftlogs.com',
      path: `/v1/${req.params[0]}?${querystring.stringify(query)}`,
      headers: {
        'User-Agent': 'WoWAnalyzer.com API',
        'Accept-Encoding': 'gzip', // using gzip is 80% quicker
      },
      agent: keepAliveAgent,
    };
    console.log('GET', options.path);
    const wclStart = Date.now();
    https
      .get(options, (wclResponse) => {
        const gunzip = zlib.createGunzip();
        wclResponse.pipe(gunzip);

        let jsonString = '';
        gunzip
          .on('data', chunk => { jsonString += chunk.toString(); })
          .on('end', () => {
            if (wclResponse.statusCode === 200) {
              cache.set(requestUrl, jsonString);
            } else {
              console.error('Error status:', wclResponse.statusCode);
            }

            // Clone WCL response
            res.setHeader('Content-Type', wclResponse.headers['content-type']);
            res.status(wclResponse.statusCode);
            res.send(jsonString);
            console.log('Finished (memory:', Math.ceil(getCurrentMemoryUsage() / 1024 / 1024), 'MB', 'wcl:', Date.now() - wclStart, 'ms', ')');
          })
          .on('error', (e) => {
            console.error(e);
            res.status(500).send();
          });
      })
      .on('error', (err) => {
        console.error('Error:', err);
        res.sendStatus(500);
      });
  }
};
<commit_msg>Also log actual response when API encounters an error<commit_after>const querystring = require('querystring');
const https = require('https');
const zlib = require('zlib');
const Agent = require('agentkeepalive').HttpsAgent;

const cache = require('./cache');

function getCurrentMemoryUsage() {
  const memoryUsage = process.memoryUsage();
  return memoryUsage.rss;
}

const keepAliveAgent = new Agent({
});

module.exports = function (req, res) {
  // This allows users to cache bust, this is useful when live logging. It stores the result in the regular (uncachebusted) spot so that future requests for the regular request are also updated.
  let cacheBust = false;
  if (req.query._) {
    console.log('Cache busting...');
    cacheBust = true;
    delete req.query._;
  }

  // Set header already so that all request, good or bad, have it
  res.setHeader('Access-Control-Allow-Origin', '*');

  const requestUrl = `${req.params[0]}?${querystring.stringify(req.query)}`;
  const jsonString = !cacheBust && cache.get(requestUrl);
  if (jsonString) {
    console.log('++++++cache hit', requestUrl);
    res.setHeader('Content-Type', 'application/json; charset=utf-8');
    res.send(jsonString);
  } else {
    console.log('------cache miss', requestUrl);
    const query = Object.assign({}, req.query, {
      // Allow users to provide their own API key. This is required during development so that other developers don't lock out the production in case they mess something up.
      api_key: req.query.api_key || '97c84db1a100b32a6d5abb763711244e',
    });

    const options = {
      host: 'www.warcraftlogs.com',
      path: `/v1/${req.params[0]}?${querystring.stringify(query)}`,
      headers: {
        'User-Agent': 'WoWAnalyzer.com API',
        'Accept-Encoding': 'gzip', // using gzip is 80% quicker
      },
      agent: keepAliveAgent,
    };
    console.log('GET', options.path);
    const wclStart = Date.now();
    https
      .get(options, (wclResponse) => {
        const gunzip = zlib.createGunzip();
        wclResponse.pipe(gunzip);

        let jsonString = '';
        gunzip
          .on('data', chunk => { jsonString += chunk.toString(); })
          .on('end', () => {
            if (wclResponse.statusCode === 200) {
              cache.set(requestUrl, jsonString);
            } else {
              console.error('Error status:', wclResponse.statusCode);
            }

            // Clone WCL response
            res.setHeader('Content-Type', wclResponse.headers['content-type']);
            res.status(wclResponse.statusCode);
            res.send(jsonString);
            console.log('Finished (memory:', Math.ceil(getCurrentMemoryUsage() / 1024 / 1024), 'MB', 'wcl:', Date.now() - wclStart, 'ms', ')');
          })
          .on('error', (e) => {
            console.error(e, wclResponse);
            res.status(500).send();
          });
      })
      .on('error', (err) => {
        console.error('Error:', err);
        res.sendStatus(500);
      });
  }
};
<|endoftext|>


<commit_before>'use strict';

var RSVP    = require('rsvp');
var Promise = RSVP.Promise;

module.exports = PromiseExt;

// Utility functions on on the native CTOR need some massaging
module.exports.hash = function() {
  return this.resolve(RSVP.hash.apply(null, arguments));
};

module.exports.denodeify = function() {
  var fn = RSVP.denodeify.apply(null, arguments);
  var Constructor = this;

  return function() {
    return Constructor.resolve(fn.apply(null, arguments));
  };
};

module.exports.filter = function() {
  return this.resolve(RSVP.filter.apply(null, arguments));
};

module.exports.map = function() {
  return this.resolve(RSVP.map.apply(null, arguments));
};

function PromiseExt() {
  Promise.apply(this, arguments);
}

PromiseExt.prototype = Object.create(Promise.prototype);
PromiseExt.prototype.constructor = PromiseExt;
PromiseExt.__proto__ = Promise;

PromiseExt.prototype.returns = function(value) {
  return this.then(function() {
    return value;
  });
};

PromiseExt.prototype.invoke = function(method) {
  var args = Array.prototype.slice(arguments, 1);

  return this.then(function(value) {
    return value[method].apply(value, args);
  }, undefined, 'invoke: ' + method + ' with: ' + args);
};

PromiseExt.prototype.map = function(mapFn) {
  var Constructor = this.constructor;

  return this.then(function(values) {
    return Constructor.map(values, mapFn);
  });
};

PromiseExt.prototype.filter = function(mapFn) {
  var Constructor = this.constructor;

  return this.then(function(values) {
    return Constructor.filter(values, mapFn);
  });
};
<commit_msg>Fix typo<commit_after>'use strict';

var RSVP    = require('rsvp');
var Promise = RSVP.Promise;

module.exports = PromiseExt;

// Utility functions on the native CTOR need some massaging
module.exports.hash = function() {
  return this.resolve(RSVP.hash.apply(null, arguments));
};

module.exports.denodeify = function() {
  var fn = RSVP.denodeify.apply(null, arguments);
  var Constructor = this;

  return function() {
    return Constructor.resolve(fn.apply(null, arguments));
  };
};

module.exports.filter = function() {
  return this.resolve(RSVP.filter.apply(null, arguments));
};

module.exports.map = function() {
  return this.resolve(RSVP.map.apply(null, arguments));
};

function PromiseExt() {
  Promise.apply(this, arguments);
}

PromiseExt.prototype = Object.create(Promise.prototype);
PromiseExt.prototype.constructor = PromiseExt;
PromiseExt.__proto__ = Promise;

PromiseExt.prototype.returns = function(value) {
  return this.then(function() {
    return value;
  });
};

PromiseExt.prototype.invoke = function(method) {
  var args = Array.prototype.slice(arguments, 1);

  return this.then(function(value) {
    return value[method].apply(value, args);
  }, undefined, 'invoke: ' + method + ' with: ' + args);
};

PromiseExt.prototype.map = function(mapFn) {
  var Constructor = this.constructor;

  return this.then(function(values) {
    return Constructor.map(values, mapFn);
  });
};

PromiseExt.prototype.filter = function(mapFn) {
  var Constructor = this.constructor;

  return this.then(function(values) {
    return Constructor.filter(values, mapFn);
  });
};
<|endoftext|>


<commit_before>import { createFieldClass } from '../components/field-component';

const View = process.env.NODE_ENV === 'test'
  ? require('react-native').View
  : 'div';

const NativeField = createFieldClass({
  MapView: props => ({
    onRegionChange: props.onChange,
    onRegionChangeComplete: props.onBlur,
    region: props.modelValue,
  }),
  Picker: props => ({
    onValueChange: props.onChange,
    selectedValue: props.modelValue,
  }),
  Switch: props => ({
    onValueChange: props.onChange,
  }),
  TextInput: props => ({
    defaultValue: props.modelValue,
    onChangeText: props.onChange,
    onBlur: props.onBlur,
    onFocus: props.onFocus,
  }),
  DatePickerIOS: props => ({
    date: props.modelValue,
    onDateChange: props.onChange,
  }),
  PickerIOS: props => ({
    onValueChange: props.onChange,
    selectedValue: props.modelValue,
  }),
  SegmentedControlIOS: props => ({
    onValueChange: props.onChange,
    selectedIndex: props.values.indexOf(props.modelValue),
  }),
  SliderIOS: props => ({
    onSlidingComplete: props.onBlur,
    onValueChange: props.onChange,
    value: props.modelValue,
  }),
}, {
  component: View,
});

export { NativeField as Field };
<commit_msg>Fixing react-native issue<commit_after>import { createFieldClass } from '../components/field-component';

const View = process.env.NODE_ENV !== 'test'
  ? require('react-native').View
  : 'div';

const NativeField = createFieldClass({
  MapView: props => ({
    onRegionChange: props.onChange,
    onRegionChangeComplete: props.onBlur,
    region: props.modelValue,
  }),
  Picker: props => ({
    onValueChange: props.onChange,
    selectedValue: props.modelValue,
  }),
  Switch: props => ({
    onValueChange: props.onChange,
  }),
  TextInput: props => ({
    defaultValue: props.modelValue,
    onChangeText: props.onChange,
    onBlur: props.onBlur,
    onFocus: props.onFocus,
  }),
  DatePickerIOS: props => ({
    date: props.modelValue,
    onDateChange: props.onChange,
  }),
  PickerIOS: props => ({
    onValueChange: props.onChange,
    selectedValue: props.modelValue,
  }),
  SegmentedControlIOS: props => ({
    onValueChange: props.onChange,
    selectedIndex: props.values.indexOf(props.modelValue),
  }),
  SliderIOS: props => ({
    onSlidingComplete: props.onBlur,
    onValueChange: props.onChange,
    value: props.modelValue,
  }),
}, {
  component: View,
});

export { NativeField as Field };
<|endoftext|>