<commit_before>Pool = {
  add_post: function(post_id, pool_id) {
    notice("Adding to pool...")

    new Ajax.Request("/pool/add_post.json", {
      parameters: {
        "post_id": post_id,
        "pool_id": pool_id
      },
      onComplete: function(resp) {
        var resp = resp.responseJSON

        if (resp.success) {
          notice("Post added to pool")
        } else {
          notice("Error: " + resp.reason)
        }
      }
    })
  },

  remove_post: function(post_id, pool_id) {
    new Ajax.Request('/pool/remove_post.json', {
      parameters: {
        "post_id": post_id,
        "pool_id": pool_id
      },
      onComplete: function(resp) {
        var resp = resp.responseJSON

        if (resp.success) {
          notice("Post removed from pool")
          if($("p" + post_id))
            $("p" + post_id).remove()
          if($("pool" + pool_id))
            $("pool" + pool_id).remove()
        } else {
          notice("Error: " + resp.reason)
        }
      }
    })
  }
}
<commit_msg>add Pool.transfer_post<commit_after>Pool = {
  add_post: function(post_id, pool_id) {
    notice("Adding to pool...")

    new Ajax.Request("/pool/add_post.json", {
      parameters: {
        "post_id": post_id,
        "pool_id": pool_id
      },
      onComplete: function(resp) {
        var resp = resp.responseJSON

        if (resp.success) {
          notice("Post added to pool")
        } else {
          notice("Error: " + resp.reason)
        }
      }
    })
  },

  remove_post: function(post_id, pool_id) {
    new Ajax.Request('/pool/remove_post.json', {
      parameters: {
        "post_id": post_id,
        "pool_id": pool_id
      },
      onComplete: function(resp) {
        var resp = resp.responseJSON

        if (resp.success) {
          notice("Post removed from pool")
          if($("p" + post_id))
            $("p" + post_id).remove()
          if($("pool" + pool_id))
            $("pool" + pool_id).remove()
        } else {
          notice("Error: " + resp.reason)
        }
      }
    })
  },
  transfer_post: function(old_post_id, new_post_id, pool_id, sequence)
  {
    Post.update_batch(
      [{ id: old_post_id, tags: "-pool:" + pool_id },
       { id: new_post_id, tags: "pool:" + pool_id + ":" + sequence }],
      function() {
        notice("Pool post transferred to parent")
        if($("p" + old_post_id))
          $("p" + old_post_id).remove()
        if($("pool" + pool_id))
          $("pool" + pool_id).remove()
      }
    );
  }
}
<|endoftext|>


<commit_before>var express = require('express');
var nodemailer = require('nodemailer');
var pgp = require('pg-promise')(/*options*/);
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Teknologföreningens årsfest' });
});

/* GET register form */
router.get('/register/', function(req, res, next) {
  res.render('register', { title: 'Anmälan' });
});

/* POST submit form */
router.post('/submit/', function(req, res, next) {
  console.log(req.body);
  var transporter = nodemailer.createTransport('smtp://smtp.ayy.fi');

  req.sanitizeBody('first_name').escape();
  req.checkBody('first_name', 'Felaktigt förnamn!').notEmpty();
  req.sanitizeBody('last_name').escape();
  req.checkBody('last_name', 'Felaktigt efternamn!').notEmpty();
  req.sanitizeBody('email').escape();
  req.checkBody('email', 'Felaktig e-postadress!').isEmail();
  req.sanitizeBody('organisation').escape();
  req.sanitizeBody('diet').escape();
  req.sanitizeBody('avec').escape();
  req.sanitizeBody('misc').escape();

  if (req.validationErrors()) {
    var err = new Error(req.validationErrors()[0].msg);
    res.status(400);
    res.render('error', { error: err });
  } else if (['free', 'student', 'normal', 'supporter'].indexOf(req.body.price) < 0) {
    var err = new Error("Du har inte valt priskategori!");
    res.status(400);
    res.render('error', { error: err });
  } else {
    var settings = require('../settings.js');
    var db = pgp("postgres://" + db_user + ":" + db_password + "@" + db_host + "/" + db_name);

    db.query("INSERT INTO Participants(first_name, last_name, organisation, greeting, email, diet, alcoholfree, sillis, solenn_akt, avec, misc, category) VALUES (${last_name}, ${organisation}, ${greeting}, ${email}, ${diet}, ${alcoholfree}, ${sillis}, ${solenn_akt}, ${avec}, ${misc}, ${price})", req.body)
        .then(function() {
          console.log("Added to the database");

          var mailOptions = {
            from: 'TF144 <arsfest@teknolog.fi>',
            to: req.body.email,
            subject: 'Bekräftelse',
            text: 'Hej,\n\nDin anmälan till Teknologföreningens årsfest har mottagits. Vidare instruktioner angående betalning kommer att skickas senare.\n\nVälkommen med på festen!',
          };

          transporter.sendMail(mailOptions, function(error, info) {
            if (error) {
              res.send(error);
            } else {
              console.log('Message sent: ' + info.response);
            }
          });

          // Informational message
          var infoMailOptions = {
            from: 'TF144 <arsfest@teknolog.fi>',
            to: 'oleg.stikhin@aalto.fi',
            subject: 'Ny anmälning',
            text: JSON.stringify(req.body),
          };

          transporter.sendMail(infoMailOptions, function(error, info) {
            if (error) {
              res.send(error);
            } else {
              console.log('Informational message sent: ' + info.response);
            }
          });

          res.render('submit', { title: 'Bekräftelse' });
        })

        .catch(function(error) {
          console.log("Database error: " + error);
          var err = new Error(error);
          res.status(500);
          res.render('error', { error: err });
        });

  }
});

/* GET the participants' list */
router.get('/list/', function(req, res, next) {
    var settings = require('../settings.js');
    var db = pgp("postgres://" + db_user + ":" + db_password + "@" + db_host + "/" + db_name);
    query = db.query("SELECT first_name, last_name, organisation FROM participants;")
      .then(function (data) {
        res.render('list', { title: 'Deltagare', data: data });
      })
      .catch(function (error) {
        console.log("Database error: " + error);
        var err = new Error(error);
        res.status(500);
        res.render('error', { error: err });
      });
});

module.exports = router;
<commit_msg>changed the checkbox logics<commit_after>var express = require('express');
var nodemailer = require('nodemailer');
var pgp = require('pg-promise')(/*options*/);
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Teknologföreningens årsfest' });
});

/* GET register form */
router.get('/register/', function(req, res, next) {
  res.render('register', { title: 'Anmälan' });
});

/* POST submit form */
router.post('/submit/', function(req, res, next) {
  console.log(req.body);
  var transporter = nodemailer.createTransport('smtp://smtp.ayy.fi');

  req.sanitizeBody('first_name').escape();
  req.checkBody('first_name', 'Felaktigt förnamn!').notEmpty();
  req.sanitizeBody('last_name').escape();
  req.checkBody('last_name', 'Felaktigt efternamn!').notEmpty();
  req.sanitizeBody('email').escape();
  req.checkBody('email', 'Felaktig e-postadress!').isEmail();
  req.sanitizeBody('organisation').escape();
  req.sanitizeBody('diet').escape();
  req.sanitizeBody('avec').escape();
  req.sanitizeBody('misc').escape();

  if (req.body.solenn_akt != "1") req.body.solenn_akt = "0";
  if (req.body.greeting != "1") req.body.greeting = "0";
  if (req.body.alcoholfree != "1") req.body.alcoholfree = "0";
  if (req.body.sillis != "1") req.body.sillis = "0";

  if (req.validationErrors()) {
    var err = new Error(req.validationErrors()[0].msg);
    res.status(400);
    res.render('error', { error: err });
  } else if (['free', 'student', 'normal', 'supporter'].indexOf(req.body.price) < 0) {
    var err = new Error("Du har inte valt priskategori!");
    res.status(400);
    res.render('error', { error: err });
  } else {
    var settings = require('../settings.js');
    var db = pgp("postgres://" + db_user + ":" + db_password + "@" + db_host + "/" + db_name);

    db.query("INSERT INTO Participants(first_name, last_name, organisation, greeting, email, diet, alcoholfree, sillis, solenn_akt, avec, misc, category) VALUES (${first_name}, ${last_name}, ${organisation}, ${greeting}, ${email}, ${diet}, ${alcoholfree}, ${sillis}, ${solenn_akt}, ${avec}, ${misc}, ${price})", req.body)
        .then(function() {
          console.log("Added to the database");

          var mailOptions = {
            from: 'TF144 <arsfest@teknolog.fi>',
            to: req.body.email,
            subject: 'Bekräftelse',
            text: 'Hej,\n\nDin anmälan till Teknologföreningens årsfest har mottagits. Vidare instruktioner angående betalning kommer att skickas senare.\n\nVälkommen med på festen!',
          };

          transporter.sendMail(mailOptions, function(error, info) {
            if (error) {
              res.send(error);
            } else {
              console.log('Message sent: ' + info.response);
            }
          });

          // Informational message
          var infoMailOptions = {
            from: 'TF144 <arsfest@teknolog.fi>',
            to: 'oleg.stikhin@aalto.fi',
            subject: 'Ny anmälning',
            text: JSON.stringify(req.body),
          };

          transporter.sendMail(infoMailOptions, function(error, info) {
            if (error) {
              res.send(error);
            } else {
              console.log('Informational message sent: ' + info.response);
            }
          });

          res.render('submit', { title: 'Bekräftelse' });
        })

        .catch(function(error) {
          console.log("Database error: " + error);
          var err = new Error(error);
          res.status(500);
          res.render('error', { error: err });
        });

  }
});

/* GET the participants' list */
router.get('/list/', function(req, res, next) {
    var settings = require('../settings.js');
    var db = pgp("postgres://" + db_user + ":" + db_password + "@" + db_host + "/" + db_name);
    query = db.query("SELECT first_name, last_name, organisation FROM participants;")
      .then(function (data) {
        res.render('list', { title: 'Deltagare', data: data });
      })
      .catch(function (error) {
        console.log("Database error: " + error);
        var err = new Error(error);
        res.status(500);
        res.render('error', { error: err });
      });
});

module.exports = router;
<|endoftext|>


<commit_before>
    var GPUMediaPlayer = function ()
    {

    };

    GPUMediaPlayer.prototype.start = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            mediaURL: options.mediaURL ? options.mediaURL : null,
            mediaOrientation: options.mediaOrientation ? options.mediaOrientation : 0,
            mediaType: options.mediaType ? options.mediaType : 0,

            mediaPosX: options.mediaPosX ? options.mediaPosX : 0,
            mediaPosY: options.mediaPosY ? options.mediaPosY : 0,
            mediaWidth: options.mediaWidth ? options.mediaWidth : 0,
            mediaHeight: options.mediaHeight ? options.mediaHeight : 0,

            framesPerSecond: options.framesPerSecond ? options.framesPerSecond : 0,

            playerPosX: options.playerPosX ? options.playerPosX : 0,
            playerPosY: options.playerPosY ? options.playerPosY : 0,
            playerWidth: options.playerWidth ? options.playerWidth : 0,
            playerHeight: options.playerHeight ? options.playerHeight : 0,

            captionEnabled: options.captionEnabled ? options.captionEnabled : 0,
            captionText: options.captionText ? options.captionText : null,
            captionFontSize: options.captionFontSize ? options.captionFontSize : 0,

            frameEnabled: options.frameEnabled ? options.frameEnabled : 0,
            frameShapeURL: options.frameShapeURL ? options.frameShapeURL : null,
            frameThemeURL: options.frameThemeURL ? options.frameThemeURL : null,

            overlayEnabled: options.overlayEnabled ? options.overlayEnabled : 0,
            overlayURL: options.overlayURL ? options.overlayURL : null,
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "start", [params]);

    };

    GPUMediaPlayer.prototype.pause = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "pause", null);
    };

    GPUMediaPlayer.prototype.play = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "play", null);
    };

    GPUMediaPlayer.prototype.stop = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "stop", null);
    };

    GPUMediaPlayer.prototype.save = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            mediaURL: options.mediaURL ? options.mediaURL : null,
            mediaType: options.mediaType ? options.mediaType : 0,
            mediaWidth: options.mediaWidth ? options.mediaWidth : 0,
            mediaHeight: options.mediaHeight ? options.mediaHeight : 0,
            avgBitRate: options.avgBitRate ? options.avgBitRate : 0,
            gifFramesPerSecond: options.gifFramesPerSecond ? options.gifFramesPerSecond : 0,
            gifPlaybackSpeed: options.gifPlaybackSpeed ? options.gifPlaybackSpeed : 0,
            gifMaxDuration: options.gifMaxDuration ? options.gifMaxDuration : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "save", [params]);
    };

    GPUMediaPlayer.prototype.addSticker = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            stickerURL: options.stickerURL ? options.stickerURL : null,
            stickerID: options.stickerID ? options.stickerID : 0,
            stickerPosX: options.stickerPosX ? options.stickerPosX : 0,
            stickerPosY: options.stickerPosY ? options.stickerPosY : 0,
            stickerWidth: options.stickerWidth ? options.stickerWidth : 0,
            stickerHeight: options.stickerHeight ? options.stickerHeight : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "addSticker", [params]);
    };

    GPUMediaPlayer.prototype.addLabel = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            labelID: options.labelID ? options.labelID : 0,
            labelPosX: options.labelPosX ? options.labelPosX : 0,
            labelPosY: options.labelPosY ? options.labelPosY : 0,
            labelWidth: options.labelWidth ? options.labelWidth : 0,
            labelHeight: options.labelHeight ? options.labelHeight : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "addLabel", [params]);
    };

    GPUMediaPlayer.prototype.updateLabel = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            //labelID: options.labelID ? options.labelID : 0,
            labelColor: options.labelColor ? options.labelColor : null,
            labelSize: options.labelSize ? options.labelSize : 0,
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "updateLabel", [params]);
    };

    GPUMediaPlayer.prototype.updateSticker = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            //stickerID: options.stickerID ? options.stickerID : 0,
            stickerColor: options.stickerColor ? options.stickerColor : null,
            stickerSize: options.stickerSize ? options.stickerSize : 0,
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "updateSticker", [params]);
    };

    GPUMediaPlayer.prototype.changeFilter = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            filterID: options.filterID ? options.filterID : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "changeFilter", [params]);
    };

    GPUMediaPlayer.prototype.changeFrame = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            mediaWidth: options.mediaWidth ? options.mediaWidth : 0,
            mediaHeight: options.mediaHeight ? options.mediaHeight : 0,
            frameShapeURL: options.frameShapeURL ? options.frameShapeURL : null,
            frameThemeURL: options.frameThemeURL ? options.frameThemeURL : null,
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "changeFrame", [params]);
    };

    window.gpuMediaPlayer = new GPUMediaPlayer();
<commit_msg>Update gpumediaplayer.js<commit_after>  var GPUMediaPlayer = function ()
    {

    };

    GPUMediaPlayer.prototype.start = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            mediaURL: options.mediaURL ? options.mediaURL : null,
            mediaOrientation: options.mediaOrientation ? options.mediaOrientation : 0,
            mediaType: options.mediaType ? options.mediaType : 0,

            mediaPosX: options.mediaPosX ? options.mediaPosX : 0,
            mediaPosY: options.mediaPosY ? options.mediaPosY : 0,
            mediaWidth: options.mediaWidth ? options.mediaWidth : 0,
            mediaHeight: options.mediaHeight ? options.mediaHeight : 0,

            framesPerSecond: options.framesPerSecond ? options.framesPerSecond : 0,

            playerPosX: options.playerPosX ? options.playerPosX : 0,
            playerPosY: options.playerPosY ? options.playerPosY : 0,
            playerWidth: options.playerWidth ? options.playerWidth : 0,
            playerHeight: options.playerHeight ? options.playerHeight : 0,

            captionEnabled: options.captionEnabled ? options.captionEnabled : 0,
            captionText: options.captionText ? options.captionText : null,
            captionFontSize: options.captionFontSize ? options.captionFontSize : 0,

            frameEnabled: options.frameEnabled ? options.frameEnabled : 0,
            frameShapeURL: options.frameShapeURL ? options.frameShapeURL : null,
            frameThemeURL: options.frameThemeURL ? options.frameThemeURL : null,

            overlayEnabled: options.overlayEnabled ? options.overlayEnabled : 0,
            overlayURL: options.overlayURL ? options.overlayURL : null,
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "start", [params]);

    };

    GPUMediaPlayer.prototype.pause = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "pause", null);
    };

    GPUMediaPlayer.prototype.play = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "play", null);
    };

    GPUMediaPlayer.prototype.stop = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "stop", null);
    };

    GPUMediaPlayer.prototype.restart = function (success, fail, options)
    {
        return cordova.exec(success, fail, "GPUMediaPlayer", "restart", null);
    };

    GPUMediaPlayer.prototype.save = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            mediaURL: options.mediaURL ? options.mediaURL : null,
            mediaType: options.mediaType ? options.mediaType : 0,
            mediaWidth: options.mediaWidth ? options.mediaWidth : 0,
            mediaHeight: options.mediaHeight ? options.mediaHeight : 0,
            avgBitRate: options.avgBitRate ? options.avgBitRate : 0,
            gifFramesPerSecond: options.gifFramesPerSecond ? options.gifFramesPerSecond : 0,
            gifPlaybackSpeed: options.gifPlaybackSpeed ? options.gifPlaybackSpeed : 0,
            gifMaxDuration: options.gifMaxDuration ? options.gifMaxDuration : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "save", [params]);
    };

    GPUMediaPlayer.prototype.addSticker = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            stickerURL: options.stickerURL ? options.stickerURL : null,
            stickerID: options.stickerID ? options.stickerID : 0,
            stickerPosX: options.stickerPosX ? options.stickerPosX : 0,
            stickerPosY: options.stickerPosY ? options.stickerPosY : 0,
            stickerWidth: options.stickerWidth ? options.stickerWidth : 0,
            stickerHeight: options.stickerHeight ? options.stickerHeight : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "addSticker", [params]);
    };

    GPUMediaPlayer.prototype.addLabel = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            labelID: options.labelID ? options.labelID : 0,
            labelPosX: options.labelPosX ? options.labelPosX : 0,
            labelPosY: options.labelPosY ? options.labelPosY : 0,
            labelWidth: options.labelWidth ? options.labelWidth : 0,
            labelHeight: options.labelHeight ? options.labelHeight : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "addLabel", [params]);
    };

    GPUMediaPlayer.prototype.updateLabel = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            //labelID: options.labelID ? options.labelID : 0,
            labelColor: options.labelColor ? options.labelColor : null,
            labelSize: options.labelSize ? options.labelSize : 0,
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "updateLabel", [params]);
    };

    GPUMediaPlayer.prototype.updateSticker = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            //stickerID: options.stickerID ? options.stickerID : 0,
            stickerColor: options.stickerColor ? options.stickerColor : null,
            stickerSize: options.stickerSize ? options.stickerSize : 0,
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "updateSticker", [params]);
    };

    GPUMediaPlayer.prototype.changeFilter = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            filterID: options.filterID ? options.filterID : 0
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "changeFilter", [params]);
    };

    GPUMediaPlayer.prototype.changeFrame = function (success, fail, options)
    {
        if (!options) {
            options = {};
        }

        var params = {
            mediaWidth: options.mediaWidth ? options.mediaWidth : 0,
            mediaHeight: options.mediaHeight ? options.mediaHeight : 0,
            frameShapeURL: options.frameShapeURL ? options.frameShapeURL : null,
            frameThemeURL: options.frameThemeURL ? options.frameThemeURL : null,
        };

        return cordova.exec(success, fail, "GPUMediaPlayer", "changeFrame", [params]);
    };

    window.gpuMediaPlayer = new GPUMediaPlayer();
<|endoftext|>


<commit_before>// global variables
cur_word_idx = -1
cur_word = ''

// chosen copy category.
// this will be used.. later
// 1 = literary passages, 2 = news, 3 = random words
copy_category = 1

// an array of words in the copy, filled by prepare_copy()
words = null

// an array of recently-typed characters, sorted from oldest to newest.
// this is digested by eval_next_in_queue().
// adding char codes to queue + polling > event-based checks, on some slower systems
check_queue = []

// stores the interval timer so that polling can stop once typing finishes
poll = null

// prevent continuous flashing when a typing error occurs
// (since the polling function would keep noticing the error until it was fixed)
can_show_error = true

// track start time and end time for calculating stats
start_time = null
end_time = null

// used to store DOM els rather than continually fetch them
// set @ $(document).ready()
type_area = null

// stats
stat_delta = null
stat_wpm = null
stat_cpm = null
done = false

function prepare_copy(words_arr, note) {
	$.each(words_arr, function(idx, word) {
		$('#copy').append('' + word + ' ')
	})

	$('#note').text(note)

	words = $('#copy span.word')
	next_word()
}

function eval_next_in_queue() {
	if ( check_queue.length == 0 ) return;

	var code = check_queue.shift()
	var typed_text = type_area.val().split(' ')[0]
	var check = cur_word.substr(0, typed_text.length)

	if ( code == 32 ) // spacebar
		if ( typed_text.length == cur_word.length && typed_text == check )
			next_word()
		else
			show_error()
	else
		if ( typed_text != check )
			show_error()
}

function next_word() {
	var old_word = cur_word
	cur_word_idx += 1

	if ( words[cur_word_idx] == undefined ) {
		done()
	} else {
		cur_word = words[cur_word_idx].innerText

		// remove highlighting from the old word
		if ( words[cur_word_idx - 1] != undefined )
			words[cur_word_idx - 1].style.color = 'inherit'

		// highlight the new word
		words[cur_word_idx].style.color = '#6fbf4d'

		// remove this successfully-typed word from the entry box
		// but don't remove any other things that could've been typed since the success!
		// String.replace(str) replaces the first occurrence only
		type_area.val(type_area.val().replace(old_word + ' ', ''));
	}
}

function done() {
	done = true

	end_time = new Date()
	clearInterval(poll)
	type_area.css('background-color', '#6fbf4d')

	calculate_stats()
	submit_results(words.length, stat_delta, stat_wpm, stat_cpm)
	$('#results').show()
}

function calculate_stats() {
	compare_time = ( end_time == undefined ) ? new Date() : end_time
	stat_delta = ( compare_time.getTime() - start_time.getTime() ) / 60000

	stat_wpm = words.length / stat_delta
	stat_cpm = $('#copy').text().length / stat_delta

	$('#results-wpm').text(Math.round(stat_wpm))
	$('#results-cpm').text(Math.round(stat_wpm))
}

function submit_results(words, duration, words_per_minute, characters_per_minute) {
	$.post('/type/submit', {
		words: words,
		duration: delta,
		wpm: words_per_minute,
		cpm: characters_per_minute
	}, null, 'json')
}

function show_error() {
	if ( can_show_error ) {
		type_area.css('background-color', '#ff7878')
		setTimeout(hide_error, 500)
	}

	can_show_error = false
}

function hide_error() {
	type_area.css('background-color', '#fafafa')
}

$(document).ready(function() {
	type_area = $('#type_area')

	prepare()
	init_pollers()
})<commit_msg>evaluate stats using chars / words typed so far, not chars / words of the whole copy<commit_after>// global variables
cur_word_idx = -1
cur_word = ''

// chosen copy category.
// this will be used.. later
// 1 = literary passages, 2 = news, 3 = random words
copy_category = 1

// an array of words in the copy, filled by prepare_copy()
words = null

// an array of recently-typed characters, sorted from oldest to newest.
// this is digested by eval_next_in_queue().
// adding char codes to queue + polling > event-based checks, on some slower systems
check_queue = []

// stores the interval timer so that polling can stop once typing finishes
poll = null

// prevent continuous flashing when a typing error occurs
// (since the polling function would keep noticing the error until it was fixed)
can_show_error = true

// track start time and end time for calculating stats
start_time = null
end_time = null

// used to store DOM els rather than continually fetch them
// set @ $(document).ready()
type_area = null

// stats
stat_delta = null
stat_wpm = null
stat_cpm = null
done = false

// more stats
words_typed = 0
chars_typed = 0

function prepare_copy(words_arr, note) {
	$.each(words_arr, function(idx, word) {
		$('#copy').append('' + word + ' ')
	})

	$('#note').text(note)

	words = $('#copy span.word')
	next_word()
}

function eval_next_in_queue() {
	if ( check_queue.length == 0 ) return;

	var code = check_queue.shift()
	var typed_text = type_area.val().split(' ')[0]
	var check = cur_word.substr(0, typed_text.length)

	if ( code == 32 ) // spacebar
		if ( typed_text.length == cur_word.length && typed_text == check )
			next_word()
		else
			show_error()
	else
		if ( typed_text != check )
			show_error()
		else
			chars_typed += 1
}

function next_word() {
	var old_word = cur_word
	cur_word_idx += 1

	// increase words_typed, and account for the spacebar char
	// increment chars_typed as well
	words_typed += 1
	chars_typed += 1

	if ( words[cur_word_idx] == undefined ) {
		done()
	} else {
		cur_word = words[cur_word_idx].innerText

		// remove highlighting from the old word
		if ( words[cur_word_idx - 1] != undefined )
			words[cur_word_idx - 1].style.color = 'inherit'

		// highlight the new word
		words[cur_word_idx].style.color = '#6fbf4d'

		// remove this successfully-typed word from the entry box
		// but don't remove any other things that could've been typed since the success!
		// String.replace(str) replaces the first occurrence only
		type_area.val(type_area.val().replace(old_word + ' ', ''));
	}
}

function done() {
	done = true

	end_time = new Date()
	clearInterval(poll)
	type_area.css('background-color', '#6fbf4d')

	calculate_stats()
	submit_results(words.length, stat_delta, stat_wpm, stat_cpm)
	$('#results').show()
}

function calculate_stats() {
	compare_time = ( end_time == undefined ) ? new Date() : end_time
	stat_delta = ( compare_time.getTime() - start_time.getTime() ) / 60000

	stat_wpm = words_typed / stat_delta
	stat_cpm = chars_typed / stat_delta

	$('#results-wpm').text(Math.round(stat_wpm))
	$('#results-cpm').text(Math.round(stat_wpm))
}

function submit_results(words, duration, words_per_minute, characters_per_minute) {
	$.post('/type/submit', {
		words: words,
		duration: delta,
		wpm: words_per_minute,
		cpm: characters_per_minute
	}, null, 'json')
}

function show_error() {
	if ( can_show_error ) {
		type_area.css('background-color', '#ff7878')
		setTimeout(hide_error, 500)
	}

	can_show_error = false
}

function hide_error() {
	type_area.css('background-color', '#fafafa')
}

$(document).ready(function() {
	type_area = $('#type_area')

	prepare()
	init_pollers()
})<|endoftext|>


<commit_before>angular.module('omniwallet')
  .factory('enumerated_addresses', function($http, $q, $timeout, $injector) {
    var count = 1;
    return {
      "getData": function() {
        var deferred = $q.defer();

        _.defer(function() {
          var wallet = $injector.get('userService').getWallet();
          if (wallet && wallet.addresses.length > 0) {

            deferred.resolve({
              addresses: wallet.addresses
            });
          } else {
            deferred.resolve({
              addresses: []
            });
          }
        });
        return deferred.promise;
      }
    };
  })
  .controller('AddAddressController', function($modal, $injector, $scope, $timeout, userService, enumerated_addresses) {

  function decodeAddressFromPrivateKey(key) {

    //  Return the address decoded from the private key.
    var eckey = new Bitcoin.ECKey(key);
    var addr = eckey.getBitcoinAddress().toString();

    return addr;
  };

  function encodePrivateKey(key, passphrase) {

    //  Return encoded key.  Forget the passphrase forever.
    var eckey = new Bitcoin.ECKey(key);
    var enc = eckey.getEncryptedFormat(passphrase);

    return enc;
  };

  $scope.backupWallet = function() {
    $scope.login = {
      uuid: userService.data.wallet.uuid,
      action: 'verify',
      title: 'Verify Account',
      button: 'Validate',
      disable: true //disable UUID field in template
    };
    var modalInstance = $modal.open({
      templateUrl: '/partials/login_modal.html',
      controller: LoginController,
      scope: $scope
    });

    modalInstance.result.then(function(wallet) {
      $scope.exportData = {
        backupName : wallet.uuid,
        exportPrivate : true,
        exportWatch : true
      };
      $scope.exportInProgress=false;
      var exportModalInstance = $modal.open({
        templateUrl: '/partials/export_wallet.html',
        controller: function($scope, $modalInstance, wallet){
          $scope.exportWallet = function(exportData){
            $scope.exportInProgress=true;
            $scope.exported = 0;
            var walletAddresses = wallet.addresses;
            $scope.total = walletAddresses.length;
            var blob = {
              addresses: []
            };

            var next = function(){
              $timeout(function(){
                return exportAddress(walletAddresses[$scope.exported]);
              },0,false);
            };

            var exportAddress = function(obj){
              if($scope.exported == $scope.total) {
                var exportBlob = new Blob([JSON.stringify(blob)], {
                  type: 'application/json;charset=utf-8'
                });
                fileName=exportData.backupName+".json";
                saveAs(exportBlob, fileName);

                return $modalInstance.dismiss("success");
              }

              $scope.$apply(function(){
                if(exportData.exportPrivate && obj.privkey) {
                  var ecKey = Bitcoin.ECKey.decodeEncryptedFormat(obj.privkey, obj.address);
                  var addr = ecKey.getBitcoinAddress().toString();
                  var key = ecKey.getWalletImportFormat();
                  blob.addresses.push({ address: addr, privkey: key });
                  $scope.progressMessage = "Exported trading address " + addr;
                }
                if(exportData.exportWatch && !obj.privkey) {
                  blob.addresses.push({ address: obj.address, privkey: "" });
                  $scope.progressMessage = "Exported watch address " + addr;
                }
                $scope.exported++;
              });
              return next();
            };

            // Start the loop
            next();
          };
        },
        scope: $scope,
        resolve:{
          wallet: function(){
            return wallet;
          }
        }
      });
    });
  };

  // Begin Import watch only Form Code
  $scope.openImportWatchOnlyForm = function() {
    var modalInstance = $modal.open({
      templateUrl: '/partials/import_watch_only.html',
      controller: AddBtcAddressModal
    });

    modalInstance.result.then(function(result) {

      if (result.address) {
        $injector.get('userService').addAddress(result.address);
      }
      $scope.refresh();

    }, function() {});
  };

  var AddBtcAddressModal = function($scope, $modalInstance) {
    $scope.validate = function(address) {
      return Bitcoin.Address.validate(address);
    };

    $scope.addressNotListed = function(address) {
      var addresses = $injector.get('userService').getAllAddresses();
      for (var i in addresses) {
        if (addresses[i].address == address) {
          return false;
        }
      }

      return true;
    };

    $scope.ok = function(result) {
      if (Bitcoin.Address.validate(result.address))
        $modalInstance.close(result);
      else
        console.log('*** Invalid address: ' + result.address);
    };

    $scope.cancel = function() {
      $modalInstance.dismiss('cancel');
    };
  };
  // Done Import Watch Only Form Code.

  // Begin Import Private Key Form Code
  $scope.openImportPrivateKeyForm = function() {
    var modalInstance = $modal.open({
      templateUrl: '/partials/import_private.html',
      controller: AddPrivateKeyModal
    });

    modalInstance.result.then(function(result) {

      if (result.privKey) {
        // Use address as passphrase for now
        var addr = decodeAddressFromPrivateKey(result.privKey);
        $injector.get('userService').addAddress(
        addr,
        encodePrivateKey(result.privKey, addr));
      }
      $scope.refresh();

    }, function() {});
  };

  var AddPrivateKeyModal = function($scope, $modalInstance) {
    $scope.validate = function(address) {
      if (!address) return false;

      try {
        var eckey = new Bitcoin.ECKey(address);
        var addr = eckey.getBitcoinAddress().toString();
        return true;
      } catch (e) {
        return false;
      }
    };

    $scope.ok = function(result) {
      $modalInstance.close(result);
    };

    $scope.cancel = function() {
      $modalInstance.dismiss('cancel');
    };
  };
  // Done Import Private Key Form Code.
  // Begin Import Encrypted Key Form Code
  $scope.openImportEncryptedKeyForm = function() {
    var modalInstance = $modal.open({
      templateUrl: '/partials/import_encrypted_private.html',
      controller: AddEncryptedPrivateModal
    });

    modalInstance.result.then(function(result) {

      if (result.encryptedPrivKey && result.password) {
        // Decrypt key then store with default password of addr
        var key = Bitcoin.ECKey.decodeEncryptedFormat(result.encryptedPrivKey, result.password);
        var privkey = Bitcoin.Util.bytesToHex(key.getPrivateKeyByteArray());
        // Use address as passphrase for now
        var addr = decodeAddressFromPrivateKey(privkey);
        $injector.get('userService').addAddress(
        addr,
        encodePrivateKey(privkey, addr));
      }
      $scope.refresh();

    }, function() {});
  };

  var AddEncryptedPrivateModal = function($scope, $modalInstance) {
    $scope.ok = function(result) {
      $modalInstance.close(result);
    };

    $scope.cancel = function() {
      $modalInstance.dismiss('cancel');
    };
  };
  // Done Import Encrypted Private Key Code.

  // Begine Create Form Code.
  $scope.createBTCAddress = createBTCAddress;
  function createBTCAddress() {
    var ecKey = new Bitcoin.ECKey();
    var address = ecKey.getBitcoinAddress().toString();
    var encryptedPrivateKey = ecKey.getEncryptedFormat(address);
    $injector.get('userService').addAddress(address, encryptedPrivateKey);
    $scope.refresh();
  }
  ;
  // Done Create Form Code.
  // Begin Import Backup Form Code
  $scope.openImportWalletForm = function() {
    var modalInstance = $modal.open({
      templateUrl: '/partials/import_wallet.html',
      controller: ImportWalletModal
    });

    modalInstance.result.then(function(result) {

      if (result) {
        var wallet = JSON.parse(result);

        wallet.addresses.forEach(function(addr){
          // Use address as passphrase for now
          if(addr.privkey)
            $injector.get('userService').addAddress(
              addr.address,
              encodePrivateKey(addr.privkey, addr.address));
          else
            $injector.get('userService').addAddress(
              addr.address);
        });
      }
      $scope.refresh();

    });
  };

  var ImportWalletModal = function($scope, $modalInstance, $q, $timeout) {
    $scope.startImport = function(){
      $scope.validate(walletData).then(function(result){$scope.ok($scope.walletData);},function(reason){$scope.progressMessage= reason;});
    };
    $scope.validate = function(backup) {
      var deferred = $q.deferred();

      if (!backup) deferred.reject("No File");
      $scope.processing = true;
      try {
        var wallet = JSON.parse(backup);
        $scope.completed = 0;
        $scope.total = wallet.addresses.length;

        var next = function(){
          $timeout(function(){
            return validateAddress(wallet.addresses[$scope.completed]);
          },0,false);
        };
        var validated = {
          addresses : []
        };

        var validateAddress = function(address){
          if($scope.completed == $scope.total){
            return deferred.resolve(validated);
          }
          $scope.$apply(function(){
            var addr = address.address;
            if(address.privkey){
              var eckey = new Bitcoin.ECKey(address.privkey);
              addr = eckey.getBitcoinAddress().toString();
            }

            if(Bitcoin.Address.validate(addr)){
              validated.push(address);
              $scope.progressMessage = "Validated address " + addr;
              $scope.progressColor = "green";
            } else {
              $scope.progressMessage = "Invalid address " + addr;
              $scope.progressColor = "red";
            }
          });

          return next();
        };

        // Start the loop
        next();

        deferred.info("Validating...");
      } catch (e) {
        deferred.reject("Error during validation:" +e);
      }

      return deferred.promise;
    };

    $scope.ok = function(result) {
      $modalInstance.close(result);
    };

    $scope.cancel = function() {
      $modalInstance.dismiss('cancel');
    };
  };
  // Done Import Import Backup Form Code.

  $scope.enumerateAddresses = function() {

    $scope.items = enumerated_addresses.getData().then(function(result) {
      if (result.addresses.length == 0) {
        createBTCAddress();
	$scope.newAddress=true;
      }
      $scope.addresses = result.addresses;
    });
  };

});

<commit_msg>Import only validated addresses.<commit_after>angular.module('omniwallet')
  .factory('enumerated_addresses', function($http, $q, $timeout, $injector) {
    var count = 1;
    return {
      "getData": function() {
        var deferred = $q.defer();

        _.defer(function() {
          var wallet = $injector.get('userService').getWallet();
          if (wallet && wallet.addresses.length > 0) {

            deferred.resolve({
              addresses: wallet.addresses
            });
          } else {
            deferred.resolve({
              addresses: []
            });
          }
        });
        return deferred.promise;
      }
    };
  })
  .controller('AddAddressController', function($modal, $injector, $scope, $timeout, userService, enumerated_addresses) {

  function decodeAddressFromPrivateKey(key) {

    //  Return the address decoded from the private key.
    var eckey = new Bitcoin.ECKey(key);
    var addr = eckey.getBitcoinAddress().toString();

    return addr;
  };

  function encodePrivateKey(key, passphrase) {

    //  Return encoded key.  Forget the passphrase forever.
    var eckey = new Bitcoin.ECKey(key);
    var enc = eckey.getEncryptedFormat(passphrase);

    return enc;
  };

  $scope.backupWallet = function() {
    $scope.login = {
      uuid: userService.data.wallet.uuid,
      action: 'verify',
      title: 'Verify Account',
      button: 'Validate',
      disable: true //disable UUID field in template
    };
    var modalInstance = $modal.open({
      templateUrl: '/partials/login_modal.html',
      controller: LoginController,
      scope: $scope
    });

    modalInstance.result.then(function(wallet) {
      $scope.exportData = {
        backupName : wallet.uuid,
        exportPrivate : true,
        exportWatch : true
      };
      $scope.exportInProgress=false;
      var exportModalInstance = $modal.open({
        templateUrl: '/partials/export_wallet.html',
        controller: function($scope, $modalInstance, wallet){
          $scope.exportWallet = function(exportData){
            $scope.exportInProgress=true;
            $scope.exported = 0;
            var walletAddresses = wallet.addresses;
            $scope.total = walletAddresses.length;
            var blob = {
              addresses: []
            };

            var next = function(){
              $timeout(function(){
                return exportAddress(walletAddresses[$scope.exported]);
              },0,false);
            };

            var exportAddress = function(obj){
              if($scope.exported == $scope.total) {
                var exportBlob = new Blob([JSON.stringify(blob)], {
                  type: 'application/json;charset=utf-8'
                });
                fileName=exportData.backupName+".json";
                saveAs(exportBlob, fileName);

                return $modalInstance.dismiss("success");
              }

              $scope.$apply(function(){
                if(exportData.exportPrivate && obj.privkey) {
                  var ecKey = Bitcoin.ECKey.decodeEncryptedFormat(obj.privkey, obj.address);
                  var addr = ecKey.getBitcoinAddress().toString();
                  var key = ecKey.getWalletImportFormat();
                  blob.addresses.push({ address: addr, privkey: key });
                  $scope.progressMessage = "Exported trading address " + addr;
                }
                if(exportData.exportWatch && !obj.privkey) {
                  blob.addresses.push({ address: obj.address, privkey: "" });
                  $scope.progressMessage = "Exported watch address " + addr;
                }
                $scope.exported++;
              });
              return next();
            };

            // Start the loop
            next();
          };
        },
        scope: $scope,
        resolve:{
          wallet: function(){
            return wallet;
          }
        }
      });
    });
  };

  // Begin Import watch only Form Code
  $scope.openImportWatchOnlyForm = function() {
    var modalInstance = $modal.open({
      templateUrl: '/partials/import_watch_only.html',
      controller: AddBtcAddressModal
    });

    modalInstance.result.then(function(result) {

      if (result.address) {
        $injector.get('userService').addAddress(result.address);
      }
      $scope.refresh();

    }, function() {});
  };

  var AddBtcAddressModal = function($scope, $modalInstance) {
    $scope.validate = function(address) {
      return Bitcoin.Address.validate(address);
    };

    $scope.addressNotListed = function(address) {
      var addresses = $injector.get('userService').getAllAddresses();
      for (var i in addresses) {
        if (addresses[i].address == address) {
          return false;
        }
      }

      return true;
    };

    $scope.ok = function(result) {
      if (Bitcoin.Address.validate(result.address))
        $modalInstance.close(result);
      else
        console.log('*** Invalid address: ' + result.address);
    };

    $scope.cancel = function() {
      $modalInstance.dismiss('cancel');
    };
  };
  // Done Import Watch Only Form Code.

  // Begin Import Private Key Form Code
  $scope.openImportPrivateKeyForm = function() {
    var modalInstance = $modal.open({
      templateUrl: '/partials/import_private.html',
      controller: AddPrivateKeyModal
    });

    modalInstance.result.then(function(result) {

      if (result.privKey) {
        // Use address as passphrase for now
        var addr = decodeAddressFromPrivateKey(result.privKey);
        $injector.get('userService').addAddress(
        addr,
        encodePrivateKey(result.privKey, addr));
      }
      $scope.refresh();

    }, function() {});
  };

  var AddPrivateKeyModal = function($scope, $modalInstance) {
    $scope.validate = function(address) {
      if (!address) return false;

      try {
        var eckey = new Bitcoin.ECKey(address);
        var addr = eckey.getBitcoinAddress().toString();
        return true;
      } catch (e) {
        return false;
      }
    };

    $scope.ok = function(result) {
      $modalInstance.close(result);
    };

    $scope.cancel = function() {
      $modalInstance.dismiss('cancel');
    };
  };
  // Done Import Private Key Form Code.
  // Begin Import Encrypted Key Form Code
  $scope.openImportEncryptedKeyForm = function() {
    var modalInstance = $modal.open({
      templateUrl: '/partials/import_encrypted_private.html',
      controller: AddEncryptedPrivateModal
    });

    modalInstance.result.then(function(result) {

      if (result.encryptedPrivKey && result.password) {
        // Decrypt key then store with default password of addr
        var key = Bitcoin.ECKey.decodeEncryptedFormat(result.encryptedPrivKey, result.password);
        var privkey = Bitcoin.Util.bytesToHex(key.getPrivateKeyByteArray());
        // Use address as passphrase for now
        var addr = decodeAddressFromPrivateKey(privkey);
        $injector.get('userService').addAddress(
        addr,
        encodePrivateKey(privkey, addr));
      }
      $scope.refresh();

    }, function() {});
  };

  var AddEncryptedPrivateModal = function($scope, $modalInstance) {
    $scope.ok = function(result) {
      $modalInstance.close(result);
    };

    $scope.cancel = function() {
      $modalInstance.dismiss('cancel');
    };
  };
  // Done Import Encrypted Private Key Code.

  // Begine Create Form Code.
  $scope.createBTCAddress = createBTCAddress;
  function createBTCAddress() {
    var ecKey = new Bitcoin.ECKey();
    var address = ecKey.getBitcoinAddress().toString();
    var encryptedPrivateKey = ecKey.getEncryptedFormat(address);
    $injector.get('userService').addAddress(address, encryptedPrivateKey);
    $scope.refresh();
  }
  ;
  // Done Create Form Code.
  // Begin Import Backup Form Code
  $scope.openImportWalletForm = function() {
    var modalInstance = $modal.open({
      templateUrl: '/partials/import_wallet.html',
      controller: ImportWalletModal
    });

    modalInstance.result.then(function(result) {

      if (result) {
        var wallet = JSON.parse(result);

        wallet.addresses.forEach(function(addr){
          // Use address as passphrase for now
          if(addr.privkey)
            $injector.get('userService').addAddress(
              addr.address,
              encodePrivateKey(addr.privkey, addr.address));
          else
            $injector.get('userService').addAddress(
              addr.address);
        });
      }
      $scope.refresh();

    });
  };

  var ImportWalletModal = function($scope, $modalInstance, $q, $timeout) {
    $scope.startImport = function(){
      $scope.validate($scope.walletData).then(function(result){$scope.ok(result);},function(reason){$scope.progressMessage= reason;});
    };
    $scope.validate = function(backup) {
      var deferred = $q.deferred();

      if (!backup) deferred.reject("No File");
      $scope.processing = true;
      try {
        var wallet = JSON.parse(backup);
        $scope.completed = 0;
        $scope.total = wallet.addresses.length;

        var next = function(){
          $timeout(function(){
            return validateAddress(wallet.addresses[$scope.completed]);
          },0,false);
        };
        var validated = {
          addresses : []
        };

        var validateAddress = function(address){
          if($scope.completed == $scope.total){
            return deferred.resolve(validated);
          }
          $scope.$apply(function(){
            var addr = address.address;
            if(address.privkey){
              var eckey = new Bitcoin.ECKey(address.privkey);
              addr = eckey.getBitcoinAddress().toString();
            }

            if(Bitcoin.Address.validate(addr)){
              validated.push(address);
              $scope.progressMessage = "Validated address " + addr;
              $scope.progressColor = "green";
            } else {
              $scope.progressMessage = "Invalid address " + addr;
              $scope.progressColor = "red";
            }
          });

          return next();
        };

        // Start the loop
        next();

        deferred.info("Validating...");
      } catch (e) {
        deferred.reject("Error during validation:" +e);
      }

      return deferred.promise;
    };

    $scope.ok = function(result) {
      $modalInstance.close(result);
    };

    $scope.cancel = function() {
      $modalInstance.dismiss('cancel');
    };
  };
  // Done Import Import Backup Form Code.

  $scope.enumerateAddresses = function() {

    $scope.items = enumerated_addresses.getData().then(function(result) {
      if (result.addresses.length == 0) {
        createBTCAddress();
	$scope.newAddress=true;
      }
      $scope.addresses = result.addresses;
    });
  };

});

<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();
var moment = require('moment');
var promise = require('bluebird');
var options = {
    promiseLib: promise
};

var pgp = require('pg-promise')(options);
var connectionString = {
    //host: 'localhost',
    host: process.env.DATABASE_URL,
    port: 5432,
    database: 'openmicnight',
    user: 'openmicer'
};

var db = pgp(connectionString);

router.post('/api/openmic/save', function(req, res) {
//TODO don't save if this openmic already exists
  var params = req.body;
  var data = {name: params.openMicName, weekday : params.openMicWeekDay,
    regularity : params.openMicRegularity, comedian: params.comedians, poet: params.poets, musician: params.musicians,
    contact_email_address: params.contactEmailAddress, contact_phone_number: params.contactPhoneNumber,
    venue_name: params.venueName, venue_address: params.venueAddress, state: params.state, city: params.city,
    sign_up_time: params.signUpTime, start_time: params.startTime, is_free: params.isOpenMicFree,
    next_openmic_day: params.nextOpenMicDate, notes: params.notes, monday: params.monday,
    tuesday: params.tuesday, wednesday: params.wednesday, thursday: params.thursday,
    friday: params.friday, saturday: params.saturday, sunday: params.sunday};

    if (data.weekday) {
        data[data.weekday] = true;
    }

    data.regularity = data.regularity.replace('-', '');

    var insertOpenMicStatement = 'INSERT INTO openmic(name, regularity, comedian, poet, ' +
    'musician, contact_email_address, contact_phone_number, venue_name, venue_address, state, city, sign_up_time, ' +
    'start_time, is_free, next_openmic_date, notes, monday, tuesday, wednesday, thursday, friday, saturday, sunday) ' +
    'VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23)';

    db.none(insertOpenMicStatement, [data.name, data.regularity, data.comedian, data.poet, data.musician,
                                    data.contact_email_address, data.contact_phone_number, data.venue_name,
                                    data.venue_address, data.state, data.city, data.sign_up_time, data.start_time,
                                    data.is_free, data.next_openmic_day, data.notes, data.monday, data.tuesday,
                                    data.wednesday, data.thursday, data.friday, data.saturday, data.sunday])
        .then(function () {
            console.log('success!')
        })
        .catch(function (error) {
            console.log(error);
        });

  res.json({ title: 'some open mic' });
});

router.post('/api/openmic/update', function(req, res) {
    var params = req.body;
    var data = {name: params.openmic.openMicName, weekday : params.openmic.openMicWeekDay,
        regularity : params.openmic.openMicRegularity, comedian: params.openmic.comedians, poet: params.openmic.poets, musician: params.openmic.musicians,
        contact_email_address: params.openmic.contactEmailAddress, contact_phone_number: params.openmic.contactPhoneNumber,
        venue_name: params.openmic.venueName, venue_address: params.openmic.venueAddress, state: params.openmic.state, city: params.openmic.city,
        sign_up_time: params.openmic.signUpTime, start_time: params.openmic.startTime, is_free: params.openmic.isOpenMicFree,
        next_openmic_day: params.openmic.nextOpenMicDate, notes: params.openmic.otherNotes, monday: params.openmic.monday,
        tuesday: params.openmic.tuesday, wednesday: params.openmic.wednesday, thursday: params.openmic.thursday,
        friday: params.openmic.friday, saturday: params.openmic.saturday, sunday: params.openmic.sunday, id: params.id};

    if (data.weekday) {
        data[data.weekday] = true;
    }

    data.regularity = data.regularity.replace('-', '');

    for (var key in data) {
        if (data.hasOwnProperty(key) && typeof data[key] === 'undefined') {
            data[key] = false;
        }
    }

    var updateOpenMicStatement = 'UPDATE openmic SET (name, regularity, comedian, poet, ' +
        'musician, contact_email_address, contact_phone_number, venue_name, venue_address, state, city, sign_up_time, ' +
        'start_time, is_free, next_openmic_date, notes, monday, tuesday, wednesday, thursday, friday, saturday, sunday) = ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, ' +
        '$14, $15, $16, $17, $18, $19, $20, $21, $22, $23) WHERE id = $24';

    db.none(updateOpenMicStatement, [data.name, data.regularity,
            data.comedian, data.poet, data.musician, data.contact_email_address,
            data.contact_phone_number, data.venue_name, data.venue_address, data.state,
            data.city, data.sign_up_time, data.start_time, data.is_free,
            new Date(data.next_openmic_day), data.notes, data.monday, data.tuesday,
            data.wednesday, data.thursday, data.friday, data.saturday, data.sunday, data.id])
        .then(function () {
            console.log('success!')
        })
        .catch(function (error) {
            console.log(error);
        });

    res.json({ title: 'some open mic' });
});

router.post('/api/openmic/flagForDeletion', function(req, res) {
    var params = req.body;
    var flagOpenMicForDeletionStatement = 'UPDATE openmic SET deletion_requests = deletion_requests + 1 ' +
        'WHERE id = $1';

    db.none(flagOpenMicForDeletionStatement, [params.id])
        .then(function () {
            console.log('success!')
        })
        .catch(function (error) {
            console.log(error);
        });

    res.json({'title': 'flagged this open mic for deletion'});
});

function isOpenMicRelevantToDate(openmic, date) {
  var dateMoment = moment(date);
  var runningDate = moment(openmic.next_openmic_date);
  var regularity = openmic.regularity;
  if (regularity === 'weekly') {
      var weekday = date.format('dddd').toLowerCase();
      if (openmic[weekday] && (dateMoment.isAfter(runningDate, 'day') || dateMoment.isSame(runningDate, 'day'))) {
          return true;
      }
  }

  while(runningDate.isBefore(dateMoment)) {
    if (runningDate.isSame(dateMoment, 'day')){
      return true;
    }

    switch (regularity) {
      case "weekly":
        runningDate.add(7, 'days');
        break;
      case "bi-weekly":
      case "biweekly":
        runningDate.add(14, 'days');
        break;
      case "monthly":
        runningDate.add(1, 'months');
        break;
      default:
        console.log("Unrecognized openmic regularity found.");
    }
  }

  return false;
}

function compareMoments(result1, result2) {
    var moment1 = moment(result1.dateMoment);
    var moment2 = moment(result2.dateMoment);
    if (moment1.isBefore(moment2)) {
        return -1;
    }
    if (moment1.isAfter(moment2)) {
        return 1;
    }

    return 0;
}

router.get('/api/openmic/listForCity', function(req, res) {
    var params = req.query;
    var data = {city: params.city, state: params.state, date: moment()};
    var originalDateMoment = moment(data.date);
    var dateMoment = originalDateMoment.clone();
    var openmicsByDate = [];
    var openMicsPromises = [];

    var createOpenMicPromise = function(openmicPromises, openmicsByDate, data, dateMoment){
        var _this = this;
        _this.dateMomentClone = dateMoment.clone();
        var dbPromise = getOpenMicsForDate(data.city, data.state, _this.dateMomentClone);
        openMicsPromises.push(dbPromise);
        dbPromise.then(function(openMicResults){
            var dateSection = {
                dateMoment: _this.dateMomentClone,
                date: _this.dateMomentClone.format("dddd, MMMM Do YYYY"),
                id: _this.dateMomentClone.unix(),
                openmics: openMicResults
            };
            openmicsByDate.push(dateSection);
        });

        dateMoment.add(1, 'days');
    };

    for (var i = 0; i < 14; i ++) {
        var boundClosure = createOpenMicPromise.bind({});
            boundClosure(openMicsPromises, openmicsByDate, data, dateMoment);
    }

    Promise.all(openMicsPromises).then(function() {
        openmicsByDate.sort(compareMoments);
        return res.json(openmicsByDate);
    });
});

function getOpenMicsForDate(city, state, date) {
  var selectOpenMicByCity = 'SELECT * FROM openmic WHERE LOWER(city) = LOWER($1) AND state = $2';
  var updateNextOpenMicDate = 'UPDATE openmic SET next_openmic_date = $1 WHERE id = $2';

    return db.query(selectOpenMicByCity, [city, abbrState(state, 'abbr')]).then(function(openmicsInTown){
      var openMicsForDate = openmicsInTown.filter(function(openmic) {
          return isOpenMicRelevantToDate(openmic, date);
      });

      var iscurrentDate = date.isSame(new Date(), "day");
      if (openMicsForDate.length && iscurrentDate) {
          openMicsForDate.forEach(function(openmic){
              db.none(updateNextOpenMicDate, [date.startOf('day'), openmic.id]);
          });
      }

      return openMicsForDate;
  });
}

function abbrState(input, to){

    var states = [
        ['Alabama', 'AL'],
        ['Alaska', 'AK'],
        ['Arizona', 'AZ'],
        ['Arkansas', 'AR'],
        ['California', 'CA'],
        ['Colorado', 'CO'],
        ['Connecticut', 'CT'],
        ['Delaware', 'DE'],
        ['Florida', 'FL'],
        ['Georgia', 'GA'],
        ['Hawaii', 'HI'],
        ['Idaho', 'ID'],
        ['Illinois', 'IL'],
        ['Indiana', 'IN'],
        ['Iowa', 'IA'],
        ['Kansas', 'KS'],
        ['Kentucky', 'KY'],
        ['Kentucky', 'KY'],
        ['Louisiana', 'LA'],
        ['Maine', 'ME'],
        ['Maryland', 'MD'],
        ['Massachusetts', 'MA'],
        ['Michigan', 'MI'],
        ['Minnesota', 'MN'],
        ['Mississippi', 'MS'],
        ['Missouri', 'MO'],
        ['Montana', 'MT'],
        ['Nebraska', 'NE'],
        ['Nevada', 'NV'],
        ['New Hampshire', 'NH'],
        ['New Jersey', 'NJ'],
        ['New Mexico', 'NM'],
        ['New York', 'NY'],
        ['North Carolina', 'NC'],
        ['North Dakota', 'ND'],
        ['Ohio', 'OH'],
        ['Oklahoma', 'OK'],
        ['Oregon', 'OR'],
        ['Pennsylvania', 'PA'],
        ['Rhode Island', 'RI'],
        ['South Carolina', 'SC'],
        ['South Dakota', 'SD'],
        ['Tennessee', 'TN'],
        ['Texas', 'TX'],
        ['Utah', 'UT'],
        ['Vermont', 'VT'],
        ['Virginia', 'VA'],
        ['Washington', 'WA'],
        ['West Virginia', 'WV'],
        ['Wisconsin', 'WI'],
        ['Wyoming', 'WY'],
    ];

    if (to === 'abbr'){
        input = input.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
        for(i = 0; i < states.length; i++){
            if(states[i][0] == input){
                return(states[i][1]);
            }
        }
    } else if (to === 'name'){
        input = input.toUpperCase();
        for(i = 0; i < states.length; i++){
            if(states[i][1] == input){
                return(states[i][0]);
            }
        }
    }
}

module.exports = router;
<commit_msg>changing connection string<commit_after>var express = require('express');
var router = express.Router();
var moment = require('moment');
var promise = require('bluebird');
var options = {
    promiseLib: promise
};

var pgp = require('pg-promise')(options);
var connectionString = {
    //host: 'localhost',
    host: process.env.DATABASE_URL,
    port: 5432,
    database: 'openmicnight',
    user: 'openmicer'
};

//var db = pgp(connectionString);
var db = pgp(process.env.DATABASE_URL);

router.post('/api/openmic/save', function(req, res) {
//TODO don't save if this openmic already exists
  var params = req.body;
  var data = {name: params.openMicName, weekday : params.openMicWeekDay,
    regularity : params.openMicRegularity, comedian: params.comedians, poet: params.poets, musician: params.musicians,
    contact_email_address: params.contactEmailAddress, contact_phone_number: params.contactPhoneNumber,
    venue_name: params.venueName, venue_address: params.venueAddress, state: params.state, city: params.city,
    sign_up_time: params.signUpTime, start_time: params.startTime, is_free: params.isOpenMicFree,
    next_openmic_day: params.nextOpenMicDate, notes: params.notes, monday: params.monday,
    tuesday: params.tuesday, wednesday: params.wednesday, thursday: params.thursday,
    friday: params.friday, saturday: params.saturday, sunday: params.sunday};

    if (data.weekday) {
        data[data.weekday] = true;
    }

    data.regularity = data.regularity.replace('-', '');

    var insertOpenMicStatement = 'INSERT INTO openmic(name, regularity, comedian, poet, ' +
    'musician, contact_email_address, contact_phone_number, venue_name, venue_address, state, city, sign_up_time, ' +
    'start_time, is_free, next_openmic_date, notes, monday, tuesday, wednesday, thursday, friday, saturday, sunday) ' +
    'VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23)';

    db.none(insertOpenMicStatement, [data.name, data.regularity, data.comedian, data.poet, data.musician,
                                    data.contact_email_address, data.contact_phone_number, data.venue_name,
                                    data.venue_address, data.state, data.city, data.sign_up_time, data.start_time,
                                    data.is_free, data.next_openmic_day, data.notes, data.monday, data.tuesday,
                                    data.wednesday, data.thursday, data.friday, data.saturday, data.sunday])
        .then(function () {
            console.log('success!')
        })
        .catch(function (error) {
            console.log(error);
        });

  res.json({ title: 'some open mic' });
});

router.post('/api/openmic/update', function(req, res) {
    var params = req.body;
    var data = {name: params.openmic.openMicName, weekday : params.openmic.openMicWeekDay,
        regularity : params.openmic.openMicRegularity, comedian: params.openmic.comedians, poet: params.openmic.poets, musician: params.openmic.musicians,
        contact_email_address: params.openmic.contactEmailAddress, contact_phone_number: params.openmic.contactPhoneNumber,
        venue_name: params.openmic.venueName, venue_address: params.openmic.venueAddress, state: params.openmic.state, city: params.openmic.city,
        sign_up_time: params.openmic.signUpTime, start_time: params.openmic.startTime, is_free: params.openmic.isOpenMicFree,
        next_openmic_day: params.openmic.nextOpenMicDate, notes: params.openmic.otherNotes, monday: params.openmic.monday,
        tuesday: params.openmic.tuesday, wednesday: params.openmic.wednesday, thursday: params.openmic.thursday,
        friday: params.openmic.friday, saturday: params.openmic.saturday, sunday: params.openmic.sunday, id: params.id};

    if (data.weekday) {
        data[data.weekday] = true;
    }

    data.regularity = data.regularity.replace('-', '');

    for (var key in data) {
        if (data.hasOwnProperty(key) && typeof data[key] === 'undefined') {
            data[key] = false;
        }
    }

    var updateOpenMicStatement = 'UPDATE openmic SET (name, regularity, comedian, poet, ' +
        'musician, contact_email_address, contact_phone_number, venue_name, venue_address, state, city, sign_up_time, ' +
        'start_time, is_free, next_openmic_date, notes, monday, tuesday, wednesday, thursday, friday, saturday, sunday) = ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, ' +
        '$14, $15, $16, $17, $18, $19, $20, $21, $22, $23) WHERE id = $24';

    db.none(updateOpenMicStatement, [data.name, data.regularity,
            data.comedian, data.poet, data.musician, data.contact_email_address,
            data.contact_phone_number, data.venue_name, data.venue_address, data.state,
            data.city, data.sign_up_time, data.start_time, data.is_free,
            new Date(data.next_openmic_day), data.notes, data.monday, data.tuesday,
            data.wednesday, data.thursday, data.friday, data.saturday, data.sunday, data.id])
        .then(function () {
            console.log('success!')
        })
        .catch(function (error) {
            console.log(error);
        });

    res.json({ title: 'some open mic' });
});

router.post('/api/openmic/flagForDeletion', function(req, res) {
    var params = req.body;
    var flagOpenMicForDeletionStatement = 'UPDATE openmic SET deletion_requests = deletion_requests + 1 ' +
        'WHERE id = $1';

    db.none(flagOpenMicForDeletionStatement, [params.id])
        .then(function () {
            console.log('success!')
        })
        .catch(function (error) {
            console.log(error);
        });

    res.json({'title': 'flagged this open mic for deletion'});
});

function isOpenMicRelevantToDate(openmic, date) {
  var dateMoment = moment(date);
  var runningDate = moment(openmic.next_openmic_date);
  var regularity = openmic.regularity;
  if (regularity === 'weekly') {
      var weekday = date.format('dddd').toLowerCase();
      if (openmic[weekday] && (dateMoment.isAfter(runningDate, 'day') || dateMoment.isSame(runningDate, 'day'))) {
          return true;
      }
  }

  while(runningDate.isBefore(dateMoment)) {
    if (runningDate.isSame(dateMoment, 'day')){
      return true;
    }

    switch (regularity) {
      case "weekly":
        runningDate.add(7, 'days');
        break;
      case "bi-weekly":
      case "biweekly":
        runningDate.add(14, 'days');
        break;
      case "monthly":
        runningDate.add(1, 'months');
        break;
      default:
        console.log("Unrecognized openmic regularity found.");
    }
  }

  return false;
}

function compareMoments(result1, result2) {
    var moment1 = moment(result1.dateMoment);
    var moment2 = moment(result2.dateMoment);
    if (moment1.isBefore(moment2)) {
        return -1;
    }
    if (moment1.isAfter(moment2)) {
        return 1;
    }

    return 0;
}

router.get('/api/openmic/listForCity', function(req, res) {
    var params = req.query;
    var data = {city: params.city, state: params.state, date: moment()};
    var originalDateMoment = moment(data.date);
    var dateMoment = originalDateMoment.clone();
    var openmicsByDate = [];
    var openMicsPromises = [];

    var createOpenMicPromise = function(openmicPromises, openmicsByDate, data, dateMoment){
        var _this = this;
        _this.dateMomentClone = dateMoment.clone();
        var dbPromise = getOpenMicsForDate(data.city, data.state, _this.dateMomentClone);
        openMicsPromises.push(dbPromise);
        dbPromise.then(function(openMicResults){
            var dateSection = {
                dateMoment: _this.dateMomentClone,
                date: _this.dateMomentClone.format("dddd, MMMM Do YYYY"),
                id: _this.dateMomentClone.unix(),
                openmics: openMicResults
            };
            openmicsByDate.push(dateSection);
        });

        dateMoment.add(1, 'days');
    };

    for (var i = 0; i < 14; i ++) {
        var boundClosure = createOpenMicPromise.bind({});
            boundClosure(openMicsPromises, openmicsByDate, data, dateMoment);
    }

    Promise.all(openMicsPromises).then(function() {
        openmicsByDate.sort(compareMoments);
        return res.json(openmicsByDate);
    });
});

function getOpenMicsForDate(city, state, date) {
  var selectOpenMicByCity = 'SELECT * FROM openmic WHERE LOWER(city) = LOWER($1) AND state = $2';
  var updateNextOpenMicDate = 'UPDATE openmic SET next_openmic_date = $1 WHERE id = $2';

    return db.query(selectOpenMicByCity, [city, abbrState(state, 'abbr')]).then(function(openmicsInTown){
      var openMicsForDate = openmicsInTown.filter(function(openmic) {
          return isOpenMicRelevantToDate(openmic, date);
      });

      var iscurrentDate = date.isSame(new Date(), "day");
      if (openMicsForDate.length && iscurrentDate) {
          openMicsForDate.forEach(function(openmic){
              db.none(updateNextOpenMicDate, [date.startOf('day'), openmic.id]);
          });
      }

      return openMicsForDate;
  });
}

function abbrState(input, to){

    var states = [
        ['Alabama', 'AL'],
        ['Alaska', 'AK'],
        ['Arizona', 'AZ'],
        ['Arkansas', 'AR'],
        ['California', 'CA'],
        ['Colorado', 'CO'],
        ['Connecticut', 'CT'],
        ['Delaware', 'DE'],
        ['Florida', 'FL'],
        ['Georgia', 'GA'],
        ['Hawaii', 'HI'],
        ['Idaho', 'ID'],
        ['Illinois', 'IL'],
        ['Indiana', 'IN'],
        ['Iowa', 'IA'],
        ['Kansas', 'KS'],
        ['Kentucky', 'KY'],
        ['Kentucky', 'KY'],
        ['Louisiana', 'LA'],
        ['Maine', 'ME'],
        ['Maryland', 'MD'],
        ['Massachusetts', 'MA'],
        ['Michigan', 'MI'],
        ['Minnesota', 'MN'],
        ['Mississippi', 'MS'],
        ['Missouri', 'MO'],
        ['Montana', 'MT'],
        ['Nebraska', 'NE'],
        ['Nevada', 'NV'],
        ['New Hampshire', 'NH'],
        ['New Jersey', 'NJ'],
        ['New Mexico', 'NM'],
        ['New York', 'NY'],
        ['North Carolina', 'NC'],
        ['North Dakota', 'ND'],
        ['Ohio', 'OH'],
        ['Oklahoma', 'OK'],
        ['Oregon', 'OR'],
        ['Pennsylvania', 'PA'],
        ['Rhode Island', 'RI'],
        ['South Carolina', 'SC'],
        ['South Dakota', 'SD'],
        ['Tennessee', 'TN'],
        ['Texas', 'TX'],
        ['Utah', 'UT'],
        ['Vermont', 'VT'],
        ['Virginia', 'VA'],
        ['Washington', 'WA'],
        ['West Virginia', 'WV'],
        ['Wisconsin', 'WI'],
        ['Wyoming', 'WY'],
    ];

    if (to === 'abbr'){
        input = input.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
        for(i = 0; i < states.length; i++){
            if(states[i][0] == input){
                return(states[i][1]);
            }
        }
    } else if (to === 'name'){
        input = input.toUpperCase();
        for(i = 0; i < states.length; i++){
            if(states[i][1] == input){
                return(states[i][0]);
            }
        }
    }
}

module.exports = router;
<|endoftext|>


<commit_before>if ($("#livepic").length > 0) {
	setInterval(function() {
		$("#livepic").attr("src", "https://kadbudapest.hu/gombcam/igynezkimostakemping.jpg?"+new Date().getTime());
	}, 20000)
}

if ($("#weatherwrap").length > 0) {

	function fillZeros(st){
		if((st.toString().length)<2){
			return "0" + st;
		}
		return st;
	}

	function K2C(kelvin) {
		return Math.round(kelvin-273.15);
	}

	function mps2kmph(mps) {
		return Math.round(36*mps)/10;
	}

	function deg2et(deg) {
		if (deg <= 22.5 || deg >= 337.5) {
			return "észak";
		} else if (deg <= 67.5) {
			return "északkelet";
		} else if (deg <= 112.5) {
			return "kelet";
		} else if (deg <= 157.5) {
			return "délkelet"
		} else if (deg <= 202.5) {
			return "dél";
		} else if (deg <= 247.5) {
			return "délnyugat";
		} else if (deg <= 292.5) {
			return "nyugat";
		} else if (deg <= 337.5) {
			return "északnyugat";
		}
	}

	function renderWeather(wData) {
		var wIconWrap = document.getElementById("weatherimage");
		while (wIconWrap.firstChild) {
			wIconWrap.removeChild(wIconWrap.firstChild);
		}
		var imgNode = document.createElement("IMG");
		imgNode.setAttribute("class", "weatherimage-image");
		imgNode.setAttribute("src", "http://openweathermap.org/img/w/" + wData.weather[0].icon + ".png");
		wIconWrap.appendChild(imgNode);

		var wTemp = document.getElementById("weathertemp");
		wTemp.innerHTML = K2C(wData.main.temp) + " ℃";

		var wPressure = document.getElementById("weatherpressure");
		wPressure.innerHTML = "Légnyomás
" + (wData.main.sea_level || wData.main.pressure) + " hPa";

		var wHumid = document.getElementById("weatherhumidity");
		wHumid.innerHTML = "Páratartalom
" + wData.main.humidity + "%";

		var wWind = document.getElementById("weatherwind");
		wWind.innerHTML = "Szélsebesség
" + mps2kmph(wData.wind.speed) + " km/h";

		var wWindDir = document.getElementById("weatherwinddir");
		wWindDir.innerHTML = "Szélirány
" + deg2et(wData.wind.deg) + "";

		var wSunR = document.getElementById("weathersunrise");
		var wSunS = document.getElementById("weathersunset");
		var sunRise = new Date(parseInt(wData.sys.sunrise*1000));
		var sunSet = new Date(wData.sys.sunset*1000);
		wSunR.innerHTML = "Napkelte
" + fillZeros(sunRise.getHours()) + ":" + fillZeros(sunRise.getMinutes()) + "";
		wSunS.innerHTML = "Naplemente
" + fillZeros(sunSet.getHours()) + ":" + fillZeros(sunSet.getMinutes()) + "";
	}

	function updateWeather() {
		var xmlhttp=new XMLHttpRequest();
		var rnsr = Math.round(Math.random()*19182);
		xmlhttp.open("GET", 'https://kadbudapest.hu/cachemeteo/');
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState === 4) {
				if (xmlhttp.status === 200) {
					var wData = JSON.parse(xmlhttp.responseText);
					renderWeather(wData);
				} else {
					console.log('News download error: ' + xmlhttp.statusText )
				}
			}
		}
		xmlhttp.send();
	}

	updateWeather();

	setInterval(function() {
		updateWeather();
	}, 200000)
}

<commit_msg>return something if no wind direction is present<commit_after>if ($("#livepic").length > 0) {
	setInterval(function() {
		$("#livepic").attr("src", "https://kadbudapest.hu/gombcam/igynezkimostakemping.jpg?"+new Date().getTime());
	}, 20000)
}

if ($("#weatherwrap").length > 0) {

	function fillZeros(st){
		if((st.toString().length)<2){
			return "0" + st;
		}
		return st;
	}

	function K2C(kelvin) {
		return Math.round(kelvin-273.15);
	}

	function mps2kmph(mps) {
		return Math.round(36*mps)/10;
	}

	function deg2et(deg) {
		if (!deg) {
			return "össze-vissza";
		} else if (deg <= 22.5 || deg >= 337.5) {
			return "észak";
		} else if (deg <= 67.5) {
			return "északkelet";
		} else if (deg <= 112.5) {
			return "kelet";
		} else if (deg <= 157.5) {
			return "délkelet"
		} else if (deg <= 202.5) {
			return "dél";
		} else if (deg <= 247.5) {
			return "délnyugat";
		} else if (deg <= 292.5) {
			return "nyugat";
		} else if (deg <= 337.5) {
			return "északnyugat";
		}
	}

	function renderWeather(wData) {
		var wIconWrap = document.getElementById("weatherimage");
		while (wIconWrap.firstChild) {
			wIconWrap.removeChild(wIconWrap.firstChild);
		}
		var imgNode = document.createElement("IMG");
		imgNode.setAttribute("class", "weatherimage-image");
		imgNode.setAttribute("src", "http://openweathermap.org/img/w/" + wData.weather[0].icon + ".png");
		wIconWrap.appendChild(imgNode);

		var wTemp = document.getElementById("weathertemp");
		wTemp.innerHTML = K2C(wData.main.temp) + " ℃";

		var wPressure = document.getElementById("weatherpressure");
		wPressure.innerHTML = "Légnyomás
" + (wData.main.sea_level || wData.main.pressure) + " hPa";

		var wHumid = document.getElementById("weatherhumidity");
		wHumid.innerHTML = "Páratartalom
" + wData.main.humidity + "%";

		var wWind = document.getElementById("weatherwind");
		wWind.innerHTML = "Szélsebesség
" + mps2kmph(wData.wind.speed) + " km/h";

		var wWindDir = document.getElementById("weatherwinddir");
		wWindDir.innerHTML = "Szélirány
" + deg2et(wData.wind.deg) + "";

		var wSunR = document.getElementById("weathersunrise");
		var wSunS = document.getElementById("weathersunset");
		var sunRise = new Date(parseInt(wData.sys.sunrise*1000));
		var sunSet = new Date(wData.sys.sunset*1000);
		wSunR.innerHTML = "Napkelte
" + fillZeros(sunRise.getHours()) + ":" + fillZeros(sunRise.getMinutes()) + "";
		wSunS.innerHTML = "Naplemente
" + fillZeros(sunSet.getHours()) + ":" + fillZeros(sunSet.getMinutes()) + "";
	}

	function updateWeather() {
		var xmlhttp=new XMLHttpRequest();
		var rnsr = Math.round(Math.random()*19182);
		xmlhttp.open("GET", 'https://kadbudapest.hu/cachemeteo/');
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState === 4) {
				if (xmlhttp.status === 200) {
					var wData = JSON.parse(xmlhttp.responseText);
					renderWeather(wData);
				} else {
					console.log('News download error: ' + xmlhttp.statusText )
				}
			}
		}
		xmlhttp.send();
	}

	updateWeather();

	setInterval(function() {
		updateWeather();
	}, 200000)
}

<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const webpack = require('webpack');

const version = require('../package.json').version;
const license = require('./license-template');
const header = `
/*!
@fileoverview gl-matrix - High performance matrix and vector operations
@author Brandon Jones
@author Colin MacKenzie IV
@version ${version}

${license}

*/`;

module.exports = {
  entry: './src/gl-matrix.js',
  mode: 'development',
  output: {
    path: path.join(process.cwd(), 'dist'),
    filename: 'gl-matrix.js',
    libraryTarget: 'umd',
  },
  module: {
    rules: [{
      test: path.join(process.cwd(), 'src'),
      loader: 'babel-loader',
    }]
  },
  plugins: [
    new webpack.BannerPlugin({ banner: header, raw: true }),
  ]
};
<commit_msg>updating entry file.<commit_after>const fs = require('fs');
const path = require('path');
const webpack = require('webpack');

const version = require('../package.json').version;
const license = require('./license-template');
const header = `
/*!
@fileoverview gl-matrix - High performance matrix and vector operations
@author Brandon Jones
@author Colin MacKenzie IV
@version ${version}

${license}

*/`;

module.exports = {
  entry: path.join(process.cwd(), 'src/gl-matrix.js'),
  mode: 'development',
  output: {
    path: path.join(process.cwd(), 'dist'),
    filename: 'gl-matrix.js',
    libraryTarget: 'umd',
  },
  module: {
    rules: [{
      test: path.join(process.cwd(), 'src'),
      loader: 'babel-loader',
    }]
  },
  plugins: [
    new webpack.BannerPlugin({ banner: header, raw: true }),
  ]
};
<|endoftext|>


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

/* GET home page. */
router.get('/', function (req, res, next) {
  res.sendfile('./views/index.html');
});

module.exports = router;<commit_msg>修改：登陆后刷新页面找不到资源的Bug<commit_after>var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function (req, res, next) {
  res.sendfile('./views/index.html');
});
router.get('/main/*', function (req, res, next) {
  res.sendfile('./views/index.html');
})

module.exports = router;<|endoftext|>