<commit_before>#!/usr/bin/env node
"use strict";

const fs = require("fs"),
      iq = require("inquirer"),
      gitLabel = require("git-label"),
      octonode = require("octonode"),
      readRepo = require("./components/read-repo"),
      cleanup  = require("./components/remove-tmp-pkg"),
      mainPrompts = require("./components/main-prompts"),
      addPrompts  = require("./components/add-prompts");

//  Responsible for fetching and returning our config/token
const fetchToken = () => {
        return new Promise((res, rej)=>{
          fs.readFile(__dirname+"/.token.json", 'utf8', (e, data) => {
            if (e) rej("No token.json file found!");
            if (JSON.parse(data).token === "") rej("No token found!");
            res(JSON.parse(data).token);
            res();
          });
        });
      };
//  Responsible for asking the user what their token is, and then storing it
//  executed only if it can't be found!
const setToken = (done) => {
        iq.prompt([{
            type: "input",
            name: "token",
            message: "What is your GitHub Access Token?",
            default: "eg: 12345678..."
        }], (answer) => {
          fs.writeFile( __dirname+'/.token.json', JSON.stringify( { "token": answer.token }, null, 2 ), 'utf8', (e)=>{
            if (e) throw e;
            console.log("Stored new token!");
            done(answer.token);
          });
        });
      };
//  Recursivly asks if you want to add another new label, then calls a callback when youre all done
const doAddPrompts = ( newLabels, done ) => {
        iq.prompt( addPrompts, ( answers ) => {
          newLabels.push({ name: answers.labelName, color: answers.labelColor });
          if ( answers.addAnother ){
            doAddPrompts( newLabels, done );
          }else{
            done( newLabels );
          }
        });
      };

const doRemovePrompts = ( token, repo ) => {
        octonode.client(token).get('/repos/'+repo+'/labels', (e, status, body) => {
          iq.prompt([{
            name:     "removals",
            type:     "checkbox",
            message:  "Which labels would you like to remove?",
            choices:  body.map((label) => label.name),
            filter:   (removals) => {
              return body.filter((label) => {
                return removals.indexOf(label.name) > -1 ? { name: label.name, color: label.color } : false;
              });
            }
          }], (answers) => {
            gitLabel.remove( configGitLabel(repo, token), answers.removals )
              .then(console.log)
              .catch(console.warn);
          });
        });
      };

//  Promise-based check to see if we're even in a Git repo
const isGitRepo = () => {
        return new Promise((res, rej) => {
          fs.readdir(process.cwd()+'/.git/', (e, files) => {
            if (e) rej(false);
            res(true);
          })
        });
      };
//  Promise-based reading the git config to find the repo
const readGitConfig  = () => {
        return new Promise((res, rej)=>{
          fs.readFile( process.cwd()+'/.git/config', 'utf8', (e, data) => {
            if (e) rej(e);
            res( data );// split it at newlines
          })
        });
      };
//  Returns a config for gitLabel
const configGitLabel = (repo, token) => {
        return {
          //  TODO: HARDCODING THE API IN TSK TSK TSK...
          api:    'https://api.github.com',
          repo:   repo,
          token:  token
        }
      };

const handleAddPrompts = (repo, token, newLabels) => {
        gitLabel.add( configGitLabel(repo, token), newLabels )
          .then(console.log)
          .catch(console.warn);
      };

const handleMainPrompts = (repo, ans) => {
        if ( ans.main.toLowerCase() === "reset token" ){
          return setToken((token) => {
            iq.prompt( mainPrompts, handleMainPrompts.bind(null, repo));
          });
        }
        //  if it's not to reset the token then we
        fetchToken()
          .then((token)=>{
            if ( ans.main.toLowerCase() === "add labels" ){
              doAddPrompts( [], handleAddPrompts.bind(null, repo, token));
            }
            if ( ans.main.toLowerCase() === "remove labels" ){
              doRemovePrompts(token, repo);
            }
          })
          .catch((msg)=>{
            console.log(msg);
            setToken((token) => {
              iq.prompt( mainPrompts, handleMainPrompts.bind(null, repo));
            });
          });
      };

//    LET'S DO IT
    Promise.all([ isGitRepo(), readGitConfig() ])
      .then(( values )=>{
        let repo = readRepo(values[1].split("\n"));
        iq.prompt( mainPrompts, handleMainPrompts.bind(null, repo));
      })
      .catch((e)=>{
        console.warn(e);
        console.warn("Please run git-labelmaker from inside a git repo!")
        process.exit(1);
      });
<commit_msg>Adds a prompt for custom labels or for a label package<commit_after>#!/usr/bin/env node
"use strict";

const fs = require("fs"),
      iq = require("inquirer"),
      gitLabel = require("git-label"),
      octonode = require("octonode"),
      readRepo = require("./components/read-repo"),
      cleanup  = require("./components/remove-tmp-pkg"),
      mainPrompts = require("./components/main-prompts"),
      addPrompts  = require("./components/add-prompts");

//  Responsible for fetching and returning our config/token
const fetchToken = () => {
        return new Promise((res, rej)=>{
          fs.readFile(__dirname+"/.token.json", 'utf8', (e, data) => {
            if (e) rej("No token.json file found!");
            if (JSON.parse(data).token === "") rej("No token found!");
            res(JSON.parse(data).token);
            res();
          });
        });
      };
//  Responsible for asking the user what their token is, and then storing it
//  executed only if it can't be found!
const setToken = (done) => {
        iq.prompt([{
            type: "input",
            name: "token",
            message: "What is your GitHub Access Token?",
            default: "eg: 12345678..."
        }], (answer) => {
          fs.writeFile( __dirname+'/.token.json', JSON.stringify( { "token": answer.token }, null, 2 ), 'utf8', (e)=>{
            if (e) throw e;
            console.log("Stored new token!");
            done(answer.token);
          });
        });
      };
//  Recursivly asks if you want to add another new label, then calls a callback when youre all done
const doCustomLabelPrompts = ( newLabels, done ) => {
        iq.prompt( addPrompts, ( answers ) => {
          newLabels.push({ name: answers.labelName, color: answers.labelColor });
          if ( answers.addAnother ){
            doCustomLabelPrompts( newLabels, done );
          }else{
            done( newLabels );
          }
        });
      };

const doRemovePrompts = ( token, repo ) => {
        octonode.client(token).get('/repos/'+repo+'/labels', (e, status, body) => {
          iq.prompt([{
            name:     "removals",
            type:     "checkbox",
            message:  "Which labels would you like to remove?",
            choices:  body.map((label) => label.name),
            filter:   (removals) => {
              return body.filter((label) => {
                return removals.indexOf(label.name) > -1 ? { name: label.name, color: label.color } : false;
              });
            }
          }], (answers) => {
            gitLabel.remove( configGitLabel(repo, token), answers.removals )
              .then(console.log)
              .catch(console.warn);
          });
        });
      };

//  Promise-based check to see if we're even in a Git repo
const isGitRepo = () => {
        return new Promise((res, rej) => {
          fs.readdir(process.cwd()+'/.git/', (e, files) => {
            if (e) rej(false);
            res(true);
          })
        });
      };
//  Promise-based reading the git config to find the repo
const readGitConfig  = () => {
        return new Promise((res, rej)=>{
          fs.readFile( process.cwd()+'/.git/config', 'utf8', (e, data) => {
            if (e) rej(e);
            res( data );// split it at newlines
          })
        });
      };
//  Returns a config for gitLabel
const configGitLabel = (repo, token) => {
        return {
          api:    'https://api.github.com',
          repo:   repo,
          token:  token
        }
      };

const handleAddPrompts = (repo, token, newLabels) => {
        gitLabel.add( configGitLabel(repo, token), newLabels )
          .then(console.log)
          .catch(console.warn);
      };

const handleMainPrompts = (repo, ans) => {
        if ( ans.main.toLowerCase() === "reset token" ){
          return setToken((token) => {
            iq.prompt( mainPrompts, handleMainPrompts.bind(null, repo));
          });
        }
        //  if it's not to reset the token then we
        fetchToken()
          .then((token)=>{
            if ( ans.main.toLowerCase() === "add labels" ){
              // check if they want to add labels from a package
              iq.prompt([{
                name:    "addMethod",
                type:    "list",
                message: "Do you want to use a label package or create custom labels?",
                choices: [ "Use a package", "Create custom labels" ]
              }], (addMethodAns) => {
                if ( addMethodAns.addMethod.toLowerCase() === "create custom labels" ) {
                  doCustomLabelPrompts( [], handleAddPrompts.bind(null, repo, token));
                }
              });
            }
            if ( ans.main.toLowerCase() === "remove labels" ){
              doRemovePrompts(token, repo);
            }
          })
          .catch((msg)=>{
            console.log(msg);
            setToken((token) => {
              iq.prompt( mainPrompts, handleMainPrompts.bind(null, repo));
            });
          });
      };

//    LET'S DO IT
    Promise.all([ isGitRepo(), readGitConfig() ])
      .then(( values )=>{
        let repo = readRepo(values[1].split("\n"));
        iq.prompt( mainPrompts, handleMainPrompts.bind(null, repo));
      })
      .catch((e)=>{
        console.warn(e);
        console.warn("Please run git-labelmaker from inside a git repo!")
        process.exit(1);
      });
<|endoftext|>


<commit_before>const uuid = require('uuid');
const lua = require('./lua.json');

function BQueue(redisClient, queueName = 'bqueue', queueCount = 1) {
  if (typeof queueName !== 'string') {
    throw new Error('Queue name must be a string!');
  } else if (!Number.isInteger(queueCount)) {
    throw new Error('Queue count must be an integer!');
  } else if (queueCount < 1 || queueCount > 1000) {
    throw new Error('Queue count must be between 1 and 1000!');
  }

  this.redisClient = redisClient;
  this.queueName = queueName;
  this.queueCount = queueCount;

  this.redisClient.defineCommand('pushMessage', {
    numberOfKeys: 1,
    lua: lua.pushMessage
  });
  this.redisClient.defineCommand('getBatch', {
    numberOfKeys: 1,
    lua: lua.getBatch
  });
  this.redisClient.defineCommand('removeMessages', {
    numberOfKeys: 1,
    lua: lua.removeMessages
  });
  this.redisClient.defineCommand('reinsertUnprocessed', {
    numberOfKeys: 1,
    lua: lua.reinsertUnprocessed
  });
}

BQueue.prototype.pushMessage = function(message = '') {
  return new Promise((resolve, reject) => {
    const queueNumber = Math.floor(Math.random() * this.queueCount);
    const queue = this.queueName + ':' + queueNumber;
    const id = uuid.v4();
    this.redisClient.pushMessage(queue, id, JSON.stringify({id, message}), (err, result) => {
      if (err) {
        return reject(err);
      } else {
        return resolve(result);
      }
    });
  });
};

BQueue.prototype.getBatch = function(maxBatchSize = 1, processingTimeout = 5000) {
  return new Promise((resolve, reject) => {
    if (!Number.isInteger(maxBatchSize)) {
      return reject(Error('Max batch size must be an integer!'));
    } else if (maxBatchSize < 1 || maxBatchSize > 10000) {
      return reject(Error('Max batch sizee must be between 1 and 10000!'));
    } else if (!Number.isInteger(processingTimeout)) {
      return reject(Error('Processing timeout must be an integer!'));
    } else if (processingTimeout < 1000 || processingTimeout > 604800000) {
      return reject(Error('Processing timeout must be between 1000 and 604800000!'));
    }
    const queueNumber = Math.floor(Math.random() * this.queueCount);
    const queue = this.queueName + ':' + queueNumber;
    this.redisClient.getBatch(queue, maxBatchSize, processingTimeout, (err, results) => {
      if (err) {
        return reject(err);
      } else {
        const messages = results.map(value => JSON.parse(value));
        return resolve({
          messages: messages,
          remove: () => {
            return new Promise((resolve, reject) => {
              const ids = messages.map(message => message.id);
              this.redisClient.removeMessages(queue, ...ids, (err, results) => {
                if (err) {
                  return reject(err);
                } else {
                  return resolve(results);
                }
              });
            });
          }
        });
      }
    });
  });
};

BQueue.prototype.reinsertUnprocessed = function(maxMessages = 1000) {
  if (!Number.isInteger(maxMessages)) {
    return reject(Error('Max messages must be an integer!'));
  } else if (maxMessages < 1 || maxMessages > 10000) {
    return reject(Error('Max messages must be between 1 and 10000!'));
  }
  return new Promise((resolve, reject) => {
    const queueNumber = Math.floor(Math.random() * this.queueCount);
    const queue = this.queueName + ':' + queueNumber;
    this.redisClient.reinsertUnprocessed(queue, maxMessages, (err, result) => {
      if (err) {
        return reject(err);
      } else {
        return resolve(result);
      }
    });
  });
};

module.exports = BQueue;
<commit_msg>Fix validation bug<commit_after>const uuid = require('uuid');
const lua = require('./lua.json');

function BQueue(redisClient, queueName = 'bqueue', queueCount = 1) {
  if (typeof queueName !== 'string') {
    throw new Error('Queue name must be a string!');
  } else if (!Number.isInteger(queueCount)) {
    throw new Error('Queue count must be an integer!');
  } else if (queueCount < 1 || queueCount > 1000) {
    throw new Error('Queue count must be between 1 and 1000!');
  }

  this.redisClient = redisClient;
  this.queueName = queueName;
  this.queueCount = queueCount;

  this.redisClient.defineCommand('pushMessage', {
    numberOfKeys: 1,
    lua: lua.pushMessage
  });
  this.redisClient.defineCommand('getBatch', {
    numberOfKeys: 1,
    lua: lua.getBatch
  });
  this.redisClient.defineCommand('removeMessages', {
    numberOfKeys: 1,
    lua: lua.removeMessages
  });
  this.redisClient.defineCommand('reinsertUnprocessed', {
    numberOfKeys: 1,
    lua: lua.reinsertUnprocessed
  });
}

BQueue.prototype.pushMessage = function(message = '') {
  return new Promise((resolve, reject) => {
    const queueNumber = Math.floor(Math.random() * this.queueCount);
    const queue = this.queueName + ':' + queueNumber;
    const id = uuid.v4();
    this.redisClient.pushMessage(queue, id, JSON.stringify({id, message}), (err, result) => {
      if (err) {
        return reject(err);
      } else {
        return resolve(result);
      }
    });
  });
};

BQueue.prototype.getBatch = function(maxBatchSize = 1, processingTimeout = 5000) {
  return new Promise((resolve, reject) => {
    if (!Number.isInteger(maxBatchSize)) {
      return reject(Error('Max batch size must be an integer!'));
    } else if (maxBatchSize < 1 || maxBatchSize > 10000) {
      return reject(Error('Max batch sizee must be between 1 and 10000!'));
    } else if (!Number.isInteger(processingTimeout)) {
      return reject(Error('Processing timeout must be an integer!'));
    } else if (processingTimeout < 1000 || processingTimeout > 604800000) {
      return reject(Error('Processing timeout must be between 1000 and 604800000!'));
    }
    const queueNumber = Math.floor(Math.random() * this.queueCount);
    const queue = this.queueName + ':' + queueNumber;
    this.redisClient.getBatch(queue, maxBatchSize, processingTimeout, (err, results) => {
      if (err) {
        return reject(err);
      } else {
        const messages = results.map(value => JSON.parse(value));
        return resolve({
          messages: messages,
          remove: () => {
            return new Promise((resolve, reject) => {
              const ids = messages.map(message => message.id);
              this.redisClient.removeMessages(queue, ...ids, (err, results) => {
                if (err) {
                  return reject(err);
                } else {
                  return resolve(results);
                }
              });
            });
          }
        });
      }
    });
  });
};

BQueue.prototype.reinsertUnprocessed = function(maxMessages = 1000) {
  return new Promise((resolve, reject) => {
    if (!Number.isInteger(maxMessages)) {
      return reject(Error('Max messages must be an integer!'));
    } else if (maxMessages < 1 || maxMessages > 10000) {
      return reject(Error('Max messages must be between 1 and 10000!'));
    }
    const queueNumber = Math.floor(Math.random() * this.queueCount);
    const queue = this.queueName + ':' + queueNumber;
    this.redisClient.reinsertUnprocessed(queue, maxMessages, (err, result) => {
      if (err) {
        return reject(err);
      } else {
        return resolve(result);
      }
    });
  });
};

module.exports = BQueue;
<|endoftext|>


<commit_before>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('pager-control', 'Integration | Component | pager control', {
  integration: true
});

test('it renders', function(assert) {
  this.render(hbs`{{pager-control}}`);
  assert.equal(this.$('.pager-control').length, 1, 'The element is rendered');
});

test('it renders the correct control elements', function(assert) {
  this.set('options', {
    pageSize: 5,
    totalRecords: 43,
    currentPage: 3,
    totalPages: 5
  });

  this.render(hbs`{{pager-control options=options}}`);

  assert.equal(this.$('.next-page').length, 1, 'It renders the next page button');
  assert.equal(this.$('.previous-page').length, 1, 'It renders the previous page button');

  assert.equal(this.$('.page-button').length, 5, 'Total pages is > 5, so 5 page buttons are rendered');
  assert.equal(this.$('.page-button:first').text().trim(), '1', 'First rendered page button is page 1');
  assert.equal(this.$('.page-button:last').text().trim(), '5', 'Last rendered page button is page 5');
  assert.equal(this.$('.page-button.current').text().trim(), '3', 'Current page is 3');
});

test('The previous page button changes the current page to one smaller', function(assert) {
  this.set('options', {
    pageSize: 5,
    totalRecords: 43,
    currentPage: 3,
    totalPages: 5
  });

  assert.expect(2);

  this.on('pageChanged', function(page) {
    assert.equal(page, 2);
  });

  this.render(hbs`{{pager-control options=options pageChanged='pageChanged'}}`);
  this.$('.previous-page').click();
  assert.equal(this.$('.page-button.current').text().trim(), '2', 'Current page is now 2');
});

test('The next page button changes the current page to one larger', function(assert) {
  this.set('options', {
    pageSize: 5,
    totalRecords: 43,
    currentPage: 3,
    totalPages: 5
  });

  assert.expect(2);

  this.on('pageChanged', function(page) {
    assert.equal(page, 4);
  });

  this.render(hbs`{{pager-control options=options pageChanged='pageChanged'}}`);
  this.$('.next-page').click();
  assert.equal(this.$('.page-button.current').text().trim(), '4', 'Current page is now 4');
});

test('Individual page buttons set the current page to the one specified', function(assert) {
  this.set('options', {
    pageSize: 5,
    totalRecords: 43,
    currentPage: 3,
    totalPages: 5
  });

  this.render(hbs`{{pager-control options=options pageChanged='pageChanged'}}`);

  assert.expect(4);

  this.on('pageChanged', function(page) {
    assert.equal(page, 1);
  });

  this.$('.page-button:first').click();
  assert.equal(this.$('.page-button.current').text().trim(), '1', 'Current page is now 1');

  this.on('pageChanged', function(page) {
    assert.equal(page, 5);
  });

  this.$('.page-button:last').click();
  assert.equal(this.$('.page-button.current').text().trim(), '5', 'Current page is now 5');

});

test('If there is less than 5 pages of records in total, it only renders buttons for those pages', function (assert) {
  this.set('options', {
    pageSize: 5,
    totalRecords: 7,
    currentPage: 1,
    totalPages: 2
  });

  this.render(hbs`{{pager-control options=options}}`);

  assert.equal(this.$('.page-button').length, 2, 'Only two pages total are rendered');
});
<commit_msg>Additional assertions for previously added test<commit_after>import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';

moduleForComponent('pager-control', 'Integration | Component | pager control', {
  integration: true
});

test('it renders', function(assert) {
  this.render(hbs`{{pager-control}}`);
  assert.equal(this.$('.pager-control').length, 1, 'The element is rendered');
});

test('it renders the correct control elements', function(assert) {
  this.set('options', {
    pageSize: 5,
    totalRecords: 43,
    currentPage: 3,
    totalPages: 5
  });

  this.render(hbs`{{pager-control options=options}}`);

  assert.equal(this.$('.next-page').length, 1, 'It renders the next page button');
  assert.equal(this.$('.previous-page').length, 1, 'It renders the previous page button');

  assert.equal(this.$('.page-button').length, 5, 'Total pages is > 5, so 5 page buttons are rendered');
  assert.equal(this.$('.page-button:first').text().trim(), '1', 'First rendered page button is page 1');
  assert.equal(this.$('.page-button:last').text().trim(), '5', 'Last rendered page button is page 5');
  assert.equal(this.$('.page-button.current').text().trim(), '3', 'Current page is 3');
});

test('The previous page button changes the current page to one smaller', function(assert) {
  this.set('options', {
    pageSize: 5,
    totalRecords: 43,
    currentPage: 3,
    totalPages: 5
  });

  assert.expect(2);

  this.on('pageChanged', function(page) {
    assert.equal(page, 2);
  });

  this.render(hbs`{{pager-control options=options pageChanged='pageChanged'}}`);
  this.$('.previous-page').click();
  assert.equal(this.$('.page-button.current').text().trim(), '2', 'Current page is now 2');
});

test('The next page button changes the current page to one larger', function(assert) {
  this.set('options', {
    pageSize: 5,
    totalRecords: 43,
    currentPage: 3,
    totalPages: 5
  });

  assert.expect(2);

  this.on('pageChanged', function(page) {
    assert.equal(page, 4);
  });

  this.render(hbs`{{pager-control options=options pageChanged='pageChanged'}}`);
  this.$('.next-page').click();
  assert.equal(this.$('.page-button.current').text().trim(), '4', 'Current page is now 4');
});

test('Individual page buttons set the current page to the one specified', function(assert) {
  this.set('options', {
    pageSize: 5,
    totalRecords: 43,
    currentPage: 3,
    totalPages: 5
  });

  this.render(hbs`{{pager-control options=options pageChanged='pageChanged'}}`);

  assert.expect(4);

  this.on('pageChanged', function(page) {
    assert.equal(page, 1);
  });

  this.$('.page-button:first').click();
  assert.equal(this.$('.page-button.current').text().trim(), '1', 'Current page is now 1');

  this.on('pageChanged', function(page) {
    assert.equal(page, 5);
  });

  this.$('.page-button:last').click();
  assert.equal(this.$('.page-button.current').text().trim(), '5', 'Current page is now 5');

});

test('If there is less than 5 pages of records in total, it only renders buttons for those pages', function (assert) {
  this.set('options', {
    pageSize: 5,
    totalRecords: 7,
    currentPage: 1,
    totalPages: 2
  });

  this.render(hbs`{{pager-control options=options}}`);

  assert.equal(this.$('.page-button').length, 2, 'Only two pages total are rendered');
  assert.equal(this.$('.page-button.1').length, 1, 'Page 1 is rendered');
  assert.equal(this.$('.page-button.2').length, 1, 'Page 2 is rendered');
});
<|endoftext|>


<commit_before>const jwt = require('jsonwebtoken')

const Users = require('../models/user')
const Conversations = require('../models/conversation')
const Messages = require('../models/message')

var connectedUsers = []

exports.load_chat_data = (req, res) => {
    jwt.verify(req.headers.authorization, 'supersecretsecret', (err, decoded) => {
        if(err) {
            res.send({
                status: "error"
            })
        }
        else {
            Users.find({_id: { $ne: decoded.id }}, 'username _id', (err, users) => {
                if(err) {
                    res.send({
                        status: "error"
                    })
                }
                else {
                    res.send({
                        status: "success",
                        users: users
                    })
                }
            })
        }
    })

}

exports.chat_connection = (id, socket) => {
    socket.emit('connected_users', connectedUsers)
    connectedUsers.push({
        id: id,
        socketId: socket.id
    })
    socket.broadcast.emit('user_change', {id: id, isActive: true})
}

exports.chat_disconnection = socket => {
    let dcUser
    connectedUsers = connectedUsers.filter(user => {
        if(user.socketId !== socket.id)
            return true
        else {
            dcUser = user.id
            return false
        }
    })
    socket.broadcast.emit('user_change', {id: dcUser, isActive: false})
    Users.findOneAndUpdate({
        _id: dcUser
    }, {
        $set: { lastLogin: Date.now() }
    }, err => {
        if(err) console.log(err)
    })
}

exports.new_message = (message, ack, socket) => {
    Messages.create({
        content: message.content,
        author: message.author,
        wasDelivered: true,
        wasSeen: false,
        conversationId: message.conversationId

    }, (err, messageInstance) => {
        if (err) {
            console.log("error")
        }
        else {
            let target = connectedUsers.find(user => user.id === message.addresse)
            if (target) {
                socket.broadcast.to(target.socketId).emit("new_message", messageInstance)
            }
            ack(messageInstance._id)
        }
    })
}

exports.message_seen = (messageId, socket) => {
    Messages.findOneAndUpdate({ _id: messageId }, { $set: { wasSeen: true } }, (err, message) => {
        if(err) {
            console.log("error")
        }
        else {
            let target = connectedUsers.find(user => user.id === message.author)
            if (target) {
                socket.broadcast.to(target.socketId).emit("message_seen", message._id)
            }
        }
    })
}<commit_msg>hotfix<commit_after>const jwt = require('jsonwebtoken')

const Users = require('../models/user')
const Conversations = require('../models/conversation')
const Messages = require('../models/message')

var connectedUsers = []

exports.load_chat_data = (req, res) => {
    jwt.verify(req.headers.authorization, 'supersecretsecret', (err, decoded) => {
        if(err) {
            res.send({
                status: "error"
            })
        }
        else {
            Users.find({_id: { $ne: decoded.id }}, 'username _id', (err, users) => {
                if(err) {
                    res.send({
                        status: "error"
                    })
                }
                else {
                    res.send({
                        status: "success",
                        users: users
                    })
                }
            })
        }
    })

}

exports.chat_connection = (id, socket) => {
    socket.emit('connected_users', connectedUsers)
    connectedUsers.push({
        id: id,
        socketId: socket.id
    })
    socket.broadcast.emit('user_change', {id: id, isActive: true})
}

exports.chat_disconnection = socket => {
    let dcUser
    connectedUsers = connectedUsers.filter(user => {
        if(user.socketId !== socket.id)
            return true
        else {
            dcUser = user.id
            return false
        }
    })
    socket.broadcast.emit('user_change', {id: dcUser, isActive: false})
    Users.findOneAndUpdate({
        _id: dcUser
    }, {
        $set: { lastLogin: Date.now() }
    }, err => {
        if(err) console.log(err)
    })
}

exports.new_message = (message, ack, socket) => {
    Messages.create({
        content: message.content,
        author: message.author,
        wasDelivered: true,
        wasSeen: false,
        conversationId: message.conversationId

    }, (err, messageInstance) => {
        if (err) {
            console.log("error")
        }
        else {
            let target = connectedUsers.find(user => user.id === message.addresse)
            if (target) {
                socket.broadcast.to(target.socketId).emit("new_message", messageInstance)
            }
            ack(messageInstance._id)
        }
    })
}

exports.message_seen = (messageId, socket) => {
    Messages.findOneAndUpdate({ _id: messageId }, { $set: { wasSeen: true } }, (err, message) => {
        if(err) {
            console.log("error")
        }
        else {
            let target = connectedUsers.find(user => user.id === message.author.toString())
            if (target) {
                socket.broadcast.to(target.socketId).emit("message_seen", message._id)
            }
        }
    })
}<|endoftext|>


<commit_before>const SchemaManager = require("./schemaManager");
const SQL = require("./sql");

/* eslint-disable no-restricted-syntax, class-methods-use-this */
module.exports = class SettingGateway extends SchemaManager {
  constructor(store, type, validateFunction, schema) {
    super(store.client);

    /** @type {SettingCache} */
    Object.defineProperty(this, "store", { value: store });

    /** @type {string} */
    this.type = `${type}_`;

    /** @type {string} */
    this.engine = this.client.config.provider.engine || "json";

    this.provider = this.client.providers.get(this.engine);
    if (!this.provider) throw `This provider (${this.engine}) does not exist in your system.`;

    this.sql = this.provider.conf.sql ? new SQL(this.client, this, this.provider) : false;

    Object.defineProperty(this.prototype, "validate", { value: validateFunction });

    this.defaultDataSchema = schema;
  }

  /**
   * Initialize the configuration for this gateway.
   * @returns {void}
   */
  async init() {
    await this.initSchema();
    if (!(await this.provider.hasTable(this.type))) {
      const SQLCreate = this.sql ? this.sql.buildSQLSchema(this.schema) : undefined;
      await this.provider.createTable(this.type, SQLCreate);
    }
    const data = await this.provider.getAll(this.type);
    if (this.sql) {
      this.sql.initDeserialize();
      for (let i = 0; i < data.length; i++) this.sql.deserializer(data[i]);
    }
    if (data[0]) for (const key of data) super.set(key.id, key);
  }

  /**
   * Create a new entry in the configuration.
   * @param {Object|string} input An object containing a id property, like discord.js objects, or a string.
   * @returns {void}
   */
  async create(input) {
    const target = await this.validate(input).then(output => (output.id || output));
    await this.provider.create(this.type, target, this.defaults);
    super.set(target, this.defaults);
  }

  /**
   * Remove an entry from the configuration.
   * @param {string} input A key to delete from the cache.
   * @returns {void}
   */
  async destroy(input) {
    await this.provider.delete(this.type, input);
    super.delete(this.type, input);
  }

  /**
   * Get an entry from the cache.
   * @param {string} input A key to get the value for.
   * @returns {Object}
   */
  get(input) {
    if (input === "default") return this.defaults;
    return super.get(input) || this.defaults;
  }

  /**
   * Get a Resolved Guild entry from the configuration.
   * @param {(Guild|Snowflake)} guild The Guild object or snowflake.
   * @returns {Object}
   */
  async getResolved(guild) {
    guild = await this.validate(guild);
    const settings = this.get(guild.id);
    const resolved = await Promise.all(Object.entries(settings).map(([key, data]) => {
      if (this.schema[key] && this.schema[key].array) return { [key]: Promise.all(data.map(entry => this.resolver[this.schema[key].type.toLowerCase()](entry, guild, this.schema[key]))) };
      return { [key]: this.schema[key] && data ? this.resolver[this.schema[key].type.toLowerCase()](data, guild, this.schema[key]) : data };
    }));
    return Object.assign({}, ...resolved);
  }

  /**
   * Sync either all entries from the configuration, or a single one.
   * @param {Object|string} [input=null] An object containing a id property, like discord.js objects, or a string.
   * @returns {void}
   */
  async sync(input = null) {
    if (!input) {
      const data = await this.provider.getAll(this.type);
      if (this.sql) for (let i = 0; i < data.length; i++) this.sql.deserializer(data[i]);
      for (const key of data) super.set(key.id, key);
      return;
    }
    const target = await this.validate(input).then(output => (output.id || output));
    const data = await this.provider.get(this.type, target.id);
    if (this.sql) this.sql.deserializer(data);
    await super.set(target, data);
  }

  /**
   * Reset a key's value to default from a entry.
   * @param {Object|string} input An object containing a id property, like discord.js objects, or a string.
   * @param {string} key The key to reset.
   * @returns {*}
   */
  async reset(input, key) {
    const target = await this.validate(input).then(output => (output.id || output));
    if (!(key in this.schema)) throw `The key ${key} does not exist in the current data schema.`;
    const defaultKey = this.schema[key].default;
    await this.provider.update(this.type, target, { [key]: defaultKey });
    this.sync(target);
    return defaultKey;
  }

  /**
   * Updates an entry.
   * @param {Object|string} input An object containing a id property, like discord.js objects, or a string.
   * @param {string} key The key to update.
   * @param {any} data The new value for the key.
   * @returns {any}
   */
  async update(input, key, data) {
    if (!(key in this.schema)) throw `The key ${key} does not exist in the current data schema.`;
    const target = await this.validate(input).then(output => (output.id || output));
    let result = await this.resolver[this.schema[key].type.toLowerCase()](data, this.client.guilds.get(target), this.schema[key]);
    if (result.id) result = result.id;
    await this.provider.update(this.type, target, { [key]: result });
    await this.sync(target.id);
    return result;
  }

  /**
   * Update an array from the a Guild's configuration.
   * @param {Object|string} input An object containing a id property, like discord.js objects, or a string.
   * @param {string} type Either 'add' or 'remove'.
   * @param {string} key The key from the Schema.
   * @param {any} data The value to be added or removed.
   * @returns {boolean}
   */
  async updateArray(input, type, key, data) {
    if (!["add", "remove"].includes(type)) throw "The type parameter must be either add or remove.";
    if (!(key in this.schema)) throw `The key ${key} does not exist in the current data schema.`;
    if (!this.schema[key].array) throw `The key ${key} is not an Array.`;
    if (data === undefined) throw "You must specify the value to add or filter.";
    const target = await this.validate(input).then(output => (output.id || output));
    let result = await this.resolver[this.schema[key].type.toLowerCase()](data, this.client.guilds.get(target), this.schema[key]);
    if (result.id) result = result.id;
    const cache = this.get(target);
    if (type === "add") {
      if (cache[key].includes(result)) throw `The value ${data} for the key ${key} already exists.`;
      cache[key].push(result);
      await this.provider.update(this.type, target, { [key]: cache[key] });
      await this.sync(target.id);
      return result;
    }
    if (!cache[key].includes(result)) throw `The value ${data} for the key ${key} does not exist.`;
    cache[key] = cache[key].filter(v => v !== result);
    await this.provider.update(this.type, target, { [key]: cache[key] });
    await this.sync(target);
    return true;
  }

  get client() {
    return this.store.client;
  }

  get resolver() {
    return this.store.resolver;
  }
};
<commit_msg>this.prototype is undefined inside the constructor.<commit_after>const SchemaManager = require("./schemaManager");
const SQL = require("./sql");

/* eslint-disable no-restricted-syntax, class-methods-use-this */
module.exports = class SettingGateway extends SchemaManager {
  constructor(store, type, validateFunction, schema) {
    super(store.client);

    /** @type {SettingCache} */
    Object.defineProperty(this, "store", { value: store });

    /** @type {string} */
    this.type = `${type}_`;

    /** @type {string} */
    this.engine = this.client.config.provider.engine || "json";

    this.provider = this.client.providers.get(this.engine);
    if (!this.provider) throw `This provider (${this.engine}) does not exist in your system.`;

    this.sql = this.provider.conf.sql ? new SQL(this.client, this, this.provider) : false;

    this.validate = validateFunction;

    this.defaultDataSchema = schema;
  }

  /**
   * Initialize the configuration for this gateway.
   * @returns {void}
   */
  async init() {
    await this.initSchema();
    if (!(await this.provider.hasTable(this.type))) {
      const SQLCreate = this.sql ? this.sql.buildSQLSchema(this.schema) : undefined;
      await this.provider.createTable(this.type, SQLCreate);
    }
    const data = await this.provider.getAll(this.type);
    if (this.sql) {
      this.sql.initDeserialize();
      for (let i = 0; i < data.length; i++) this.sql.deserializer(data[i]);
    }
    if (data[0]) for (const key of data) super.set(key.id, key);
  }

  /**
   * Create a new entry in the configuration.
   * @param {Object|string} input An object containing a id property, like discord.js objects, or a string.
   * @returns {void}
   */
  async create(input) {
    const target = await this.validate(input).then(output => (output.id || output));
    await this.provider.create(this.type, target, this.defaults);
    super.set(target, this.defaults);
  }

  /**
   * Remove an entry from the configuration.
   * @param {string} input A key to delete from the cache.
   * @returns {void}
   */
  async destroy(input) {
    await this.provider.delete(this.type, input);
    super.delete(this.type, input);
  }

  /**
   * Get an entry from the cache.
   * @param {string} input A key to get the value for.
   * @returns {Object}
   */
  get(input) {
    if (input === "default") return this.defaults;
    return super.get(input) || this.defaults;
  }

  /**
   * Get a Resolved Guild entry from the configuration.
   * @param {(Guild|Snowflake)} guild The Guild object or snowflake.
   * @returns {Object}
   */
  async getResolved(guild) {
    guild = await this.validate(guild);
    const settings = this.get(guild.id);
    const resolved = await Promise.all(Object.entries(settings).map(([key, data]) => {
      if (this.schema[key] && this.schema[key].array) return { [key]: Promise.all(data.map(entry => this.resolver[this.schema[key].type.toLowerCase()](entry, guild, this.schema[key]))) };
      return { [key]: this.schema[key] && data ? this.resolver[this.schema[key].type.toLowerCase()](data, guild, this.schema[key]) : data };
    }));
    return Object.assign({}, ...resolved);
  }

  /**
   * Sync either all entries from the configuration, or a single one.
   * @param {Object|string} [input=null] An object containing a id property, like discord.js objects, or a string.
   * @returns {void}
   */
  async sync(input = null) {
    if (!input) {
      const data = await this.provider.getAll(this.type);
      if (this.sql) for (let i = 0; i < data.length; i++) this.sql.deserializer(data[i]);
      for (const key of data) super.set(key.id, key);
      return;
    }
    const target = await this.validate(input).then(output => (output.id || output));
    const data = await this.provider.get(this.type, target.id);
    if (this.sql) this.sql.deserializer(data);
    await super.set(target, data);
  }

  /**
   * Reset a key's value to default from a entry.
   * @param {Object|string} input An object containing a id property, like discord.js objects, or a string.
   * @param {string} key The key to reset.
   * @returns {*}
   */
  async reset(input, key) {
    const target = await this.validate(input).then(output => (output.id || output));
    if (!(key in this.schema)) throw `The key ${key} does not exist in the current data schema.`;
    const defaultKey = this.schema[key].default;
    await this.provider.update(this.type, target, { [key]: defaultKey });
    this.sync(target);
    return defaultKey;
  }

  /**
   * Updates an entry.
   * @param {Object|string} input An object containing a id property, like discord.js objects, or a string.
   * @param {string} key The key to update.
   * @param {any} data The new value for the key.
   * @returns {any}
   */
  async update(input, key, data) {
    if (!(key in this.schema)) throw `The key ${key} does not exist in the current data schema.`;
    const target = await this.validate(input).then(output => (output.id || output));
    let result = await this.resolver[this.schema[key].type.toLowerCase()](data, this.client.guilds.get(target), this.schema[key]);
    if (result.id) result = result.id;
    await this.provider.update(this.type, target, { [key]: result });
    await this.sync(target.id);
    return result;
  }

  /**
   * Update an array from the a Guild's configuration.
   * @param {Object|string} input An object containing a id property, like discord.js objects, or a string.
   * @param {string} type Either 'add' or 'remove'.
   * @param {string} key The key from the Schema.
   * @param {any} data The value to be added or removed.
   * @returns {boolean}
   */
  async updateArray(input, type, key, data) {
    if (!["add", "remove"].includes(type)) throw "The type parameter must be either add or remove.";
    if (!(key in this.schema)) throw `The key ${key} does not exist in the current data schema.`;
    if (!this.schema[key].array) throw `The key ${key} is not an Array.`;
    if (data === undefined) throw "You must specify the value to add or filter.";
    const target = await this.validate(input).then(output => (output.id || output));
    let result = await this.resolver[this.schema[key].type.toLowerCase()](data, this.client.guilds.get(target), this.schema[key]);
    if (result.id) result = result.id;
    const cache = this.get(target);
    if (type === "add") {
      if (cache[key].includes(result)) throw `The value ${data} for the key ${key} already exists.`;
      cache[key].push(result);
      await this.provider.update(this.type, target, { [key]: cache[key] });
      await this.sync(target.id);
      return result;
    }
    if (!cache[key].includes(result)) throw `The value ${data} for the key ${key} does not exist.`;
    cache[key] = cache[key].filter(v => v !== result);
    await this.provider.update(this.type, target, { [key]: cache[key] });
    await this.sync(target);
    return true;
  }

  get client() {
    return this.store.client;
  }

  get resolver() {
    return this.store.resolver;
  }
};
<|endoftext|>


<commit_before>'use strict';

import { NativeAppEventEmitter, NativeModules } from 'react-native';
const ReactNativeBluetooth = NativeModules.ReactNativeBluetooth;

const didChangeState = (callback) => {
  var subscription = NativeAppEventEmitter.addListener(
    ReactNativeBluetooth.StateChanged,
    callback
  );

  ReactNativeBluetooth.notifyCurrentState();

  return function() {
    subscription.remove();
  };
};

const DefaultScanOptions = {
  uuids: [],
};

const Scan = {
  stopAfter: (timeout) => {
    return new Promise(resolve => {
      setTimeout(() => {
        ReactNativeBluetooth.stopScan()
          .then(resolve)
          .catch(console.log.bind(console));
      }, timeout);
    })
  }
}

const startScan = (customOptions = {}) => {
  let options = Object.assign({}, DefaultScanOptions, customOptions);

  return ReactNativeBluetooth.startScan(options.uuids).then(() => Scan);
}

const didDiscoverDevice = (callback) => {
  var subscription = NativeAppEventEmitter.addListener(
    ReactNativeBluetooth.DeviceDiscovered,
    callback
  );

  return function() {
    subscription.remove();
  };
};

export default {
  didChangeState,
  startScan,
  didDiscoverDevice,
};
<commit_msg>js: Extract unsubscription()<commit_after>'use strict';

import { NativeAppEventEmitter, NativeModules } from 'react-native';
const ReactNativeBluetooth = NativeModules.ReactNativeBluetooth;

const unsubscription = (listener) => {
  return () => listener.remove();
};

const didChangeState = (callback) => {
  var listener = NativeAppEventEmitter.addListener(
    ReactNativeBluetooth.StateChanged,
    callback
  );

  ReactNativeBluetooth.notifyCurrentState();

  return unsubscription(listener);
};

const DefaultScanOptions = {
  uuids: [],
};

const Scan = {
  stopAfter: (timeout) => {
    return new Promise(resolve => {
      setTimeout(() => {
        ReactNativeBluetooth.stopScan()
          .then(resolve)
          .catch(console.log.bind(console));
      }, timeout);
    })
  }
}

const startScan = (customOptions = {}) => {
  let options = Object.assign({}, DefaultScanOptions, customOptions);

  return ReactNativeBluetooth.startScan(options.uuids).then(() => Scan);
}

const didDiscoverDevice = (callback) => {
  return unsubscription(NativeAppEventEmitter.addListener(
    ReactNativeBluetooth.DeviceDiscovered,
    callback
  ));
};

export default {
  didChangeState,
  startScan,
  didDiscoverDevice,
};
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var contra = require('contra');
var Article = require('../../models/Article');
var Comment = require('../../models/Comment');

module.exports = function (req, res, next) {
  var model = validate(req);

  contra.waterfall([findArticle, decisionTree, create], respond);

  function findArticle (next) {
    Article.findOne(req.params.slug).populate('comments').exec(next);
  }

  function decisionTree (article, next) {
    if (!article) {
      res.json(404, { messages: ['Article not found'] }); return;
    }
    next(null, article);
  }

  function create (article, next) {
    var parent;
    if (model.parent) {
      var parent = _.find(article.comments, { _id: model.parent });
      if (parent.parent) {
        res.json(400, { messages: ['Comments can\'t be nested that deep!'] }); return;
      }
    }
    article.comments.push(model);
    article.save(saved);

    function saved (err) {
      next(err);
    }
  }

  function respond (err) {
    if (err) {
      next(err); return;
    }
  }
};
<commit_msg>validate<commit_after>'use strict';

var _ = require('lodash');
var contra = require('contra');
var Article = require('../../models/Article');
var Comment = require('../../models/Comment');
var validate = require('./lib/validate');

module.exports = function (req, res, next) {
  var body = req.body;
  var validation = validate(body);
  if (validation.length) {
    res.json(400, { messages: validation }); return;
  }
  var model = validation.model;
console.log(model);
  contra.waterfall([findArticle, decisionTree, create], respond);

  function findArticle (next) {
    Article.findOne(req.params.slug).populate('comments').exec(next);
  }

  function decisionTree (article, next) {
    if (!article) {
      res.json(404, { messages: ['Article not found'] }); return;
    }
    next(null, article);
  }

  function create (article, next) {
    var parent;
    if (model.parent) {
      var parent = _.find(article.comments, { _id: model.parent });
      if (parent.parent) {
        res.json(400, { messages: ['Comments can\'t be nested that deep!'] }); return;
      }
    }
    article.comments.push(model);
    article.save(saved);

    function saved (err) {
      next(err);
    }
  }

  function respond (err) {
    if (err) {
      next(err); return;
    }
  }
};
<|endoftext|>


<commit_before>var Writable = require('stream').Writable;
var levelup = require('levelup');
var sublevel = require('level-sublevel');
var incr = require('level-incr');
var Stats = require('fast-stats').Stats;

function Interest(options) {
    var self = this;

    if (!(self instanceof Interest)) {
        return new Interest(options);
    }
    if (!options) {
        self.options = {};
    } else {
        self.options = options;
    }

    self.options.sep = self.options.sep || '\n';
    var dbName = self.options.dbName || 'interestdb';

    self.db = incr(sublevel(levelup(dbName)));
    self._ws = Writable();

    return function thing(k, v) {
        if (k) {
            self.key = k;
        }

        if (v) {
            self.value = v;
        }
        return self;
    };
}

Interest.prototype.createWriteStream = function () {
    var self = this;

    if (!self.key) {
        throw new Error('Key must be set');
    }

    self._ws._write = function (chunk, enc, next) {
        var likes = chunk.toString().split(self.options.sep);
        likes.forEach(function (like) {
            if (like) {
                var sub = incr(self.db.sublevel(self.key));
                sub.incr(like, function (err, c) {
                    self.db.put(like, c);
                });
            }
        });
        next();
    };
    return self._ws;
};

Interest.prototype.createReadStream = function () {
    var self = this;
    var rs;
    if (!self.key) {
        rs = self.db.createReadStream();
    } else {
        rs = self.db.sublevel(self.key).createReadStream();
    }
    return rs;
};

Interest.prototype.count = function (v, cb) {
    var self = this;
    if (typeof v === 'function') {
        cb = v;
    } else {
        self.value = v;
    }

    if (!self.key || !self.value) {
        throw new Error('Key and Value must be set');
    }
    var sub = self.db.sublevel(self.key);
    sub.get(self.value, cb);
};

Interest.prototype.likes = function (v, cb) {
    var self = this;
    if (typeof v === 'function') {
        cb = v;
    } else {
        self.value = v;
    }
    if (!self.key || !self.value) {
        throw new Error('Key and Value must be set');
    }

    var sub = incr(self.db.sublevel(self.key));
    sub.incr(self.value, function (err, c) {
        self.db.put(self.value, c, cb);
    });
};

Interest.prototype.keys = function (cb) {
    var self = this;
    var keys = [];
    var rs = self.db.createReadStream();
    rs.on('data', function (data) {
        keys.push(data.key);
    });
    rs.on('end', function () {
        cb(null, keys);
    });
};

Interest.prototype.keysAndValues = function (cb) {
    var self = this;
    var keysAndValues = [];
    var rs = self.db.createReadStream();
    rs.on('data', function (data) {
        keysAndValues.push(data);
    });
    rs.on('end', function () {
        cb(null, keysAndValues);
    });
};

Interest.prototype.values = function (cb) {
    var self = this;
    var values = [];
    var rs = self.db.createReadStream();
    rs.on('data', function (data) {
        values.push(data.value);
    });
    rs.on('end', function () {
        cb(null, values);
    });
};

Interest.prototype.close = function (cb) {
    var self = this;
    cb = cb || function(){};
    self.db.close(cb);
};

Interest.prototype.stddev = function (cb) {
    var self = this;
    var stats = new Stats();
    self.values(function (err, data) {
        data.forEach(function (value) {
            stats.push(Number(value));
        });
        cb(null, stats.stddev());
    });
};

module.exports = Interest;
<commit_msg>zscore<commit_after>var Writable = require('stream').Writable;
var levelup = require('levelup');
var sublevel = require('level-sublevel');
var incr = require('level-incr');
var Stats = require('fast-stats').Stats;

function Interest(options) {
    var self = this;

    if (!(self instanceof Interest)) {
        return new Interest(options);
    }
    if (!options) {
        self.options = {};
    } else {
        self.options = options;
    }

    self.options.sep = self.options.sep || '\n';
    var dbName = self.options.dbName || 'interestdb';

    self.db = incr(sublevel(levelup(dbName)));
    self._ws = Writable();

    return function thing(k, v) {
        if (k) {
            self.key = k;
        }

        if (v) {
            self.value = v;
        }
        return self;
    };
}

Interest.prototype.createWriteStream = function () {
    var self = this;

    if (!self.key) {
        throw new Error('Key must be set');
    }

    self._ws._write = function (chunk, enc, next) {
        var likes = chunk.toString().split(self.options.sep);
        likes.forEach(function (like) {
            if (like) {
                var sub = incr(self.db.sublevel(self.key));
                sub.incr(like, function (err, c) {
                    self.db.put(like, c);
                });
            }
        });
        next();
    };
    return self._ws;
};

Interest.prototype.createReadStream = function () {
    var self = this;
    var rs;
    if (!self.key) {
        rs = self.db.createReadStream();
    } else {
        rs = self.db.sublevel(self.key).createReadStream();
    }
    return rs;
};

Interest.prototype.count = function (v, cb) {
    var self = this;
    if (typeof v === 'function') {
        cb = v;
    } else {
        self.value = v;
    }

    if (!self.key || !self.value) {
        throw new Error('Key and Value must be set');
    }
    var sub = self.db.sublevel(self.key);
    sub.get(self.value, cb);
};

Interest.prototype.likes = function (v, cb) {
    var self = this;
    if (typeof v === 'function') {
        cb = v;
    } else {
        self.value = v;
    }
    if (!self.key || !self.value) {
        throw new Error('Key and Value must be set');
    }

    var sub = incr(self.db.sublevel(self.key));
    sub.incr(self.value, function (err, c) {
        self.db.put(self.value, c, cb);
    });
};

Interest.prototype.keys = function (cb) {
    var self = this;
    var keys = [];
    var rs = self.db.createReadStream();
    rs.on('data', function (data) {
        keys.push(data.key);
    });
    rs.on('end', function () {
        cb(null, keys);
    });
};

Interest.prototype.keysAndValues = function (cb) {
    var self = this;
    var keysAndValues = [];
    var rs = self.db.createReadStream();
    rs.on('data', function (data) {
        keysAndValues.push(data);
    });
    rs.on('end', function () {
        cb(null, keysAndValues);
    });
};

Interest.prototype.values = function (cb) {
    var self = this;
    var values = [];
    var rs = self.db.createReadStream();
    rs.on('data', function (data) {
        values.push(data.value);
    });
    rs.on('end', function () {
        cb(null, values);
    });
};

Interest.prototype.close = function (cb) {
    var self = this;
    cb = cb || function(){};
    self.db.close(cb);
};

Interest.prototype.stddev = function (cb) {
    var self = this;
    var stats = new Stats();
    self.values(function (err, data) {
        data.forEach(function (value) {
            stats.push(Number(value));
        });
        cb(null, stats.stddev());
    });
};

Interest.prototype.zscore = function (x, cb) {
    var self = this;
    var stats = new Stats();
    self.values(function (err, data) {
        data.forEach(function (value) {
            stats.push(Number(value));
        });
        var z = (x - stats.amean()) / stats.stddev();
        cb(null, z);
    });
};

module.exports = Interest;
<|endoftext|>


<commit_before>import ipRegex from "ip-regex";
import cidrRegex from "cidr-regex";
import naturalCompare from "string-natural-compare";
import {parseIp, stringifyIp} from "ip-bigint";

const bits = {
  "v4": 32,
  "v6": 128,
};

const normalizeIp = str => stringifyIp(parseIp(str));
const uniq = arr => [...new Set(arr)];

function isIP(ip) {
  if (ipRegex.v4({exact: true}).test(ip)) return 4;
  if (ipRegex.v6({exact: true}).test(ip)) return 6;
  return 0;
}

function isCidr(ip) {
  if (cidrRegex.v4({exact: true}).test(ip)) return 4;
  if (cidrRegex.v6({exact: true}).test(ip)) return 6;
  return 0;
}

function doNormalize(cidr) {
  const {start, prefix, single, version} = parse(cidr);
  if (!single) { // cidr
    // set network address to first address
    const addr = normalizeIp(stringifyIp({number: start, version}));
    return `${addr}/${prefix}`;
  } else { // single ip
    if (!version) throw new Error(`Invalid network: ${cidr}`);
    return normalizeIp(cidr);
  }
}

export function normalize(cidr) {
  return Array.isArray(cidr) ? cidr.map(doNormalize) : doNormalize(cidr);
}

function parse(str) {
  const cidrVersion = isCidr(str);
  const parsed = Object.create(null);
  if (cidrVersion) {
    parsed.cidr = str;
    parsed.version = cidrVersion;
  } else {
    const version = isIP(str);
    if (version) {
      parsed.cidr = `${str}/${bits[`v${version}`]}`;
      parsed.version = version;
      parsed.single = true;
    } else {
      throw new Error(`Network is not a CIDR or IP: ${str}`);
    }
  }

  const [ip, prefix] = parsed.cidr.split("/");
  parsed.prefix = prefix;
  const {number, version} = parseIp(ip);
  const numBits = bits[`v${version}`];
  const ipBits = number.toString(2).padStart(numBits, "0");
  const prefixLen = Number(numBits - prefix);
  const startBits = ipBits.substring(0, numBits - prefixLen);
  parsed.start = BigInt(`0b${startBits}${"0".repeat(prefixLen)}`);
  parsed.end = BigInt(`0b${startBits}${"1".repeat(prefixLen)}`);
  return parsed;
}

// returns whether networks fully or partially overlap
function doNetsOverlap(a, b) {
  //    aaa
  // bbb
  if (a.start > b.end) return false; // a starts after b

  // aaa
  //    bbb
  if (b.start > a.end) return false; // b starts after a

  return true;
}

// returns whether network a fully contains network b;
function netContains(a, b) {
  //  aaa
  // bbbb
  if (b.start < a.start) return false; // a starts after b

  // aaa
  // bbbb
  if (b.end > a.end) return false; // b starts after a

  return true;
}

// exclude b from a and return remainder cidrs
function excludeNets(a, b, v) {
  const parts = [];

  // compareTo returns negative if left is less than right

  //       aaa
  //   bbb
  //   aaa
  //       bbb
  if (a.start > b.end || a.end < b.start) {
    return [a.cidr];
  }

  //   aaa
  //   bbb
  if (a.start === b.start && a.end === b.end) {
    return [];
  }

  //   aa
  //  bbbb
  if (a.start > b.start && a.end < b.end) {
    return [];
  }

  // aaaa
  //   bbbb
  // aaaa
  //   bb
  if (a.start < b.start && a.end <= b.end) {
    parts.push({start: a.start, end: b.start - 1n});
  }

  //    aaa
  //   bbb
  //   aaaa
  //   bbb
  if (a.start >= b.start && a.end > b.end) {
    parts.push({start: b.end + 1n, end: a.end});
  }

  //  aaaa
  //   bb
  if (a.start < b.start && a.end > b.end) {
    parts.push(
      {start: a.start, end: b.start - 1n},
      {start: b.end + 1n, end: a.end},
    );
  }

  const remaining = [];
  for (const part of parts) {
    for (const subpart of subparts(part, v)) {
      remaining.push(formatPart(subpart, v));
    }
  }

  return merge(remaining);
}

function biggestPowerOfTwo(num) {
  if (num === 0n) return 0n;
  return 2n ** BigInt(String(num.toString(2).length - 1));
}

function subparts(part) {
  // special case for when part is length 1
  if ((part.end - part.start) === 1n) {
    if (part.end % 2n === 0n) {
      return [{start: part.start, end: part.start}, {start: part.end, end: part.end}];
    } else {
      return [{start: part.start, end: part.end}];
    }
  }

  const size = diff(part.end, part.start);
  let biggest = biggestPowerOfTwo(size);

  let start, end;
  if (size === biggest && part.start + size === part.end) {
    return [part];
  } else if (part.start % biggest === 0n) {
    // start is matching on the size-defined boundary - ex: 0-12, use 0-8
    start = part.start;
    end = start + biggest - 1n;
  } else {
    start = (part.end / biggest) * biggest;

    // start is not matching on the size-defined boundary - 4-16, use 8-16
    if ((start + biggest - 1n) > part.end) {
      // divide will floor to nearest integer
      start = ((part.end / biggest) - 1n) * biggest;

      while (start < part.start) {
        biggest /= 2n;
        start = ((part.end / biggest) - 1n) * biggest;
      }

      end = start + biggest - 1n;
    } else {
      start = (part.end / biggest) * biggest;
      end = start + biggest - 1n;
    }
  }

  let parts = [{start, end}];

  // additional subnets on left side
  if (start !== part.start) {
    parts = parts.concat(subparts({start: part.start, end: start - 1n}));
  }

  // additional subnets on right side
  if (end !== part.end) {
    parts = parts.concat(subparts({start: end + 1n, end: part.end}));
  }

  return parts;
}

function diff(a, b) {
  if (typeof a !== "bigint") a = BigInt(a);
  if (typeof b !== "bigint") b = BigInt(b);
  a += 1n;
  return a - b;
}

function formatPart(part, v) {
  const ip = normalize(stringifyIp({
    number: BigInt(part.start.toString()),
    version: Number(v.substring(1)),
  }));
  const zeroes = diff(part.end, part.start).toString(2);
  const prefix = bits[v] - (zeroes.match(/0/g) || []).length;
  return `${ip}/${prefix}`;
}

function mapNets(nets) {
  const maps = {v4: {}, v6: {}};
  for (const {start, end, version} of nets) {
    const v = `v${version}`;

    if (!maps[v][start]) maps[v][start] = {};
    if (!maps[v][end]) maps[v][end] = {};

    if (maps[v][start].start) {
      maps[v][start].start += 1;
    } else {
      maps[v][start].start = 1;
    }

    if (maps[v][end].end) {
      maps[v][end].end += 1;
    } else {
      maps[v][end].end = 1;
    }
  }
  return maps;
}

export function merge(nets) {
  nets = uniq((Array.isArray(nets) ? nets : [nets]).map(parse));
  const maps = mapNets(nets);

  const merged = {v4: [], v6: []};
  const start = {v4: null, v6: null};
  const end = {v4: null, v6: null};

  for (const v of ["v4", "v6"]) {
    const numbers = Object.keys(maps[v]).sort(naturalCompare);
    let depth = 0;

    for (const [index, number] of numbers.entries()) {
      const marker = maps[v][number];

      if (start[v] === null && marker.start) {
        start[v] = BigInt(number);
      }
      if (marker.end) {
        end[v] = BigInt(number);
      }

      if (marker.start) depth += marker.start;
      if (marker.end) depth -= marker.end;

      if (marker.end && depth === 0 && ((numbers[index + 1] - numbers[index]) > 1)) {
        for (const sub of subparts({start: start[v], end: end[v]})) {
          merged[v].push(formatPart(sub, v));
        }
        start[v] = null;
        end[v] = null;
      } else if (index === (numbers.length - 1)) {
        for (const sub of subparts({start: start[v], end: end[v]})) {
          merged[v].push(formatPart(sub, v));
        }
      }
    }
  }

  return [...merged.v4.sort(naturalCompare), ...merged.v6.sort(naturalCompare)];
}

export function exclude(basenets, exclnets) {
  basenets = uniq(Array.isArray(basenets) ? basenets : [basenets]);
  exclnets = uniq(Array.isArray(exclnets) ? exclnets : [exclnets]);

  basenets = merge(basenets);
  exclnets = merge(exclnets);

  const bases = {v4: [], v6: []};
  const excls = {v4: [], v6: []};

  for (const basenet of basenets) {
    bases[`v${isCidr(basenet)}`].push(basenet);
  }

  for (const exclnet of exclnets) {
    excls[`v${isCidr(exclnet)}`].push(exclnet);
  }

  for (const v of ["v4", "v6"]) {
    for (const exclcidr of excls[v]) {
      for (const [index, basecidr] of bases[v].entries()) {
        const base = parse(basecidr);
        const excl = parse(exclcidr);
        const remainders = excludeNets(base, excl, v);
        if (base.cidr !== remainders.toString()) {
          bases[v] = bases[v].concat(remainders);
          bases[v].splice(index, 1);
        }
      }
    }
  }

  return bases.v4.concat(bases.v6);
}

export function expand(nets) {
  nets = uniq(Array.isArray(nets) ? nets : [nets]);

  const ips = [];
  for (const net of merge(nets)) {
    const {start, end, version} = parse(net);
    for (let number = start; number <= end; number++) {
      ips.push(stringifyIp({number, version}));
    }
  }
  return ips.map(normalize);
}

export function overlap(a, b) {
  const aNets = uniq(Array.isArray(a) ? a : [a]);
  const bNets = uniq(Array.isArray(b) ? b : [b]);

  for (const a of aNets) {
    const aParsed = parse(a);
    for (const b of bNets) {
      const bParsed = parse(b);

      // version mismatch
      if (aParsed.version !== bParsed.version) {
        continue;
      }

      if (doNetsOverlap(aParsed, bParsed)) {
        return true;
      }
    }
  }

  return false;
}

export function contains(a, b) {
  const aNets = uniq(Array.isArray(a) ? a : [a]);
  const bNets = uniq(Array.isArray(b) ? b : [b]);

  const numExpected = bNets.length;
  let numFound = 0;
  for (const a of aNets) {
    const aParsed = parse(a);
    for (const b of bNets) {
      const bParsed = parse(b);

      // version mismatch
      if (aParsed.version !== bParsed.version) {
        continue;
      }

      if (netContains(aParsed, bParsed)) {
        numFound++;
        continue;
      }
    }
  }

  return numFound === numExpected;
}
<commit_msg>remove unreachable condition<commit_after>import ipRegex from "ip-regex";
import cidrRegex from "cidr-regex";
import naturalCompare from "string-natural-compare";
import {parseIp, stringifyIp} from "ip-bigint";

const bits = {
  "v4": 32,
  "v6": 128,
};

const normalizeIp = str => stringifyIp(parseIp(str));
const uniq = arr => [...new Set(arr)];

function isIP(ip) {
  if (ipRegex.v4({exact: true}).test(ip)) return 4;
  if (ipRegex.v6({exact: true}).test(ip)) return 6;
  return 0;
}

function isCidr(ip) {
  if (cidrRegex.v4({exact: true}).test(ip)) return 4;
  if (cidrRegex.v6({exact: true}).test(ip)) return 6;
  return 0;
}

function doNormalize(cidr) {
  const {start, prefix, single, version} = parse(cidr);
  if (!single) { // cidr
    // set network address to first address
    const addr = normalizeIp(stringifyIp({number: start, version}));
    return `${addr}/${prefix}`;
  } else { // single ip
    return normalizeIp(cidr);
  }
}

export function normalize(cidr) {
  return Array.isArray(cidr) ? cidr.map(doNormalize) : doNormalize(cidr);
}

function parse(str) {
  const cidrVersion = isCidr(str);
  const parsed = Object.create(null);
  if (cidrVersion) {
    parsed.cidr = str;
    parsed.version = cidrVersion;
  } else {
    const version = isIP(str);
    if (version) {
      parsed.cidr = `${str}/${bits[`v${version}`]}`;
      parsed.version = version;
      parsed.single = true;
    } else {
      throw new Error(`Network is not a CIDR or IP: ${str}`);
    }
  }

  const [ip, prefix] = parsed.cidr.split("/");
  parsed.prefix = prefix;
  const {number, version} = parseIp(ip);
  const numBits = bits[`v${version}`];
  const ipBits = number.toString(2).padStart(numBits, "0");
  const prefixLen = Number(numBits - prefix);
  const startBits = ipBits.substring(0, numBits - prefixLen);
  parsed.start = BigInt(`0b${startBits}${"0".repeat(prefixLen)}`);
  parsed.end = BigInt(`0b${startBits}${"1".repeat(prefixLen)}`);
  return parsed;
}

// returns whether networks fully or partially overlap
function doNetsOverlap(a, b) {
  //    aaa
  // bbb
  if (a.start > b.end) return false; // a starts after b

  // aaa
  //    bbb
  if (b.start > a.end) return false; // b starts after a

  return true;
}

// returns whether network a fully contains network b;
function netContains(a, b) {
  //  aaa
  // bbbb
  if (b.start < a.start) return false; // a starts after b

  // aaa
  // bbbb
  if (b.end > a.end) return false; // b starts after a

  return true;
}

// exclude b from a and return remainder cidrs
function excludeNets(a, b, v) {
  const parts = [];

  // compareTo returns negative if left is less than right

  //       aaa
  //   bbb
  //   aaa
  //       bbb
  if (a.start > b.end || a.end < b.start) {
    return [a.cidr];
  }

  //   aaa
  //   bbb
  if (a.start === b.start && a.end === b.end) {
    return [];
  }

  //   aa
  //  bbbb
  if (a.start > b.start && a.end < b.end) {
    return [];
  }

  // aaaa
  //   bbbb
  // aaaa
  //   bb
  if (a.start < b.start && a.end <= b.end) {
    parts.push({start: a.start, end: b.start - 1n});
  }

  //    aaa
  //   bbb
  //   aaaa
  //   bbb
  if (a.start >= b.start && a.end > b.end) {
    parts.push({start: b.end + 1n, end: a.end});
  }

  //  aaaa
  //   bb
  if (a.start < b.start && a.end > b.end) {
    parts.push(
      {start: a.start, end: b.start - 1n},
      {start: b.end + 1n, end: a.end},
    );
  }

  const remaining = [];
  for (const part of parts) {
    for (const subpart of subparts(part, v)) {
      remaining.push(formatPart(subpart, v));
    }
  }

  return merge(remaining);
}

function biggestPowerOfTwo(num) {
  if (num === 0n) return 0n;
  return 2n ** BigInt(String(num.toString(2).length - 1));
}

function subparts(part) {
  // special case for when part is length 1
  if ((part.end - part.start) === 1n) {
    if (part.end % 2n === 0n) {
      return [{start: part.start, end: part.start}, {start: part.end, end: part.end}];
    } else {
      return [{start: part.start, end: part.end}];
    }
  }

  const size = diff(part.end, part.start);
  let biggest = biggestPowerOfTwo(size);

  let start, end;
  if (size === biggest && part.start + size === part.end) {
    return [part];
  } else if (part.start % biggest === 0n) {
    // start is matching on the size-defined boundary - ex: 0-12, use 0-8
    start = part.start;
    end = start + biggest - 1n;
  } else {
    start = (part.end / biggest) * biggest;

    // start is not matching on the size-defined boundary - 4-16, use 8-16
    if ((start + biggest - 1n) > part.end) {
      // divide will floor to nearest integer
      start = ((part.end / biggest) - 1n) * biggest;

      while (start < part.start) {
        biggest /= 2n;
        start = ((part.end / biggest) - 1n) * biggest;
      }

      end = start + biggest - 1n;
    } else {
      start = (part.end / biggest) * biggest;
      end = start + biggest - 1n;
    }
  }

  let parts = [{start, end}];

  // additional subnets on left side
  if (start !== part.start) {
    parts = parts.concat(subparts({start: part.start, end: start - 1n}));
  }

  // additional subnets on right side
  if (end !== part.end) {
    parts = parts.concat(subparts({start: end + 1n, end: part.end}));
  }

  return parts;
}

function diff(a, b) {
  if (typeof a !== "bigint") a = BigInt(a);
  if (typeof b !== "bigint") b = BigInt(b);
  a += 1n;
  return a - b;
}

function formatPart(part, v) {
  const ip = normalize(stringifyIp({
    number: BigInt(part.start.toString()),
    version: Number(v.substring(1)),
  }));
  const zeroes = diff(part.end, part.start).toString(2);
  const prefix = bits[v] - (zeroes.match(/0/g) || []).length;
  return `${ip}/${prefix}`;
}

function mapNets(nets) {
  const maps = {v4: {}, v6: {}};
  for (const {start, end, version} of nets) {
    const v = `v${version}`;

    if (!maps[v][start]) maps[v][start] = {};
    if (!maps[v][end]) maps[v][end] = {};

    if (maps[v][start].start) {
      maps[v][start].start += 1;
    } else {
      maps[v][start].start = 1;
    }

    if (maps[v][end].end) {
      maps[v][end].end += 1;
    } else {
      maps[v][end].end = 1;
    }
  }
  return maps;
}

export function merge(nets) {
  nets = uniq((Array.isArray(nets) ? nets : [nets]).map(parse));
  const maps = mapNets(nets);

  const merged = {v4: [], v6: []};
  const start = {v4: null, v6: null};
  const end = {v4: null, v6: null};

  for (const v of ["v4", "v6"]) {
    const numbers = Object.keys(maps[v]).sort(naturalCompare);
    let depth = 0;

    for (const [index, number] of numbers.entries()) {
      const marker = maps[v][number];

      if (start[v] === null && marker.start) {
        start[v] = BigInt(number);
      }
      if (marker.end) {
        end[v] = BigInt(number);
      }

      if (marker.start) depth += marker.start;
      if (marker.end) depth -= marker.end;

      if (marker.end && depth === 0 && ((numbers[index + 1] - numbers[index]) > 1)) {
        for (const sub of subparts({start: start[v], end: end[v]})) {
          merged[v].push(formatPart(sub, v));
        }
        start[v] = null;
        end[v] = null;
      } else if (index === (numbers.length - 1)) {
        for (const sub of subparts({start: start[v], end: end[v]})) {
          merged[v].push(formatPart(sub, v));
        }
      }
    }
  }

  return [...merged.v4.sort(naturalCompare), ...merged.v6.sort(naturalCompare)];
}

export function exclude(basenets, exclnets) {
  basenets = uniq(Array.isArray(basenets) ? basenets : [basenets]);
  exclnets = uniq(Array.isArray(exclnets) ? exclnets : [exclnets]);

  basenets = merge(basenets);
  exclnets = merge(exclnets);

  const bases = {v4: [], v6: []};
  const excls = {v4: [], v6: []};

  for (const basenet of basenets) {
    bases[`v${isCidr(basenet)}`].push(basenet);
  }

  for (const exclnet of exclnets) {
    excls[`v${isCidr(exclnet)}`].push(exclnet);
  }

  for (const v of ["v4", "v6"]) {
    for (const exclcidr of excls[v]) {
      for (const [index, basecidr] of bases[v].entries()) {
        const base = parse(basecidr);
        const excl = parse(exclcidr);
        const remainders = excludeNets(base, excl, v);
        if (base.cidr !== remainders.toString()) {
          bases[v] = bases[v].concat(remainders);
          bases[v].splice(index, 1);
        }
      }
    }
  }

  return bases.v4.concat(bases.v6);
}

export function expand(nets) {
  nets = uniq(Array.isArray(nets) ? nets : [nets]);

  const ips = [];
  for (const net of merge(nets)) {
    const {start, end, version} = parse(net);
    for (let number = start; number <= end; number++) {
      ips.push(stringifyIp({number, version}));
    }
  }
  return ips.map(normalize);
}

export function overlap(a, b) {
  const aNets = uniq(Array.isArray(a) ? a : [a]);
  const bNets = uniq(Array.isArray(b) ? b : [b]);

  for (const a of aNets) {
    const aParsed = parse(a);
    for (const b of bNets) {
      const bParsed = parse(b);

      // version mismatch
      if (aParsed.version !== bParsed.version) {
        continue;
      }

      if (doNetsOverlap(aParsed, bParsed)) {
        return true;
      }
    }
  }

  return false;
}

export function contains(a, b) {
  const aNets = uniq(Array.isArray(a) ? a : [a]);
  const bNets = uniq(Array.isArray(b) ? b : [b]);

  const numExpected = bNets.length;
  let numFound = 0;
  for (const a of aNets) {
    const aParsed = parse(a);
    for (const b of bNets) {
      const bParsed = parse(b);

      // version mismatch
      if (aParsed.version !== bParsed.version) {
        continue;
      }

      if (netContains(aParsed, bParsed)) {
        numFound++;
        continue;
      }
    }
  }

  return numFound === numExpected;
}
<|endoftext|>


<commit_before>var models = require('../models/models.js');
var por = '%';
var search;
var misearch;
var c = 0;

//GET /quizes/new
exports.new = function(req,res){
	var quiz = models.Quiz.build( //Crea un objeto Quiz
		{pregunta: "Pregunta", respuesta: "Respuesta"}
		);

	res.render('quizes/new', {quiz: quiz, errors: []});
};
// POST /quizes/create
exports.create = function(req, res) {
	var quiz = models.Quiz.build( req.body.quiz);
	quiz.validate().then(function(err){
		if(err){
			res.render('quizes/new',{quiz: quiz, errors: err.errors});
		}else{
	//Guarda en la DB los campos pregunta y respuesta de quiz
	quiz.save({fields: ["pregunta", "respuesta"]})
	.then(function(){res.redirect('/quizes');})
	//REdireccion HTTP (URL relativo) lista e preguntas
	}
		}
	);
};

//POST /quizes/:id/edit
exports.edit = function(req,res){
	var quiz = req.quiz;
	res.render('quizes/edit',{quiz: quiz, errors: []});
};

// PUT /quizes/:id
exports.update = function(req, res){
	req.quiz.pregunta = req.body.quiz.pregunta;
	req.quiz.respuesta = req.body.quiz.respuesta;

	req.quiz.validate().then(function(err){
		if(err) {
			res.render('quizes/edit',{quiz: req.quiz, errors: err.errors});
		}else{
			//Guarda en la DB los campos pregunta y respuesta de quiz
	req.quiz.save({fields: ["pregunta", "respuesta"]})
	.then(function(){res.redirect('/quizes');})
	//REdireccion HTTP (URL relativo) lista e preguntas
		}
	}
);
};

//DELETE /quizes/:id
exports.destroy = function(req,res){
	req.quiz.destroy().then(function(){
		res.redirect('/quizes');
	}).catch(function(error){next(error)});
};

//Autoload - factoriza el codigo si ruta incluye :quizId
exports.load = function(req, res, next, quizId){
	models.Quiz.find({
		where: {
			id: Number(quizId)
		},
		include: [{
		 model: models.Comment
		}]
	}).then(function(quiz) {
			if(quiz) {
				req.quiz = quiz;
				next();
			}else { next(new Error('No existe quizId='+ quizId))}
		}
	).catch(function(error) {next(error);});
};

//Get /quizes/index
exports.index = function(req, res, next) {
	misearch = req.query.search;
	search = por
	if(undefined === req.query.search){
		misearch = '.'

	}else{
	misearch = misearch.replace(/[^\w]/g,por);
	search = search.concat(misearch);
	search = search.concat(por);
	misearch = ' para "' + misearch +'".';
	}

	models.Quiz.findAll({
		where:["pregunta like ?", search], //ilike es case-INsensitive frente a like !! extension de postgreSQL
		order:'pregunta ASC',
		include: [{
		 model: models.Comment
		}]
		}).then(function(quizes){
		res.render('quizes/index.ejs', {quizes: quizes, errors: [], misearch: misearch, search: search});
	}).catch(function(error){next(error);});
};

//GEt /quizes/:id
exports.show = function(req,res) {
	models.Quiz.find(req.params.quizId).then(function(quiz){
		res.render('quizes/show' , {quiz: req.quiz, errors: []});
	})
};

//GEt /quizes/:id/answer
exports.answer = function(req,res) {
	var resultado = 'Incorrecto';
		if(req.query.respuesta.toLowerCase() === req.quiz.respuesta.toLowerCase()){
			resultado = 'Correcto';
		}
		res.render('quizes/answer',	{quiz: req.quiz, respuesta: resultado, errors: []});
};

//Get /quizes/statistics
exports.statistics = function(req,res){

/*Funciona en Local
	----------------------

	models.Quiz.count().then(function(nP){
		 models.Comment.count().then(function(nC){
		 	var media = nC / nP;
		 	models.Quiz.count(
		 		{ distinct:"Comments.QuizId",
		 		  where: ["Comments.QuizId not like ?", "NULL"],
		 		  include: [models.Comment]}
		 		).then(function(nPcC){
			 		console.log("hay" + nPcC + "con comentarios alsaask");
			 		var nPsC = nP - nPcC;
			 		console.log("hay" + nPsC + "sin comentarios alsaask");
					console.log(media);
	 				res.render('quizes/statistics',{errors: [], nP: nP, nC: nC, media: media.toFixed(2),nPcC: nPcC, nPsC: nPsC});
		 			});
		});
	});

	------------------------
*/

	models.Quiz.count().then(function(nP){
		 models.Comment.count().then(function(nC){
		 	var media = nC / nP;
		 models.Quiz.count(
		 		{
		 			//select
		 			DISTINCT:"Comments.QuizId",
		 		  WHERE: ["Comments.QuizId not like ?", "NULL"],
		 		  INCLUDE: [models.Comment]}
		 		).then(function(nPcC){
			 		console.log("hay" + nPcC + "con comentarios alsaask");
			 		var nPsC = nP - nPcC;
			 		console.log("hay" + nPsC + "sin comentarios alsaask");
					console.log(media);
	 				res.render('quizes/statistics',{errors: [], nP: nP, nC: nC, media: media.toFixed(2),nPcC: nPcC, nPsC: nPsC});
		 			});
		});
	});

};

/*
function contarComentarios(){
	models.Comment.count().then(function(nc){
		 c = nc;
	});
	return c ;
};
function contarPreguntas(){
	models.Quiz.count().then(function(q){
		 c = q;
	});
	return c ;
};
*/<commit_msg>pruebaK12<commit_after>var models = require('../models/models.js');
var por = '%';
var search;
var misearch;
var c = 0;

//GET /quizes/new
exports.new = function(req,res){
	var quiz = models.Quiz.build( //Crea un objeto Quiz
		{pregunta: "Pregunta", respuesta: "Respuesta"}
		);

	res.render('quizes/new', {quiz: quiz, errors: []});
};
// POST /quizes/create
exports.create = function(req, res) {
	var quiz = models.Quiz.build( req.body.quiz);
	quiz.validate().then(function(err){
		if(err){
			res.render('quizes/new',{quiz: quiz, errors: err.errors});
		}else{
	//Guarda en la DB los campos pregunta y respuesta de quiz
	quiz.save({fields: ["pregunta", "respuesta"]})
	.then(function(){res.redirect('/quizes');})
	//REdireccion HTTP (URL relativo) lista e preguntas
	}
		}
	);
};

//POST /quizes/:id/edit
exports.edit = function(req,res){
	var quiz = req.quiz;
	res.render('quizes/edit',{quiz: quiz, errors: []});
};

// PUT /quizes/:id
exports.update = function(req, res){
	req.quiz.pregunta = req.body.quiz.pregunta;
	req.quiz.respuesta = req.body.quiz.respuesta;

	req.quiz.validate().then(function(err){
		if(err) {
			res.render('quizes/edit',{quiz: req.quiz, errors: err.errors});
		}else{
			//Guarda en la DB los campos pregunta y respuesta de quiz
	req.quiz.save({fields: ["pregunta", "respuesta"]})
	.then(function(){res.redirect('/quizes');})
	//REdireccion HTTP (URL relativo) lista e preguntas
		}
	}
);
};

//DELETE /quizes/:id
exports.destroy = function(req,res){
	req.quiz.destroy().then(function(){
		res.redirect('/quizes');
	}).catch(function(error){next(error)});
};

//Autoload - factoriza el codigo si ruta incluye :quizId
exports.load = function(req, res, next, quizId){
	models.Quiz.find({
		where: {
			id: Number(quizId)
		},
		include: [{
		 model: models.Comment
		}]
	}).then(function(quiz) {
			if(quiz) {
				req.quiz = quiz;
				next();
			}else { next(new Error('No existe quizId='+ quizId))}
		}
	).catch(function(error) {next(error);});
};

//Get /quizes/index
exports.index = function(req, res, next) {
	misearch = req.query.search;
	search = por
	if(undefined === req.query.search){
		misearch = '.'

	}else{
	misearch = misearch.replace(/[^\w]/g,por);
	search = search.concat(misearch);
	search = search.concat(por);
	misearch = ' para "' + misearch +'".';
	}

	models.Quiz.findAll({
		where:["pregunta like ?", search], //ilike es case-INsensitive frente a like !! extension de postgreSQL
		order:'pregunta ASC',
		include: [{
		 model: models.Comment
		}]
		}).then(function(quizes){
		res.render('quizes/index.ejs', {quizes: quizes, errors: [], misearch: misearch, search: search});
	}).catch(function(error){next(error);});
};

//GEt /quizes/:id
exports.show = function(req,res) {
	models.Quiz.find(req.params.quizId).then(function(quiz){
		res.render('quizes/show' , {quiz: req.quiz, errors: []});
	})
};

//GEt /quizes/:id/answer
exports.answer = function(req,res) {
	var resultado = 'Incorrecto';
		if(req.query.respuesta.toLowerCase() === req.quiz.respuesta.toLowerCase()){
			resultado = 'Correcto';
		}
		res.render('quizes/answer',	{quiz: req.quiz, respuesta: resultado, errors: []});
};

//Get /quizes/statistics
exports.statistics = function(req,res){

/*Funciona en Local
	----------------------

	models.Quiz.count().then(function(nP){
		 models.Comment.count().then(function(nC){
		 	var media = nC / nP;
		 	models.Quiz.count(
		 		{ distinct:"Comments.QuizId",
		 		  where: ["Comments.QuizId not like ?", "NULL"],
		 		  include: [models.Comment]}
		 		).then(function(nPcC){
			 		console.log("hay" + nPcC + "con comentarios alsaask");
			 		var nPsC = nP - nPcC;
			 		console.log("hay" + nPsC + "sin comentarios alsaask");
					console.log(media);
	 				res.render('quizes/statistics',{errors: [], nP: nP, nC: nC, media: media.toFixed(2),nPcC: nPcC, nPsC: nPsC});
		 			});
		});
	});

	------------------------
*/

	models.Quiz.count().then(function(nP){
		 models.Comment.count().then(function(nC){
		 	var media = nC / nP;
		 models.Quiz.count(
		 		{
		 			//select
		 			//DISTINCT:"Comments.QuizId",
		 		  //WHERE: ["Comments.QuizId not like ?", "NULL"],
		 		  INCLUDE: [{model: models.Comment, where: ["Comments.QuizId not like ?", "NULL"],distinct:"Comments.QuizId"}]}
		 		).then(function(nPcC){
			 		console.log("hay" + nPcC + "con comentarios alsaask");
			 		var nPsC = nP - nPcC;
			 		console.log("hay" + nPsC + "sin comentarios alsaask");
					console.log(media);
	 				res.render('quizes/statistics',{errors: [], nP: nP, nC: nC, media: media.toFixed(2),nPcC: nPcC, nPsC: nPsC});
		 			});
		});
	});

};

/*
function contarComentarios(){
	models.Comment.count().then(function(nc){
		 c = nc;
	});
	return c ;
};
function contarPreguntas(){
	models.Quiz.count().then(function(q){
		 c = q;
	});
	return c ;
};
*/<|endoftext|>


<commit_before>console.log("welcome to goe")

var h = require('hyperscript');
var $ = require("jquery");
var Promise = require('bluebird')
var fs = Promise.promisifyAll(require('fs'))
var request = require('superagent')

// window.setInterval(refreshMsg, 5000)
// function refreshMsg(){
//   $('div.message').remove()
//   console.log("Time : " )
//   getMessages()
// }

function getMessages() {
  $.get("http://localhost:3000/v1/messages")
  .done(function(data){
    oldMessages = data.messages.length;
    for (var i = 0; i < data.messages.length; i++){
      //console.log("data : ", data.messages +" : " + "old" + oldMessages)
      var sender = data.messages[i].sender;
      var message = data.messages[i].message;
      var html = h('div.message', {style: {'font-size': '1.5em'}}, h('p', {}, sender + ": " + message), h('hr',{}))
      $('main').append(html)
    }
  })
  .fail(function(err){
    console.log(err);
  })
}

$(document).ready(function(){
  getMessages()
  $('form').submit(function(event){
    var newMessage = {}
    newMessage["sender"] = $('input#name').val()
    newMessage["message"] = $('textarea#message').val()
    //this was input#message maybe here need to push new message onto messages array
    $.post("http://localhost:3000/v1/messages", newMessage)//this posts to server
})
})

// $(document).ready(function(){
//   $('form').submit(function(event){
//     var newMessage = {}
//     newMessage["sender"] = $('input#name').val()
//     newMessage["message"] = $('textarea#message').val() //this was input#message
//     // maybe here need to push new message onto messages array
//     $.post("http://localhost:3000/v1/messages", newMessage)//this posts to server
// })
// })

// console.log("welcome to goe")

// var h = require('hyperscript');
// var $ = require("jquery");

// window.setInterval(refreshMsg, 5000)
// function refreshMsg(){
//   $('div.message').remove()
//   console.log("Time : ")
//   getMessages()
// }

// function getMessages() {
//   $.get("http://localhost:3000/v1/messages")
//   .done(function(data){
//     oldMessages = data.messages.length;
//     for (var i = 0; i < data.messages.length; i++){
//       console.log("data : ", data.messages +" : " + "old" + oldMessages)
//       var sender = data.messages[i].sender;
//       var message = data.messages[i].message;
//       var html = h('div.message', {style: {'font-size': '1.5em'}}, h('p', {}, sender + ": " + message), h('hr',{}))
//       $('main').append(html)
//     }
//   })
//   .fail(function(err){
//     console.log(err);
//   })
// }

// $(document).ready(function(){
//   $('form').submit(function(event){
//     var newMessage = {}
//     newMessage["sender"] = $('input#name').val()
//     newMessage["message"] = $('textarea#message').val() //this was input#message
//     $.post("http://localhost:3000/v1/messages", newMessage)// function(){
//     // })
//     // .done(function() {
//     //   console.log('new message sent!')
//     // })
//     // .fail(function() {
//     //   console.log( 'error' );
//     // })
// })
// })
<commit_msg>Update client-side<commit_after>console.log("welcome to goe")

var h = require('hyperscript');
var $ = require("jquery");
var Promise = require('bluebird')
var fs = Promise.promisifyAll(require('fs'))
var request = require('superagent')

// window.setInterval(refreshMsg, 5000)
// function refreshMsg(){
//   $('div.message').remove()
//   console.log("Time : " )
//   getMessages()
// }
// function testEndPoint(){
//   request
//     .get("http://localhost:3000/v1/messages")
//     .end(function(error,result){
//       console.log("result :", result)
//       console.log("hi: " ,request)
//     });
// }

function testEndPoint(){
  $.get("http://localhost:3000/v1/messages")
    .done(function(data,status){
      console.log("result :", data)
      //oldMessages = data.messages.length;
      for( var i = 0; i < data.messages.length; i++){
        var user_name = data[i].user_name;
        var message = data[i].messages;
        var html = h('div.message', {style: {'font-size': '1.3em'}}, h('p', {}, user_name + ": " + message), h('hr',{}))
        $('main').append(html)
    }
  })
  .fail(function(err){
    console.log(err);
  })
}
// function getMessages() {
//   $.get("http://localhost:3000/v1/messages")
//   .done(function(data){
//     console.log("client", data)
//     oldMessages = data.messages.length;
//     for (var i = 0; i < data.messages.length; i++){
//       //console.log("data : ", data.messages +" : " + "old" + oldMessages)
//       var sender = data.messages[i].sender;
//       var message = data.messages[i].message;
//       var html = h('div.message', {style: {'font-size': '1.5em'}}, h('p', {}, sender + ": " + message), h('hr',{}))
//       $('main').append(html)
//     }
//   })
//   .fail(function(err){
//     console.log(err);
//   })
// }

$(document).ready(function(){
  testEndPoint()
  //getMessages()
  $('form').submit(function(event){
    var newMessage = {}
    newMessage["sender"] = $('input#name').val()
    newMessage["message"] = $('textarea#message').val()
    //this was input#message maybe here need to push new message onto messages array
    $.post("http://localhost:3000/v1/messages", newMessage)//this posts to server
})
})
<|endoftext|>


<commit_before>var models = require('../models/models.js');
var temas = ["otro","humanidades","ocio","ciencia","tecnologia"];

// Autoload :id
exports.load = function(req, res, next, quizId) {
  models.Quiz.find({
            where: {
                id: Number(quizId)
            },
            include: [{
                model: models.Comment
            }]
        }).then(function(quiz) {
      if (quiz) {
        req.quiz = quiz;
        next();
      } else{next(new Error('No existe quizId=' + quizId))}
    }
  ).catch(function(error){next(error)});
};

//GET /quizes
exports.index= function(req, res){
	res.render('quizes/index', {errors:[]});
};

//GET /quizes:search
exports.listQuestion= function(req, res){
  if(req.query.search) {
     var filtro  = (req.query.search || '').replace(" ", "%");
     models.Quiz.findAll({where:["pregunta like ?", '%'+filtro+'%'],order:'pregunta ASC'}).then(function(quizes){
       res.render('quizes/listQuestion', {quizes: quizes,errors:[]});
     }).catch(function(error) { next(error);});

  } else {

   models.Quiz.findAll().then(function(quizes){
       res.render('quizes/listQuestion', {quizes: quizes,errors:[]});
       }).catch(function(error) { next(error);});
  }
};

//GET /quizes/:id
exports.show = function (req,res){
	res.render('quizes/show', {quiz:req.quiz,errors:[]});
};

//GET /quizes/answer
exports.answer = function (req,res){
		var resultado='Incorrecto';
		if(req.query.respuesta===req.quiz.respuesta){
			resultado='Correcto';
		}
		res.render('quizes/answer',{quiz:req.quiz, respuesta:resultado,errors:[]});
};

//GET /quizes/new
exports.new = function(req, res){
	var quiz = models.Quiz.build(//crea objeto quiz
		{pregunta:"Pregunta", respuesta:"Respuesta",tema:"otro"}
	);
	res.render('quizes/new', {quiz:quiz,temas:temas,errors:[]});
};

//GET /quizes/create
exports.create = function(req, res){
	var quiz = models.Quiz.build( req.body.quiz );

	var errors = quiz.validate();//ya qe el objeto errors no tiene then(
	if (errors || (typeof errors === 'undefined') )
		{
			var i=0;
			var errores=new Array();//se convierte en [] con la propiedad message por compatibilida con layout
			for (var prop in errors)
				errores[i++]={message: errors[prop]};
			res.render('quizes/new', {quiz: quiz, errors: errores});
		} else {
			quiz // save: guarda en DB campos pregunta y respuesta de quiz
			.save({fields: ["pregunta", "respuesta","tema"]})
			.then( function(){ res.redirect('/quizes')}) ;
		}
};

//GET /quizes/:id/edit
exports.edit = function(req,res){
	var quiz= req.quiz;//autoload de instancia quiz
	res.render('quizes/edit',{quiz:quiz,temas:temas,errors:[]});
};

//PUT /quizes:id
exports.update = function(req,res){
	req.quiz.pregunta=req.body.quiz.pregunta;
	req.quiz.respuesta=req.body.quiz.respuesta;
	req.quiz.tema=req.body.quiz.tema;
	var errors = req.quiz.validate();//ya qe el objeto errors no tiene then(
	if (errors)
		{
			var i=0; var errores=new Array();//se convierte en [] con la propiedad message por compatibilida con layout
			for (var prop in errors) errores[i++]={message: errors[prop]};
			res.render('quizes/edit', {quiz: req.quiz, errors: errores});
		} else {
			req.quiz // save: guarda en DB campos pregunta y respuesta de quiz
			.save({fields: ["pregunta", "respuesta", "tema"]})
			.then( function(){ res.redirect('/quizes')}) ;
		}
};

//DELETE /quizes/:id
exports.destroy= function(req, res){
	req.quiz.destroy(). then( function(){
		res.redirect('/quizes');
	}).catch(function(error){next(error)});
};

//Para la estadísticas de la base de datos
exports.statistics=function(req, res){
	var numeroPgtas;
	var numeroComentarios=10;
	var pgtasSinComentarios=2;
	var mensaje;
	//Obtengo número de preguntas
	models.Quiz.findAndCountAll().then(function (result) {
	  numeroPgtas=result.count;
	}).catch(function(error) { next(error);});

	mensaje='Número de preguntas : '+ numeroPgtas +"\n" +
		  'Número de comentarios : '+ numeroComentarios +"\n";
		  //'Número medio de comentarios por pregunta : '+(numeroPgtas/numeroComentarios)+"\n"+
		 // 'Número de preguntas sin comentarios : '+pgtasSinComentarios+"\n"+
		 // 'Número de preguntas con comentarios : '+(numeroPgtas-pgtasSinComentarios);
	res.render('statistics', {texto:mensaje,errors:[]});
};<commit_msg>estadisticas Version 0.2<commit_after>var models = require('../models/models.js');
var temas = ["otro","humanidades","ocio","ciencia","tecnologia"];

// Autoload :id
exports.load = function(req, res, next, quizId) {
  models.Quiz.find({
            where: {
                id: Number(quizId)
            },
            include: [{
                model: models.Comment
            }]
        }).then(function(quiz) {
      if (quiz) {
        req.quiz = quiz;
        next();
      } else{next(new Error('No existe quizId=' + quizId))}
    }
  ).catch(function(error){next(error)});
};

//GET /quizes
exports.index= function(req, res){
	res.render('quizes/index', {errors:[]});
};

//GET /quizes:search
exports.listQuestion= function(req, res){
  if(req.query.search) {
     var filtro  = (req.query.search || '').replace(" ", "%");
     models.Quiz.findAll({where:["pregunta like ?", '%'+filtro+'%'],order:'pregunta ASC'}).then(function(quizes){
       res.render('quizes/listQuestion', {quizes: quizes,errors:[]});
     }).catch(function(error) { next(error);});

  } else {

   models.Quiz.findAll().then(function(quizes){
       res.render('quizes/listQuestion', {quizes: quizes,errors:[]});
       }).catch(function(error) { next(error);});
  }
};

//GET /quizes/:id
exports.show = function (req,res){
	res.render('quizes/show', {quiz:req.quiz,errors:[]});
};

//GET /quizes/answer
exports.answer = function (req,res){
		var resultado='Incorrecto';
		if(req.query.respuesta===req.quiz.respuesta){
			resultado='Correcto';
		}
		res.render('quizes/answer',{quiz:req.quiz, respuesta:resultado,errors:[]});
};

//GET /quizes/new
exports.new = function(req, res){
	var quiz = models.Quiz.build(//crea objeto quiz
		{pregunta:"Pregunta", respuesta:"Respuesta",tema:"otro"}
	);
	res.render('quizes/new', {quiz:quiz,temas:temas,errors:[]});
};

//GET /quizes/create
exports.create = function(req, res){
	var quiz = models.Quiz.build( req.body.quiz );

	var errors = quiz.validate();//ya qe el objeto errors no tiene then(
	if (errors || (typeof errors === 'undefined') )
		{
			var i=0;
			var errores=new Array();//se convierte en [] con la propiedad message por compatibilida con layout
			for (var prop in errors)
				errores[i++]={message: errors[prop]};
			res.render('quizes/new', {quiz: quiz, errors: errores});
		} else {
			quiz // save: guarda en DB campos pregunta y respuesta de quiz
			.save({fields: ["pregunta", "respuesta","tema"]})
			.then( function(){ res.redirect('/quizes')}) ;
		}
};

//GET /quizes/:id/edit
exports.edit = function(req,res){
	var quiz= req.quiz;//autoload de instancia quiz
	res.render('quizes/edit',{quiz:quiz,temas:temas,errors:[]});
};

//PUT /quizes:id
exports.update = function(req,res){
	req.quiz.pregunta=req.body.quiz.pregunta;
	req.quiz.respuesta=req.body.quiz.respuesta;
	req.quiz.tema=req.body.quiz.tema;
	var errors = req.quiz.validate();//ya qe el objeto errors no tiene then(
	if (errors)
		{
			var i=0; var errores=new Array();//se convierte en [] con la propiedad message por compatibilida con layout
			for (var prop in errors) errores[i++]={message: errors[prop]};
			res.render('quizes/edit', {quiz: req.quiz, errors: errores});
		} else {
			req.quiz // save: guarda en DB campos pregunta y respuesta de quiz
			.save({fields: ["pregunta", "respuesta", "tema"]})
			.then( function(){ res.redirect('/quizes')}) ;
		}
};

//DELETE /quizes/:id
exports.destroy= function(req, res){
	req.quiz.destroy(). then( function(){
		res.redirect('/quizes');
	}).catch(function(error){next(error)});
};

//Para la estadísticas de la base de datos
exports.statistics=function(req, res){
	var numeroPgtas;
	var numeroComentarios=10;
	var pgtasSinComentarios=2;
	var mensaje;
	//Obtengo número de preguntas
	models.Quiz.findAndCountAll().then(function (numeroPgtas) {
	}).catch(function(error) { next(error);});

	mensaje='Número de preguntas : '+ numeroPgtas.count +"\n" +
		  'Número de comentarios : '+ numeroComentarios +"\n";
		  //'Número medio de comentarios por pregunta : '+(numeroPgtas/numeroComentarios)+"\n"+
		 // 'Número de preguntas sin comentarios : '+pgtasSinComentarios+"\n"+
		 // 'Número de preguntas con comentarios : '+(numeroPgtas-pgtasSinComentarios);
	res.render('statistics', {texto:mensaje,errors:[]});
};<|endoftext|>