<commit_before>'use strict';

angular.module('emulvcApp')
    .directive('spectro', function() {
        return {
            templateUrl: 'views/spectro.html',
            restrict: 'E',
            link: function postLink(scope, element, attrs) {
                // select the needed DOM elements from the template
                var canvas = element.find("canvas")[0];
                var myid = element[0].id;
                var myWindow = {
                    BARTLETT: 1,
                    BARTLETTHANN: 2,
                    BLACKMAN: 3,
                    COSINE: 4,
                    GAUSS: 5,
                    HAMMING: 6,
                    HANN: 7,
                    LANCZOS: 8,
                    RECTANGULAR: 9,
                    TRIANGULAR: 10
                };

                // various mathematical vars
                var PI = 3.141592653589793; // value : Math.PI
                var TWO_PI = 6.283185307179586; // value : 2 * Math.PI
                var OCTAVE_FACTOR = 3.321928094887363; // value : 1.0/log10(2)
                var emphasisPerOctave = 3.9810717055349722; // value : toLinearLevel(6);
                var dynamicRange = 5000; // value : toLinearLevel(50);
                var dynRangeInDB = 50; // value : toLevelInDB(dynamicRange);
                // FFT default vars
                var N = 512; // default FFT Window Size
                var alpha = 0.16; // default alpha for Window Function
                var windowFunction = myWindow.BARTLETTHANN; // default Window Function
                var sampleRate = 44100; // default sample rate
                var channels = 1; // default number of channels
                var freq_lower = 0; // default upper Frequency
                var freq = 8000; // default upper Frequency
                var context = canvas.getContext("2d");
                var pcmperpixel = 0;
                var myImage = new Image();
                window.URL = window.URL || window.webkitURL;
                var devicePixelRatio = window.devicePixelRatio || 1;
                var response = spectroworker.textContent;
                var blob, vs;

                try {
                    blob = new Blob([response], {
                        "type": "text\/javascript"
                    });
                } catch (e) { // Backwards-compatibility
                    window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
                    blob.append(response);
                    blob = blob.getBlob();
                }
                var primeWorker = new Worker(URL.createObjectURL(blob));
                var imageCache = null;
                var imageCacheCounter = 0;

                setupEvent();
                clearImageCache();

                scope.$watch('vs.curViewPort', function() {

                    if (!$.isEmptyObject(scope.shs.currentBuffer)) {
                        var ppp = Math.round((scope.vs.curViewPort.eS - scope.vs.curViewPort.sS) / canvas.width);
                        var cache = cacheHit(scope.vs.curViewPort.sS,scope.vs.curViewPort.eS,ppp);
                        if(cache!=null) {

                            drawTimeLine(cache);
                        }
                        else {
                            drawOsci(scope.vs, scope.shs.currentBuffer);
                        }
                    }
                }, true);

                function clearImageCache() {
                    imageCache = null;
                    imageCacheCounter = 0;
                    imageCache = new Array();
                }

                function buildImageCache(cstart, cend, ppp, imgData) {
                    imageCache[imageCacheCounter] = new Array();
                    imageCache[imageCacheCounter][0] = cstart;
                    imageCache[imageCacheCounter][1] = cend;
                    imageCache[imageCacheCounter][2] = ppp;
                    imageCache[imageCacheCounter][3] = imgData;
                    ++imageCacheCounter;
                }

                function cacheHit(cstart, cend, ppp) {
                    for (var i = 0; i < imageCache.length; ++i) {
                        if (imageCache[i][0] == cstart &&
                            imageCache[i][1] == cend &&
                            imageCache[i][2] == ppp) {
                            return i;
                        }
                    }
                    return null;
                }

                function drawTimeLineContext() {
                    var posS = vs.getPos(canvas.width, vs.curViewPort.selectS);
                    var posE = vs.getPos(canvas.width, vs.curViewPort.selectE);
                    var sDist = vs.getSampleDist(canvas.width) / 2;
                    var curPos = posS + sDist;
                    if (posS != 0 && vs.selectS == vs.selectE) {
                        context.fillStyle = "#000";
                        context.fillRect(curPos, 0, 1, canvas.height);
                    }
                    if (curPos != 0 && vs.selectS != vs.selectE) {
                        context.fillStyle = "#f00";
                        context.fillRect(posS, 0, posE - posS, canvas.height);
                        context.strokeStyle = "#111";
                        context.beginPath();
                        context.moveTo(posS, 0);
                        context.lineTo(posS, canvas.height);
                        context.moveTo(posE, 0);
                        context.lineTo(posE, canvas.height);
                        context.closePath();
                        context.stroke();
                    }
                }

                function drawTimeLine(id) {

                    var image = new Image();
                    image.onload = function() {
                        context.drawImage(image, 0, 0);
                        drawTimeLineContext();
                    };
                    image.src = imageCache[id][3];
                }

                function killSpectroRenderingThread() {
                    context.fillStyle = "#222";
                    context.fillRect(0, 0, canvas.width, canvas.height);
                    context.font = "10px Verdana";
                    context.fillStyle = "#333";
                    context.fillText("loading...", 10, 25);
                    if (primeWorker != null) {
                        primeWorker.terminate();
                        primeWorker = null;
                    }
                }

                function setupEvent() {
                    primeWorker.addEventListener('message', function(event) {
                        var worker_img = event.data.img;
                        myImage.onload = function() {
                            context.drawImage(myImage, 0, 0, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
                            drawTimeLineContext();
                            var ppp = Math.round((scope.vs.curViewPort.eS - scope.vs.curViewPort.sS) / canvas.width);
                            buildImageCache(scope.vs.curViewPort.sS, scope.vs.curViewPort.eS, ppp,canvas.toDataURL("image/png"));
                        }
                        myImage.src = worker_img;
                    });
                }

                function drawOsci(viewState, buffer) {
                    killSpectroRenderingThread();
                    startSpectroRenderingThread(viewState, buffer);
                }

                function startSpectroRenderingThread(viewState, buffer) {
                    vs = viewState;
                    pcmperpixel = Math.round((vs.curViewPort.eS - vs.curViewPort.sS) / canvas.width);
                    primeWorker = new Worker(URL.createObjectURL(blob));
                    var parseData = buffer.getChannelData(0).subarray(vs.curViewPort.sS, vs.curViewPort.eS + (2 * N));
                    setupEvent();

                    primeWorker.postMessage({
                        'cmd': 'config',
                        'N': N
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'alpha': alpha
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'freq': freq
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'freq_low': freq_lower
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'start': Math.round(viewState.sS)
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'end': Math.round(viewState.eS)
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'myStep': pcmperpixel
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'window': windowFunction
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'cacheSide': 0
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'width': canvas.width
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'height': canvas.height
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'cacheWidth': 0
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'dynRangeInDB': dynRangeInDB
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'pixelRatio': devicePixelRatio
                    });
                    primeWorker.postMessage({
                        'cmd': 'pcm',
                        'config': JSON.stringify(buffer)
                    });
                    primeWorker.postMessage({
                        'cmd': 'pcm',
                        'stream': parseData
                    });
                    primeWorker.postMessage({
                        'cmd': 'render'
                    });
                }

            }
        }
    });<commit_msg>selection now also on spectro<commit_after>'use strict';

angular.module('emulvcApp')
    .directive('spectro', function() {
        return {
            templateUrl: 'views/spectro.html',
            restrict: 'E',
            link: function postLink(scope, element, attrs) {
                // select the needed DOM elements from the template
                var canvas = element.find("canvas")[0];
                var myid = element[0].id;
                var myWindow = {
                    BARTLETT: 1,
                    BARTLETTHANN: 2,
                    BLACKMAN: 3,
                    COSINE: 4,
                    GAUSS: 5,
                    HAMMING: 6,
                    HANN: 7,
                    LANCZOS: 8,
                    RECTANGULAR: 9,
                    TRIANGULAR: 10
                };

                // various mathematical vars
                var PI = 3.141592653589793; // value : Math.PI
                var TWO_PI = 6.283185307179586; // value : 2 * Math.PI
                var OCTAVE_FACTOR = 3.321928094887363; // value : 1.0/log10(2)
                var emphasisPerOctave = 3.9810717055349722; // value : toLinearLevel(6);
                var dynamicRange = 5000; // value : toLinearLevel(50);
                var dynRangeInDB = 50; // value : toLevelInDB(dynamicRange);
                // FFT default vars
                var N = 512; // default FFT Window Size
                var alpha = 0.16; // default alpha for Window Function
                var windowFunction = myWindow.BARTLETTHANN; // default Window Function
                var sampleRate = 44100; // default sample rate
                var channels = 1; // default number of channels
                var freq_lower = 0; // default upper Frequency
                var freq = 8000; // default upper Frequency
                var context = canvas.getContext("2d");
                var pcmperpixel = 0;
                var myImage = new Image();
                window.URL = window.URL || window.webkitURL;
                var devicePixelRatio = window.devicePixelRatio || 1;
                var response = spectroworker.textContent;
                var blob, vs;

                try {
                    blob = new Blob([response], {
                        "type": "text\/javascript"
                    });
                } catch (e) { // Backwards-compatibility
                    window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
                    blob.append(response);
                    blob = blob.getBlob();
                }
                var primeWorker = new Worker(URL.createObjectURL(blob));
                var imageCache = null;
                var imageCacheCounter = 0;

                setupEvent();
                clearImageCache();

                scope.$watch('vs.curViewPort', function() {

                    if (!$.isEmptyObject(scope.shs.currentBuffer)) {
                        var ppp = Math.round((scope.vs.curViewPort.eS - scope.vs.curViewPort.sS) / canvas.width);
                        var cache = cacheHit(scope.vs.curViewPort.sS,scope.vs.curViewPort.eS,ppp);
                        if(cache!=null) {

                            drawTimeLine(cache);
                        }
                        else {
                            drawOsci(scope.vs, scope.shs.currentBuffer);
                        }
                    }
                }, true);

                function clearImageCache() {
                    imageCache = null;
                    imageCacheCounter = 0;
                    imageCache = new Array();
                }

                function buildImageCache(cstart, cend, ppp, imgData) {
                    imageCache[imageCacheCounter] = new Array();
                    imageCache[imageCacheCounter][0] = cstart;
                    imageCache[imageCacheCounter][1] = cend;
                    imageCache[imageCacheCounter][2] = ppp;
                    imageCache[imageCacheCounter][3] = imgData;
                    ++imageCacheCounter;
                }

                function cacheHit(cstart, cend, ppp) {
                    for (var i = 0; i < imageCache.length; ++i) {
                        if (imageCache[i][0] == cstart &&
                            imageCache[i][1] == cend &&
                            imageCache[i][2] == ppp) {
                            return i;
                        }
                    }
                    return null;
                }

                function drawTimeLineContext() {
					var posS = vs.getPos(canvas.width, vs.curViewPort.selectS);
					var posE = vs.getPos(canvas.width, vs.curViewPort.selectE);
					var sDist = vs.getSampleDist(canvas.width);
					var xOffset;
					if (vs.curViewPort.selectS == vs.curViewPort.selectE) {
						// calc. offset dependant on type of tier of mousemove  -> default is sample exact
						if (vs.curMouseMoveTierType == "seg") {
							xOffset = 0;
						} else {
							xOffset = (sDist / 2);
						}
						context.fillStyle = scope.cps.vals.selectedBorderColor;
						context.fillRect(posS + xOffset, 0, 1, canvas.height);
						context.fillStyle = scope.cps.vals.labelColor;
						context.fillText(vs.round(vs.curViewPort.selectS / 44100 + (1 / 44100) / 2, 6), posS + xOffset + 5, scope.cps.vals.fontPxSize);
						context.fillText(vs.curViewPort.selectS, posS + xOffset + 5, scope.cps.vals.fontPxSize * 2);
					} else {
						context.fillStyle = scope.cps.vals.selectedAreaColor;
						context.fillRect(posS, 0, posE - posS, canvas.height);
						context.strokeStyle = scope.cps.vals.selectedBoundaryColor;
						context.beginPath();
						context.moveTo(posS, 0);
						context.lineTo(posS, canvas.height);
						context.moveTo(posE, 0);
						context.lineTo(posE, canvas.height);
						context.closePath();
						context.stroke();
						context.fillStyle = canvas.labelColor;
						// start values
						var tW = context.measureText(vs.curViewPort.selectS).width;
						context.fillText(vs.curViewPort.selectS, posS - tW - 4, scope.cps.vals.fontPxSize);
						tW = context.measureText(vs.round(vs.curViewPort.selectS / 44100, 6)).width;
						context.fillText(vs.round(vs.curViewPort.selectS / 44100, 6), posS - tW - 4, scope.cps.vals.fontPxSize * 2);
						// end values
						context.fillText(vs.curViewPort.selectE, posE + 5, scope.cps.vals.fontPxSize);
						context.fillText(vs.round(vs.curViewPort.selectE / 44100, 6), posE + 5, scope.cps.vals.fontPxSize * 2);
						// dur values
						// check if space
						if (posE - posS > context.measureText(vs.round((vs.curViewPort.selectE - vs.curViewPort.selectS) / 44100, 6)).width) {
							tW = context.measureText(vs.curViewPort.selectE - vs.curViewPort.selectS).width;
							context.fillText(vs.curViewPort.selectE - vs.curViewPort.selectS - 1, posS + (posE - posS) / 2 - tW / 2, scope.cps.vals.fontPxSize);
							tW = context.measureText(vs.round((vs.curViewPort.selectE - vs.curViewPort.selectS) / 44100, 6)).width;
							context.fillText(vs.round(((vs.curViewPort.selectE - vs.curViewPort.selectS) / 44100), 6), posS + (posE - posS) / 2 - tW / 2, scope.cps.vals.fontPxSize * 2);
						}
					}
                }

                function drawTimeLine(id) {

                    var image = new Image();
                    image.onload = function() {
                        context.drawImage(image, 0, 0);
                        drawTimeLineContext();
                    };
                    image.src = imageCache[id][3];
                }

                function killSpectroRenderingThread() {
                    context.fillStyle = "#222";
                    context.fillRect(0, 0, canvas.width, canvas.height);
                    context.font = "10px Verdana";
                    context.fillStyle = "#333";
                    context.fillText("loading...", 10, 25);
                    if (primeWorker != null) {
                        primeWorker.terminate();
                        primeWorker = null;
                    }
                }

                function setupEvent() {
                    primeWorker.addEventListener('message', function(event) {
                        var worker_img = event.data.img;
                        myImage.onload = function() {
                            context.drawImage(myImage, 0, 0, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height);
                            drawTimeLineContext();
                            var ppp = Math.round((scope.vs.curViewPort.eS - scope.vs.curViewPort.sS) / canvas.width);
                            buildImageCache(scope.vs.curViewPort.sS, scope.vs.curViewPort.eS, ppp,canvas.toDataURL("image/png"));
                        }
                        myImage.src = worker_img;
                    });
                }

                function drawOsci(viewState, buffer) {
                    killSpectroRenderingThread();
                    startSpectroRenderingThread(viewState, buffer);
                }

                function startSpectroRenderingThread(viewState, buffer) {
                    vs = viewState;
                    pcmperpixel = Math.round((vs.curViewPort.eS - vs.curViewPort.sS) / canvas.width);
                    primeWorker = new Worker(URL.createObjectURL(blob));
                    var parseData = buffer.getChannelData(0).subarray(vs.curViewPort.sS, vs.curViewPort.eS + (2 * N));
                    setupEvent();

                    primeWorker.postMessage({
                        'cmd': 'config',
                        'N': N
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'alpha': alpha
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'freq': freq
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'freq_low': freq_lower
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'start': Math.round(viewState.sS)
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'end': Math.round(viewState.eS)
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'myStep': pcmperpixel
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'window': windowFunction
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'cacheSide': 0
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'width': canvas.width
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'height': canvas.height
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'cacheWidth': 0
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'dynRangeInDB': dynRangeInDB
                    });
                    primeWorker.postMessage({
                        'cmd': 'config',
                        'pixelRatio': devicePixelRatio
                    });
                    primeWorker.postMessage({
                        'cmd': 'pcm',
                        'config': JSON.stringify(buffer)
                    });
                    primeWorker.postMessage({
                        'cmd': 'pcm',
                        'stream': parseData
                    });
                    primeWorker.postMessage({
                        'cmd': 'render'
                    });
                }

            }
        }
    });<|endoftext|>


<commit_before>/* global describe, it, before, beforeEach */

var path = require('path');
var when = require('when');
var delay = require('when/delay');

var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;

var Snoocore = require('../../../Snoocore');
var config = require('../config');
var util = require('./util');

describe('Snoocore Behavior Test (noauth)', function () {

  this.timeout(config.testTimeout);

  it('should GET resources while not logged in', function() {

    var reddit = util.getRawInstance();

    return reddit('/r/$subreddit/new').get({
      $subreddit: 'pcmasterrace'
    }).then(function(result) {
      var subreddit = result.data.children[0].data.subreddit;
      expect(subreddit).to.equal('pcmasterrace');
    });
  });

  it('should not get resources when not logged in', function() {
    var reddit = util.getRawInstance();
    return reddit('/api/me.json').get().then(function(data) {
      return expect(data).to.eql({});
    });
  });

  it('should not decode html', function() {
    var reddit = util.getRawInstance();
    return reddit('/r/snoocoreTest/about.json').get().then(function(result) {
      expect(result.data.description_html.indexOf('</p>')).to.not.equal(-1);
    });
  });

  it('should decode html on a per call basis', function() {
    var reddit = util.getRawInstance();
    return reddit('/r/snoocoreTest/about.json').get(null, {
      decodeHtmlEntities: true
    }).then(function(result) {
      expect(result.data.description_html.indexOf('
')).to.not.equal(-1);
    });
  });

  it('should decode html globally & respect per call override', function() {

    var reddit = util.getRawInstance();
    var secondReddit = new Snoocore({
      decodeHtmlEntities: true
    });

    return secondReddit('/r/snoocoreTest/about.json').get().then(function(result) {
      expect(result.data.description_html.indexOf('
')).to.not.equal(-1);

      // override global 'true'
      return reddit('/r/snoocoreTest/about.json').get(null, { decodeHtmlEntities: false });
    }).then(function(result) {
      expect(result.data.description_html.indexOf('</p>')).to.not.equal(-1);
    });
  });

});
<commit_msg>fix path for Snoocore require<commit_after>/* global describe, it, before, beforeEach */

var path = require('path');
var when = require('when');
var delay = require('when/delay');

var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;

var Snoocore = require('../../Snoocore');
var config = require('../config');
var util = require('./util');

describe.only('Snoocore Behavior Test (noauth)', function () {

  this.timeout(config.testTimeout);

  it('should GET resources while not logged in', function() {

    var reddit = util.getRawInstance();

    return reddit('/r/$subreddit/new').get({
      $subreddit: 'pcmasterrace'
    }).then(function(result) {
      var subreddit = result.data.children[0].data.subreddit;
      expect(subreddit).to.equal('pcmasterrace');
    });
  });

  it('should not get resources when not logged in', function() {
    var reddit = util.getRawInstance();
    return reddit('/api/me.json').get().then(function(data) {
      return expect(data).to.eql({});
    });
  });

  it('should not decode html', function() {
    var reddit = util.getRawInstance();
    return reddit('/r/snoocoreTest/about.json').get().then(function(result) {
      expect(result.data.description_html.indexOf('</p>')).to.not.equal(-1);
    });
  });

  it('should decode html on a per call basis', function() {
    var reddit = util.getRawInstance();
    return reddit('/r/snoocoreTest/about.json').get(null, {
      decodeHtmlEntities: true
    }).then(function(result) {
      expect(result.data.description_html.indexOf('
')).to.not.equal(-1);
    });
  });

  it('should decode html globally & respect per call override', function() {

    var reddit = util.getRawInstance();
    var secondReddit = new Snoocore({
      decodeHtmlEntities: true
    });

    return secondReddit('/r/snoocoreTest/about.json').get().then(function(result) {
      expect(result.data.description_html.indexOf('
')).to.not.equal(-1);

      // override global 'true'
      return reddit('/r/snoocoreTest/about.json').get(null, { decodeHtmlEntities: false });
    }).then(function(result) {
      expect(result.data.description_html.indexOf('</p>')).to.not.equal(-1);
    });
  });

});
<|endoftext|>


<commit_before>'use strict';

angular.module('confRegistrationWebApp')
  .service('ConfCache', function ConfCache($cacheFactory, $rootScope, $http, $q, uuid) {
    var cache = $cacheFactory('conf');

    var path = function (id) {
      return 'conferences/' + (id || '');
    };

    var checkCache = function (path, callback) {
      var cachedConferences = cache.get(path);
      if (angular.isDefined(cachedConferences)) {
        callback(cachedConferences, path);
      } else {
        $http.get(path).success(function (conferences) {
          cache.put(path, conferences);
          callback(conferences, path);
        });
      }
    };

    this.query = function (id) {
      checkCache(path(id), function (conferences, path) {
        $rootScope.$broadcast(path, conferences);
      });
    };

    this.get = function (id) {
      var defer = $q.defer();
      checkCache(path(id), function (conferences) {
        defer.resolve(conferences);
      });
      return defer.promise;
    };

    this.getCallback = function (id, callback) {
      checkCache(path(id), function (conferences) {
        callback(conferences);
      });
    };

    this.update = function (id, conference) {
      cache.put(path(id), conference);
    };

    this.empty = function () {
      cache.removeAll();
    };

    this.create = function (name) {
      var registrationEndTime = new Date();
      registrationEndTime.setYear(registrationEndTime.getFullYear() + 1);
      var newConferenceId = uuid();
      var newPageId = uuid();

      var data = {
        id: newConferenceId,
        name: name,
        registrationStartTime: new Date(),
        registrationEndTime: registrationEndTime,
        eventStartTime: new Date(),
        eventEndTime: registrationEndTime,
        conferenceCost: 0,
        earlyRegistrationAmount: 0,
        registrationPages: [
          {
            id: newPageId,
            conferenceId: newConferenceId,
            title: 'Your Information',
            position: 0,
            blocks: [
              {
                id: uuid(),
                pageId: newPageId,
                type: 'nameQuestion',
                profileType: 'NAME',
                title: 'Name',
                position: 0,
                required: true
              },
              {
                id: uuid(),
                pageId: newPageId,
                type: 'emailQuestion',
                title: 'Email',
                profileType: 'EMAIL',
                position: 1,
                required: true
              }
            ]
          }
        ]
      };
      return $http.post(path(), data).then(function (response) {
        if (response.status === 201) {
          var conference = response.data;
          cache.removeAll();
          return conference;
        } else {
          alert('Error creating conference. ' + response.data.errorMessage + ': ' + response.data.customErrorMessage);
        }
      });
    };
  });
<commit_msg>Set paymentGatewayType to 'TRUST COMMERCE'<commit_after>'use strict';

angular.module('confRegistrationWebApp')
  .service('ConfCache', function ConfCache($cacheFactory, $rootScope, $http, $q, uuid) {
    var cache = $cacheFactory('conf');

    var path = function (id) {
      return 'conferences/' + (id || '');
    };

    var checkCache = function (path, callback) {
      var cachedConferences = cache.get(path);
      if (angular.isDefined(cachedConferences)) {
        callback(cachedConferences, path);
      } else {
        $http.get(path).success(function (conferences) {
          cache.put(path, conferences);
          callback(conferences, path);
        });
      }
    };

    this.query = function (id) {
      checkCache(path(id), function (conferences, path) {
        $rootScope.$broadcast(path, conferences);
      });
    };

    this.get = function (id) {
      var defer = $q.defer();
      checkCache(path(id), function (conferences) {
        defer.resolve(conferences);
      });
      return defer.promise;
    };

    this.getCallback = function (id, callback) {
      checkCache(path(id), function (conferences) {
        callback(conferences);
      });
    };

    this.update = function (id, conference) {
      cache.put(path(id), conference);
    };

    this.empty = function () {
      cache.removeAll();
    };

    this.create = function (name) {
      var registrationEndTime = new Date();
      registrationEndTime.setYear(registrationEndTime.getFullYear() + 1);
      var newConferenceId = uuid();
      var newPageId = uuid();

      var data = {
        id: newConferenceId,
        name: name,
        registrationStartTime: new Date(),
        registrationEndTime: registrationEndTime,
        eventStartTime: new Date(),
        eventEndTime: registrationEndTime,
        conferenceCost: 0,
        earlyRegistrationAmount: 0,
        paymentGatewayType: 'TRUST_COMMERCE',
        registrationPages: [
          {
            id: newPageId,
            conferenceId: newConferenceId,
            title: 'Your Information',
            position: 0,
            blocks: [
              {
                id: uuid(),
                pageId: newPageId,
                type: 'nameQuestion',
                profileType: 'NAME',
                title: 'Name',
                position: 0,
                required: true
              },
              {
                id: uuid(),
                pageId: newPageId,
                type: 'emailQuestion',
                title: 'Email',
                profileType: 'EMAIL',
                position: 1,
                required: true
              }
            ]
          }
        ]
      };
      return $http.post(path(), data).then(function (response) {
        if (response.status === 201) {
          var conference = response.data;
          cache.removeAll();
          return conference;
        } else {
          alert('Error creating conference. ' + response.data.errorMessage + ': ' + response.data.customErrorMessage);
        }
      });
    };
  });
<|endoftext|>


<commit_before>define(function() {
    var console = window.console;

    function noop() {}

    function getApplyableLog(console, method) {
        method = method || "log";

        // http://stackoverflow.com/a/5539378/319878
        // IE patch
        return Function.prototype.bind.call(console[method], console);
    }

    function wrap(name, console, method) {
        return function() {
            var args = Array.prototype.slice.call(arguments);
            args = [name].concat(args);
            var log = getApplyableLog(console);
            log.apply(console, args);
        }
    }

    function createLog(name, on) {
        on = (false !== on);

        var log = !on ? noop : wrap(name, console, "log");
        var error = wrap(name, console, "error");

        var f = log;
        f.error = error;

        // Return a log function that prepends the logger name to the arguments.
        return f;
    }

    return {
        createLog: createLog
    };
});<commit_msg>Don't reference window, so this now works for node as well.<commit_after>define(function() {
    // Get handle to console in node or browser
    var _console = ("undefined" !== typeof console && console);

    function noop() {}

    function getApplyableLog(console, method) {
        method = method || "log";

        // http://stackoverflow.com/a/5539378/319878
        // IE patch
        return Function.prototype.bind.call(console[method], console);
    }

    function wrap(name, console, method) {
        return function() {
            var args = Array.prototype.slice.call(arguments);
            args = [name].concat(args);
            var log = getApplyableLog(console);
            log.apply(console, args);
        }
    }

    function createLog(name, on) {
        on = (false !== on);

        var log = !on ? noop : wrap(name, _console, "log");
        var error = wrap(name, _console, "error");

        var f = log;
        f.error = error;

        // Return a log function that prepends the logger name to the arguments.
        return f;
    }

    return {
        createLog: createLog
    };
});
<|endoftext|>


<commit_before>// The last time a refresh of the page was done
let lastRefresh = (new Date()).getTime();
let jiraLogo = chrome.extension.getURL("images/jira.png");
let jiraUrl = undefined;
let acceptanceStartString = 'h3. Acceptance Criteria';
let acceptanceEndString  = 'h3. Notes';
let prTemplate = '';
let prTemplateEnabled = true;
let prTitleEnabled = true;
let NL = "\r";
chrome.storage.sync.get({
    jiraUrl: '',
    acceptanceStartString: 'h3. Acceptance Criteria',
    acceptanceEndString: 'h3. Notes',
    prTemplateEnabled: true,
    prTitleEnabled: true,
    prTemplate: '### Fix {{TICKETNUMBER}}' + NL +
        'Link to ticket: {{TICKETURL}}' + NL +
        NL +
        '### What has been done' +  NL +
        '- ' +  NL +
        '- ' +  NL +
        NL +
        '### How to test' +  NL +
        '- ' +  NL +
        '- ' +  NL +
        NL +
        '### Acceptance criteria' +  NL +
        '{{ACCEPTANCE}}' +
        NL +
        '### Todo' +  NL +
        '- [ ] ' +  NL +
        '- [ ] ' +  NL +
        NL +
        '### Notes' +  NL +
        '- ' +  NL +
        '- '
}, function(items) {
    jiraUrl = items.jiraUrl;
    acceptanceStartString = items.acceptanceStartString;
    acceptanceEndString = items.acceptanceEndString;
    prTemplate = items.prTemplate;
    prTemplateEnabled = items.prTemplateEnabled;
    prTitleEnabled = items.prTitleEnabled;

    if (jiraUrl == '') {
        console.error('GitHub Jira plugin could not load: Jira URL is not set.');
        return;
    }

    //Check login
    chrome.runtime.sendMessage(
        {query: 'getSession', jiraUrl: jiraUrl},
        function(loginResult) {
            if (loginResult.name == undefined) {
                console.error('You are not logged in to Jira at http://'+jiraUrl+' - Please login.');
                return;
            }

            // Check page if content changed (for AJAX pages)
            $(document).on('DOMNodeInserted', function() {
                if ((new Date()).getTime() - lastRefresh >= 250) {
                    lastRefresh = (new Date()).getTime();
                    checkPage();
                }
            });

            // Check page initially
            checkPage();
        }
    );

});

function checkPage() {
    let url = window.location.href;
    if (url.match(/github\.com\/(.*)\/(.*)\/pull\//) != null) {
        setTimeout(function() {
            handleCommitsTitle();
            handlePrPage();
        }, 200); //Small timeout for dom to finish setup
    }

    if (url.match(/github\.com\/(.*)\/(.*)\/pulls/) != null) {
        //@todo PR overview page
    }

    if (url.match(/github\.com\/(.*)\/(.*)\/compare\/(.*)/) != null) {
        //Create PR page
        setTimeout(function() {
            handleCommitsTitle();
            handlePrCreatePage();
        }, 200); //Small timeout for dom to finish setup
    }
}

function handleCommitsTitle() {
    let baseTicketUrl = 'https://'+jiraUrl+'/browse/';

    $(".commit-message code").each(function(index, item) {
        let $item = $(item);
        let $itemLink = $item.find('a');
        let itemLinkHtml = $itemLink.html();

        if (!itemLinkHtml.match(/([A-Z]+-[0-9]+)/g)) {
            return;
        }

        let aHref = $itemLink[0].href;
        let splittedContent = itemLinkHtml.split(/([A-Z]+-[0-9]+)/g);

        $item.html('');
        for(var i=0; i< splittedContent.length; i+=3) {
            $item.append(
                ''+splittedContent[0]+'' +
                ''+ splittedContent[1] +'' +
                ' '+splittedContent[2].trim()+''
            );
        }
    });
}

function handlePrPage() {
    let title = $("h1 > span.js-issue-title").html();
    if (title == undefined || $('#insertedJiraData').length > 0) {
        //If we didn't find a ticket, or the data is already inserted, cancel.
        return false;
    }

    let ticketNumber = title.match(/([A-Z]+-[0-9]+)/);
    if (null == ticketNumber) {
        //Title was found, but ticket number wasn't.
        return false;
    }
    ticketNumber = ticketNumber[0];
    let ticketUrl = 'https://'+jiraUrl+'/browse/' + ticketNumber;

    //Replace title with clickable link to jira ticket
    $("h1 > span.js-issue-title").html(
        title.replace(
            /([A-Z]+-[0-9]+)/,
            ''+ticketNumber+''
        )
    );

    //Open up a handle for data
    $('#partial-discussion-header').append(
        '
Loading ticket '+ticketNumber+'...
'
    );

    //Load up data from jira
    chrome.runtime.sendMessage(
        {query: 'getTicketInfo', jiraUrl: jiraUrl, ticketNumber: ticketNumber},
        function(result) {
            let assignee = result.fields.assignee;
            let reporter = result.fields.reporter;

            let assigneeImage = assignee.avatarUrls['16x16'];
            let reporterImage = reporter.avatarUrls['16x16'];

            $("#insertedJiraData").html(
                '
' +
                    '
' +
                        '' +
                            ' Jira' +
                        '' +
                    '
' +
                    '
' +
                    '' +
                    ' ' + result.fields.status.name +
                    '' +
                    '
' +
                    '
' +
                        '['+ticketNumber+'] - '+result.fields.summary+'' +
                        ' - Reported by ' +
                        ' '+reporter.displayName+'' +
                        ' and assigned to ' +
                        ' '+assignee.displayName+'' +
                    '
' +
                '
'
            );
        }
    );
}

function handlePrCreatePage() {
    if (prTitleEnabled == false && prTemplateEnabled == false) {
        return;
    }

    let body = $("textarea#pull_request_body");
    if (body.attr('jira-loading') == 1) {
        return false; //Already loading
    }
    body.attr('jira-loading', 1);

    let title = document.title;
    let ticketUrl = '**No linked ticket**';
    let acceptanceList = '';
    let ticketNumber = '?';
    if (title != undefined) {
        let titleMatch = title.match(/([a-zA-Z]+-[0-9]+)/);
        if (titleMatch) {
            // Found a title, fetch some info from the ticket
            // Get the last one in the list.
            ticketNumber = titleMatch[titleMatch.length - 1];
            ticketUrl = 'https://'+jiraUrl+'/browse/' + ticketNumber;

            //Load up data from jira
            chrome.runtime.sendMessage(
                {query: 'getTicketInfo', jiraUrl: jiraUrl, ticketNumber: ticketNumber},
                function(result) {
                    if (prTitleEnabled) {
                        $('input#pull_request_title').val('[' + ticketNumber.toUpperCase() + '] ' + result.fields.summary);
                    }

                    let description = result.fields.description;

                    if (typeof description == 'string' || description instanceof String) {
                        description = description.substr(description.indexOf(acceptanceStartString), description.length);
                        description = description.substr(0, description.indexOf(acceptanceEndString));
                        description = description.substr(acceptanceStartString.length, description.length - acceptanceEndString.length);

                        acceptanceList = description.replace(/#/g, '- [ ]').replace(/^\s+|\s+$/g, '');
                    }
                }
            );
        }
    }

    if (prTemplateEnabled) {
        body.val(prTemplate.replace('{{TICKETURL}}', ticketUrl).replace('{{TICKETNUMBER}}', ticketNumber).replace('{{ACCEPTANCE}}', acceptanceList));
    }
}
<commit_msg>Make the assignee details optional<commit_after>// The last time a refresh of the page was done
let lastRefresh = (new Date()).getTime();
let jiraLogo = chrome.extension.getURL("images/jira.png");
let jiraUrl = undefined;
let acceptanceStartString = 'h3. Acceptance Criteria';
let acceptanceEndString  = 'h3. Notes';
let prTemplate = '';
let prTemplateEnabled = true;
let prTitleEnabled = true;
let NL = "\r";
chrome.storage.sync.get({
    jiraUrl: '',
    acceptanceStartString: 'h3. Acceptance Criteria',
    acceptanceEndString: 'h3. Notes',
    prTemplateEnabled: true,
    prTitleEnabled: true,
    prTemplate: '### Fix {{TICKETNUMBER}}' + NL +
        'Link to ticket: {{TICKETURL}}' + NL +
        NL +
        '### What has been done' +  NL +
        '- ' +  NL +
        '- ' +  NL +
        NL +
        '### How to test' +  NL +
        '- ' +  NL +
        '- ' +  NL +
        NL +
        '### Acceptance criteria' +  NL +
        '{{ACCEPTANCE}}' +
        NL +
        '### Todo' +  NL +
        '- [ ] ' +  NL +
        '- [ ] ' +  NL +
        NL +
        '### Notes' +  NL +
        '- ' +  NL +
        '- '
}, function(items) {
    jiraUrl = items.jiraUrl;
    acceptanceStartString = items.acceptanceStartString;
    acceptanceEndString = items.acceptanceEndString;
    prTemplate = items.prTemplate;
    prTemplateEnabled = items.prTemplateEnabled;
    prTitleEnabled = items.prTitleEnabled;

    if (jiraUrl == '') {
        console.error('GitHub Jira plugin could not load: Jira URL is not set.');
        return;
    }

    //Check login
    chrome.runtime.sendMessage(
        {query: 'getSession', jiraUrl: jiraUrl},
        function(loginResult) {
            if (loginResult.name == undefined) {
                console.error('You are not logged in to Jira at http://'+jiraUrl+' - Please login.');
                return;
            }

            // Check page if content changed (for AJAX pages)
            $(document).on('DOMNodeInserted', function() {
                if ((new Date()).getTime() - lastRefresh >= 250) {
                    lastRefresh = (new Date()).getTime();
                    checkPage();
                }
            });

            // Check page initially
            checkPage();
        }
    );

});

function checkPage() {
    let url = window.location.href;
    if (url.match(/github\.com\/(.*)\/(.*)\/pull\//) != null) {
        setTimeout(function() {
            handleCommitsTitle();
            handlePrPage();
        }, 200); //Small timeout for dom to finish setup
    }

    if (url.match(/github\.com\/(.*)\/(.*)\/pulls/) != null) {
        //@todo PR overview page
    }

    if (url.match(/github\.com\/(.*)\/(.*)\/compare\/(.*)/) != null) {
        //Create PR page
        setTimeout(function() {
            handleCommitsTitle();
            handlePrCreatePage();
        }, 200); //Small timeout for dom to finish setup
    }
}

function handleCommitsTitle() {
    let baseTicketUrl = 'https://'+jiraUrl+'/browse/';

    $(".commit-message code").each(function(index, item) {
        let $item = $(item);
        let $itemLink = $item.find('a');
        let itemLinkHtml = $itemLink.html();

        if (!itemLinkHtml.match(/([A-Z]+-[0-9]+)/g)) {
            return;
        }

        let aHref = $itemLink[0].href;
        let splittedContent = itemLinkHtml.split(/([A-Z]+-[0-9]+)/g);

        $item.html('');
        for(var i=0; i< splittedContent.length; i+=3) {
            $item.append(
                ''+splittedContent[0]+'' +
                ''+ splittedContent[1] +'' +
                ' '+splittedContent[2].trim()+''
            );
        }
    });
}

function handlePrPage() {
    let title = $("h1 > span.js-issue-title").html();
    if (title == undefined || $('#insertedJiraData').length > 0) {
        //If we didn't find a ticket, or the data is already inserted, cancel.
        return false;
    }

    let ticketNumber = title.match(/([A-Z]+-[0-9]+)/);
    if (null == ticketNumber) {
        //Title was found, but ticket number wasn't.
        return false;
    }
    ticketNumber = ticketNumber[0];
    let ticketUrl = 'https://'+jiraUrl+'/browse/' + ticketNumber;

    //Replace title with clickable link to jira ticket
    $("h1 > span.js-issue-title").html(
        title.replace(
            /([A-Z]+-[0-9]+)/,
            ''+ticketNumber+''
        )
    );

    //Open up a handle for data
    $('#partial-discussion-header').append(
        '
Loading ticket '+ticketNumber+'...
'
    );

    //Load up data from jira
    chrome.runtime.sendMessage(
        {query: 'getTicketInfo', jiraUrl: jiraUrl, ticketNumber: ticketNumber},
        function(result) {
            const reporter = result.fields.reporter;
            const assignee = result.fields.assignee || false;
            let assigneeDetails = '';

            if (assignee) {
                assigneeDetails = ` and assigned to

                    ${assignee.displayName}
                `;
            }

            $("#insertedJiraData").html(
                `

                            Jira

                            ${result.fields.status.name}

                                [${ticketNumber}] - ${result.fields.summary}

                         - Reported by

                                ${reporter.displayName}
                        ${assigneeDetails}

`
            );
        }
    );
}

function handlePrCreatePage() {
    if (prTitleEnabled == false && prTemplateEnabled == false) {
        return;
    }

    let body = $("textarea#pull_request_body");
    if (body.attr('jira-loading') == 1) {
        return false; //Already loading
    }
    body.attr('jira-loading', 1);

    let title = document.title;
    let ticketUrl = '**No linked ticket**';
    let acceptanceList = '';
    let ticketNumber = '?';
    if (title != undefined) {
        let titleMatch = title.match(/([a-zA-Z]+-[0-9]+)/);
        if (titleMatch) {
            // Found a title, fetch some info from the ticket
            // Get the last one in the list.
            ticketNumber = titleMatch[titleMatch.length - 1];
            ticketUrl = 'https://'+jiraUrl+'/browse/' + ticketNumber;

            //Load up data from jira
            chrome.runtime.sendMessage(
                {query: 'getTicketInfo', jiraUrl: jiraUrl, ticketNumber: ticketNumber},
                function(result) {
                    if (prTitleEnabled) {
                        $('input#pull_request_title').val('[' + ticketNumber.toUpperCase() + '] ' + result.fields.summary);
                    }

                    let description = result.fields.description;

                    if (typeof description == 'string' || description instanceof String) {
                        description = description.substr(description.indexOf(acceptanceStartString), description.length);
                        description = description.substr(0, description.indexOf(acceptanceEndString));
                        description = description.substr(acceptanceStartString.length, description.length - acceptanceEndString.length);

                        acceptanceList = description.replace(/#/g, '- [ ]').replace(/^\s+|\s+$/g, '');
                    }
                }
            );
        }
    }

    if (prTemplateEnabled) {
        body.val(prTemplate.replace('{{TICKETURL}}', ticketUrl).replace('{{TICKETNUMBER}}', ticketNumber).replace('{{ACCEPTANCE}}', acceptanceList));
    }
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
//
import * as Basic from '../../components/basic';
import * as Advanced from '../../components/advanced';
import * as Domain from '../../domain';
import { SecurityManager } from '../../redux';

const securityManager = new SecurityManager();

/**
 * Switch user - modal dialog.
 *
 * @author Radek Tomiška
 * @since 10.5.0
 */
class SwitchUser extends Basic.AbstractContent {

  constructor(props, context) {
    super(props, context);
    this.state = {
      _showLoading: false
    };
  }

  onSave(event) {
    if (event) {
      event.preventDefault();
    }
    if (!this.refs.form.isFormValid()) {
      return;
    }
    const username = this.refs.username.getValue();
    //
    this.context.store.dispatch(securityManager.switchUser(username, (result) => {
      const { onHide } = this.props;
      if (result) {
        this.addMessage({
          level: 'success',
          key: 'core-switch-user-success',
          message: this.i18n('content.identity.switch-user.message.success', { username })
        });
        this.context.history.replace(`/`);
      }
      // modal is closed on error too => currently logged user is logout anyway
      onHide();
    }));
  }

  render() {
    const {
      rendered,
      show,
      onHide,
      userContext
    } = this.props;
    const showLoading = userContext.showLoading;
    //
    if (!rendered) {
      return null;
    }
    //
    const forceSearchParameters = new Domain.SearchParameters().setFilter('_permission', 'SWITCHUSER');
    //
    return (
      <Basic.Modal
        show={ show }
        onHide={ onHide }
        keyboard
        backdrop="static"
        onEnter={ () => { this.refs.username.focus(); } }>
        <form onSubmit={ this.onSave.bind(this) }>
          <Basic.Modal.Header
            closeButton
            icon="component:switch-user"
            text={ this.i18n('content.identity.switch-user.header') }/>
          <Basic.Modal.Body>
            <Basic.AbstractForm
              ref="form"
              showLoading={ showLoading }>

              <Advanced.IdentitySelect
                ref="username"
                label={ this.i18n('content.identity.switch-user.username.label') }
                helpBlock={ this.i18n('content.identity.switch-user.username.help') }
                required
                returnProperty="username"
                emptyOptionLabel={ false }
                forceSearchParameters={ forceSearchParameters }/>

            </Basic.AbstractForm>
          </Basic.Modal.Body>
          <Basic.Modal.Footer>
            <Basic.Button
              level="link"
              showLoading={ showLoading }
              onClick={ onHide }>
              { this.i18n('button.close') }
            </Basic.Button>
            <Basic.Button
              type="submit"
              level="success"
              showLoading={ showLoading }
              showLoadingIcon
              showLoadingText={ this.i18n('content.identity.switch-user.button.saving') }
              rendered={ SecurityManager.hasAuthority('IDENTITY_SWITCHUSER') }>
              { this.i18n('content.identity.switch-user.button.save') }
            </Basic.Button>
          </Basic.Modal.Footer>
        </form>
      </Basic.Modal>
    );
  }

}

SwitchUser.propTypes = {
  ...Basic.AbstractContent.propTypes,
  /**
   * Modal is shown.
   */
  show: PropTypes.bool,
  /**
   * onHide callback
   */
  onHide: PropTypes.func
};

SwitchUser.defaultProps = {
  ...Basic.AbstractContent.defaultProps
};

function select(state) {
  return {
    userContext: state.security.userContext
  };
}

export default connect(select)(SwitchUser);
<commit_msg>FE: rename switch user input to try prevent browser autocompletition<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
//
import * as Basic from '../../components/basic';
import * as Advanced from '../../components/advanced';
import * as Domain from '../../domain';
import { SecurityManager } from '../../redux';

const securityManager = new SecurityManager();

/**
 * Switch user - modal dialog.
 *
 * @author Radek Tomiška
 * @since 10.5.0
 */
class SwitchUser extends Basic.AbstractContent {

  constructor(props, context) {
    super(props, context);
    this.state = {
      _showLoading: false
    };
  }

  onSave(event) {
    if (event) {
      event.preventDefault();
    }
    if (!this.refs.form.isFormValid()) {
      return;
    }
    const username = this.refs.targetIdentity.getValue();
    //
    this.context.store.dispatch(securityManager.switchUser(username, (result) => {
      const { onHide } = this.props;
      if (result) {
        this.addMessage({
          level: 'success',
          key: 'core-switch-user-success',
          message: this.i18n('content.identity.switch-user.message.success', { username })
        });
        this.context.history.replace(`/`);
      }
      // modal is closed on error too => currently logged user is logout anyway
      onHide();
    }));
  }

  render() {
    const {
      rendered,
      show,
      onHide,
      userContext
    } = this.props;
    const showLoading = userContext.showLoading;
    //
    if (!rendered) {
      return null;
    }
    //
    const forceSearchParameters = new Domain.SearchParameters().setFilter('_permission', 'SWITCHUSER');
    //
    return (
      <Basic.Modal
        show={ show }
        onHide={ onHide }
        keyboard
        backdrop="static"
        onEnter={ () => { this.refs.targetIdentity.focus(); } }>
        <form onSubmit={ this.onSave.bind(this) }>
          <Basic.Modal.Header
            closeButton
            icon="component:switch-user"
            text={ this.i18n('content.identity.switch-user.header') }/>
          <Basic.Modal.Body>
            <Basic.AbstractForm
              ref="form"
              showLoading={ showLoading }>

              <Advanced.IdentitySelect
                ref="targetIdentity"
                label={ this.i18n('content.identity.switch-user.username.label') }
                helpBlock={ this.i18n('content.identity.switch-user.username.help') }
                required
                returnProperty="username"
                emptyOptionLabel={ false }
                forceSearchParameters={ forceSearchParameters }/>

            </Basic.AbstractForm>
          </Basic.Modal.Body>
          <Basic.Modal.Footer>
            <Basic.Button
              level="link"
              showLoading={ showLoading }
              onClick={ onHide }>
              { this.i18n('button.close') }
            </Basic.Button>
            <Basic.Button
              type="submit"
              level="success"
              showLoading={ showLoading }
              showLoadingIcon
              showLoadingText={ this.i18n('content.identity.switch-user.button.saving') }
              rendered={ SecurityManager.hasAuthority('IDENTITY_SWITCHUSER') }>
              { this.i18n('content.identity.switch-user.button.save') }
            </Basic.Button>
          </Basic.Modal.Footer>
        </form>
      </Basic.Modal>
    );
  }

}

SwitchUser.propTypes = {
  ...Basic.AbstractContent.propTypes,
  /**
   * Modal is shown.
   */
  show: PropTypes.bool,
  /**
   * onHide callback
   */
  onHide: PropTypes.func
};

SwitchUser.defaultProps = {
  ...Basic.AbstractContent.defaultProps
};

function select(state) {
  return {
    userContext: state.security.userContext
  };
}

export default connect(select)(SwitchUser);
<|endoftext|>


<commit_before>#!/usr/bin/env node --harmony
//
//   Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing,
//   software distributed under the License is distributed on an "AS
//   IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
//   express or implied.  See the License for the specific language
//   governing permissions and limitations under the License.
//

'use strict';

// Minimal connection manager that keeps TCP sockets alive even if
// rest of the system is restarted. Allows nondistruptive updates.

require('../../lib/init')('irc-connman');

var net = require('net'),
    carrier = require('carrier'),
    isUtf8 = require('is-utf8'),
    iconv = require('iconv-lite'),
    conf = require('../../lib/conf'),
    log = require('../../lib/log'),
    courier = require('../../lib/courier').createEndPoint('connectionmanager');

var sockets = {};
var nextNetworkConnectionSlot = {};

const IDENTD_PORT = 113;

courier.sendNoWait('ircparser', 'restarted');

// Start IDENT server
if (conf.get('irc:identd')) {
    net.createServer(handleIdentConnection).listen(IDENTD_PORT);
}

function handleIdentConnection(conn) {
    var timer = setTimeout(function() {
        if (conn) {
            conn.destroy();
        }
    }, 3000);

    carrier.carry(conn, function(line) {
        var ports = line.split(',');
        var localPort = parseInt(ports[0]);
        var remotePort = parseInt(ports[1]);
        var prefix = localPort + ', ' + remotePort;
        var found = false;
        var resp;

        if (!isNaN(localPort) && !isNaN(remotePort)) {
            for (var userId in sockets) {
                if (sockets[userId].localPort === localPort &&
                    sockets[userId].remotePort === remotePort &&
                    sockets[userId].remoteAddress === conn.remoteAddress) {
                    found = true;
                    resp = prefix + ' : USERID : UNIX : ' + sockets[userId].nick + '\r\n';
                    break;
                }
            }

            if (!found) {
                resp = prefix + ' : ERROR : NO-USER\r\n';
            }
        }

        clearTimeout(timer);

        if (resp) {
            conn.write(resp);
        }
        conn.end();

        log.info('Ident request from ' + conn.remoteAddress + ', req: ' + line +', resp: ' + resp);
    });
}

// Connect
courier.on('connect', function(params) {
    var network = params.network;

    var options = {
        host: conf.get('irc:networks:' + network + ':host'),
        port: conf.get('irc:networks:' + network + ':port')
    };

    if (!nextNetworkConnectionSlot[network]) {
        nextNetworkConnectionSlot = Date.now();
    }

    var delay = nextNetworkConnectionSlot[network] - Date.now;
    var rateLimit = conf.get('irc:networks:' + network + ':rate_limit'); // connections per minute

    nextNetworkConnectionSlot[network] += Math.round(60 / rateLimit * 1000);

    setTimeout(function() {
        connect(options, params.userId, params.nick, network);
    }, delay);
});

function connect(options, userId, nick, network) {
    var pingTimer;
    var client = net.connect(options);
    client.nick = nick;

    client.setKeepAlive(true, 2 * 60 * 1000); // 2 minutes

    function sendPing() {
        client.write('PING ' + options.host + '\r\n');
    }

    client.on('connect', function() {
        courier.sendNoWait('ircparser', {
            type: 'connected',
            userId: userId,
            network: network
        });

        pingTimer = setInterval(sendPing, 60 * 1000);
    });

    var buffer = '';

    client.on('data', function(data) {
        // IRC protocol doesn't have character set concept, we need to guess.
        // Algorithm is simple. If received binary data is valid utf8 then use
        // that. Else assume that the character set is iso-8859-15.
        data = isUtf8(data) ? data.toString() : iconv.decode(data, 'iso-8859-15');
        data = buffer + data;

        var lines = data.split(/\r\n/);
        buffer = lines.pop(); // Save the potential partial line to buffer

        lines.forEach(function(line) {
            courier.sendNoWait('ircparser', {
                type: 'data',
                userId: userId,
                network: network,
                line: line
            });
        });
    });

    client.on('close', function(had_error) {
        log.info(userId, 'IRC connection closed by the server or network.');
        courier.sendNoWait('ircparser', {
            type: 'disconnected',
            userId: userId,
            network: network,
            reason: had_error ? 'transmission error' : 'connection closed by the server'
        });

        clearInterval(pingTimer);
    });

    sockets[userId + ':' + network] = client;
}

// Disconnect
courier.on('disconnect', function(params) {
    var userId = params.userId;
    var network = params.network;

    sockets[userId + ':' + network].end();
    delete sockets[userId + ':' + network];
});

// Write
courier.on('write', function(params) {
    var userId = params.userId;
    var network = params.network;
    var data = params.line;

    if (!sockets[userId + ':' + network]) {
        log.warn(userId, 'Non-existent socket');
        return;
    }

    if (typeof(data) === 'string') {
        data = [data];
    }

    for (var i = 0; i < data.length; i++) {
        sockets[userId + ':' + network].write(data[i] + '\r\n');
    }
});

courier.start();
<commit_msg>IRC connect() fixes<commit_after>#!/usr/bin/env node --harmony
//
//   Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing,
//   software distributed under the License is distributed on an "AS
//   IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
//   express or implied.  See the License for the specific language
//   governing permissions and limitations under the License.
//

'use strict';

// Minimal connection manager that keeps TCP sockets alive even if
// rest of the system is restarted. Allows nondistruptive updates.

require('../../lib/init')('irc-connman');

var net = require('net'),
    carrier = require('carrier'),
    isUtf8 = require('is-utf8'),
    iconv = require('iconv-lite'),
    conf = require('../../lib/conf'),
    log = require('../../lib/log'),
    courier = require('../../lib/courier').createEndPoint('connectionmanager');

var sockets = {};
var nextNetworkConnectionSlot = {};

const IDENTD_PORT = 113;

courier.sendNoWait('ircparser', 'restarted');

// Start IDENT server
if (conf.get('irc:identd')) {
    net.createServer(handleIdentConnection).listen(IDENTD_PORT);
}

function handleIdentConnection(conn) {
    var timer = setTimeout(function() {
        if (conn) {
            conn.destroy();
        }
    }, 3000);

    carrier.carry(conn, function(line) {
        var ports = line.split(',');
        var localPort = parseInt(ports[0]);
        var remotePort = parseInt(ports[1]);
        var prefix = localPort + ', ' + remotePort;
        var found = false;
        var resp;

        if (!isNaN(localPort) && !isNaN(remotePort)) {
            for (var userId in sockets) {
                if (sockets[userId].localPort === localPort &&
                    sockets[userId].remotePort === remotePort &&
                    sockets[userId].remoteAddress === conn.remoteAddress) {
                    found = true;
                    resp = prefix + ' : USERID : UNIX : ' + sockets[userId].nick + '\r\n';
                    break;
                }
            }

            if (!found) {
                resp = prefix + ' : ERROR : NO-USER\r\n';
            }
        }

        clearTimeout(timer);

        if (resp) {
            conn.write(resp);
        }
        conn.end();

        log.info('Ident request from ' + conn.remoteAddress + ', req: ' + line +', resp: ' + resp);
    });
}

// Connect
courier.on('connect', function(params) {
    var network = params.network;

    var options = {
        host: conf.get('irc:networks:' + network + ':host'),
        port: conf.get('irc:networks:' + network + ':port')
    };

    if (!nextNetworkConnectionSlot[network]) {
        nextNetworkConnectionSlot[network] = Date.now();
    }

    var delay = nextNetworkConnectionSlot[network] - Date.now;
    var rateLimit = conf.get('irc:networks:' + network + ':rate_limit'); // connections per minute

    nextNetworkConnectionSlot[network] += Math.round(60 / rateLimit * 1000);

    setTimeout(function() {
        connect(options, params.userId, params.nick, network);
    }, delay);
});

// Disconnect
courier.on('disconnect', function(params) {
    var userId = params.userId;
    var network = params.network;

    sockets[userId + ':' + network].end();
    delete sockets[userId + ':' + network];
});

// Write
courier.on('write', function(params) {
    var userId = params.userId;
    var network = params.network;
    var data = params.line;

    if (!sockets[userId + ':' + network]) {
        log.warn(userId, 'Non-existent socket');
        return;
    }

    if (typeof(data) === 'string') {
        data = [data];
    }

    for (var i = 0; i < data.length; i++) {
        sockets[userId + ':' + network].write(data[i] + '\r\n');
    }
});

courier.start();

function connect(options, userId, nick, network) {
    var socket = net.connect(options);
    socket.nick = nick;

    socket.setKeepAlive(true, 2 * 60 * 1000); // 2 minutes

    function sendPing() {
        socket.write('PING ' + options.host + '\r\n');
    }

    socket.on('connect', function() {
        courier.sendNoWait('ircparser', {
            type: 'connected',
            userId: userId,
            network: network
        });

        socket.pingTimer = setInterval(sendPing, 60 * 1000);
    });

    var buffer = '';

    socket.on('data', function(data) {
        // IRC protocol doesn't have character set concept, we need to guess.
        // Algorithm is simple. If received binary data is valid utf8 then use
        // that. Else assume that the character set is iso-8859-15.
        data = isUtf8(data) ? data.toString() : iconv.decode(data, 'iso-8859-15');
        data = buffer + data;

        var lines = data.split(/\r\n/);
        buffer = lines.pop(); // Save the potential partial line to buffer

        lines.forEach(function(line) {
            courier.sendNoWait('ircparser', {
                type: 'data',
                userId: userId,
                network: network,
                line: line
            });
        });
    });

    socket.on('end', function() {
        handleEnd(false, userId, network);
    });

    socket.on('error', function() {
        handleEnd(true, userId, network);
    });

    socket.on('close', function(hadError) {
        handleEnd(hadError, userId, network);
    });

    sockets[userId + ':' + network] = socket;
}

function handleEnd(hadError, userId, network) {
    var socket = sockets[userId + ':' + network];

    if (!socket) {
        // Already handled
        return;
    }

    delete sockets[userId + ':' + network];
    clearInterval(socket.pingTimer);

    log.info(userId, 'IRC connection closed by the server or network.');

    courier.sendNoWait('ircparser', {
        type: 'disconnected',
        userId: userId,
        network: network,
        reason: hadError ? 'transmission error' : 'connection closed by the server'
    });
}
<|endoftext|>


<commit_before>/*global Stem, _, Backbone, JST, $ */

Stem.Views = Stem.Views || {};

(function () {
    'use strict';

    Stem.Views.SearchAsForm = Backbone.View.extend({

        // Markup stored as external template.

        template: JST['app/scripts/templates/searchAsForm.ejs'],

        // First level element is a `<form>`.

        tagName: 'form',

        // Use `.search` class to get search form styles.

        className: 'search',

        // Listen to events that change the input or
        // click on the search link to initiate a search.

        events: {
            'input input': 'changed',
            'submit': 'submitted'
        },

        // Default values for options.

        defaults: {
            showLabel: true,   // Should label be visible
            theme: ''          // Theme to apply
        },

        // Options supported by this view
        // include:
        // - `.theme` for a theme class
        // - `.showLabel` set `false` to suppress display of search label

        initialize: function (options) {

            // Save any options passed to constructor.

            this.options = _.extend({}, this.defaults, options);

            // If the model changes, we might need to
            // update the view.

            this.listenTo(this.model, 'change', this.modelUpdated);

            // Return view for method chaining.

            return this;

        },

        render: function () {

            // After normal render, add a11y `role` and
            // other hints to make iOS treat the control
            // as a search box (without restyling it).

            this.$el.html(this.template(this.model.toJSON()))
                .attr('role','search')
                .attr('action', '.')
                .attr('id',  _.uniqueId('search_'));

            // Set the initial query parameters

            if (this.model.get('query')) {
                this.$el.find('input').val(this.model.get('query'));
            }

            // If a theme has been requested, add it
            // as a class.

            if (this.options.theme) {
                this.$el.addClass(this.options.theme);
            }

            // If the label should be visible, remove
            // the screen-reader only class.

            if (this.options.showLabel) {
                this.$el.find('label').removeClass('util--sr-only');
            }

            // Return view for method chaining.

            return this;

        },

        // If the user changes the query value, we
        // need to update the underlying model.

        changed: function(ev) {

            // Get the current input value.

            var query = $(ev.currentTarget).val();

            // Update the model with the current query..

            this.model.set('query', query);

        },

        // If user clicks on the search button,
        // pass it up the chain so the search
        // can be executed.

        submitted: function(ev) {

            // Trigger a submit event on this view.

            this.trigger('submit');

            // Prevent further event handling.

            ev.preventDefault();
            return false;

        },

        // If the model has changed due to,
        // another view, we update this view.

        modelUpdated: function() {

            var query = this.model.get('query');

            // Only update the view if it's not in
            // focus to avoid messing with the users
            // while they're typing. Note that we
            // have multiple parallel `<input>`
            // elements to handle responsive design.

            this.$el.find('input').each(function() {
                if (!$(this).is(":focus")) {
                    $(this).val(query);
                }
            });

        }

    });

})();
<commit_msg>handle model/view change conflict<commit_after>/*global Stem, _, Backbone, JST, $ */

Stem.Views = Stem.Views || {};

(function () {
    'use strict';

    Stem.Views.SearchAsForm = Backbone.View.extend({

        // Markup stored as external template.

        template: JST['app/scripts/templates/searchAsForm.ejs'],

        // First level element is a `<form>`.

        tagName: 'form',

        // Use `.search` class to get search form styles.

        className: 'search',

        // Listen to events that change the input or
        // click on the search link to initiate a search.

        events: {
            'input input': 'changed',
            'submit': 'submitted'
        },

        // Default values for options.

        defaults: {
            showLabel: true,   // Should label be visible
            theme: ''          // Theme to apply
        },

        // Options supported by this view
        // include:
        // - `.theme` for a theme class
        // - `.showLabel` set `false` to suppress display of search label

        initialize: function (options) {

            // Save any options passed to constructor.

            this.options = _.extend({}, this.defaults, options);

            // If the model changes, we might need to
            // update the view.

            this.listenTo(this.model, 'change', this.modelUpdated);

            // Define a variable to track in-progress
            // updates.

            this.updating = false;

            // Return view for method chaining.

            return this;

        },

        render: function () {

            // After normal render, add a11y `role` and
            // other hints to make iOS treat the control
            // as a search box (without restyling it).

            this.$el.html(this.template(this.model.toJSON()))
                .attr('role','search')
                .attr('action', '.')
                .attr('id',  _.uniqueId('search_'));

            // Set the initial query parameters

            if (this.model.get('query')) {
                this.$el.find('input').val(this.model.get('query'));
            }

            // If a theme has been requested, add it
            // as a class.

            if (this.options.theme) {
                this.$el.addClass(this.options.theme);
            }

            // If the label should be visible, remove
            // the screen-reader only class.

            if (this.options.showLabel) {
                this.$el.find('label').removeClass('util--sr-only');
            }

            // Return view for method chaining.

            return this;

        },

        // If the user changes the query value, we
        // need to update the underlying model.

        changed: function(ev) {

            // Get the current input value.

            var query = $(ev.currentTarget).val();

            // Note that we're about to start
            // a model update.

            this.updating = true;

            // Update the model with the current query.

            this.model.set('query', query);

        },

        // If user clicks on the search button,
        // pass it up the chain so the search
        // can be executed.

        submitted: function(ev) {

            // Trigger a submit event on this view.

            this.trigger('submit');

            // Prevent further event handling.

            ev.preventDefault();
            return false;

        },

        // If the model has changed due to,
        // another view, we update this view.

        modelUpdated: function() {

            var query = this.model.get('query');

            // Only update the view if it's not in
            // focus to avoid messing with the users
            // while they're typing. Note that we
            // have multiple parallel `<input>`
            // elements to handle responsive design.
            // We do, however, update a view that's
            // in focus if we're not in the middle
            // of a model update. This update is
            // needed, e.g., if the user clicks
            // the back button while the focus is
            // on the input.

            this.$el.find('input').each(function() {
                if (!$(this).is(":focus") || !this.updating) {
                    $(this).val(query);
                }
            });

            // If this event was triggered by
            // a model update, that update is now
            // finished.

            if (this.updating) {
                this.updating = false;
            }

        }

    });

})();
<|endoftext|>


<commit_before>describe('calendarHelper', function() {

  var calendarHelper, events;

  beforeEach(inject(function(_calendarHelper_) {
    calendarHelper = _calendarHelper_;

    events = [{
      title: 'My event title',
      type: 'info',
      startsAt: new Date(2013,5,1,1),
      endsAt: new Date(2014,8,26,15),
      incrementsBadgeTotal: true
    }, {
      title: 'My event title',
      type: 'info',
      startsAt: new Date(2013,5,1,1),
      endsAt: new Date(2014,8,26,15),
      incrementsBadgeTotal: false
    }];

  }));

  describe('getWeekDayNames', function() {

    it('should get the days of the week starting at sunday', function() {
      var weekdays = calendarHelper.getWeekDayNames();
      expect(weekdays).to.eql(['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']);
    });

    it('should get the days of the week starting at monday', inject(function(moment) {
      moment.locale('en', {
        week : {
          dow : 1 // Monday is the first day of the week
        }
      });

      var weekdays = calendarHelper.getWeekDayNames();
      expect(weekdays).to.eql(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']);

      moment.locale('en', {
        week : {
          dow : 0 // Sunday is the first day of the week
        }
      });
    }));

  });

  describe('getYearView', function() {

    //TODO

  });

  describe('getMonthView', function() {

    //TODO

  });

  describe('getWeekView', function() {

    //TODO

  });

  describe('getDayView', function() {

    //TODO

  });

});
<commit_msg>Add test placeholders<commit_after>describe('calendarHelper', function() {

  var calendarHelper, events;

  beforeEach(inject(function(_calendarHelper_) {
    calendarHelper = _calendarHelper_;

    events = [{
      title: 'My event title',
      type: 'info',
      startsAt: new Date(2015,0,1,1),
      endsAt: new Date(2015,0,1,15),
      incrementsBadgeTotal: true
    }];

  }));

  describe('getWeekDayNames', function() {

    it('should get the days of the week starting at sunday', function() {
      var weekdays = calendarHelper.getWeekDayNames();
      expect(weekdays).to.eql(['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']);
    });

    it('should get the days of the week starting at monday', inject(function(moment) {
      moment.locale('en', {
        week : {
          dow : 1 // Monday is the first day of the week
        }
      });

      var weekdays = calendarHelper.getWeekDayNames();
      expect(weekdays).to.eql(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']);

      moment.locale('en', {
        week : {
          dow : 0 // Sunday is the first day of the week
        }
      });
    }));

  });

  describe('getYearView', function() {

    it('should give back 12 months', function() {
      expect(calendarHelper.getYearView(events, new Date()).length).to.equal(12);
    });

    it('should set the isToday flag to true on the current month', function() {

    });

    it('should set the isToday flag to false every month apart from the current one', function() {

    });

    it('should allocate the events to the correct month', function() {

    });

    it('should set the correct badge total', function() {

    });

    it('should set date field to the start of each month', function() {

    });

    it('should set the correct label for each month', function() {

    });

  });

  describe('getMonthView', function() {

    it('should give back the correct amount of days for the calendar', function() {

    });

    it('should set the correct label for each day', function() {

    });

    it('should set date field to the start of each day', function() {

    });

    it('should set the inMonth flag to true', function() {

    });

    it('should set the inMonth flag to false', function() {

    });

    it('should set the isPast flag to true', function() {

    });

    it('should set the isPast flag to false', function() {

    });

    it('should set the isToday flag to true', function() {

    });

    it('should set the isToday flag to false', function() {

    });

    it('should set the isFuture flag to true', function() {

    });

    it('should set the isFuture flag to false', function() {

    });

    it('should set the isWeekend flag to true', function() {

    });

    it('should set the isWeekend flag to false', function() {

    });

    it('should allocate the events to the correct day', function() {

    });

    it('should set the correct badge total', function() {

    });

  });

  describe('getWeekView', function() {

    it('should set the weekDayLabel', function() {

    });

    it('should set the dayLabel', function() {

    });

    it('should set date field to the start of each day', function() {

    });

    it('should set the isPast flag to true', function() {

    });

    it('should set the isPast flag to false', function() {

    });

    it('should set the isToday flag to true', function() {

    });

    it('should set the isToday flag to false', function() {

    });

    it('should set the isFuture flag to true', function() {

    });

    it('should set the isFuture flag to false', function() {

    });

    it('should set the isWeekend flag to true', function() {

    });

    it('should set the isWeekend flag to false', function() {

    });

    it('should only contain events for that week', function() {

    });

    describe('setting the correct span and offset', function() {

      it('should pass when the event is contained within the current week view', function() {

      });

      it('should pass when the event starts before the current week view and ends within it', function() {

      });

      it('should pass when the event starts before the current week view and ends after the end of the week', function() {

      });

      it('should pass when the event starts within the current week but ends after it', function() {

      });

    });

  });

  describe('getDayView', function() {

    it('should only contain events for that day', function() {

    });

    it('should set the top to 0 if the event starts before the start of the day', function() {

    });

    it('should set the top correctly if the event starts after the start of the day', function() {

    });

    it('should set the height correctly if the event finishes after the end of the day', function() {

    });

    it('should set the height correctly if the event finishes before the end of the day', function() {

    });

    it('should never exceed the maximum height of the calendar', function() {

    });

    it('should remove events that start and end at the same time', function() {

    });

    it('should move events across if there are multiple ones on the same line', function() {

    });

  });

});
<|endoftext|>


<commit_before>(function () {
    var root = this;
    var W = root.W || {};
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = W;
        root.W = W;
    } else {
        root.W = W;
    }
    W.snippet = W.snippet || {};

    W.snippet.math = W.math || {};
    W.snippet.math.version = "2.0.0";

    W.snippet.math.clipNormalized = function (x, min, max) { // or (value, max), or (value)
        if (arguments.length === 2) {
            max = min;
            min = 0;
        } else if (arguments.length === 1) {
            max = 1;
            min = 0;
        }
        if (x<min) { return min; }
        if (x>max) { return max; }
        return x;
    };

    W.snippet.math.fitScaleRatio = function (width, height, boundsWidth, boundsHeight) {
        var widthScale = boundsWidth / width;
        var heightScale = boundsHeight / height;
        return Math.min(widthScale, heightScale);
    };

    W.snippet.math.map = function (value, inputMin, inputMax, outputMin, outputMax, clamp) {
        var outVal = ((value-inputMin)/(inputMax-inputMin)*(outputMax-outputMin)+outputMin);
        if (clamp) {
            if (outputMax<outputMin) {
                if (outVal<outputMax) {
                    outVal = outputMax;
                } else if (outVal>outputMin) {
                    outVal = outputMin;
                }
            } else {
                if (outVal>outputMax) {
                    outVal = outputMax;
                } else if (outVal<outputMin) {
                    outVal = outputMin;
                }
            }
        }
        return outVal;
    };

    W.snippet.math.randomBetween = function (from, to) {
        return W.snippet.math.map(Math.random(), 0, 1, from, to);
    };

    // @todo test
    W.snippet.math.close = function (num, test, tolerance) {
        tolerance = tolerance || 1;
        return (num > test-tolerance && num < test+tolerance);
    };

     // @todo accept numbers and test
    W.snippet.math.angleBetween = function (center, point) {
        var angle = Math.atan2(center.x-point.x,center.y-point.y)*(180/Math.PI);
        if(angle < 0) {
            angle = Math.abs(angle);
        } else {
            angle = 360 - angle;
        }
        return angle;
    };

    // @todo accept numbers and test
    W.snippet.math.distance = function (obj1, obj2) {
        var x = obj2.x - obj1.x;
        var y = obj2.y - obj1.y;
        return Math.sqrt((x*x)+(y*y));
    };

    // Fisher-Yates shuffle.
    // source http://stackoverflow.com/questions/962802/is-it-correct-to-use-javascript-array-sort-method-for-shuffling
    W.snippet.math.randomizedArray = function (arr, leaveOriginalUntouched) {
        var array = (leaveOriginalUntouched) ? arr.slice(0) : arr;
        var tmp, current, top = array.length;
        if(top) while(--top) {
            current = Math.floor(Math.random() * (top + 1));
            tmp = array[current];
            array[current] = array[top];
            array[top] = tmp;
        }
        return array;
    };
}());<commit_msg>Name change<commit_after>(function () {
    var root = this;
    var W = root.W || {};
    if (typeof module !== 'undefined' && module.exports) {
        module.exports = W;
        root.W = W;
    } else {
        root.W = W;
    }
    W.snippet = W.snippet || {};

    W.snippet.math = W.math || {};
    W.snippet.math.version = "2.0.0";

    W.snippet.math.clipNormalized = function (x, min, max) { // or (value, max), or (value)
        if (arguments.length === 2) {
            max = min;
            min = 0;
        } else if (arguments.length === 1) {
            max = 1;
            min = 0;
        }
        if (x<min) { return min; }
        if (x>max) { return max; }
        return x;
    };

    W.snippet.math.fitScaleRatio = function (width, height, boundsWidth, boundsHeight) {
        var widthScale = boundsWidth / width;
        var heightScale = boundsHeight / height;
        return Math.min(widthScale, heightScale);
    };

    W.snippet.math.map = function (value, inputMin, inputMax, outputMin, outputMax, clamp) {
        var outVal = ((value-inputMin)/(inputMax-inputMin)*(outputMax-outputMin)+outputMin);
        if (clamp) {
            if (outputMax<outputMin) {
                if (outVal<outputMax) {
                    outVal = outputMax;
                } else if (outVal>outputMin) {
                    outVal = outputMin;
                }
            } else {
                if (outVal>outputMax) {
                    outVal = outputMax;
                } else if (outVal<outputMin) {
                    outVal = outputMin;
                }
            }
        }
        return outVal;
    };

    W.snippet.math.randomBetween = function (from, to) {
        return W.snippet.math.map(Math.random(), 0, 1, from, to);
    };

    // @todo test
    W.snippet.math.close = function (num, test, tolerance) {
        tolerance = tolerance || 1;
        return (num > test-tolerance && num < test+tolerance);
    };

     // @todo accept numbers and test
    W.snippet.math.angleBetween = function (center, point) {
        var angle = Math.atan2(center.x-point.x,center.y-point.y)*(180/Math.PI);
        if(angle < 0) {
            angle = Math.abs(angle);
        } else {
            angle = 360 - angle;
        }
        return angle;
    };

    // @todo accept numbers and test
    W.snippet.math.distance = function (obj1, obj2) {
        var x = obj2.x - obj1.x;
        var y = obj2.y - obj1.y;
        return Math.sqrt((x*x)+(y*y));
    };

    // Fisher-Yates shuffle.
    // source http://stackoverflow.com/questions/962802/is-it-correct-to-use-javascript-array-sort-method-for-shuffling
    W.snippet.math.shuffleArray = function (arr, leaveOriginalUntouched) {
        var array = (leaveOriginalUntouched) ? arr.slice(0) : arr;
        var tmp, current, top = array.length;
        if(top) while(--top) {
            current = Math.floor(Math.random() * (top + 1));
            tmp = array[current];
            array[current] = array[top];
            array[top] = tmp;
        }
        return array;
    };
}());<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Text, View, Image } from 'react-native';
import styles from './styles/GameStartStyle';
import ActorImage from '../components/ActorImage';
import { StackNagivator } from 'react-navigation';

export default class GameStartFetch extends Component {
	constructor(props) {
		super(props);
		this.state = {
			isLoading: true,
		}
	}

	componentDidMount() {
		return fetch('http://localhost:3000/games', {
			method: 'POST',
			headers: {
				'Accept': 'applicaton/json',
				'Content-Type': 'application/json',
			}
		})
		.then((response) => response.json())
		.then((responseJson) => {
			this.setState({
				isLoading: false,
				actors: responseJson,
			})
		})
	}

	render() {
		if (this.state.isLoading) {
			return (
				<View>
					<Text>Loading...</Text>
				</View>
			)
		}

		const { navigate } = this.props.navigation;
		return (
			<View>
				<View>
					<ActorImage text={{uri: 'https://image.tmdb.org/t/p/w185/'+this.state.actors.starting_actor.image_url}} onPress={() => navigate('ActorsMovies')} />
				</View>
				<View>
					<ActorImage text={{uri: 'https://image.tmdb.org/t/p/w185/'+this.state.actors.ending_actor.image_url}} onPress={() => navigate('ActorsMovies')} />
				</View>
			</View>
		);
	}
}
// <Text>{this.ending_actor.name}</Text>
<commit_msg>Remove unnecessary text from navigate<commit_after>import React, { Component } from 'react';
import { Text, View, Image } from 'react-native';
import styles from './styles/GameStartStyle';
import ActorImage from '../components/ActorImage';
import { StackNagivator } from 'react-navigation';

export default class GameStartFetch extends Component {
	constructor(props) {
		super(props);
		this.state = {
			isLoading: true,
		}
	}

	componentDidMount() {
		return fetch('http://localhost:3000/games', {
			method: 'POST',
			headers: {
				'Accept': 'applicaton/json',
				'Content-Type': 'application/json',
			}
		})
		.then((response) => response.json())
		.then((responseJson) => {
			this.setState({
				isLoading: false,
				actors: responseJson,
			})
		})
	}

	render() {
		if (this.state.isLoading) {
			return (
				<View>
					<Text>Loading...</Text>
				</View>
			)
		}

		const { navigate } = this.props.navigation;
		return (
			<View>
				<View>
					<ActorImage text={{uri: 'https://image.tmdb.org/t/p/w185/'+this.state.actors.starting_actor.image_url}} onPress={() => navigate('ActorsMovies')} />
				</View>
				<View>
					<Image source={{uri: 'https://image.tmdb.org/t/p/w185/'+this.state.actors.ending_actor.image_url}} style={{width:40, height:40}} />
				</View>
			</View>
		);
	}
}
// <Text>{this.ending_actor.name}</Text>
<|endoftext|>


<commit_before>$.register({
  rule: 'http://urlz.so/l/*',
  ready: function () {
    'use strict';

    var i = $.$('td > a');
    if (i) {
      i = i.href;
      var m = i.match(/javascript:declocation\('(.+)'\);/);
      if (m) {
        i = atob(m[1]);
      }
      $.openLink(i);
      return;
    }
    i = $('img');
    $.captcha(i.src, function (a) {
      var b = $('input[name=captcha]');
      var c = $('input[name=submit]');
      b.value = a;
      c.click();
    });
  },
});

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>urlz.so<commit_after><|endoftext|>


<commit_before>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/bitcoin');

var newsSchema = Schema({
  title   	: String,
  url 	  	: String,
  time 		: Date,
  origin 	: String,
  intro 	: String,
  no 		: String
});

var News = mongoose.model('News', newsSchema);

exports.getNewsBySkip = function (skip, callback){

	var skipNumber = parseInt(skip);
	console.log("skipNumber: "+ skipNumber);
	// get
	News
	.aggregate()
	.sort({ no: 'asc'})
	.skip(skipNumber)
	.limit(20)
	.exec(function (err, items) {
		// body..
		if(err){
			console.dir(err);
		}
		console.log("News Skip"+skip);
		if (items) {
			callback(err, items);
		};
	});
}

<commit_msg>news page<commit_after>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/bitcoin');

var newsSchema = Schema({
  title   	: String,
  url 	  	: String,
  time 		: Date,
  origin 	: String,
  intro 	: String,
  no 		: String
});

var News = mongoose.model('News', newsSchema);

exports.getNewsBySkip = function (skip, callback){

	var skipNumber = parseInt(skip);
	console.log("skipNumber: "+ skipNumber);
	// get
	News
	.aggregate()
	.sort({ time: 'desc'})
	.skip(skipNumber)
	.limit(20)
	.exec(function (err, items) {
		// body..
		if(err){
			console.dir(err);
		}
		console.log("News Skip"+skip);
		if (items) {
			callback(err, items);
		};
	});
}

<|endoftext|>