<commit_before>'use strict';

// Declare app level module which depends on views, and components
angular.module('liveJudgingAdmin', [
  'base64',
  'ngResource',
  'ngRoute',
  'ui.bootstrap',
  'liveJudgingAdmin.login',
  'liveJudgingAdmin.event',
  'liveJudgingAdmin.teams',
  'liveJudgingAdmin.judges',
  'liveJudgingAdmin.rubrics',
  'liveJudgingAdmin.categories',
  'liveJudgingAdmin.settings',
  'liveJudgingAdmin.messages'
])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.otherwise({redirectTo: '/login'});
}])

.run(function($rootScope, $location, CurrentUserService) {
  $rootScope.$on('routeChangeStart', function() {
    console.log(CurrentUserService.isLoggedIn());
    if (CurrentUserService.isLoggedIn()) {
      $location.path('/event');
    }
  });

  $rootScope.rootURL = 'http://judging_api.stevedolan.me/';

  $rootScope.hints = new Object();
  $rootScope.hints['beginEvent'] = {'content': 'Click to begin event. Important: Event end time & date must not be expired.', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['mainHeading'] = {'content': 'Default view. Click category to see category view, then click here to return to default view.', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['catHeading'] = {'content': 'Category View. Click here to return to default view.', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['addTeam'] = {'content': '1) Click here to add a team to this event.', 'placement': 'right', 'enabled': false};
  $rootScope.hints['addTeamCategory'] = {'content': '1) Click here to add a team to this category.', 'placement': 'right', 'enabled': false};
  $rootScope.hints['addJudge'] = {'content': '1) Click here to add a judge to this event.', 'placement': 'right', 'enabled': false};
  $rootScope.hints['addJudgeCategory'] = {'content': '1) Click here to add a judge to this category.', 'placement': 'right', 'enabled': false};
  $rootScope.hints['addRubric'] = {'content': '1) Click here to add a rubric to this event.', 'placement': 'right', 'enabled': false};
  $rootScope.hints['addRubricCategory'] = {'content': '1) Click here to add a rubric to this category.', 'placement': 'right', 'enabled': false};
  $rootScope.hints['addCategory'] = {'content': '2) Click here to add a category to this event.', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['dragItem'] = {'content': '3) Drag these items over to the right →', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['destroyItem'] = {'content': '4a) Drop item here to permanently delete it from this event.', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['removeItem'] = {'content': '4b) Drop item here to remove it from selected category.', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['uncategorized'] = {'content': 'Uncategorized items. Cannot interact with.', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['category'] = {'content': '5) Drop item here to add to category. Click to see details. Click cog to edit.', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['organize'] = {'content': 'Organize out-of-place items.', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['notify'] = {'content': 'Send notification to judges.', 'placement': 'right', 'enabled': false};
  $rootScope.enableButtonText = 'Enable Hints';
  $rootScope.enableHints = function() {
    angular.forEach($rootScope.hints, function(hint) {
      hint.enabled = !hint.enabled;
    });
    if ($rootScope.enableButtonText === 'Enable Hints')
      $rootScope.enableButtonText = 'Disable Hints';
    else if ($rootScope.enableButtonText === 'Disable Hints')
      $rootScope.enableButtonText = 'Enable Hints';
  }
  $rootScope.disableHints = function() {
    angular.forEach($rootScope.hints, function(hint) {
      hint.enabled = false;
    });
    $rootScope.enableButtonText = 'Enable Hints';
  }
})

.controller('MainCtrl', ['sessionStorage',
                         '$location',
                         '$rootScope',
                         '$route',
                         '$routeParams',
                         '$scope',
                         'CurrentUserService',
                         'LogoutService',
    function(sessionStorage, $location, $rootScope, $route, $routeParams, $scope, CurrentUserService, LogoutService) {
        $scope.$on('$routeChangeSuccess', function() {
            $scope.currentPath = $location.path();
        });

    $scope.$on('$locationChangeStart', function(event, next, current) {
      if ($location.path() !== '/login' && !sessionStorage.getObject('current_user')) {
        event.preventDefault();
        // Occassionally preventDefault() would
        // still allow part of the page to load.
        $location.path('/login');
      }
    });

    // Used to determine if the sidebar should be hidden.
    $scope.isDashboard = function() {
      if ($scope.currentPath === '/login' || $scope.currentPath === '/eventSelect' || !sessionStorage.get('selected_event')) {
        return false;
      }
      return true;
    }

    $scope.$on('loggedIn', function() {
      $scope.user = CurrentUserService.getCurrentUser();
    });

    $scope.$watch(function() {
      return CurrentUserService.getCurrentUser();
    }, function(newVal, oldVal) {
      $scope.user = newVal;
    });

    $scope.goToChangeEvent = function() {
      $location.path('/eventSelect');
    }

    $scope.logout = CurrentUserService.logout;
}])

.factory('sessionStorage', ['$window',
  function($window) {
    var sessionStorage = {};

    sessionStorage.putObject = function(key, value) {
      var stringValue = JSON.stringify(value);
      $window.sessionStorage.setItem(key, stringValue);
    }

    sessionStorage.put = function(key, value) {
      $window.sessionStorage.setItem(key, value);
    }

    sessionStorage.getObject = function(key) {
      var stringValue = $window.sessionStorage.getItem(key);
      if (stringValue == "undefined") {
        return undefined;
      }
      return JSON.parse(stringValue);
    }

    sessionStorage.get = function(key) {
      return $window.sessionStorage.getItem(key);
    }

    sessionStorage.remove = function(key) {
      $window.sessionStorage.removeItem(key);
    }

    sessionStorage.clear = function() {
      $window.sessionStorage.clear();
    }

    sessionStorage.clearAllButUser = function() {
        var user = sessionStorage.getObject('current_user');
        sessionStorage.clear();
        sessionStorage.putObject('current_user', user);
    }

    return sessionStorage;
  }
])

.directive('cngWrapWord', function() {
    return {
        restrict: 'A',
        scope: {
            word: '@word',
            lineWidth: '@lineWidth',
            totalWidth: '@totalWidth'
        },
        link: function(scope, elem, attrs) {
            var wrappedWord = '';
            for (var i = 0; i < scope.word.length; i++) {
                if (i < scope.totalWidth) {
                    wrappedWord += scope.word.charAt(i);
                    if (i !== 0 && i % scope.lineWidth === 0)
                        wrappedWord += '-
';
                } else {
                    wrappedWord += '...';
                    break;
                }
            }
            elem.html(wrappedWord);
        }
    }
})

.directive('cngDraggableItem', ['$timeout', function($timeout) {

    return {
        restrict: 'A',
        scope: {
            cog: '@',
            isTransferable: '@isTransferable'
        },
        link: function(scope, elem, attrs) {
            elem.data('isTransferable', scope.isTransferable === 'true');

            elem.draggable({
                appendTo: 'body',
								containment: 'document',
                cursor: 'grab',
                start: function(event, ui) {
										$(this).css('zIndex', '100');
										$(this).draggable('option', 'cursorAt', {
											left: Math.floor(ui.helper.width() / 2),
											top: Math.floor(ui.helper.height() / 2)
										});
                },
                stop: function(event, ui) {
                  $('[cng-draggable-item]').each(function() {
                    $(this).css('zIndex', '1');
                  });
                  $(this).css('zIndex', '2');
                }
            });

            var cog = elem.find(scope.cog);
            var timeout = null;

            elem.bind('mouseenter', function() {
              cog.show();
							elem.data('isDragged', true).trigger('changeDragged');
						});

						elem.bind('mouseleave', function() {
              cog.hide();
							elem.data('isDragged', false).trigger('changeDragged');
						});

            elem.on('changeDragged', function() {
              if (!elem.data('isDragged'))
                timeout = setTimeout(function() {elem.goBack()}, 3000);
              else if (elem.data('isDragged') && timeout !== null)
                clearTimeout(timeout);
            });

            $.fn.goBack = function() {
              if ($(this).is('[cng-draggable-item]')) {
                $(this).animate({
                    'left': '0px',
                    'top': '0px'
                }, 500);
              }
            }
        }
    }

}])

.directive('cngOrganizeItems', function() {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
            elem.bind('click', function() {
                $('[cng-draggable-item]').each(function() {
                    $(this).goBack();
                });
            });
        }
    }
})

.directive('generalErrorMessage', ['$timeout', 'sessionStorage', function($timeout, sessionStorage) {
	return {
		restrict: 'A',
		scope: {
			animate: '@animate',
			color: '@color'
		},
		link: function(scope, elem, attrs) {
			elem.css('float', 'right');
			elem.css('color', scope.color);
			scope.$watch(function() {
				return sessionStorage.get('generalErrorMessage');
			}, function(newValue) {
				if (scope.animate == 'true') {
                  if (newValue !== '') {
                    elem.html(newValue);
                    $timeout(function() {
                      elem.html('');
                      sessionStorage.put('generalErrorMessage', '');
                    }, 5000);
                  }
                } else {
                    elem.html(newValue);
                }
			}, true);
		}
	}
}])

.directive('customPopover', function() {
  return {
    restrict: 'A',
    scope: {
      popoverContent: '@',
      popoverPlacement: '@',
      popoverToggle: '@',
			popoverLimit: '@'
    },
    link: function(scope, elem, attrs) {
			if (scope.popoverLimit !== undefined && scope.popoverLimit == 'false')
				return;
      elem.popover({
        animation: true,
        content: scope.popoverContent,
        html: true,
        placement: scope.popoverPlacement,
        trigger: 'manual'
      });
      elem.bind('mouseover', function() {
        scope.$apply();
        elem.popover('hide');
      });
      scope.$watch(function() {
        return scope.popoverToggle;
      }, function(newValue) {
        if (newValue == 'true') {
          elem.popover('show');
        } else if (newValue == 'false')
          elem.popover('hide');
      });
    }
  }
});
<commit_msg>Updated rootScope base Url.<commit_after>'use strict';

// Declare app level module which depends on views, and components
angular.module('liveJudgingAdmin', [
  'base64',
  'ngResource',
  'ngRoute',
  'ui.bootstrap',
  'liveJudgingAdmin.login',
  'liveJudgingAdmin.event',
  'liveJudgingAdmin.teams',
  'liveJudgingAdmin.judges',
  'liveJudgingAdmin.rubrics',
  'liveJudgingAdmin.categories',
  'liveJudgingAdmin.settings',
  'liveJudgingAdmin.messages'
])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.otherwise({redirectTo: '/login'});
}])

.run(function($rootScope, $location, CurrentUserService) {
  $rootScope.$on('routeChangeStart', function() {
    console.log(CurrentUserService.isLoggedIn());
    if (CurrentUserService.isLoggedIn()) {
      $location.path('/event');
    }
  });

  $rootScope.rootURL = 'http://live-judging-api.fmonteiro.info/';
  console.log($rootScope.rootURL);

  $rootScope.hints = new Object();
  $rootScope.hints['beginEvent'] = {'content': 'Click to begin event. Important: Event end time & date must not be expired.', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['mainHeading'] = {'content': 'Default view. Click category to see category view, then click here to return to default view.', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['catHeading'] = {'content': 'Category View. Click here to return to default view.', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['addTeam'] = {'content': '1) Click here to add a team to this event.', 'placement': 'right', 'enabled': false};
  $rootScope.hints['addTeamCategory'] = {'content': '1) Click here to add a team to this category.', 'placement': 'right', 'enabled': false};
  $rootScope.hints['addJudge'] = {'content': '1) Click here to add a judge to this event.', 'placement': 'right', 'enabled': false};
  $rootScope.hints['addJudgeCategory'] = {'content': '1) Click here to add a judge to this category.', 'placement': 'right', 'enabled': false};
  $rootScope.hints['addRubric'] = {'content': '1) Click here to add a rubric to this event.', 'placement': 'right', 'enabled': false};
  $rootScope.hints['addRubricCategory'] = {'content': '1) Click here to add a rubric to this category.', 'placement': 'right', 'enabled': false};
  $rootScope.hints['addCategory'] = {'content': '2) Click here to add a category to this event.', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['dragItem'] = {'content': '3) Drag these items over to the right →', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['destroyItem'] = {'content': '4a) Drop item here to permanently delete it from this event.', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['removeItem'] = {'content': '4b) Drop item here to remove it from selected category.', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['uncategorized'] = {'content': 'Uncategorized items. Cannot interact with.', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['category'] = {'content': '5) Drop item here to add to category. Click to see details. Click cog to edit.', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['organize'] = {'content': 'Organize out-of-place items.', 'placement': 'bottom', 'enabled': false};
  $rootScope.hints['notify'] = {'content': 'Send notification to judges.', 'placement': 'right', 'enabled': false};
  $rootScope.enableButtonText = 'Enable Hints';
  $rootScope.enableHints = function() {
    angular.forEach($rootScope.hints, function(hint) {
      hint.enabled = !hint.enabled;
    });
    if ($rootScope.enableButtonText === 'Enable Hints')
      $rootScope.enableButtonText = 'Disable Hints';
    else if ($rootScope.enableButtonText === 'Disable Hints')
      $rootScope.enableButtonText = 'Enable Hints';
  }
  $rootScope.disableHints = function() {
    angular.forEach($rootScope.hints, function(hint) {
      hint.enabled = false;
    });
    $rootScope.enableButtonText = 'Enable Hints';
  }
})

.controller('MainCtrl', ['sessionStorage',
                         '$location',
                         '$rootScope',
                         '$route',
                         '$routeParams',
                         '$scope',
                         'CurrentUserService',
                         'LogoutService',
    function(sessionStorage, $location, $rootScope, $route, $routeParams, $scope, CurrentUserService, LogoutService) {
        $scope.$on('$routeChangeSuccess', function() {
            $scope.currentPath = $location.path();
        });

    $scope.$on('$locationChangeStart', function(event, next, current) {
      if ($location.path() !== '/login' && !sessionStorage.getObject('current_user')) {
        event.preventDefault();
        // Occassionally preventDefault() would
        // still allow part of the page to load.
        $location.path('/login');
      }
    });

    // Used to determine if the sidebar should be hidden.
    $scope.isDashboard = function() {
      if ($scope.currentPath === '/login' || $scope.currentPath === '/eventSelect' || !sessionStorage.get('selected_event')) {
        return false;
      }
      return true;
    }

    $scope.$on('loggedIn', function() {
      $scope.user = CurrentUserService.getCurrentUser();
    });

    $scope.$watch(function() {
      return CurrentUserService.getCurrentUser();
    }, function(newVal, oldVal) {
      $scope.user = newVal;
    });

    $scope.goToChangeEvent = function() {
      $location.path('/eventSelect');
    }

    $scope.logout = CurrentUserService.logout;
}])

.factory('sessionStorage', ['$window',
  function($window) {
    var sessionStorage = {};

    sessionStorage.putObject = function(key, value) {
      var stringValue = JSON.stringify(value);
      $window.sessionStorage.setItem(key, stringValue);
    }

    sessionStorage.put = function(key, value) {
      $window.sessionStorage.setItem(key, value);
    }

    sessionStorage.getObject = function(key) {
      var stringValue = $window.sessionStorage.getItem(key);
      if (stringValue == "undefined") {
        return undefined;
      }
      return JSON.parse(stringValue);
    }

    sessionStorage.get = function(key) {
      return $window.sessionStorage.getItem(key);
    }

    sessionStorage.remove = function(key) {
      $window.sessionStorage.removeItem(key);
    }

    sessionStorage.clear = function() {
      $window.sessionStorage.clear();
    }

    sessionStorage.clearAllButUser = function() {
        var user = sessionStorage.getObject('current_user');
        sessionStorage.clear();
        sessionStorage.putObject('current_user', user);
    }

    return sessionStorage;
  }
])

.directive('cngWrapWord', function() {
    return {
        restrict: 'A',
        scope: {
            word: '@word',
            lineWidth: '@lineWidth',
            totalWidth: '@totalWidth'
        },
        link: function(scope, elem, attrs) {
            var wrappedWord = '';
            for (var i = 0; i < scope.word.length; i++) {
                if (i < scope.totalWidth) {
                    wrappedWord += scope.word.charAt(i);
                    if (i !== 0 && i % scope.lineWidth === 0)
                        wrappedWord += '-
';
                } else {
                    wrappedWord += '...';
                    break;
                }
            }
            elem.html(wrappedWord);
        }
    }
})

.directive('cngDraggableItem', ['$timeout', function($timeout) {

    return {
        restrict: 'A',
        scope: {
            cog: '@',
            isTransferable: '@isTransferable'
        },
        link: function(scope, elem, attrs) {
            elem.data('isTransferable', scope.isTransferable === 'true');

            elem.draggable({
                appendTo: 'body',
								containment: 'document',
                cursor: 'grab',
                start: function(event, ui) {
										$(this).css('zIndex', '100');
										$(this).draggable('option', 'cursorAt', {
											left: Math.floor(ui.helper.width() / 2),
											top: Math.floor(ui.helper.height() / 2)
										});
                },
                stop: function(event, ui) {
                  $('[cng-draggable-item]').each(function() {
                    $(this).css('zIndex', '1');
                  });
                  $(this).css('zIndex', '2');
                }
            });

            var cog = elem.find(scope.cog);
            var timeout = null;

            elem.bind('mouseenter', function() {
              cog.show();
							elem.data('isDragged', true).trigger('changeDragged');
						});

						elem.bind('mouseleave', function() {
              cog.hide();
							elem.data('isDragged', false).trigger('changeDragged');
						});

            elem.on('changeDragged', function() {
              if (!elem.data('isDragged'))
                timeout = setTimeout(function() {elem.goBack()}, 3000);
              else if (elem.data('isDragged') && timeout !== null)
                clearTimeout(timeout);
            });

            $.fn.goBack = function() {
              if ($(this).is('[cng-draggable-item]')) {
                $(this).animate({
                    'left': '0px',
                    'top': '0px'
                }, 500);
              }
            }
        }
    }

}])

.directive('cngOrganizeItems', function() {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
            elem.bind('click', function() {
                $('[cng-draggable-item]').each(function() {
                    $(this).goBack();
                });
            });
        }
    }
})

.directive('generalErrorMessage', ['$timeout', 'sessionStorage', function($timeout, sessionStorage) {
	return {
		restrict: 'A',
		scope: {
			animate: '@animate',
			color: '@color'
		},
		link: function(scope, elem, attrs) {
			elem.css('float', 'right');
			elem.css('color', scope.color);
			scope.$watch(function() {
				return sessionStorage.get('generalErrorMessage');
			}, function(newValue) {
				if (scope.animate == 'true') {
                  if (newValue !== '') {
                    elem.html(newValue);
                    $timeout(function() {
                      elem.html('');
                      sessionStorage.put('generalErrorMessage', '');
                    }, 5000);
                  }
                } else {
                    elem.html(newValue);
                }
			}, true);
		}
	}
}])

.directive('customPopover', function() {
  return {
    restrict: 'A',
    scope: {
      popoverContent: '@',
      popoverPlacement: '@',
      popoverToggle: '@',
			popoverLimit: '@'
    },
    link: function(scope, elem, attrs) {
			if (scope.popoverLimit !== undefined && scope.popoverLimit == 'false')
				return;
      elem.popover({
        animation: true,
        content: scope.popoverContent,
        html: true,
        placement: scope.popoverPlacement,
        trigger: 'manual'
      });
      elem.bind('mouseover', function() {
        scope.$apply();
        elem.popover('hide');
      });
      scope.$watch(function() {
        return scope.popoverToggle;
      }, function(newValue) {
        if (newValue == 'true') {
          elem.popover('show');
        } else if (newValue == 'false')
          elem.popover('hide');
      });
    }
  }
});
<|endoftext|>


<commit_before>'use strict';

var async = require('async');
var express = require('express');
var fs = require('fs');
var multiparty = require('multiparty');
var util = require('util');

var nodemailer = require('nodemailer');

/* Make an http server to receive the webhook. */
var server = express();

server.head('/webhook', function (req, res) {
    console.log('Received head request from webhook.');
    res.sendStatus(200);
});

server.post('/webhook', function (req, res) {
    console.log('Receiving webhook.');

    /* Respond early to avoid timouting the mailin server. */
    // res.send(200);

    /* Parse the multipart form. The attachments are parsed into fields and can
     * be huge, so set the maxFieldsSize accordingly. */
    var form = new multiparty.Form({
        maxFieldsSize: 70000000
    });

    form.on('progress', function () {
        var start = Date.now();
        var lastDisplayedPercentage = -1;
        return function (bytesReceived, bytesExpected) {
            var elapsed = Date.now() - start;
            var percentage = Math.floor(bytesReceived / bytesExpected * 100);
            if (percentage % 20 === 0 && percentage !== lastDisplayedPercentage) {
                lastDisplayedPercentage = percentage;
                console.log('Form upload progress ' +
                    percentage + '% of ' + bytesExpected / 1000000 + 'Mb. ' + elapsed + 'ms');
            }
        };
    }());

    form.parse(req, function (err, fields) {
        console.log(util.inspect(fields.mailinMsg, {
            depth: 5
        }));

        console.log('Parsed fields: ' + Object.keys(fields));

        /* Write down the payload for ulterior inspection. */
        async.auto({
            writeParsedMessage: function (cbAuto) {
                fs.writeFile('payload.json', fields.mailinMsg, cbAuto);
            },
            writeAttachments: function (cbAuto) {
                var msg = JSON.parse(fields.mailinMsg);
                async.eachLimit(msg.attachments, 3, function (attachment, cbEach) {
                    fs.writeFile(attachment.generatedFileName, fields[attachment.generatedFileName], 'base64', cbEach);
                }, cbAuto);
            }
        }, function (err) {
            if (err) {
                console.log(err.stack);
                res.sendStatus(500, 'Unable to write payload');
            } else {
                console.log('Webhook payload written.');
                res.sendStatus(200);
                var msg = JSON.parse(fields.mailinMsg);
                if (msg.mailinMsg.to[0].address == 'simon@beardedmail.com') {
                    var nodemailer = require('nodemailer');
                    var transporter = nodemailer.createTransport();
                    transporter.sendMail({
                        from: 'admin@beardedmail.com',
                        to: 'simonhoye@gmail.com',
                        subject: 'You have BeardedMail from <'+msg.mailinMsg.from[0].address + ">",
                        text: msg.mailinMsg.subject,
                        html: msg.mailinMsg.html
                    });
                }

            }
        });
    });
});

server.listen(3000, function (err) {
    if (err) {
        console.log(err);
    } else {
        console.log('Http server listening on port 3000');
    }
});<commit_msg>red wine causes silly mistakes<commit_after>'use strict';

var async = require('async');
var express = require('express');
var fs = require('fs');
var multiparty = require('multiparty');
var util = require('util');

var nodemailer = require('nodemailer');

/* Make an http server to receive the webhook. */
var server = express();

server.head('/webhook', function (req, res) {
    console.log('Received head request from webhook.');
    res.sendStatus(200);
});

server.post('/webhook', function (req, res) {
    console.log('Receiving webhook.');

    /* Respond early to avoid timouting the mailin server. */
    // res.send(200);

    /* Parse the multipart form. The attachments are parsed into fields and can
     * be huge, so set the maxFieldsSize accordingly. */
    var form = new multiparty.Form({
        maxFieldsSize: 70000000
    });

    form.on('progress', function () {
        var start = Date.now();
        var lastDisplayedPercentage = -1;
        return function (bytesReceived, bytesExpected) {
            var elapsed = Date.now() - start;
            var percentage = Math.floor(bytesReceived / bytesExpected * 100);
            if (percentage % 20 === 0 && percentage !== lastDisplayedPercentage) {
                lastDisplayedPercentage = percentage;
                console.log('Form upload progress ' +
                    percentage + '% of ' + bytesExpected / 1000000 + 'Mb. ' + elapsed + 'ms');
            }
        };
    }());

    form.parse(req, function (err, fields) {
        console.log(util.inspect(fields.mailinMsg, {
            depth: 5
        }));

        console.log('Parsed fields: ' + Object.keys(fields));

        /* Write down the payload for ulterior inspection. */
        async.auto({
            writeParsedMessage: function (cbAuto) {
                fs.writeFile('payload.json', fields.mailinMsg, cbAuto);
            },
            writeAttachments: function (cbAuto) {
                var msg = JSON.parse(fields.mailinMsg);
                async.eachLimit(msg.attachments, 3, function (attachment, cbEach) {
                    fs.writeFile(attachment.generatedFileName, fields[attachment.generatedFileName], 'base64', cbEach);
                }, cbAuto);
            }
        }, function (err) {
            if (err) {
                console.log(err.stack);
                res.sendStatus(500, 'Unable to write payload');
            } else {
                console.log('Webhook payload written.');
                res.sendStatus(200);
                var msg = JSON.parse(fields.mailinMsg);
                if (msg.to[0].address == 'simon@beardedmail.com') {
                    var nodemailer = require('nodemailer');
                    var transporter = nodemailer.createTransport();
                    transporter.sendMail({
                        from: 'admin@beardedmail.com',
                        to: 'simonhoye@gmail.com',
                        subject: 'You have BeardedMail from <'+msg.from[0].address + ">",
                        text: msg.subject,
                        html: msg.html
                    });
                }

            }
        });
    });
});

server.listen(3000, function (err) {
    if (err) {
        console.log(err);
    } else {
        console.log('Http server listening on port 3000');
    }
});<|endoftext|>


<commit_before>import React from 'react';
import { Route, IndexRoute } from 'react-router';

import {
	App
} from 'containers';

export default (
	<Route path="/" component={App}>
		<IndexRoute path="link" component={App} />
	</Route>
);<commit_msg>remove path from IndexRoute<commit_after>import React from 'react';
import { Route, IndexRoute } from 'react-router';

import {
	App
} from 'containers';

export default (
	<Route path="/" component={App}>
		<IndexRoute component={App} />
	</Route>
);<|endoftext|>


<commit_before>Ext.namespace('Vps.User.Login');
Vps.User.Login.Dialog = Ext.extend(Ext.Window,
{
    initComponent: function()
    {
        this.height = 160;
        this.width = 310;
        this.modal = true;
        this.title = 'Login';
        this.resizable = false;
        this.closable = false;
        Vps.User.Login.Dialog.superclass.initComponent.call(this);
    },
    afterRender : function()
    {
        Vps.User.Login.Dialog.superclass.afterRender.call(this);
        var frameHtml = '';
        var frame = Ext.DomHelper.append(this.body, frameHtml, true);
        function cb(){
            if(Ext.isIE){
                doc = frame.dom.contentWindow.document;
            }else {
                doc = (frame.dom.contentDocument || window.frames[id].document);
            }
            if(doc && doc.body){
                if (doc.body.innerHTML.match(/successful/)) {
                    this.hide();
                    if (this.location) {
                        location.href = this.location;
                    } else {
                        if(Vps.menu) Vps.menu.reload();
                        if(this.success) {
                            Ext.callback(this.success, this.scope);
                        }
                    }
                }
            }
        }
        Ext.EventManager.on(frame, 'load', cb, this);
    },
    showLogin: function() {
        this.show();
    }
});<commit_msg>login-dialog: focus auf username-feld beim laden<commit_after>Ext.namespace('Vps.User.Login');
Vps.User.Login.Dialog = Ext.extend(Ext.Window,
{
    initComponent: function()
    {
        this.height = 160;
        this.width = 310;
        this.modal = true;
        this.title = 'Login';
        this.resizable = false;
        this.closable = false;
        Vps.User.Login.Dialog.superclass.initComponent.call(this);
    },
    afterRender : function()
    {
        Vps.User.Login.Dialog.superclass.afterRender.call(this);
        var frameHtml = '';
        var frame = Ext.DomHelper.append(this.body, frameHtml, true);
        function cb(){
            if(Ext.isIE){
                doc = frame.dom.contentWindow.document;
            }else {
                doc = (frame.dom.contentDocument || window.frames[id].document);
            }
            if(doc && doc.body){
                if (doc.body.innerHTML.match(/successful/)) {
                    this.hide();
                    if (this.location) {
                        location.href = this.location;
                    } else {
                        if(Vps.menu) Vps.menu.reload();
                        if(this.success) {
                            Ext.callback(this.success, this.scope);
                        }
                    }
                } else {
                    doc.getElementsByName('username')[0].focus();
                }
            }
        }
        Ext.EventManager.on(frame, 'load', cb, this);
    },
    showLogin: function() {
        this.show();
    }
});<|endoftext|>


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

/*
 * Copyright (C) 2019 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

library "canvas-builds-library@${env.CANVAS_BUILDS_REFSPEC}"

def COFFEE_NODE_COUNT = 4
def DEFAULT_NODE_COUNT = 1
def JSG_NODE_COUNT = 3

def copyFiles(dockerName, dockerPath, hostPath) {
  sh "mkdir -vp ./$hostPath"
  sh "docker cp \$(docker ps -qa -f name=$dockerName):/usr/src/app/$dockerPath ./$hostPath"
}

def makeKarmaStage(group, ciNode, ciTotal) {
  return {
    withEnv([
      "CI_NODE_INDEX=${ciNode}",
      "CI_NODE_TOTAL=${ciTotal}",
      "CONTAINER_NAME=tests-karma-${group}-${ciNode}",
      "JSPEC_GROUP=${group}"
    ]) {
      try {
        credentials.withSentryCredentials {
          sh 'build/new-jenkins/js/tests-karma.sh'
        }
      } finally {
        copyFiles(env.CONTAINER_NAME, 'coverage-js', "./tmp/${env.CONTAINER_NAME}")
      }
    }
  }
}

def cleanupFn() {
  timeout(time: 2) {
    if(env.TEST_SUITE != 'upload') {
      archiveArtifacts artifacts: 'tmp/**/*.xml'
      junit "tmp/**/*.xml"
      sh 'find ./tmp -path "*.xml"'
    }
  }
}

def getLoadAllLocales() {
  return configuration.isChangeMerged() ? 1 : 0
}

pipeline {
  agent none
  options {
    ansiColor('xterm')
    timeout(time: 20)
    timestamps()
  }

  environment {
    COMPOSE_DOCKER_CLI_BUILD=1
    COMPOSE_FILE = 'docker-compose.new-jenkins-js.yml'
    DOCKER_BUILDKIT=1
    FORCE_FAILURE = configuration.forceFailureJS()
    PROGRESS_NO_TRUNC=1
    RAILS_LOAD_ALL_LOCALES = getLoadAllLocales()
    SENTRY_URL="https://sentry.insops.net"
    SENTRY_ORG="instructure"
    SENTRY_PROJECT="master-javascript-build"
  }

  stages {
    stage('Environment') {
      steps {
        script {
          protectedNode('canvas-docker', { cleanupFn() }) {
            stage('Setup') {
              timeout(time: 3) {
                sh 'rm -vrf ./tmp/*'
                def refspecToCheckout = env.GERRIT_PROJECT == "canvas-lms" ? env.JENKINSFILE_REFSPEC : env.CANVAS_LMS_REFSPEC

                checkoutRepo("canvas-lms", refspecToCheckout, 1)

                credentials.withStarlordCredentials { ->
                  sh "./build/new-jenkins/docker-with-flakey-network-protection.sh pull $KARMA_RUNNER_IMAGE"
                }
              }
            }

            stage('Run Tests') {
              timeout(time: 10) {
                script {
                  def tests = [:]

                  if(env.TEST_SUITE == 'jest') {
                    tests['Jest'] = {
                      withEnv(['CONTAINER_NAME=tests-jest']) {
                        try {
                          credentials.withSentryCredentials {
                            sh 'build/new-jenkins/js/tests-jest.sh'
                          }
                        } finally {
                          copyFiles(env.CONTAINER_NAME, 'coverage-js', "./tmp/${env.CONTAINER_NAME}")
                        }
                      }
                    }
                  } else if(env.TEST_SUITE == 'coffee') {
                    for(int i = 0; i < COFFEE_NODE_COUNT; i++) {
                      tests["Karma - Spec Group - coffee${i}"] = makeKarmaStage('coffee', i, COFFEE_NODE_COUNT)
                    }
                  } else if(env.TEST_SUITE == 'karma') {
                    tests['Packages'] = {
                      withEnv(['CONTAINER_NAME=tests-packages']) {
                        try {
                          credentials.withSentryCredentials {
                            sh 'build/new-jenkins/js/tests-packages.sh'
                          }
                        } finally {
                          copyFiles(env.CONTAINER_NAME, 'packages', "./tmp/${env.CONTAINER_NAME}")
                        }
                      }
                    }

                    for(int i = 0; i < JSG_NODE_COUNT; i++) {
                      tests["Karma - Spec Group - jsg${i}"] = makeKarmaStage('jsg', i, JSG_NODE_COUNT)
                    }

                    ['jsa', 'jsh'].each { group ->
                      tests["Karma - Spec Group - ${group}"] = makeKarmaStage(group, 0, DEFAULT_NODE_COUNT)
                    }
                  }

                  parallel(tests)
                }
              }
            }
          }
        }
      }
    }
  }
}
<commit_msg>remove cleanupFn usage from JS job<commit_after>#!/usr/bin/env groovy

/*
 * Copyright (C) 2019 - present Instructure, Inc.
 *
 * This file is part of Canvas.
 *
 * Canvas is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, version 3 of the License.
 *
 * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

library "canvas-builds-library@${env.CANVAS_BUILDS_REFSPEC}"

def COFFEE_NODE_COUNT = 4
def DEFAULT_NODE_COUNT = 1
def JSG_NODE_COUNT = 3

def copyFiles(dockerName, dockerPath, hostPath) {
  sh "mkdir -vp ./$hostPath"
  sh "docker cp \$(docker ps -qa -f name=$dockerName):/usr/src/app/$dockerPath ./$hostPath"
}

def makeKarmaStage(group, ciNode, ciTotal) {
  return {
    withEnv([
      "CI_NODE_INDEX=${ciNode}",
      "CI_NODE_TOTAL=${ciTotal}",
      "CONTAINER_NAME=tests-karma-${group}-${ciNode}",
      "JSPEC_GROUP=${group}"
    ]) {
      try {
        credentials.withSentryCredentials {
          sh 'build/new-jenkins/js/tests-karma.sh'
        }
      } finally {
        copyFiles(env.CONTAINER_NAME, 'coverage-js', "./tmp/${env.CONTAINER_NAME}")
      }
    }
  }
}

def cleanupFn() {
  timeout(time: 2) {
    if(env.TEST_SUITE != 'upload') {
      archiveArtifacts artifacts: 'tmp/**/*.xml'
      junit "tmp/**/*.xml"
      sh 'find ./tmp -path "*.xml"'
    }
  }
}

def getLoadAllLocales() {
  return configuration.isChangeMerged() ? 1 : 0
}

pipeline {
  agent none
  options {
    ansiColor('xterm')
    timeout(time: 20)
    timestamps()
  }

  environment {
    COMPOSE_DOCKER_CLI_BUILD=1
    COMPOSE_FILE = 'docker-compose.new-jenkins-js.yml'
    DOCKER_BUILDKIT=1
    FORCE_FAILURE = configuration.forceFailureJS()
    PROGRESS_NO_TRUNC=1
    RAILS_LOAD_ALL_LOCALES = getLoadAllLocales()
    SENTRY_URL="https://sentry.insops.net"
    SENTRY_ORG="instructure"
    SENTRY_PROJECT="master-javascript-build"
  }

  stages {
    stage('Environment') {
      steps {
        script {
          protectedNode('canvas-docker') {
            stage('Setup') {
              timeout(time: 3) {
                sh 'rm -vrf ./tmp/*'
                def refspecToCheckout = env.GERRIT_PROJECT == "canvas-lms" ? env.JENKINSFILE_REFSPEC : env.CANVAS_LMS_REFSPEC

                checkoutRepo("canvas-lms", refspecToCheckout, 1)

                credentials.withStarlordCredentials { ->
                  sh "./build/new-jenkins/docker-with-flakey-network-protection.sh pull $KARMA_RUNNER_IMAGE"
                }
              }
            }

            def postBuildHandler = [
              onStageResult: { _ ->
                cleanupFn()
              }
            ]

            extendedStage('Run Tests').handler(postBuildHandler).execute {
              timeout(time: 10) {
                script {
                  def tests = [:]

                  if(env.TEST_SUITE == 'jest') {
                    tests['Jest'] = {
                      withEnv(['CONTAINER_NAME=tests-jest']) {
                        try {
                          credentials.withSentryCredentials {
                            sh 'build/new-jenkins/js/tests-jest.sh'
                          }
                        } finally {
                          copyFiles(env.CONTAINER_NAME, 'coverage-js', "./tmp/${env.CONTAINER_NAME}")
                        }
                      }
                    }
                  } else if(env.TEST_SUITE == 'coffee') {
                    for(int i = 0; i < COFFEE_NODE_COUNT; i++) {
                      tests["Karma - Spec Group - coffee${i}"] = makeKarmaStage('coffee', i, COFFEE_NODE_COUNT)
                    }
                  } else if(env.TEST_SUITE == 'karma') {
                    tests['Packages'] = {
                      withEnv(['CONTAINER_NAME=tests-packages']) {
                        try {
                          credentials.withSentryCredentials {
                            sh 'build/new-jenkins/js/tests-packages.sh'
                          }
                        } finally {
                          copyFiles(env.CONTAINER_NAME, 'packages', "./tmp/${env.CONTAINER_NAME}")
                        }
                      }
                    }

                    for(int i = 0; i < JSG_NODE_COUNT; i++) {
                      tests["Karma - Spec Group - jsg${i}"] = makeKarmaStage('jsg', i, JSG_NODE_COUNT)
                    }

                    ['jsa', 'jsh'].each { group ->
                      tests["Karma - Spec Group - ${group}"] = makeKarmaStage(group, 0, DEFAULT_NODE_COUNT)
                    }
                  }

                  parallel(tests)
                }
              }
            }
          }
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>import { Component, PropTypes } from "react";
import { connect } from "react-apollo";
import { withRouter, Link } from "react-router";
import gql from "graphql-tag";

import { nav as navActions } from "../../../store";
// import ReactTooltip from "react-tooltip";
// import Truncate from "truncate";

import Split, { Left, Right } from "../../../blocks/split";
import GoogleMap from "../../../components/map";
import Layout from "./ResultLayout";

// HACK
let internalIp = null;
if (Meteor.isClient) {
  // NOTE: window.RTCPeerConnection is "not a constructor" in FF22/23
  const RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;   // compatibility for firefox and chrome

  if (RTCPeerConnection) {
    const pc = new RTCPeerConnection({ iceServers: [] }), noop = function () {};
    pc.createDataChannel("");    // create a bogus data channel
    pc.createOffer(pc.setLocalDescription.bind(pc), noop);    // create offer and set local description
    pc.onicecandidate = function (ice) {  // listen for candidate events
      if (!ice || !ice.candidate || !ice.candidate.candidate) return;
      const myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1];
      internalIp = myIP;
      pc.onicecandidate = noop;
    };
  }
}

const mapStateToProps = ({ routing }) => {
  const { location } = routing;
  const tags = Object.keys(location.query).length && location.query.tags ? location.query.tags : "";
  const q = Object.keys(location.query).length && location.query.q ? location.query.q : null;
  const campus = Object.keys(location.query).length && location.query.campus ? location.query.campus : null;
  const campuses = (
    Object.keys(location.query).length && location.query.campuses ? location.query.campuses : ""
  );
  return { tags, q, location, campuses };
};

const mapQueriesToProps = ({ ownProps }) => ({
  campusLocations: {
    query: gql`
      query GetCampuses { campuses { entityId, id, name } }
    `,
  },
  data: {
    query: gql`
      query GroupFinder($query: String, $tags: [String], $limit: Int, $offset: Int, $ip: String, $campuses: [String]) {
        groups(query: $query, attributes: $tags, limit: $limit, offset: $offset, clientIp: $ip, campuses: $campuses) {
          count
          results {
            id
            name
            entityId
            type
            kidFriendly
            demographic
            description
            photo
            ageRange
            distance
            schedule { description }
            locations { location { latitude, longitude } }
            tags { id, value }
            campus { name, entityId }
          }
        }
      }
    `,
    ssr: false,
    variables: {
      tags: ownProps.tags.split(",").filter(x => x),
      query: ownProps.q,
      ip: internalIp,
      limit: 10,
      offset: 0,
      campuses: ownProps.campuses.split(",").filter(x => x),
    },
  },
});
const defaultArray = [];
@withRouter
@connect({ mapQueriesToProps, mapStateToProps })
export default class Template extends Component {

  state = {
    markers: [],
    showTags: false,
    showSearch: false,
    hover: null,
    groups: [], // XXX after refetchMore lands in apollo client, remove
    offset: 0,
  }

  paginate = () => {
    const { q, tags, campuses } = this.props;
    this.props.data.refetch({
      tags: tags.split(",").filter(x => x),
      campuses: campuses.split(",").filter(x => x),
      query: q,
      limit: 10,
      offset: this.state.offset + 10,
      ip: internalIp,
    })
      .then(({ data }) => {
        const { results } = data.groups;
        this.setState({
          groups: this.state.groups.concat(results),
          offset: this.state.offset + 10,
        });
      });
  }

  componentWillMount() {
    if (this.props.q) this.setState({ showSearch: true });
    this.props.dispatch(navActions.setLevel("BASIC_CONTENT"));

    if (this.props.data.groups) {
      const markers = this.getMarkers(this.props.data.groups.results);
      this.setState({ markers, groups: this.props.data.groups.results });
    }
  }

  onCardHover = (e) => {
    const { id } = e.currentTarget;
    this.setState({ hover: id });
  }

  onMarkerHover = (marker) => {
    this.setState({ hover: marker.id });
  }

  componentWillReceiveProps(nextProps) {
    const newState = {};
    let clear = false;
    if (
      this.props.q !== nextProps.q ||
      this.props.tags !== nextProps.tags ||
      this.props.campuses !== nextProps.campuses
    ) {
      clear = true; // variables have changed
      if (nextProps.data.groups && nextProps.data.groups) {
        newState.groups = nextProps.data.groups.results;
      } else {
        newState.groups = [];
      }
    }

    if (this.props.data.loading && !nextProps.data.loading && !this.state.groups.length) {
      newState.groups = nextProps.data.groups.results;
    }
    newState.markers = this.getMarkers(
      nextProps.data.groups && nextProps.data.groups.results, clear
    );
    this.setState(newState);
  }

  toggleTags = () => this.setState({ showTags: !this.state.showTags })
  toggleSearch = () => this.setState({ showSearch: !this.state.showSearch })

  getMarkers = (groups = [], clear = false) => {
    let { markers } = this.state;
    if (clear) markers = [];
    return _.uniq(markers.concat(groups
      .filter(x => x.locations && x.locations.length && x.locations[0].location)
      .map(x => ({
        latitude: x.locations[0].location.latitude,
        longitude: x.locations[0].location.longitude,
        id: x.id,
        // children: this.createChild(x),
      }))
      .filter(x => x.latitude && x.longitude)
    ), x => x.id);
  }

  removeQueryString = (e) => {
    if (e) e.preventDefault();
    const { location, router } = this.props;

    if (location && location.query && location.query.q) delete location.query.q;
    const newPath = router.createPath(location);
    router.replace(newPath);
  }

  render() {
    const { data, location, tags, campusLocations, campuses, q } = this.props;
    let count, groups = defaultArray;
    if (data.groups && data.groups.count) count = data.groups.count;
    groups = this.state.groups;

    let isMobile;
    if (typeof window != "undefined" && window != null) {
      isMobile = window.matchMedia("(max-width: 768px)").matches;
    }

    return (

        <Split>
          {/* Map */}
          <Right mobile={false} classes={["background--left"]}>
            {(() => {
              if (isMobile || Meteor.isServer) return null;
              return (
                <GoogleMap
                  autoCenter
                  markers={this.state.markers}
                  onMarkerHover={this.onMarkerHover}
                  hover={this.state.hover}
                  onChildClick={({ id }) => this.props.router.push(`/groups/${id}`)}
                />
              );
            })()}
          </Right>
        </Split>
        <Left scroll classes={["background--light-secondary"]}>
          <Layout
              loading={data.loading}
              groups={groups}
              count={count}
              tags={tags && tags.split(",").filter(x => x)}
              campuses={campuses && campuses.split(",").filter(x => x)}
              campusLocations={campusLocations}
              query={q}
              removeQueryString={this.removeQueryString}
              showTags={this.state.showTags}
              toggleTags={this.toggleTags}
              showSearch={this.state.showSearch}
              toggleSearch={this.toggleSearch}
              onCardHover={this.onCardHover}
              paginate={this.paginate}
          />
        </Left>

    );
  }
}
<commit_msg>lint groups result<commit_after>import { Component, PropTypes } from "react";
import { connect } from "react-apollo";
import { withRouter } from "react-router";
import gql from "graphql-tag";

import { nav as navActions } from "../../../store";
// import ReactTooltip from "react-tooltip";
// import Truncate from "truncate";

import Split, { Left, Right } from "../../../blocks/split";
import GoogleMap from "../../../components/map";
import Layout from "./ResultLayout";

// HACK
let internalIp = null;
if (Meteor.isClient) {
  // NOTE: window.RTCPeerConnection is "not a constructor" in FF22/23
  const RTCPeerConnection = window.RTCPeerConnection ||
    window.mozRTCPeerConnection ||
    window.webkitRTCPeerConnection;   // compatibility for firefox and chrome

  if (RTCPeerConnection) {
    const pc = new RTCPeerConnection({ iceServers: [] });
    const noop = () => {};
    // create a bogus data channel
    pc.createDataChannel("");
    // create offer and set local description
    pc.createOffer(pc.setLocalDescription.bind(pc), noop);
    // listen for candidate events
    pc.onicecandidate = (ice) => {
      if (!ice || !ice.candidate || !ice.candidate.candidate) return;
      const myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/
        .exec(ice.candidate.candidate)[1];
      internalIp = myIP;
      pc.onicecandidate = noop;
    };
  }
}

const mapStateToProps = ({ routing }) => {
  const { location } = routing;
  const tags = Object.keys(location.query).length && location.query.tags ? location.query.tags : "";
  const q = Object.keys(location.query).length && location.query.q ? location.query.q : null;
  const campus = Object.keys(location.query).length && location.query.campus ? location.query.campus : null;
  const campuses = (
    Object.keys(location.query).length && location.query.campuses ? location.query.campuses : ""
  );
  return { tags, q, location, campuses };
};

const mapQueriesToProps = ({ ownProps }) => ({
  campusLocations: {
    query: gql`
      query GetCampuses { campuses { entityId, id, name } }
    `,
  },
  data: {
    query: gql`
      query GroupFinder($query: String, $tags: [String], $limit: Int, $offset: Int, $ip: String, $campuses: [String]) {
        groups(query: $query, attributes: $tags, limit: $limit, offset: $offset, clientIp: $ip, campuses: $campuses) {
          count
          results {
            id
            name
            entityId
            type
            kidFriendly
            demographic
            description
            photo
            ageRange
            distance
            schedule { description }
            locations { location { latitude, longitude } }
            tags { id, value }
            campus { name, entityId }
          }
        }
      }
    `,
    ssr: false,
    variables: {
      tags: ownProps.tags.split(",").filter(x => x),
      query: ownProps.q,
      ip: internalIp,
      limit: 10,
      offset: 0,
      campuses: ownProps.campuses.split(",").filter(x => x),
    },
  },
});
const defaultArray = [];
@withRouter
@connect({ mapQueriesToProps, mapStateToProps })
export default class Template extends Component {

  static propTypes = {
    q: PropTypes.string.isRequired,
    dispatch: PropTypes.func.isRequired,
    data: {
      groups: {
        results: PropTypes.array.isRequired,
      },
    },
    tags: PropTypes.string.isRequired,
    location: PropTypes.object.isRequired,
    router: PropTypes.object.isRequired,
  }

  state = {
    markers: [],
    showTags: false,
    showSearch: false,
    hover: null,
    groups: [], // XXX after refetchMore lands in apollo client, remove
    offset: 0,
  }

  paginate = () => {
    const { q, tags, campuses } = this.props;
    this.props.data.refetch({
      tags: tags.split(",").filter(x => x),
      campuses: campuses.split(",").filter(x => x),
      query: q,
      limit: 10,
      offset: this.state.offset + 10,
      ip: internalIp,
    })
      .then(({ data }) => {
        const { results } = data.groups;
        this.setState({
          groups: this.state.groups.concat(results),
          offset: this.state.offset + 10,
        });
      });
  }

  componentWillMount() {
    if (this.props.q) this.setState({ showSearch: true });
    this.props.dispatch(navActions.setLevel("BASIC_CONTENT"));

    if (this.props.data.groups) {
      const markers = this.getMarkers(this.props.data.groups.results);
      this.setState({ markers, groups: this.props.data.groups.results });
    }
  }

  componentWillReceiveProps(nextProps) {
    const newState = {};
    let clear = false;
    if (
      this.props.q !== nextProps.q ||
      this.props.tags !== nextProps.tags ||
      this.props.campuses !== nextProps.campuses
    ) {
      clear = true; // variables have changed
      if (nextProps.data.groups && nextProps.data.groups) {
        newState.groups = nextProps.data.groups.results;
      } else {
        newState.groups = [];
      }
    }

    if (this.props.data.loading && !nextProps.data.loading && !this.state.groups.length) {
      newState.groups = nextProps.data.groups.results;
    }
    newState.markers = this.getMarkers(
      nextProps.data.groups && nextProps.data.groups.results, clear
    );
    this.setState(newState);
  }

  onCardHover = (e) => {
    const { id } = e.currentTarget;
    this.setState({ hover: id });
  }

  onMarkerHover = (marker) => {
    this.setState({ hover: marker.id });
  }

  getMarkers = (groups = [], clear = false) => {
    let { markers } = this.state;
    if (clear) markers = [];
    return _.uniq(markers.concat(groups
      .filter(x => x.locations && x.locations.length && x.locations[0].location)
      .map(x => ({
        latitude: x.locations[0].location.latitude,
        longitude: x.locations[0].location.longitude,
        id: x.id,
        // children: this.createChild(x),
      }))
      .filter(x => x.latitude && x.longitude)
    ), x => x.id);
  }

  toggleSearch = () => this.setState({ showSearch: !this.state.showSearch })
  toggleTags = () => this.setState({ showTags: !this.state.showTags })

  paginate = () => {
    const { q, tags } = this.props;
    this.props.data.refetch({
      tags: tags.split(",").filter(x => x),
      query: q,
      limit: 10,
      offset: this.state.offset + 10,
      ip: internalIp,
    })
      .then(({ data }) => {
        const { results } = data.groups;
        this.setState({
          groups: this.state.groups.concat(results),
          offset: this.state.offset + 10,
        });
      });
  }

  removeQueryString = (e) => {
    if (e) e.preventDefault();
    const { location, router } = this.props;

    if (location && location.query && location.query.q) delete location.query.q;
    const newPath = router.createPath(location);
    router.replace(newPath);
  }

  render() {
    const { data, location, tags, campusLocations, campuses, q } = this.props;
    let count;
    let groups = defaultArray;
    if (data.groups && data.groups.count) count = data.groups.count;
    groups = this.state.groups;

    let isMobile;
    if (typeof window !== "undefined" && window !== null) {
      isMobile = window.matchMedia("(max-width: 768px)").matches;
    }

    return (

        <Split>
          {/* Map */}
          <Right mobile={false} classes={["background--left"]}>
            {(() => {
              if (isMobile || Meteor.isServer) return null;
              return (
                <GoogleMap
                  autoCenter
                  markers={this.state.markers}
                  onMarkerHover={this.onMarkerHover}
                  hover={this.state.hover}
                  onChildClick={({ id }) => this.props.router.push(`/groups/${id}`)}
                />
              );
            })()}
          </Right>
        </Split>
        <Left scroll classes={["background--light-secondary"]}>
          <Layout
              loading={data.loading}
              groups={groups}
              count={count}
              tags={tags && tags.split(",").filter(x => x)}
              campuses={campuses && campuses.split(",").filter(x => x)}
              campusLocations={campusLocations}
              query={q}
              removeQueryString={this.removeQueryString}
              showTags={this.state.showTags}
              toggleTags={this.toggleTags}
              showSearch={this.state.showSearch}
              toggleSearch={this.toggleSearch}
              onCardHover={this.onCardHover}
              paginate={this.paginate}
          />
        </Left>

    );
  }
}
<|endoftext|>


<commit_before>exports.run = async (client, message, [member]) => {
    const sqlite3 = require("sqlite3").verbose();
    let db = new sqlite3.Database("./bwd/data/score.sqlite");

    var user = client.funcs.userSearch(client, message, member);

    if (user.username === undefined) { return; }
    if (user.bot === true) { return message.reply("You can't give your credits to a bot user!"); }

    db.get(`SELECT * FROM scores WHERE userId = "${user.id}"`, [], (err, row) => {
        if (err) { return console.log(err); }
        if (!row) {
            if (user.id === message.author.id) {
                db.run("INSERT INTO scores (userId, credits, level, daily, rep, repDaily) VALUES (?, ?, ?, ?, ?, ?)", [user.id, 100, 0, Date.now(), 0, 0]);
                db.run("INSERT INTO fish_inv (userId, common, uncommon, rare, epic, trash) VALUES (?, ?, ?, ?, ?, ?)", [user.id, 0, 0, 0, 0, 0]);
                db.run("INSERT INTO fish_stats (userId, common, uncommon, rare, epic, trash) VALUES (?, ?, ?, ?, ?, ?)", [user.id, 0, 0, 0, 0, 0]);
                db.run("INSERT INTO badges (userId, betaTester, bugSmasher) VALUES (?, ?, ?)", [user.id, "no", "no"]);
                db.run("INSERT INTO awards (userId, suggest, bugs, minor, major) VALUES (?, ?, ?, ?, ?)", [user.id, 0, 0, 0, 0]);
                return message.channel.send("You have received your daily amount of 100 credits.");
            } else {
                db.get(`SELECT * FROM scores WHERE userId = "${message.author.id}"`, [], (err, row) => {
                    if (err) { return console.log(err); }
                    if (!row) { return message.reply("You have not gotten your first daily yet. Before giving credits to others, you must recieve the daily!"); }
                });
                return message.channel.send("That user has not gotten their first daily to start off with so you can not give them any credits at the moment. :cry:");
            }
        } if (user.id !== message.author.id) {
            var credit = Number((100 * (1 + Math.random())).toFixed(0));
            db.get(`SELECT * FROM scores WHERE userId = "${message.author.id}"`, [], (err, row) => {
                if ((parseInt(row.daily) + 86400000) > Date.now()) {
                    return message.reply("You have already redeemed your daily for today.");
                } else {
                    db.run(`UPDATE scores SET daily = ${Date.now()} WHERE userId = ${message.author.id}`);
                    db.get(`SELECT * FROM scores WHERE userId = "${user.id}"`, [], (err, row) => {
                        if (err) { return console.log(err); }
                        db.run(`UPDATE scores SET credits = ${parseInt(row.credits) + credit} WHERE userId = ${user.id}`);
                    });
                    return message.channel.send(`${user.username} has received ${credit} credits.`);
                }
            });
        } else {
            credit = row.credits + 100;
            db.run(`UPDATE scores SET daily = ${Date.now()} WHERE userId = ${user.id}`);
            db.run(`UPDATE scores SET credits = ${row.credits + 100} WHERE userId = ${user.id}`);
            return message.channel.send(`${user.username} has received ${credit - row.credits} credits.`);
        }
    });
    db.close();
};

exports.conf = {
    enabled: true,
    runIn: ["text"],
    aliases: [],
    permLevel: 0,
    botPerms: [],
    requiredFuncs: [],
};

exports.help = {
    name: "daily",
    description: "Get a daily amount of credits or give them to someone else.",
    usage: "[member:str]",
    usageDelim: "",
};
<commit_msg>Update daily.js<commit_after>exports.run = async (client, message, [member]) => {
    const sqlite3 = require("sqlite3").verbose();
    let db = new sqlite3.Database("./bwd/data/score.sqlite");

    var user = client.funcs.userSearch(client, message, member);

    console.log(user.username);
    if (user.username === undefined) { return; }
    if (user.bot === true) { return message.reply("You can't give your credits to a bot user!"); }

    db.get(`SELECT * FROM scores WHERE userId = "${user.id}"`, [], (err, row) => {
        if (err) { return console.log(err); }
        if (!row) {
            if (user.id === message.author.id) {
                db.run("INSERT INTO scores (userId, credits, level, daily, rep, repDaily) VALUES (?, ?, ?, ?, ?, ?)", [user.id, 100, 0, Date.now(), 0, 0]);
                db.run("INSERT INTO fish_inv (userId, common, uncommon, rare, epic, trash) VALUES (?, ?, ?, ?, ?, ?)", [user.id, 0, 0, 0, 0, 0]);
                db.run("INSERT INTO fish_stats (userId, common, uncommon, rare, epic, trash) VALUES (?, ?, ?, ?, ?, ?)", [user.id, 0, 0, 0, 0, 0]);
                db.run("INSERT INTO badges (userId, betaTester, bugSmasher) VALUES (?, ?, ?)", [user.id, "no", "no"]);
                db.run("INSERT INTO awards (userId, suggest, bugs, minor, major) VALUES (?, ?, ?, ?, ?)", [user.id, 0, 0, 0, 0]);
                return message.channel.send("You have received your daily amount of 100 credits.");
            } else {
                db.get(`SELECT * FROM scores WHERE userId = "${message.author.id}"`, [], (err, row) => {
                    if (err) { return console.log(err); }
                    if (!row) { return message.reply("You have not gotten your first daily yet. Before giving credits to others, you must recieve the daily!"); }
                });
                return message.channel.send("That user has not gotten their first daily to start off with so you can not give them any credits at the moment. :cry:");
            }
        } if (user.id !== message.author.id) {
            var credit = Number((100 * (1 + Math.random())).toFixed(0));
            db.get(`SELECT * FROM scores WHERE userId = "${message.author.id}"`, [], (err, row) => {
                if ((parseInt(row.daily) + 86400000) > Date.now()) {
                    return message.reply("You have already redeemed your daily for today.");
                } else {
                    db.run(`UPDATE scores SET daily = ${Date.now()} WHERE userId = ${message.author.id}`);
                    db.get(`SELECT * FROM scores WHERE userId = "${user.id}"`, [], (err, row) => {
                        if (err) { return console.log(err); }
                        db.run(`UPDATE scores SET credits = ${parseInt(row.credits) + credit} WHERE userId = ${user.id}`);
                    });
                    return message.channel.send(`${user.username} has received ${credit} credits.`);
                }
            });
        } else {
            if ((parseInt(row.daily) + 86400000) > Date.now()) {
                return message.reply("You have already redeemed your daily for today.");
            } else {
                credit = row.credits + 100;
                db.run(`UPDATE scores SET daily = ${Date.now()} WHERE userId = ${user.id}`);
                db.run(`UPDATE scores SET credits = ${row.credits + 100} WHERE userId = ${user.id}`);
                return message.channel.send(`${user.username} has received ${credit - row.credits} credits.`);
            }
        }
    });
    db.close();
};

exports.conf = {
    enabled: true,
    runIn: ["text"],
    aliases: [],
    permLevel: 0,
    botPerms: [],
    requiredFuncs: [],
};

exports.help = {
    name: "daily",
    description: "Get a daily amount of credits or give them to someone else.",
    usage: "[member:str]",
    usageDelim: "",
};
<|endoftext|>


<commit_before><commit_msg>fixed updated profile<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
// Copyright (c) 2008-2011 by Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the LICENSE.txt file included with this file.
"use strict";

/** @scope modules */

/**
 * @instance browser
 */
var Browser = Module("browser", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
    init: function init() {
        this.cleanupProgressListener = overlay.overlayObject(window.XULBrowserWindow,
                                                             this.progressListener);
        util.addObserver(this);
    },

    destroy: function () {
        this.cleanupProgressListener();
        this.observe.unregister();
    },

    observers: {
        "chrome-document-global-created": function (win, uri) { this.observe(win, "content-document-global-created", uri); },
        "content-document-global-created": function (win, uri) {
            let top = util.topWindow(win);

            if (uri == "null")
                uri = null;

            if (top == window && (win.location.href || uri))
                this._triggerLoadAutocmd("PageLoadPre", win.document, win.location.href || uri);
        }
    },

    _triggerLoadAutocmd: function _triggerLoadAutocmd(name, doc, uri) {
        if (!(uri || doc.location))
            return;

        uri = isObject(uri) ? uri : util.newURI(uri || doc.location.href);
        let args = {
            url: { toString: function () uri.spec, valueOf: function () uri },
            title: doc.title
        };

        if (!dactyl.has("tabs"))
            update(args, { doc: doc, win: doc.defaultView });
        else {
            args.tab = tabs.getContentIndex(doc) + 1;
            args.doc = {
                valueOf: function () doc,
                toString: function () "tabs.getTab(" + (args.tab - 1) + ").linkedBrowser.contentDocument"
            };
            args.win = {
                valueOf: function () doc.defaultView,
                toString: function () "tabs.getTab(" + (args.tab - 1) + ").linkedBrowser.contentWindow"
            };
        }

        autocommands.trigger(name, args);
    },

    events: {
        DOMContentLoaded: function onDOMContentLoaded(event) {
            let doc = event.originalTarget;
            if (doc instanceof HTMLDocument)
                this._triggerLoadAutocmd("DOMLoad", doc);
        },

        // TODO: see what can be moved to onDOMContentLoaded()
        // event listener which is is called on each page load, even if the
        // page is loaded in a background tab
        load: function onLoad(event) {
            let doc = event.originalTarget;
            if (doc instanceof Document)
                dactyl.initDocument(doc);

            if (doc instanceof HTMLDocument) {
                if (doc.defaultView.frameElement) {
                    // document is part of a frameset

                    // hacky way to get rid of "Transferring data from ..." on sites with frames
                    // when you click on a link inside a frameset, because asyncUpdateUI
                    // is not triggered there (Gecko bug?)
                    this.timeout(function () { statusline.updateStatus(); }, 10);
                }
                else {
                    // code which should happen for all (also background) newly loaded tabs goes here:
                    if (doc != config.browser.contentDocument)
                        dactyl.echomsg({ domains: [util.getHost(doc.location)], message: _("buffer.backgroundLoaded", (doc.title || doc.location.href)) }, 3);

                    this._triggerLoadAutocmd("PageLoad", doc);
                }
            }
        }
    },

    /**
     * @property {Object} The document loading progress listener.
     */
    progressListener: {
        // XXX: function may later be needed to detect a canceled synchronous openURL()
        onStateChange: util.wrapCallback(function onStateChange(webProgress, request, flags, status) {
            const L = Ci.nsIWebProgressListener;

            if (request)
                dactyl.applyTriggerObserver("browser.stateChange", arguments);

            if (flags & (L.STATE_IS_DOCUMENT | L.STATE_IS_WINDOW)) {
                // This fires when the load event is initiated
                // only thrown for the current tab, not when another tab changes
                if (flags & L.STATE_START) {
                    while (document.commandDispatcher.focusedWindow == webProgress.DOMWindow
                           && modes.have(modes.INPUT))
                        modes.pop();

                }
                else if (flags & L.STATE_STOP) {
                    // Workaround for bugs 591425 and 606877, dactyl bug #81
                    config.browser.mCurrentBrowser.collapsed = false;
                    if (!dactyl.focusedElement || dactyl.focusedElement === document.documentElement)
                        dactyl.focusContent();
                }
            }

            onStateChange.superapply(this, arguments);
        }),
        onSecurityChange: util.wrapCallback(function onSecurityChange(webProgress, request, state) {
            onSecurityChange.superapply(this, arguments);
            dactyl.applyTriggerObserver("browser.securityChange", arguments);
        }),
        onStatusChange: util.wrapCallback(function onStatusChange(webProgress, request, status, message) {
            onStatusChange.superapply(this, arguments);
            dactyl.applyTriggerObserver("browser.statusChange", arguments);
        }),
        onProgressChange: util.wrapCallback(function onProgressChange(webProgress, request, curSelfProgress, maxSelfProgress, curTotalProgress, maxTotalProgress) {
            onProgressChange.superapply(this, arguments);
            dactyl.applyTriggerObserver("browser.progressChange", arguments);
        }),
        // happens when the users switches tabs
        onLocationChange: util.wrapCallback(function onLocationChange(webProgress, request, uri) {
            onLocationChange.superapply(this, arguments);

            dactyl.applyTriggerObserver("browser.locationChange", arguments);

            let win = webProgress.DOMWindow;
            if (win && uri) {
                Buffer(win).updateZoom();

                let oldURI = overlay.getData(win.document)["uri"];
                if (overlay.getData(win.document)["load-idx"] === webProgress.loadedTransIndex
                    || !oldURI || uri.spec.replace(/#.*/, "") !== oldURI.replace(/#.*/, ""))
                    for (let frame in values(buffer.allFrames(win)))
                        overlay.setData(frame.document, "focus-allowed", false);

                overlay.setData(win.document, "uri", uri.spec);
                overlay.setData(win.document, "load-idx", webProgress.loadedTransIndex);
            }

            // Workaround for bugs 591425 and 606877, dactyl bug #81
            let collapse = uri && uri.scheme === "dactyl" && webProgress.isLoadingDocument;
            if (collapse)
                dactyl.focus(document.documentElement);
            config.browser.mCurrentBrowser.collapsed = collapse;

            util.timeout(function () {
                browser._triggerLoadAutocmd("LocationChange",
                                            (win || content).document,
                                            uri);
            });
        }),
        // called at the very end of a page load
        asyncUpdateUI: util.wrapCallback(function asyncUpdateUI() {
            asyncUpdateUI.superapply(this, arguments);
            util.timeout(function () { statusline.updateStatus(); }, 100);
        }),
        setOverLink: util.wrapCallback(function setOverLink(link, b) {
            setOverLink.superapply(this, arguments);
            dactyl.triggerObserver("browser.overLink", link);
        })
    }
}, {
}, {
    events: function initEvents(dactyl, modules, window) {
        events.listen(config.browser, browser, "events", true);
    },
    commands: function initCommands(dactyl, modules, window) {
        commands.add(["o[pen]"],
            "Open one or more URLs in the current tab",
            function (args) { dactyl.open(args[0] || "about:blank"); },
            {
                completer: function (context) completion.url(context),
                domains: function (args) array.compact(dactyl.parseURLs(args[0] || "").map(
                    function (url) util.getHost(url))),
                literal: 0,
                privateData: true
            });

        commands.add(["redr[aw]"],
            "Redraw the screen",
            function () {
                window.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils)
                      .redraw();
                statusline.overLink = null;
                statusline.updateStatus();
                commandline.clear();
            },
            { argCount: "0" });
    },
    mappings: function initMappings(dactyl, modules, window) {
        let openModes = array.toObject([
            [dactyl.CURRENT_TAB, ""],
            [dactyl.NEW_TAB, "tab"],
            [dactyl.NEW_BACKGROUND_TAB, "background tab"],
            [dactyl.NEW_WINDOW, "win"]
        ]);

        function open(mode, args) {
            if (dactyl.forceTarget in openModes)
                mode = openModes[dactyl.forceTarget];

            CommandExMode().open(mode + "open " + (args || ""))
        }

        function decode(uri) util.losslessDecodeURI(uri)
                                 .replace(/%20(?!(?:%20)*$)/g, " ")
                                 .replace(RegExp(options["urlseparator"], "g"), encodeURIComponent);

        mappings.add([modes.NORMAL],
            ["o"], "Open one or more URLs",
            function () { open(""); });

        mappings.add([modes.NORMAL], ["O"],
            "Open one or more URLs, based on current location",
            function () { open("", decode(buffer.uri.spec)); });

        mappings.add([modes.NORMAL], ["s"],
            "Open a search prompt",
            function () { open("", options["defsearch"] + " "); });

        mappings.add([modes.NORMAL], ["S"],
            "Open a search prompt for a new tab",
            function () { open("tab", options["defsearch"] + " "); });

        mappings.add([modes.NORMAL], ["t"],
            "Open one or more URLs in a new tab",
            function () { CommandExMode().open("tabopen "); });

        mappings.add([modes.NORMAL], ["T"],
            "Open one or more URLs in a new tab, based on current location",
            function () { open("tab", decode(buffer.uri.spec)); });

        mappings.add([modes.NORMAL], ["w"],
            "Open one or more URLs in a new window",
            function () { open("win"); });

        mappings.add([modes.NORMAL], ["W"],
            "Open one or more URLs in a new window, based on current location",
            function () { open("win", decode(buffer.uri.spec)); });

        mappings.add([modes.NORMAL], ["<open-home-directory>", "~"],
            "Open home directory",
            function () { dactyl.open("~"); });

        mappings.add([modes.NORMAL], ["<open-homepage>", "gh"],
            "Open homepage",
            function () { BrowserHome(); });

        mappings.add([modes.NORMAL], ["<tab-open-homepage>", "gH"],
            "Open homepage in a new tab",
            function () {
                let homepages = gHomeButton.getHomePage();
                dactyl.open(homepages, { from: "homepage", where: dactyl.NEW_TAB });
            });

        mappings.add([modes.MAIN], ["<redraw-screen>", "<C-l>"],
            "Redraw the screen",
            function () { ex.redraw(); });
    }
});

// vim: set fdm=marker sw=4 ts=4 et:
<commit_msg>Fix homepage mappings<commit_after>// Copyright (c) 2006-2008 by Martin Stubenschrott <stubenschrott@vimperator.org>
// Copyright (c) 2007-2011 by Doug Kearns <dougkearns@gmail.com>
// Copyright (c) 2008-2011 by Kris Maglione <maglione.k at Gmail>
//
// This work is licensed for reuse under an MIT license. Details are
// given in the LICENSE.txt file included with this file.
"use strict";

/** @scope modules */

/**
 * @instance browser
 */
var Browser = Module("browser", XPCOM(Ci.nsISupportsWeakReference, ModuleBase), {
    init: function init() {
        this.cleanupProgressListener = overlay.overlayObject(window.XULBrowserWindow,
                                                             this.progressListener);
        util.addObserver(this);
    },

    destroy: function () {
        this.cleanupProgressListener();
        this.observe.unregister();
    },

    observers: {
        "chrome-document-global-created": function (win, uri) { this.observe(win, "content-document-global-created", uri); },
        "content-document-global-created": function (win, uri) {
            let top = util.topWindow(win);

            if (uri == "null")
                uri = null;

            if (top == window && (win.location.href || uri))
                this._triggerLoadAutocmd("PageLoadPre", win.document, win.location.href || uri);
        }
    },

    _triggerLoadAutocmd: function _triggerLoadAutocmd(name, doc, uri) {
        if (!(uri || doc.location))
            return;

        uri = isObject(uri) ? uri : util.newURI(uri || doc.location.href);
        let args = {
            url: { toString: function () uri.spec, valueOf: function () uri },
            title: doc.title
        };

        if (!dactyl.has("tabs"))
            update(args, { doc: doc, win: doc.defaultView });
        else {
            args.tab = tabs.getContentIndex(doc) + 1;
            args.doc = {
                valueOf: function () doc,
                toString: function () "tabs.getTab(" + (args.tab - 1) + ").linkedBrowser.contentDocument"
            };
            args.win = {
                valueOf: function () doc.defaultView,
                toString: function () "tabs.getTab(" + (args.tab - 1) + ").linkedBrowser.contentWindow"
            };
        }

        autocommands.trigger(name, args);
    },

    events: {
        DOMContentLoaded: function onDOMContentLoaded(event) {
            let doc = event.originalTarget;
            if (doc instanceof HTMLDocument)
                this._triggerLoadAutocmd("DOMLoad", doc);
        },

        // TODO: see what can be moved to onDOMContentLoaded()
        // event listener which is is called on each page load, even if the
        // page is loaded in a background tab
        load: function onLoad(event) {
            let doc = event.originalTarget;
            if (doc instanceof Document)
                dactyl.initDocument(doc);

            if (doc instanceof HTMLDocument) {
                if (doc.defaultView.frameElement) {
                    // document is part of a frameset

                    // hacky way to get rid of "Transferring data from ..." on sites with frames
                    // when you click on a link inside a frameset, because asyncUpdateUI
                    // is not triggered there (Gecko bug?)
                    this.timeout(function () { statusline.updateStatus(); }, 10);
                }
                else {
                    // code which should happen for all (also background) newly loaded tabs goes here:
                    if (doc != config.browser.contentDocument)
                        dactyl.echomsg({ domains: [util.getHost(doc.location)], message: _("buffer.backgroundLoaded", (doc.title || doc.location.href)) }, 3);

                    this._triggerLoadAutocmd("PageLoad", doc);
                }
            }
        }
    },

    /**
     * @property {Object} The document loading progress listener.
     */
    progressListener: {
        // XXX: function may later be needed to detect a canceled synchronous openURL()
        onStateChange: util.wrapCallback(function onStateChange(webProgress, request, flags, status) {
            const L = Ci.nsIWebProgressListener;

            if (request)
                dactyl.applyTriggerObserver("browser.stateChange", arguments);

            if (flags & (L.STATE_IS_DOCUMENT | L.STATE_IS_WINDOW)) {
                // This fires when the load event is initiated
                // only thrown for the current tab, not when another tab changes
                if (flags & L.STATE_START) {
                    while (document.commandDispatcher.focusedWindow == webProgress.DOMWindow
                           && modes.have(modes.INPUT))
                        modes.pop();

                }
                else if (flags & L.STATE_STOP) {
                    // Workaround for bugs 591425 and 606877, dactyl bug #81
                    config.browser.mCurrentBrowser.collapsed = false;
                    if (!dactyl.focusedElement || dactyl.focusedElement === document.documentElement)
                        dactyl.focusContent();
                }
            }

            onStateChange.superapply(this, arguments);
        }),
        onSecurityChange: util.wrapCallback(function onSecurityChange(webProgress, request, state) {
            onSecurityChange.superapply(this, arguments);
            dactyl.applyTriggerObserver("browser.securityChange", arguments);
        }),
        onStatusChange: util.wrapCallback(function onStatusChange(webProgress, request, status, message) {
            onStatusChange.superapply(this, arguments);
            dactyl.applyTriggerObserver("browser.statusChange", arguments);
        }),
        onProgressChange: util.wrapCallback(function onProgressChange(webProgress, request, curSelfProgress, maxSelfProgress, curTotalProgress, maxTotalProgress) {
            onProgressChange.superapply(this, arguments);
            dactyl.applyTriggerObserver("browser.progressChange", arguments);
        }),
        // happens when the users switches tabs
        onLocationChange: util.wrapCallback(function onLocationChange(webProgress, request, uri) {
            onLocationChange.superapply(this, arguments);

            dactyl.applyTriggerObserver("browser.locationChange", arguments);

            let win = webProgress.DOMWindow;
            if (win && uri) {
                Buffer(win).updateZoom();

                let oldURI = overlay.getData(win.document)["uri"];
                if (overlay.getData(win.document)["load-idx"] === webProgress.loadedTransIndex
                    || !oldURI || uri.spec.replace(/#.*/, "") !== oldURI.replace(/#.*/, ""))
                    for (let frame in values(buffer.allFrames(win)))
                        overlay.setData(frame.document, "focus-allowed", false);

                overlay.setData(win.document, "uri", uri.spec);
                overlay.setData(win.document, "load-idx", webProgress.loadedTransIndex);
            }

            // Workaround for bugs 591425 and 606877, dactyl bug #81
            let collapse = uri && uri.scheme === "dactyl" && webProgress.isLoadingDocument;
            if (collapse)
                dactyl.focus(document.documentElement);
            config.browser.mCurrentBrowser.collapsed = collapse;

            util.timeout(function () {
                browser._triggerLoadAutocmd("LocationChange",
                                            (win || content).document,
                                            uri);
            });
        }),
        // called at the very end of a page load
        asyncUpdateUI: util.wrapCallback(function asyncUpdateUI() {
            asyncUpdateUI.superapply(this, arguments);
            util.timeout(function () { statusline.updateStatus(); }, 100);
        }),
        setOverLink: util.wrapCallback(function setOverLink(link, b) {
            setOverLink.superapply(this, arguments);
            dactyl.triggerObserver("browser.overLink", link);
        })
    }
}, {
}, {
    events: function initEvents(dactyl, modules, window) {
        events.listen(config.browser, browser, "events", true);
    },
    commands: function initCommands(dactyl, modules, window) {
        commands.add(["o[pen]"],
            "Open one or more URLs in the current tab",
            function (args) { dactyl.open(args[0] || "about:blank"); },
            {
                completer: function (context) completion.url(context),
                domains: function (args) array.compact(dactyl.parseURLs(args[0] || "").map(
                    function (url) util.getHost(url))),
                literal: 0,
                privateData: true
            });

        commands.add(["redr[aw]"],
            "Redraw the screen",
            function () {
                window.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowUtils)
                      .redraw();
                statusline.overLink = null;
                statusline.updateStatus();
                commandline.clear();
            },
            { argCount: "0" });
    },
    mappings: function initMappings(dactyl, modules, window) {
        let openModes = array.toObject([
            [dactyl.CURRENT_TAB, ""],
            [dactyl.NEW_TAB, "tab"],
            [dactyl.NEW_BACKGROUND_TAB, "background tab"],
            [dactyl.NEW_WINDOW, "win"]
        ]);

        function open(mode, args) {
            if (dactyl.forceTarget in openModes)
                mode = openModes[dactyl.forceTarget];

            CommandExMode().open(mode + "open " + (args || ""))
        }

        function decode(uri) util.losslessDecodeURI(uri)
                                 .replace(/%20(?!(?:%20)*$)/g, " ")
                                 .replace(RegExp(options["urlseparator"], "g"), encodeURIComponent);

        mappings.add([modes.NORMAL],
            ["o"], "Open one or more URLs",
            function () { open(""); });

        mappings.add([modes.NORMAL], ["O"],
            "Open one or more URLs, based on current location",
            function () { open("", decode(buffer.uri.spec)); });

        mappings.add([modes.NORMAL], ["s"],
            "Open a search prompt",
            function () { open("", options["defsearch"] + " "); });

        mappings.add([modes.NORMAL], ["S"],
            "Open a search prompt for a new tab",
            function () { open("tab", options["defsearch"] + " "); });

        mappings.add([modes.NORMAL], ["t"],
            "Open one or more URLs in a new tab",
            function () { CommandExMode().open("tabopen "); });

        mappings.add([modes.NORMAL], ["T"],
            "Open one or more URLs in a new tab, based on current location",
            function () { open("tab", decode(buffer.uri.spec)); });

        mappings.add([modes.NORMAL], ["w"],
            "Open one or more URLs in a new window",
            function () { open("win"); });

        mappings.add([modes.NORMAL], ["W"],
            "Open one or more URLs in a new window, based on current location",
            function () { open("win", decode(buffer.uri.spec)); });

        mappings.add([modes.NORMAL], ["<open-home-directory>", "~"],
            "Open home directory",
            function () { dactyl.open("~"); });

        mappings.add([modes.NORMAL], ["<open-homepage>", "gh"],
            "Open homepage",
            function () { window.BrowserHome(); });

        mappings.add([modes.NORMAL], ["<tab-open-homepage>", "gH"],
            "Open homepage in a new tab",
            function () {
                let homepages = window.gHomeButton.getHomePage();
                dactyl.open(homepages, { from: "homepage", where: dactyl.NEW_TAB });
            });

        mappings.add([modes.MAIN], ["<redraw-screen>", "<C-l>"],
            "Redraw the screen",
            function () { ex.redraw(); });
    }
});

// vim: set fdm=marker sw=4 ts=4 et:
<|endoftext|>


<commit_before>/**
 *
 * @param realGraph
 * @param displayGraph
 * @param managerInstance
 * @param clickManager
 * @param overlayId the id where the overlay will be created
 */
function FeatureCreator(realGraph, displayGraph, managerInstance, clickManager, args) {
	var overlayId = args[0];
	/**
	 * Pops up an overlay
	 */
	function createNewFeature(e, oldNode) {
		alert('new feature being made!');
		if (!window.featureCreatorLoaded) {
			// load window here
			var fileref = document.createElement('link');
			fileref.id = "createNewFeatureImport";
			fileref.setAttribute("rel", "import");
			fileref.setAttribute("href", 'nodeClickActions/createNewFeature/featureCreator.html');
			document.querySelector("head").appendChild(fileref);
			fileref.onload = function(event) {
				alert('file loaded');
				produceOverlay(e, oldNode, event);
			}
		} else {
			produceOverlay(e, oldNode);
		}
	}

	/**
	 * Saves the data of the form to a new node
	 */
	function saveData(e, formData) {
		var nameElement = formData.querySelector('.featureName');
		alert(nameElement.value);
		document.getElementById(overlayId).style.display = 'none';
	}

	/**
	 * Produces the grayed overlay where the node data is inserted
	 */
	function produceOverlay(e, oldNode) {
		var importedDocument = document.querySelector('#createNewFeatureImport').import;
		var content = importedDocument.querySelector('#createNewFeature').content;
		var importedNode = document.importNode(content, true);
		var shadowRoot = document.querySelector('#' + overlayId).createShadowRoot();
		shadowRoot.appendChild(importedNode);
		console.log(importedNode);
		console.log(shadowRoot);
		var saveButton = shadowRoot.querySelector('.save');
		console.log(saveButton);
		saveButton.onclick = function() {
			alert('saving!');
			saveData(e, shadowRoot);
		};
		document.getElementById(overlayId).style.display = 'block';
	}

	clickManager.setClickFunction('newFeature', createNewFeature);
}<commit_msg>removed alerts<commit_after>/**
 *
 * @param realGraph
 * @param displayGraph
 * @param managerInstance
 * @param clickManager
 * @param overlayId the id where the overlay will be created
 */
function FeatureCreator(realGraph, displayGraph, managerInstance, clickManager, args) {
	var overlayId = args[0];
	/**
	 * Pops up an overlay
	 */
	function createNewFeature(e, oldNode) {
		if (!window.featureCreatorLoaded) {
			// load window here
			var fileref = document.createElement('link');
			fileref.id = "createNewFeatureImport";
			fileref.setAttribute("rel", "import");
			fileref.setAttribute("href", 'nodeClickActions/createNewFeature/featureCreator.html');
			document.querySelector("head").appendChild(fileref);
			fileref.onload = function(event) {
				produceOverlay(e, oldNode, event);
			}
		} else {
			produceOverlay(e, oldNode);
		}
	}

	/**
	 * Saves the data of the form to a new node
	 */
	function saveData(e, formData) {
		var nameElement = formData.querySelector('.featureName');
		document.getElementById(overlayId).style.display = 'none';
	}

	/**
	 * Produces the grayed overlay where the node data is inserted
	 */
	function produceOverlay(e, oldNode) {
		var importedDocument = document.querySelector('#createNewFeatureImport').import;
		var content = importedDocument.querySelector('#createNewFeature').content;
		var importedNode = document.importNode(content, true);
		var shadowRoot = document.querySelector('#' + overlayId).createShadowRoot();
		shadowRoot.appendChild(importedNode);
		console.log(importedNode);
		console.log(shadowRoot);
		var saveButton = shadowRoot.querySelector('.save');
		console.log(saveButton);
		saveButton.onclick = function() {
			saveData(e, shadowRoot);
		};
		document.getElementById(overlayId).style.display = 'block';
	}

	clickManager.setClickFunction('newFeature', createNewFeature);
}<|endoftext|>


<commit_before>define(function () {
	function Particle(p) {
		var i = 0, prop,
			props = ['x', 'y', 'dx', 'dy', 'r', 'dead'];

		p = p || {};
		for (i in props) {
			prop = props[i];
			this[prop] = p[prop] || 0;
		}

		return this;
	}

	Particle.prototype = {
		get r() {
			return this._r;
		},

		set r(r) {
			this._r = r;
			this.mass = 0.1 * Math.pow(this.r, 2);
		},

		update: function () {
			this.x += this.dx;
			this.y += this.dy;
		},

		kill: function () {
			this.dead = true;
		},

		collidesWith: function (p2) {
			var dx = p2.x - this.x;
				dy = p2.y - this.y;

			return Math.pow(dx, 2) + Math.pow(dy, 2) < Math.pow(this.r + p2.r, 2);
		}
	};
	return Particle;
});<commit_msg>cube instead of square and increase particle mass<commit_after>define(function () {
	function Particle(p) {
		var i = 0, prop,
			props = ['x', 'y', 'dx', 'dy', 'r', 'dead'];

		p = p || {};
		for (i in props) {
			prop = props[i];
			this[prop] = p[prop] || 0;
		}

		return this;
	}

	Particle.prototype = {
		get r() {
			return this._r;
		},

		set r(r) {
			this._r = r;
			this.mass = 0.5 * Math.pow(this.r, 3);
		},

		update: function () {
			this.x += this.dx;
			this.y += this.dy;
		},

		kill: function () {
			this.dead = true;
		},

		collidesWith: function (p2) {
			var dx = p2.x - this.x;
				dy = p2.y - this.y;

			return Math.pow(dx, 2) + Math.pow(dy, 2) < Math.pow(this.r + p2.r, 2);
		}
	};
	return Particle;
});
<|endoftext|>