<commit_before>/*global WufooForm */

import layout from '../templates/components/wufoo-form';

import Component from '@ember/component';
import { get, set, getWithDefault } from '@ember/object';
import { computed } from '@ember/object';
import { getOwner } from '@ember/application';
import { assert } from '@ember/debug';

export default Component.extend({
  layout,

  classNames: ['wufoo-form'],

  attributeBindings: ['data-test-selector'],
  'data-test-selector': 'wufoo-form',

  parentSelector: computed('target', {
    get() {
      return get(this, 'target') || `#${get(this, 'elementId')}`;
    }
  }),

  formTarget: computed('parentSelector', {
    get() {
      return `${get(this, 'parentSelector')} .wufoo-form-container`;
    }
  }),

  init() {
    this._super(...arguments);
    assert(
      '`formId` and `userName` attributes are required.',
      get(this, 'formId') && get(this, 'userName')
    );
  },

  didInsertElement() {
    this._super(...arguments);

    if (get(this, 'target')) {
      let target = get(this, 'target');
      // move content to optional target node
      this.$('.wufoo-form-container').appendTo(target);
    }

    // don't run wufoo iframe content in tests
    let config = getOwner(this).resolveRegistration('config:environment');
    if (config.environment !== 'test') {
      this.appendWufooJs();
    }
  },

  appendWufooJs() {
    // loosely based on Wufoo's form embed code
    let scriptTag = document.createElement('script');
    scriptTag.type = 'text/javascript';
    scriptTag.onload = this.initWufooForm.bind(this);
    scriptTag.onerror = () => {
      set(this, 'isShowingFallback', true);
    };

    let formContainer = document.querySelector(get(this, 'formTarget'));
    let parentNode = document.querySelector(get(this, 'parentSelector'));

    assert(
      'Wufoo form requires a valid DOM target node to be inserted into.',
      formContainer && parentNode
    );

    // add wufoo script to document
    document.head.appendChild(scriptTag);
    scriptTag.src = `${
      document.location.protocol
    }//www.wufoo.com/scripts/embed/form.js`;
  },

  initWufooForm() {
    let wufooForm = new WufooForm();

    let options = {
      // required
      userName: get(this, 'userName'),
      formHash: get(this, 'formId'),
      // optional
      autoResize: getWithDefault(this, 'autoResize', true),
      height: getWithDefault(this, 'height', '500'),
      header: getWithDefault(this, 'header', 'show'),
      ssl: getWithDefault(this, 'ssl', true),
      // static
      async: true,
      host: 'wufoo.com'
    };

    wufooForm.initialize(options);

    // override wufoo's method to inject the form into the component container
    let formTarget = get(this, 'formTarget');
    wufooForm.display = function() {
      if (this.async) {
        document.querySelector(
          formTarget
        ).innerHTML = this.generateFrameMarkup();
      } else {
        document.write(this.generateFrameMarkup());
      }

      window.postMessage ||
        this.addEvent(
          document.querySelector(formTarget),
          'load',
          this.bindMethod(this.addResizeScript, this)
        );
    };
    wufooForm.display();
    set(this, 'isLoading', false);
  }
});
<commit_msg>fixes issue with getWithDefault import<commit_after>/*global WufooForm */

import layout from '../templates/components/wufoo-form';

import Component from '@ember/component';
import { get, set } from '@ember/object';
import { computed } from '@ember/object';
import { getOwner } from '@ember/application';
import { assert } from '@ember/debug';

function getWithDefault(context, property, defaultValue) {
  return get(context, property) === undefined
    ? defaultValue
    : get(context, property);
}

export default Component.extend({
  layout,

  classNames: ['wufoo-form'],

  attributeBindings: ['data-test-selector'],
  'data-test-selector': 'wufoo-form',

  parentSelector: computed('target', {
    get() {
      return get(this, 'target') || `#${get(this, 'elementId')}`;
    }
  }),

  formTarget: computed('parentSelector', {
    get() {
      return `${get(this, 'parentSelector')} .wufoo-form-container`;
    }
  }),

  init() {
    this._super(...arguments);
    assert(
      '`formId` and `userName` attributes are required.',
      get(this, 'formId') && get(this, 'userName')
    );
  },

  didInsertElement() {
    this._super(...arguments);

    if (get(this, 'target')) {
      let target = get(this, 'target');
      // move content to optional target node
      this.$('.wufoo-form-container').appendTo(target);
    }

    // don't run wufoo iframe content in tests
    let config = getOwner(this).resolveRegistration('config:environment');
    if (config.environment !== 'test') {
      this.appendWufooJs();
    }
  },

  appendWufooJs() {
    // loosely based on Wufoo's form embed code
    let scriptTag = document.createElement('script');
    scriptTag.type = 'text/javascript';
    scriptTag.onload = this.initWufooForm.bind(this);
    scriptTag.onerror = () => {
      set(this, 'isShowingFallback', true);
    };

    let formContainer = document.querySelector(get(this, 'formTarget'));
    let parentNode = document.querySelector(get(this, 'parentSelector'));

    assert(
      'Wufoo form requires a valid DOM target node to be inserted into.',
      formContainer && parentNode
    );

    // add wufoo script to document
    document.head.appendChild(scriptTag);
    scriptTag.src = `${
      document.location.protocol
    }//www.wufoo.com/scripts/embed/form.js`;
  },

  initWufooForm() {
    let wufooForm = new WufooForm();

    let options = {
      // required
      userName: get(this, 'userName'),
      formHash: get(this, 'formId'),
      // optional
      autoResize: getWithDefault(this, 'autoResize', true),
      height: getWithDefault(this, 'height', '500'),
      header: getWithDefault(this, 'header', 'show'),
      ssl: getWithDefault(this, 'ssl', true),
      // static
      async: true,
      host: 'wufoo.com'
    };

    wufooForm.initialize(options);

    // override wufoo's method to inject the form into the component container
    let formTarget = get(this, 'formTarget');
    wufooForm.display = function() {
      if (this.async) {
        document.querySelector(
          formTarget
        ).innerHTML = this.generateFrameMarkup();
      } else {
        document.write(this.generateFrameMarkup());
      }

      window.postMessage ||
        this.addEvent(
          document.querySelector(formTarget),
          'load',
          this.bindMethod(this.addResizeScript, this)
        );
    };
    wufooForm.display();
    set(this, 'isLoading', false);
  }
});
<|endoftext|>


<commit_before>module.exports = function(controller) {
    controller.hears('rozvrh', 'message_received', function(bot, message) {
        bot.reply(message, { type: "typing" });
        bot.reply(message, 'Here you go! 👉 http://novamedia.ff.cuni.cz/studium/rozvrh-harmonogram-semestru/');
    });

    controller.hears('prax[ei]', 'message_received', function(bot, message) {
        bot.reply(message, 'Vše o praxi se dočteš tady 👉 http://novamedia.ff.cuni.cz/studium/praxe/');
    });
};
<commit_msg>Trying typing<commit_after>module.exports = function(controller) {
    controller.hears('rozvrh', 'message_received', function(bot, message) {
        bot.reply(message, { type: "typing" });
        setTimeout(function(){
            bot.reply(message, 'Here you go! 👉 http://novamedia.ff.cuni.cz/studium/rozvrh-harmonogram-semestru/');
        }, 2000);

    });

    controller.hears('prax[ei]', 'message_received', function(bot, message) {
        bot.reply(message, 'Vše o praxi se dočteš tady 👉 http://novamedia.ff.cuni.cz/studium/praxe/');
    });
};
<|endoftext|>


<commit_before>/*
 * Closure: Unterbindet die Benutzung globaler Variablen.
 */
var myUserName = userNameGenerator();
var CheerChat = (function() {
  'use-strict';

  /*
   * Erzeugt nötige Objekte, aber verbindet noch nicht.
   */
  var CheerChat = function() {
    var that = this;

    that.isConnected = false;

    that._peerConnection = new CheerChat.RTCPeerConnection({iceServers : [{ url : 'stun:stun.l.google.com:19302'}, { url : 'stun:stun1.l.google.com:19302'}, { url : 'stun:stun2.l.google.com:19302'}, { url : 'stun:stun3.l.google.com:19302'}]});

    that.strangersCam = document.getElementById('CAMForeign');

    that._peerConnection.onaddstream = function(e){
      that.strangersCam.src = CheerChat.vendorURL.createObjectURL(e.stream);
      console.log('Remote stream added');
    };
  };

  /*
   * Pollyfills
   */
  CheerChat.RTCPeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection || window.RTCPeerConnection;
  CheerChat.RTCSessionDescription = window.mozRTCSessionDescription || window.webkitRTCSessionDescription || window.RTCSessionDescription;
  navigator.getMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.getUserMedia;
  CheerChat.vendorURL = window.URL || window.webkitURL;

  /*
   * Stellt die Verbindung zum Signalling-Server her.
   */
  CheerChat.prototype.initConnection = function(userName, callback) {
    var that = this;
    that.userName = userName;

    that._peerConnection.onicecandidate = function(e){
      if(e.candidate == null){
        return;
      }
      that._signallingSocket.send("candidate", JSON.stringify(e.candidate));
      that._peerConnection.onicecandidate = null;
    };

    that._signallingSocket = new WebSocket('ws://' + location.hostname + ':8081');
    that._signallingSocket.onopen = function(event) {
      console.log('Connected with signalling server.');

      //Den eigenen Usernamen zum Server senden.
      var nameChangeObj = {
        Joghurt_type: "name_change",
        value: that.userName
      };
      that._signallingSocket.send(JSON.stringify(nameChangeObj));
    };

    //Socket-Events registrieren
    that._signallingSocket.onmessage = function(msg){
      var recvData;
      try {
        recvData = JSON.parse(msg.data);
      } catch (e) {
        return;
      }

      if(recvData.Joghurt == that.userName){
        return;
      }
      if (typeof recvData.value !== 'object' && typeof recvData.value !== 'array') {
        return;
      }

      console.log(recvData);
      if(recvData.Joghurt_type == "offer"){
        var offer = new CheerChat.RTCSessionDescription(recvData.value);
        for (var i in recvData.value) {
          if (!recvData.value.hasOwnProperty(i)) {
            continue;
          }

          offer[i] = recvData.value[i];
        }

        that._peerConnection.setRemoteDescription(offer, function() {
          that._peerConnection.createAnswer(function(answer){
            answer.Joghurt_type = "answer";
            that._peerConnection.setLocalDescription(answer, function(){}, function(){});

            var wrapper = {Joghurt : userName, Joghurt_type : "answer", value : answer, Joghurt_target : recvData.Joghurt };
            var jsonAnswer = JSON.stringify(wrapper);
            that._signallingSocket.send(jsonAnswer);

            callback(recvData.Joghurt);

            that.isConnected = true;
          });
          console.log('offer received');
        },
        function(e) {
          console.log('session error:', e);
        });

      } else if (recvData.Joghurt_type == "answer"){
        var offer = new CheerChat.RTCSessionDescription(recvData.value);
        for (var i in recvData.value) {
          if (!recvData.value.hasOwnProperty(i)) {
            continue;
          }

          offer[i] = recvData.value[i];
        }
        that._peerConnection.setRemoteDescription(offer, function(){}, function(){});

        console.log('answer received');
      } else if (recvData.Joghurt_type == "namelist") {
        var selectElement = document.getElementsByName("chatpartners")[0];
        selectElement.innerHTML = "";

        for (i in recvData.value) {
          if (recvData.value[i] != userName) {
            selectElement.innerHTML += "<option value='" + recvData.value[i] + "'>"
            + recvData.value[i] + "</option>";
          }
        }
      }
    };
  };

  /*
   * Verbindet sich mit einem anderen User (aktiv).
   */
  CheerChat.prototype.connect = function(foreignUser) {
    var that = this;

    if (that.isConnected) {
      //return;
    }

    that._peerConnection.createOffer(
      function(offer){
        var wrapper = {Joghurt : that.userName, Joghurt_type : "offer", value : offer, Joghurt_target : foreignUser };
        that._peerConnection.setLocalDescription(offer, function(){}, function(){});
        that._signallingSocket.send(JSON.stringify(wrapper));

        that.isConnected = true;
        console.log('Connected with other User.');
      },
      function(e){
        console.log('Error 1:', e);
      },
      {
        mandatory : getMandatoryContents()
      }
    );
  };

  function getMandatoryContents() {
    // boo, case difference!
    if (window.RTCPeerConnection) {
      return {
       'OfferToReceiveAudio' : true,
       'OfferToReceiveVideo' : true
      }
    } else {
      return {
       'offerToReceiveAudio' : true,
       'offerToReceiveVideo' : true
      }
    }
  }

  CheerChat.prototype.startTextChat = function() {
    var that = this;

    that._chatChannel = that._peerConnection.createDataChannel('chat', {reliable:true});

    that._chatChannel.onopen = function(event) {
    };

    that._chatChannel.onerror = function (err) {
      console.log("Channel Error:", err);
    };

    that._peerConnection.ondatachannel = function (e) {
      e.channel.onmessage = function(e) {
        chatLogElement.innerHTML += "
Partner wrote: " + e.data;
        scrollDownHistory();
      };
    };
  };

  CheerChat.prototype.sendMessage = function(msg) {
    var that = this;

    chatLogElement.innerHTML += "
You wrote: " + msg;
    that._chatChannel.send(msg);
    scrollDownHistory();
  };

  CheerChat.prototype.startVideo = function(foreignUser) {
    var that = this;
    that.cam = document.getElementById('CAM');

    navigator.getMedia(
      {
        video : true,
        audio : false
      },
      function (stream){
        that.cam.src = CheerChat.vendorURL.createObjectURL(stream);
        that._peerConnection.addStream(stream);

        console.log('Local stream added.');
        that.connect(foreignUser);

      }, function(error) {
        console.log(error);
      }
    );
  };

  return CheerChat;
})();

var chat;
var video = false;
function connect() {
  chat = new CheerChat();
  chat.initConnection(myUserName, function(foreignUser) {
    startVideo(foreignUser, false);
  });
}

function startVideo(foreignUser, active) {
  if (!video) {
    if (!active && !window.confirm('Connect video stream with ' + foreignUser + '?')) {
      return;
    }

    chat.startVideo(foreignUser);
    chat.startTextChat(foreignUser);
    video = true;
  }
}

function sendMessage(msg) {
  if (!video) {
    alert('Not connected!');
    return;
  }

  chat.sendMessage(msg);
};

function userNameGenerator() {
  var attributes = ["Stiffler's", "Bad", "Awesome", "Dancing", "Singing", "Crying", "Cool", "Jim's"];
  var people = ["Mum", "Grandpa", "Grandma", "Daddy", "Dad"];

  var a = Math.floor(Math.random() * attributes.length);
  var g = Math.floor(Math.random() * people.length);
  return attributes[a] + " " + people[g];
}
<commit_msg>Removed german comments<commit_after>/*
 * Closure
 */
var myUserName = userNameGenerator();
var CheerChat = (function() {
  'use-strict';

  /*
   *
   */
  var CheerChat = function() {
    var that = this;

    that.isConnected = false;

    that._peerConnection = new CheerChat.RTCPeerConnection({iceServers : [{ url : 'stun:stun.l.google.com:19302'}, { url : 'stun:stun1.l.google.com:19302'}, { url : 'stun:stun2.l.google.com:19302'}, { url : 'stun:stun3.l.google.com:19302'}]});

    that.strangersCam = document.getElementById('CAMForeign');

    that._peerConnection.onaddstream = function(e){
      that.strangersCam.src = CheerChat.vendorURL.createObjectURL(e.stream);
      console.log('Remote stream added');
    };
  };

  /*
   * Pollyfills
   */
  CheerChat.RTCPeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection || window.RTCPeerConnection;
  CheerChat.RTCSessionDescription = window.mozRTCSessionDescription || window.webkitRTCSessionDescription || window.RTCSessionDescription;
  navigator.getMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.getUserMedia;
  CheerChat.vendorURL = window.URL || window.webkitURL;

  /*
   * Connects to signalling server.
   */
  CheerChat.prototype.initConnection = function(userName, callback) {
    var that = this;
    that.userName = userName;

    that._peerConnection.onicecandidate = function(e){
      if(e.candidate == null){
        return;
      }
      that._signallingSocket.send("candidate", JSON.stringify(e.candidate));
      that._peerConnection.onicecandidate = null;
    };

    that._signallingSocket = new WebSocket('ws://' + location.hostname + ':8081');
    that._signallingSocket.onopen = function(event) {
      console.log('Connected with signalling server.');

      var nameChangeObj = {
        Joghurt_type: "name_change",
        value: that.userName
      };
      that._signallingSocket.send(JSON.stringify(nameChangeObj));
    };

    that._signallingSocket.onmessage = function(msg){
      var recvData;
      try {
        recvData = JSON.parse(msg.data);
      } catch (e) {
        return;
      }

      if(recvData.Joghurt == that.userName){
        return;
      }
      if (typeof recvData.value !== 'object' && typeof recvData.value !== 'array') {
        return;
      }

      console.log(recvData);
      if(recvData.Joghurt_type == "offer"){
        var offer = new CheerChat.RTCSessionDescription(recvData.value);
        for (var i in recvData.value) {
          if (!recvData.value.hasOwnProperty(i)) {
            continue;
          }

          offer[i] = recvData.value[i];
        }

        that._peerConnection.setRemoteDescription(offer, function() {
          that._peerConnection.createAnswer(function(answer){
            answer.Joghurt_type = "answer";
            that._peerConnection.setLocalDescription(answer, function(){}, function(){});

            var wrapper = {Joghurt : userName, Joghurt_type : "answer", value : answer, Joghurt_target : recvData.Joghurt };
            var jsonAnswer = JSON.stringify(wrapper);
            that._signallingSocket.send(jsonAnswer);

            callback(recvData.Joghurt);

            that.isConnected = true;
          });
          console.log('offer received');
        },
        function(e) {
          console.log('session error:', e);
        });

      } else if (recvData.Joghurt_type == "answer"){
        var offer = new CheerChat.RTCSessionDescription(recvData.value);
        for (var i in recvData.value) {
          if (!recvData.value.hasOwnProperty(i)) {
            continue;
          }

          offer[i] = recvData.value[i];
        }
        that._peerConnection.setRemoteDescription(offer, function(){}, function(){});

        console.log('answer received');
      } else if (recvData.Joghurt_type == "namelist") {
        var selectElement = document.getElementsByName("chatpartners")[0];
        selectElement.innerHTML = "";

        for (i in recvData.value) {
          if (recvData.value[i] != userName) {
            selectElement.innerHTML += "<option value='" + recvData.value[i] + "'>"
            + recvData.value[i] + "</option>";
          }
        }
      }
    };
  };

  /*
   *
   */
  CheerChat.prototype.connect = function(foreignUser) {
    var that = this;

    if (that.isConnected) {
      //return;
    }

    that._peerConnection.createOffer(
      function(offer){
        var wrapper = {Joghurt : that.userName, Joghurt_type : "offer", value : offer, Joghurt_target : foreignUser };
        that._peerConnection.setLocalDescription(offer, function(){}, function(){});
        that._signallingSocket.send(JSON.stringify(wrapper));

        that.isConnected = true;
        console.log('Connected with other User.');
      },
      function(e){
        console.log('Error 1:', e);
      },
      {
        mandatory : getMandatoryContents()
      }
    );
  };

  function getMandatoryContents() {
    // boo, case difference!
    if (window.RTCPeerConnection) {
      return {
       'OfferToReceiveAudio' : true,
       'OfferToReceiveVideo' : true
      }
    } else {
      return {
       'offerToReceiveAudio' : true,
       'offerToReceiveVideo' : true
      }
    }
  }

  CheerChat.prototype.startTextChat = function() {
    var that = this;

    that._chatChannel = that._peerConnection.createDataChannel('chat', {reliable:true});

    that._chatChannel.onopen = function(event) {
    };

    that._chatChannel.onerror = function (err) {
      console.log("Channel Error:", err);
    };

    that._peerConnection.ondatachannel = function (e) {
      e.channel.onmessage = function(e) {
        chatLogElement.innerHTML += "
Partner wrote: " + e.data;
        scrollDownHistory();
      };
    };
  };

  CheerChat.prototype.sendMessage = function(msg) {
    var that = this;

    chatLogElement.innerHTML += "
You wrote: " + msg;
    that._chatChannel.send(msg);
    scrollDownHistory();
  };

  CheerChat.prototype.startVideo = function(foreignUser) {
    var that = this;
    that.cam = document.getElementById('CAM');

    navigator.getMedia(
      {
        video : true,
        audio : false
      },
      function (stream){
        that.cam.src = CheerChat.vendorURL.createObjectURL(stream);
        that._peerConnection.addStream(stream);

        console.log('Local stream added.');
        that.connect(foreignUser);

      }, function(error) {
        console.log(error);
      }
    );
  };

  return CheerChat;
})();

var chat;
var video = false;
function connect() {
  chat = new CheerChat();
  chat.initConnection(myUserName, function(foreignUser) {
    startVideo(foreignUser, false);
  });
}

function startVideo(foreignUser, active) {
  if (!video) {
    if (!active && !window.confirm('Connect video stream with ' + foreignUser + '?')) {
      return;
    }

    chat.startVideo(foreignUser);
    chat.startTextChat(foreignUser);
    video = true;
  }
}

function sendMessage(msg) {
  if (!video) {
    alert('Not connected!');
    return;
  }

  chat.sendMessage(msg);
};

function userNameGenerator() {
  var attributes = ["Stiffler's", "Bad", "Awesome", "Dancing", "Singing", "Crying", "Cool", "Jim's"];
  var people = ["Mum", "Grandpa", "Grandma", "Daddy", "Dad"];

  var a = Math.floor(Math.random() * attributes.length);
  var g = Math.floor(Math.random() * people.length);
  return attributes[a] + " " + people[g];
}
<|endoftext|>


<commit_before>var h = 360,
		s = 0,
		b = 100,
		a = 100;

var h2 = 12,
		s2 = 40,
		b2 = 23,
		a2 = 100;

var h3 = 0,
		s3 = 0,
		b3 = 15,
		a3 = 100,
		a3Wipe = 40;

// vars for line
var eX, eY, // position
		eX2, eY2,
		eW = 2; // width

// for bounces on wall
var bounces = 0,
		bouncesMax,
		bouncesTotal = 0; // current total amount of bounces

// for conversion from polar to cartesian coordinates.
// basically getting x and y from an angle and a radius.
// angle: 0 to 360 ... duh
var angle,
		radius ; // sets the speed

var quadrant;

var wall;	// which wall? t,r,b,l?

// for Dot
var dot = [];

// for saving position of corner of triangle
var tWallPosX = [],
		tWallPosY = [],
		triangle = [];

// for filling whole document
var w = window,
		wX = w.innerWidth,
		wY = w.innerHeight;

/*
* only executed once
*/
function setup(){
	createCanvas(wX, wY);
	// createCanvas(1600/2, 900/2);

	// change color mode to hsl
	colorMode(HSB, 360, 100, 100, 100);

	// start line at...
	eX = random(0,width);
	eY = 0;
	angle = radians(random(1,179));
	radius = 10; //speed of line drawing
	bouncesMax = 4;

	// rectangle/background
	background(h3, s3, b3);
}

/*
* this will be executed all the time
*/
function draw(){
	// translate from angle: polar to cartesian coordianates
	eX += cartesianX(radius,angle);
	eY += cartesianY(radius,angle);

	// DRAW LINE
	stroke(h,s,b,a);
	strokeWeight(eW);
	line(eX,eY, eX2,eY2);

	// quadrants:
	// 1: 0° - 90°
	// 2: 90° - 180°
	// 3: 180° - 270°
	// 4: 270° - 360°
	if (angle >= radians(0) && angle < radians(90)) {
		quadrant = 1;
	}
	else if (angle >= radians(90) && angle < radians(180)) {
		quadrant = 2;
	}
	else if (angle >= radians(180) && angle < radians(270)) {
		quadrant = 3;
	}
	else if (angle >= radians(270) && angle < radians(360)) {
		quadrant = 4;
	}

	// wall sides
	if (eY < 0) {
		wall = 1;
	}
	else if (eX > width) {
		wall = 2;
	}
	else if (eY > height) {
		wall = 3;
	}
	else if (eX < 0) {
		wall = 4;
	}

	// if bounce from specific wall from specific angle
	// 0° - 90°
	if (quadrant === 1 && wall === 2) { // right
		angle += radians(90);
		bounces++;
		eX = width;
	}
	else if (quadrant === 1 && wall === 3) { // bottom
		angle -= radians(90);
		bounces++;
		eY = height;
	}
	// 90° - 180°
	else if (quadrant === 2 && wall === 3) { // bottom
		angle += radians(90);
		bounces++;
		eY = height;
	}
	else if (quadrant === 2 && wall === 4) { // left
		angle -= radians(90);
		bounces++;
		eX = 0;
	}
	// 180° - 270°
	else if (quadrant === 3 && wall === 4) { // left
		angle += radians(90);
		bounces++;
		eX = 0;
	}
	else if (quadrant === 3 && wall === 1) { // top
		angle -= radians(90);
		bounces++;
		eY = 0;
	}
	// 270° - 360°
	else if (quadrant === 4 && wall === 1) { // top
		angle += radians(90);
		bounces++;
		eY = 0;
	}
	else if (quadrant === 4 && wall === 2) { // right
		angle -= radians(90);
		bounces++;
		eX = width;
	}

	// stay in 360°
	if (angle >= radians(360)) {
		angle -= radians(360);
	}
	else if (angle < radians(0)) {
		angle += radians(360);
	}

	if (frameCount === 1) {
		dot[bouncesTotal] = new Dot();
		dot[bouncesTotal].show();
	}
	// if specific amount of bouncing, reset position
	if (bounces > bouncesMax) {
		noStroke();
		// eX = random(0,width);
		// eY = 0;
		angle = radians(random(0,180));
		bounces = 0; // reset bounces counter
		frameCount = 1;
	}
	// "cleaning on isle five"... reset the canvas
	if (bouncesTotal%(bouncesMax*4) === (bouncesMax*4)-1) {
		fill(h3,s3,b3,90);
		noStroke();
		rect(0,0, width, height);
		frameCount = 1;
	}
	// if at wall-bounce, add thing
	if (eX === width || eY === height || eX === 0 || eY === 0) {

		// save position at wall
		tWallPosX[bouncesTotal] = eX;
		tWallPosY[bouncesTotal] = eY;

		// create new Dot at wall
		dot[bouncesTotal] = new Dot();
		dot[bouncesTotal].show();
		triangle[bouncesTotal] = new Triangle();

		// draw triangle, start at third bounce
		if (bouncesTotal >= 2) {
			triangle[bouncesTotal].show();
		}

		// add count
		bouncesTotal++;
	}

	// get last coordinate for drawing a line
	eX2 = eX;
	eY2 = eY;

	console.log(bouncesTotal);
}

/*
* custom functions
*/
// create cartesian coordinates
function cartesianX(radius,angle) {
	var x = radius*cos(angle);

	return x;
}

function cartesianY(radius,angle) {
	var y = radius*sin(angle);

	return y;
}

/*
* Classes
*/
// Dot constructor
var Dot = function() {
	this.x = eX;
	this.y = eY;
	this.width = eW;
	this.color = color(h,s,b,a);
	// this.color = color(h2,50,50,50);
};

// show method
Dot.prototype.show = function() {
	noStroke();
	fill(this.color);
	ellipse(this.x,this.y, this.width*5,this.width*5);
};

// Triangle constructor
var Triangle = function() {
	this.x1 = tWallPosX[bouncesTotal];
	this.y1 = tWallPosY[bouncesTotal];
	this.x2 = tWallPosX[bouncesTotal-2];
	this.y2 = tWallPosY[bouncesTotal-2];

	// this.colorFill = color(h2,s2,b2,10);
	this.colorStroke = color(h,s,b,a);
};

Triangle.prototype.show = function() {
	stroke(this.colorStroke);
	// noFill();
	// noStroke();
	// fill(this.colorFill);

	// triangle(
	// 	this.x1,this.y1,
	// 	this.x2,this.y2,
	// 	this.x3,this.y3
	// );
line(
		this.x1,this.y1,
		this.x2,this.y2
	);
};<commit_msg>add fadeout effect<commit_after>var h = 360,
		s = 0,
		b = 100,
		a = 100;

var h2 = 12,
		s2 = 40,
		b2 = 23,
		a2 = 100;

var h3 = 0,
		s3 = 0,
		b3 = 15,
		a3 = 100,
		a3Wipe = 40;

// vars for line
var eX, eY, // position
		eX2, eY2,
		eW = 2; // width

// for bounces on wall
var bounces = 0,
		bouncesMax,
		bouncesTotal = 0; // current total amount of bounces

// for conversion from polar to cartesian coordinates.
// basically getting x and y from an angle and a radius.
// angle: 0 to 360 ... duh
var angle,
		radius ; // sets the speed

var quadrant;

var wall;	// which wall? t,r,b,l?

// for Dot
var dot = [];

// for saving position of corner of triangle
var tWallPosX = [],
		tWallPosY = [],
		triangle = [];

// for filling whole document
var w = window,
		wX = w.innerWidth,
		wY = w.innerHeight;

/*
* only executed once
*/
function setup(){
	createCanvas(wX, wY);
	// createCanvas(1600/2, 900/2);

	// change color mode to hsl
	colorMode(HSB, 360, 100, 100, 100);

	// start line at...
	eX = random(0,width);
	eY = 0;
	angle = radians(random(1,179));
	radius = 10; //speed of line drawing
	bouncesMax = 4;

	// rectangle/background
	background(h3, s3, b3);
}

/*
* this will be executed all the time
*/
function draw(){
	// translate from angle: polar to cartesian coordianates
	eX += cartesianX(radius,angle);
	eY += cartesianY(radius,angle);

	// DRAW LINE
	stroke(h,s,b,a);
	strokeWeight(eW);
	line(eX,eY, eX2,eY2);

	// quadrants:
	// 1: 0° - 90°
	// 2: 90° - 180°
	// 3: 180° - 270°
	// 4: 270° - 360°
	if (angle >= radians(0) && angle < radians(90)) {
		quadrant = 1;
	}
	else if (angle >= radians(90) && angle < radians(180)) {
		quadrant = 2;
	}
	else if (angle >= radians(180) && angle < radians(270)) {
		quadrant = 3;
	}
	else if (angle >= radians(270) && angle < radians(360)) {
		quadrant = 4;
	}

	// wall sides
	if (eY < 0) {
		wall = 1;
	}
	else if (eX > width) {
		wall = 2;
	}
	else if (eY > height) {
		wall = 3;
	}
	else if (eX < 0) {
		wall = 4;
	}

	// if bounce from specific wall from specific angle
	// 0° - 90°
	if (quadrant === 1 && wall === 2) { // right
		angle += radians(90);
		bounces++;
		eX = width;
	}
	else if (quadrant === 1 && wall === 3) { // bottom
		angle -= radians(90);
		bounces++;
		eY = height;
	}
	// 90° - 180°
	else if (quadrant === 2 && wall === 3) { // bottom
		angle += radians(90);
		bounces++;
		eY = height;
	}
	else if (quadrant === 2 && wall === 4) { // left
		angle -= radians(90);
		bounces++;
		eX = 0;
	}
	// 180° - 270°
	else if (quadrant === 3 && wall === 4) { // left
		angle += radians(90);
		bounces++;
		eX = 0;
	}
	else if (quadrant === 3 && wall === 1) { // top
		angle -= radians(90);
		bounces++;
		eY = 0;
	}
	// 270° - 360°
	else if (quadrant === 4 && wall === 1) { // top
		angle += radians(90);
		bounces++;
		eY = 0;
	}
	else if (quadrant === 4 && wall === 2) { // right
		angle -= radians(90);
		bounces++;
		eX = width;
	}

	// stay in 360°
	if (angle >= radians(360)) {
		angle -= radians(360);
	}
	else if (angle < radians(0)) {
		angle += radians(360);
	}

	if (frameCount === 1) {
		dot[bouncesTotal] = new Dot();
		dot[bouncesTotal].show();
	}
	// if specific amount of bouncing, reset position
	if (bounces > bouncesMax) {
		noStroke();
		// eX = random(0,width);
		// eY = 0;
		angle = radians(random(0,180));
		bounces = 0; // reset bounces counter
		frameCount = 1;
	}
	// "cleaning on isle five"... reset the canvas
	if (bouncesTotal%(bouncesMax*4) === (bouncesMax*4)-1) {
		fill(h3,s3,b3,90);
		noStroke();
		rect(0,0, width, height);
		frameCount = 1;
	}
	// if at wall-bounce, add thing
	if (eX === width || eY === height || eX === 0 || eY === 0) {

		// save position at wall
		tWallPosX[bouncesTotal] = eX;
		tWallPosY[bouncesTotal] = eY;

		// create new Dot at wall
		dot[bouncesTotal] = new Dot();
		dot[bouncesTotal].show();
		triangle[bouncesTotal] = new Triangle();

		// draw triangle, start at third bounce
		if (bouncesTotal >= 2) {
			triangle[bouncesTotal].show();
		}

		// add count
		bouncesTotal++;
	}

	// fadeout effect
	background(h3, s3, b3, 1);

	// get last coordinate for drawing a line
	eX2 = eX;
	eY2 = eY;

	console.log(bouncesTotal);
}

/*
* custom functions
*/
// create cartesian coordinates
function cartesianX(radius,angle) {
	var x = radius*cos(angle);

	return x;
}

function cartesianY(radius,angle) {
	var y = radius*sin(angle);

	return y;
}

/*
* Classes
*/
// Dot constructor
var Dot = function() {
	this.x = eX;
	this.y = eY;
	this.width = eW;
	this.color = color(h,s,b,a);
	// this.color = color(h2,50,50,50);
};

// show method
Dot.prototype.show = function() {
	noStroke();
	fill(this.color);
	ellipse(this.x,this.y, this.width*5,this.width*5);
};

// Triangle constructor
var Triangle = function() {
	this.x1 = tWallPosX[bouncesTotal];
	this.y1 = tWallPosY[bouncesTotal];
	this.x2 = tWallPosX[bouncesTotal-2];
	this.y2 = tWallPosY[bouncesTotal-2];

	// this.colorFill = color(h2,s2,b2,10);
	this.colorStroke = color(h,s,b,a);
};

Triangle.prototype.show = function() {
	stroke(this.colorStroke);
	// noFill();
	// noStroke();
	// fill(this.colorFill);

	// triangle(
	// 	this.x1,this.y1,
	// 	this.x2,this.y2,
	// 	this.x3,this.y3
	// );
line(
		this.x1,this.y1,
		this.x2,this.y2
	);
};<|endoftext|>


<commit_before>/* @flow */
'use babel';

'use strict';

var DB_NAME = 'blogel';
var POST_TABLE_NAME = 'posts';
var AUTHORS_TABLE_NAME = 'authors';

var r = require('rethinkdb');
var root = require('./util').path();
var options = { host: 'localhost', port: 28015, authkey:'', db:DB_NAME};

import type { Post, Author } from './core/types.js';

var samplePost:Post = {
    title: 'Post',
    content: 'Hello, World!',
    postCreated : new Date(),
    postPublished: '22-07-2015',
    lastUpdated: '22-07-2015',
    status: 'draft',
    author: 'Maheso Anabrang',
    tags: ['hello', 'dummy']
}

asyncInitDb();

function asyncInitDb(log:boolean = true) {
    getDbConnection()
    .then((conn) => {
        dbIsExist(conn).then((status) => {
            if(!status.exist) {
                return createDatabase(conn);
            }
            return p(status.conn);
        })
        .then( (response) => {
            isTableExist(POST_TABLE_NAME, response.conn).then((status) => {
                if(!status.exist) {
                    return createTable(POST_TABLE_NAME, status.conn);
                }
                return p(status.conn)
            })
            .then( (response) => {
                isTableExist(AUTHORS_TABLE_NAME, response.conn).then((status) => {
                    if(!status.exist) {
                        return createTable(AUTHORS_TABLE_NAME, status.conn);
                    }
                    return p(status.conn);
                })
                .then( (res) => {
                    res.conn.close((err) => {
                        if(err) console.log(err) ;
                    });
                })
                .catch( (err) => {
                    console.log(err.message);
                    process.exit(1);
                });
            })
        })
    })
}

function p(conn: any): Promise {
    return new Promise((resolve, reject) => {
        resolve({conn:conn});
    })
}

function dbIsExist(conn: any): Promise {
    return new Promise((resolve, reject) => {
        r.dbList().run(conn, (err,list) => {
            if(err) {
                reject(err);
            } else {
                var blogel: boolean = false;
                list.forEach((v,i,a) => {
                    if(v === DB_NAME) {
                        blogel = true;
                    }
                })
                blogel ? resolve({ exist:true, conn:conn}):resolve({ exist:false, conn:conn});
            }
        });
    });
}

function isTableExist(tableName: string, conn: any): Promise {
    return new Promise( (resolve, reject) => {
        r.db(DB_NAME).tableList().run(conn, (err,table) => {
            if(err) {
                reject(err);
            } else {
                var _tableName: boolean = false;
                table.forEach((v,i,a) => {
                    if(v === tableName) {
                        _tableName = true;
                    }
                })
                _tableName ? resolve({ exist:true, conn:conn}) : resolve({ exist:false, conn:conn});
            }
        });
    });
}

function createDatabase(conn: any): Promise {
    return new Promise((resolve, reject) => {
        r.dbCreate(DB_NAME).run(conn, (err, res) => {
            err ? reject(err) : resolve({ res: res, conn: conn });
        })
    })
}

function createTable(tableName: string, conn: any): Promise {
    return new Promise((resolve, reject) => {
        r.db(DB_NAME).tableCreate(tableName).run(conn, (err, res) => {
            err ? reject(err) : resolve({ res: res, conn: conn });
        })
    })
}

function getDbConnection(): Promise {
    return r.connect(options);
}

function savePost(post:Post): Promise {
    return new Promise((resolve, reject) => {
        getDbConnection().then((conn) => {
            r.db(DB_NAME).table(POST_TABLE_NAME).insert(post).run(conn, (err, result) => {
                err ? reject(err) : resolve(result);
            });
        })
    })
}

function getAllPost(): Array<Post> {
    var allPost:Array<Post> = [samplePost, samplePost];

    return allPost;
}

function getPostById(id:string): Promise {
    return new	Promise((resolve, reject) => {
        getDbConnection().then((conn) => {
	    r.db(DB_NAME).table(POST_TABLE_NAME).get(id).run(conn, function(err, result){
	        err ? reject(err) : resolve(result);
	    })
	})
    });
}

function updatePost(post:Post): Promise {

    return new Promise((resolve, reject) => {
        getDbConnection().then((conn) => {
	    r.db(DB_NAME).table(POST_TABLE_NAME).get(post.generated_keys[0]).update(post).run(conn, (err, status) => {
	        err ? reject(err) : resolve(status);
	    })
	})
    });
}

function deletePost(id:string): Promise {
    return new Promise((resolve, reject) => {
        getDbConnection().then((conn) => {
	    r.db(DB_NAME).table(POST_TABLE_NAME).get(id).delete().run(conn, (err, result) => {
	        err ? reject(err) : resolve(result);
	    });
	})
    })
}

function saveAuthor(author: Author): Promise {
    return new Promise((resolve, reject) => {
        getDbConnection().then((conn) => {
	    r.db(DB_NAME).table(AUTHORS_TABLE_NAME).insert(author).run(conn, (err, result) => {
	      err ? reject(err) : resolve(result);
	    })
	})
    })
}

function deleteAuthor(id: string): Promise {
    return new Promise((resolve, reject) => {
        getDbConnection().then((conn) => {
	    r.db(DB_NAME).table(AUTHORS_TABLE_NAME).get(id).delete().run(conn, (err, result) => {
	       err ? reject(err) : resolve(result);
	    })
	})
    });
}

function getAuthorById(id: string): Promise {
    return new Promise((resolve, reject) => {
        getDbConnection().then((conn) => {
	   r.db(DB_NAME).table(AUTHORS_TABLE_NAME).get(id).run(conn, (err, result) => {
	       err ? reject(err) : resolve(result);
	   })
	})
    })
}

function updateAuthor(author: Author): Promise {
    return new Promise((resolve, reject) => {
        getDbConnection().then((conn) => {
	    r.db(DB_NAME).table(AUTHORS_TABLE_NAME).get(author.generated_keys[0]).update(author).run(conn, (err, result) => {
	        err ? reject(err) : resolve(result);
	    })
	})
    })
}

function getPostByAuthor(authorId: string): Array<Post> {
    var postsByAuthor: Array<Post> = [samplePost, samplePost];
    return postsByAuthor;
}

module.exports = {
    DB_NAME,
    POST_TABLE_NAME,
    AUTHORS_TABLE_NAME,
    getDbConnection,
    getAllPost,
    getPostById,
    getPostByAuthor,
    savePost,
    updatePost,
    deletePost,
    saveAuthor,
    deleteAuthor,
    getAuthorById,
    updateAuthor
}
<commit_msg>Type checking for null or undefined value<commit_after>/* @flow */
'use babel';

'use strict';

var DB_NAME = 'blogel';
var POST_TABLE_NAME = 'posts';
var AUTHORS_TABLE_NAME = 'authors';

var r = require('rethinkdb');
var root = require('./util').path();
var options = { host: 'localhost', port: 28015, authkey:'', db:DB_NAME};

import type { Post, Author } from './core/types.js';

var samplePost:Post = {
    title: 'Post',
    content: 'Hello, World!',
    postCreated : new Date(),
    postPublished: '22-07-2015',
    lastUpdated: '22-07-2015',
    status: 'draft',
    author: 'Maheso Anabrang',
    tags: ['hello', 'dummy']
}

asyncInitDb();

function asyncInitDb(log:boolean = true) {
    getDbConnection()
    .then((conn) => {
        dbIsExist(conn).then((status) => {
            if(!status.exist) {
                return createDatabase(conn);
            }
            return p(status.conn);
        })
        .then( (response) => {
            isTableExist(POST_TABLE_NAME, response.conn).then((status) => {
                if(!status.exist) {
                    return createTable(POST_TABLE_NAME, status.conn);
                }
                return p(status.conn)
            })
            .then( (response) => {
                isTableExist(AUTHORS_TABLE_NAME, response.conn).then((status) => {
                    if(!status.exist) {
                        return createTable(AUTHORS_TABLE_NAME, status.conn);
                    }
                    return p(status.conn);
                })
                .then( (res) => {
                    res.conn.close((err) => {
                        if(err) console.log(err) ;
                    });
                })
                .catch( (err) => {
                    console.log(err.message);
                    process.exit(1);
                });
            })
        })
    })
}

function p(conn: any): Promise {
    return new Promise((resolve, reject) => {
        resolve({conn:conn});
    })
}

function dbIsExist(conn: any): Promise {
    return new Promise((resolve, reject) => {
        r.dbList().run(conn, (err,list) => {
            if(err) {
                reject(err);
            } else {
                var blogel: boolean = false;
                list.forEach((v,i,a) => {
                    if(v === DB_NAME) {
                        blogel = true;
                    }
                })
                blogel ? resolve({ exist:true, conn:conn}):resolve({ exist:false, conn:conn});
            }
        });
    });
}

function isTableExist(tableName: string, conn: any): Promise {
    return new Promise( (resolve, reject) => {
        r.db(DB_NAME).tableList().run(conn, (err,table) => {
            if(err) {
                reject(err);
            } else {
                var _tableName: boolean = false;
                table.forEach((v,i,a) => {
                    if(v === tableName) {
                        _tableName = true;
                    }
                })
                _tableName ? resolve({ exist:true, conn:conn}) : resolve({ exist:false, conn:conn});
            }
        });
    });
}

function createDatabase(conn: any): Promise {
    return new Promise((resolve, reject) => {
        r.dbCreate(DB_NAME).run(conn, (err, res) => {
            err ? reject(err) : resolve({ res: res, conn: conn });
        })
    })
}

function createTable(tableName: string, conn: any): Promise {
    return new Promise((resolve, reject) => {
        r.db(DB_NAME).tableCreate(tableName).run(conn, (err, res) => {
            err ? reject(err) : resolve({ res: res, conn: conn });
        })
    })
}

function getDbConnection(): Promise {
    return r.connect(options);
}

function savePost(post:Post): Promise {
    return new Promise((resolve, reject) => {
        getDbConnection().then((conn) => {
            r.db(DB_NAME).table(POST_TABLE_NAME).insert(post).run(conn, (err, result) => {
                err ? reject(err) : resolve(result);
            });
        })
    })
}

function getAllPost(): Array<Post> {
    var allPost:Array<Post> = [samplePost, samplePost];

    return allPost;
}

function getPostById(id:string): Promise {
    return new	Promise((resolve, reject) => {
        getDbConnection().then((conn) => {
	        r.db(DB_NAME).table(POST_TABLE_NAME).get(id).run(conn, function(err, result){
	            err ? reject(err) : resolve(result);
	        })
	    })
    });
}

function updatePost(post:Post): Promise {
    return new Promise((resolve, reject) => {
        getDbConnection().then((conn) => {
	        if(post.generated_keys != null){
                r.db(DB_NAME).table(POST_TABLE_NAME).get(post.generated_keys[0]).update(post).run(conn, (err, status) => {
                    err ? reject(err) : resolve(status);
                })
            }
	      })
    });
}

function deletePost(id:string): Promise {
    return new Promise((resolve, reject) => {
      getDbConnection().then((conn) => {
	      r.db(DB_NAME).table(POST_TABLE_NAME).get(id).delete().run(conn, (err, result) => {
	        err ? reject(err) : resolve(result);
	      });
	  })
    })
}

function saveAuthor(author: Author): Promise {
    return new Promise((resolve, reject) => {
      getDbConnection().then((conn) => {
	      r.db(DB_NAME).table(AUTHORS_TABLE_NAME).insert(author).run(conn, (err, result) => {
	        err ? reject(err) : resolve(result);
	      })
	    })
    })
}

function deleteAuthor(id: string): Promise {
    return new Promise((resolve, reject) => {
      getDbConnection().then((conn) => {
	      r.db(DB_NAME).table(AUTHORS_TABLE_NAME).get(id).delete().run(conn, (err, result) => {
	        err ? reject(err) : resolve(result);
	      })
	    })
    });
}

function getAuthorById(id: string): Promise {
    return new Promise((resolve, reject) => {
      getDbConnection().then((conn) => {
	      r.db(DB_NAME).table(AUTHORS_TABLE_NAME).get(id).run(conn, (err, result) => {
	        err ? reject(err) : resolve(result);
	      })
	    })
    })
}

function updateAuthor(author: Author): Promise {
    return new Promise((resolve, reject) => {
      getDbConnection().then((conn) => {
          if(author.generated_keys != null){
              r.db(DB_NAME).table(AUTHORS_TABLE_NAME).get(author.generated_keys[0]).update(author).run(conn, (err, result) => {
                  err ? reject(err) : resolve(result);
              })
          }
	    })
    })
}

function getPostByAuthor(authorId: string): Array<Post> {
    var postsByAuthor: Array<Post> = [samplePost, samplePost];
    return postsByAuthor;
}

module.exports = {
    DB_NAME,
    POST_TABLE_NAME,
    AUTHORS_TABLE_NAME,
    getDbConnection,
    getAllPost,
    getPostById,
    getPostByAuthor,
    savePost,
    updatePost,
    deletePost,
    saveAuthor,
    deleteAuthor,
    getAuthorById,
    updateAuthor
}
<|endoftext|>


<commit_before>import RSVP from 'rsvp';
import { isEmpty } from '@ember/utils';
import { get, computed } from '@ember/object';
import Service, { inject as service } from '@ember/service';
import moment from 'moment';
import jwtDecode from '../utils/jwt-decode';

const { map } = RSVP;

export default Service.extend({
  store: service(),
  session: service(),
  currentUserId: computed('session.data.authenticated.jwt', function(){
    const session = this.get('session');
    if(isEmpty(session)){
      return null;
    }

    const jwt = session.get('data.authenticated.jwt');

    if(isEmpty(jwt)){
      return null;
    }
    const obj = jwtDecode(jwt);

    return get(obj, 'user_id');
  }),

  model: computed('currentUserId', async function(){
    let currentUserId = this.get('currentUserId');
    if (!currentUserId) {
      return null;
    }
    return await this.get('store').find('user', currentUserId);
  }),

  /**
   * All cohorts from all schools that the current user is associated with,
   * via primary school association and the explicit schools permissions.
   * @property cohortsInAllAssociatedSchools
   * @type {Ember.computed}
   * @readOnly
   * @public
   */
  cohortsInAllAssociatedSchools: computed('model.schools.[]', async function(){
    const user = await this.get('model');
    if (!user) {
      return [];
    }
    const schools = await user.get('schools');
    const cohorts = await map(schools, async school => {
      const programs = await school.get('programs');
      const schoolCohorts = await map(programs.toArray(), async program => {
        return await program.get('cohorts');
      });
      return schoolCohorts.reduce((array, set) => {
        return array.pushObjects(set);
      }, []);
    });

    return cohorts.reduce((array, set) => {
      return array.pushObjects(set.toArray());
    }, []);
  }).readOnly(),

  userRoleTitles: computed('model.roles.[]', async function(){
    const user = await this.get('model');
    if(!user) {
      return [];
    }
    const roles = await user.get('roles');
    return roles.map(role => role.get('title').toLowerCase());
  }),

  userIsCourseDirector: computed('useRoleTitles.[]', async function(){
    const roleTitles = await this.get('userRoleTitles');
    return roleTitles.includes('course director');
  }),

  userIsFaculty: computed('useRoleTitles.[]', async function(){
    const roleTitles = await this.get('userRoleTitles');
    return roleTitles.includes('faculty');
  }),

  userIsDeveloper: computed('useRoleTitles.[]', async function(){
    const roleTitles = await this.get('userRoleTitles');
    return roleTitles.includes('developer');

  }),
  userIsStudent: computed('useRoleTitles.[]', async function(){
    const roleTitles = await this.get('userRoleTitles');
    return roleTitles.includes('student');
  }),
  userIsPublic: computed('useRoleTitles.[]', async function(){
    const roleTitles = await this.get('userRoleTitles');
    return roleTitles.includes('public');
  }),
  userIsFormerStudent: computed('useRoleTitles.[]', async function(){
    const roleTitles = await this.get('userRoleTitles');
    return roleTitles.includes('former student');
  }),
  activeRelatedCoursesInThisYearAndLastYear: computed(
    'model',
    'model.instructedOfferings.[]',
    'model.instructorGroups.[]',
    'model.instructedLearnerGroups.[]',
    'model.directedCourses.[]',
    'model.instructorIlmSessions.[]',
    async function(){
      const user = await this.get('model');
      if(isEmpty(user)){
        return [];
      }
      let currentYear = moment().format('YYYY');
      const currentMonth = parseInt(moment().format('M'), 10);
      if(currentMonth < 6){
        currentYear--;
      }
      const previousYear = currentYear -1;
      const nextYear = currentYear +1;
      return await this.get('store').query('course', {
        my: true,
        filters: {
          year: [previousYear, currentYear, nextYear],
          locked: false,
          archived: false
        }
      });
    }
  ),
  getBooleanAttributeFromToken(attribute) {
    const session = this.get('session');
    if(isEmpty(session)){
      return false;
    }

    const jwt = session.get('data.authenticated.jwt');

    if(isEmpty(jwt)){
      return false;
    }
    const obj = jwtDecode(jwt);

    return !!get(obj, attribute);
  },
  isRoot: computed('session.data.authenticated.jwt', function(){
    return this.getBooleanAttributeFromToken('is_root');
  }),
  performsNonLearnerFunction: computed('session.data.authenticated.jwt', function(){
    return this.getBooleanAttributeFromToken('performs_non_learner_function');
  }),
  canCreateOrUpdateUserInAnySchool: computed('session.data.authenticated.jwt', function(){
    return this.getBooleanAttributeFromToken('can_create_or_update_user_in_any_school');
  }),
  canCreateCIReportInAnySchool: computed('session.data.authenticated.jwt', function(){
    return this.getBooleanAttributeFromToken('can_create_curriculum_inventory_report_in_any_school');
  }),
  schools: computed('model.schools', async function () {
    const model = await this.get('model');
    return model.get('schools');
  }),
  async isDirectingSchool(school) {
    const user = await this.get('model');
    const ids = user.hasMany('directedSchools').ids();
    return ids.includes(school.get('id'));
  },
  async isAdministeringSchool(school) {
    const user = await this.get('model');
    const ids = user.hasMany('administeredSchools').ids();
    return ids.includes(school.get('id'));
  },
  async isDirectingCourseInSchool(school) {
    const user = await this.get('model');
    const schoolCourseIds = school.hasMany('courses').ids();

    const ids = user.hasMany('directedCourses').ids();
    const matches = ids.filter(id => schoolCourseIds.includes(id));

    return matches.length > 0;
  },
  async isAdministeringCourseInSchool(school) {
    const user = await this.get('model');
    const schoolCourseIds = school.hasMany('courses').ids();

    const ids = user.hasMany('administeredCourses').ids();
    const matches = ids.filter(id => schoolCourseIds.includes(id));

    return matches.length > 0;
  },
  async isAdministeringSessionInSchool(school) {
    const user = await this.get('model');
    const schoolCourseIds = school.hasMany('courses').ids();

    const sessions = await user.get('administeredSessions');
    const matches = sessions.filter(session => schoolCourseIds.includes(session.belongsTo('course').id()));

    return matches.length > 0;
  },
  async isTeachingCourseInSchool(school) {
    const user = await this.get('model');
    const schoolCourseIds = school.hasMany('courses').ids();

    const courses = await user.get('allInstructedCourses');
    const matches = courses.filter(course => schoolCourseIds.includes(course.get('id')));

    return matches.length > 0;
  },
  async isAdministeringCurriculumInventoryReportInSchool(school) {
    const user = await this.get('model');
    const schoolProgramIds = school.hasMany('programs').ids();

    const reports = await user.get('administeredCurriculumInventoryReports');
    const matches = reports.filter(report => schoolProgramIds.includes(report.belongsTo('program').id()));

    return matches.length > 0;
  },
  async isDirectingCourse(course) {
    const user = await this.get('model');

    const ids = user.hasMany('directedCourses').ids();

    return ids.includes(course.get('id'));
  },
  async isAdministeringCourse(course) {
    const user = await this.get('model');

    const ids = user.hasMany('administeredCourses').ids();

    return ids.includes(course.get('id'));
  },
  async isAdministeringSessionInCourse(course) {
    const user = await this.get('model');

    const sessions = await user.get('administeredSessions');
    const matches = sessions.filter(session => course.get('id') === session.belongsTo('course').id());

    return matches.length > 0;
  },
  async isTeachingCourse(course) {
    const user = await this.get('model');

    const courses = await user.get('allInstructedCourses');
    const matches = courses.filterBy('id', course.get('id'));

    return matches.length > 0;
  },
  async isAdministeringSession(session) {
    const user = await this.get('model');

    const ids = user.hasMany('administeredSessions').ids();

    return ids.includes(session.get('id'));
  },
  async isTeachingSession(session) {
    const user = await this.get('model');

    const sessions = await user.get('allInstructedSessions');
    const matches = sessions.filterBy('id', session.get('id'));

    return matches.length > 0;
  },
  async isDirectingProgram(program) {
    const user = await this.get('model');

    const ids = user.hasMany('directedPrograms').ids();

    return ids.includes(program.get('id'));
  },
  async isDirectingProgramYearInProgram(program) {
    const user = await this.get('model');

    const programYears = await user.get('programYears');
    const matches = programYears.filter(programYear => program.get('id') === programYear.belongsTo('program').id());

    return matches.length > 0;
  },
  async isAdministeringCurriculumInventoryReport(report) {
    const user = await this.get('model');

    const ids = user.hasMany('administeredCurriculumInventoryReports').ids();

    return ids.includes(report.get('id'));
  },
  async getRolesInSchool(school) {
    let roles = [];
    if (await this.isDirectingSchool(school)) {
      roles.pushObject('SCHOOL_DIRECTOR');
    }
    if (await this.isAdministeringSchool(school)) {
      roles.pushObject('SCHOOL_ADMINISTRATOR');
    }
    if (await this.isDirectingCourseInSchool(school)) {
      roles.pushObject('COURSE_DIRECTOR');
    }
    if (await this.isAdministeringCourseInSchool(school)) {
      roles.pushObject('COURSE_ADMINISTRATOR');
    }
    if (await this.isAdministeringSessionInSchool(school)) {
      roles.pushObject('SESSION_ADMINISTRATOR');
    }
    if (await this.isTeachingCourseInSchool(school)) {
      roles.pushObject('COURSE_INSTRUCTOR');
    }
    if (await this.isAdministeringCurriculumInventoryReportInSchool(school)) {
      roles.pushObject('CURRICULUM_INVENTORY_REPORT_ADMINISTRATOR');
    }

    return roles;
  },
  async getRolesInCourse(course) {
    let roles = [];
    if (await this.isDirectingCourse(course)) {
      roles.pushObject('COURSE_DIRECTOR');
    }
    if (await this.isAdministeringCourse(course)) {
      roles.pushObject('COURSE_ADMINISTRATOR');
    }
    if (await this.isAdministeringSessionInCourse(course)) {
      roles.pushObject('SESSION_ADMINISTRATOR');
    }
    if (await this.isTeachingCourse(course)) {
      roles.pushObject('COURSE_INSTRUCTOR');
    }

    return roles;
  },
  async getRolesInSession(session) {
    let roles = [];
    if (await this.isAdministeringSession(session)) {
      roles.pushObject('SESSION_ADMINISTRATOR');
    }
    if (await this.isTeachingSession(session)) {
      roles.pushObject('COURSE_INSTRUCTOR');
    }

    return roles;
  },
  async getRolesInProgram(program) {
    let roles = [];
    if (await this.isDirectingProgram(program)) {
      roles.pushObject('PROGRAM_DIRECTOR');
    }
    if (await this.isDirectingProgramYearInProgram(program)) {
      roles.pushObject('PROGRAM_YEAR_DIRECTOR');
    }

    return roles;
  },
  async getRolesInCurriculumInventoryReport(report) {
    let roles = [];
    if (await this.isAdministeringCurriculumInventoryReport(report)) {
      roles.pushObject('CURRICULUM_INVENTORY_REPORT_ADMINISTRATOR');
    }

    return roles;
  },
});
<commit_msg>Add missing methods for program year roles<commit_after>import RSVP from 'rsvp';
import { isEmpty } from '@ember/utils';
import { get, computed } from '@ember/object';
import Service, { inject as service } from '@ember/service';
import moment from 'moment';
import jwtDecode from '../utils/jwt-decode';

const { map } = RSVP;

export default Service.extend({
  store: service(),
  session: service(),
  currentUserId: computed('session.data.authenticated.jwt', function(){
    const session = this.get('session');
    if(isEmpty(session)){
      return null;
    }

    const jwt = session.get('data.authenticated.jwt');

    if(isEmpty(jwt)){
      return null;
    }
    const obj = jwtDecode(jwt);

    return get(obj, 'user_id');
  }),

  model: computed('currentUserId', async function(){
    let currentUserId = this.get('currentUserId');
    if (!currentUserId) {
      return null;
    }
    return await this.get('store').find('user', currentUserId);
  }),

  /**
   * All cohorts from all schools that the current user is associated with,
   * via primary school association and the explicit schools permissions.
   * @property cohortsInAllAssociatedSchools
   * @type {Ember.computed}
   * @readOnly
   * @public
   */
  cohortsInAllAssociatedSchools: computed('model.schools.[]', async function(){
    const user = await this.get('model');
    if (!user) {
      return [];
    }
    const schools = await user.get('schools');
    const cohorts = await map(schools, async school => {
      const programs = await school.get('programs');
      const schoolCohorts = await map(programs.toArray(), async program => {
        return await program.get('cohorts');
      });
      return schoolCohorts.reduce((array, set) => {
        return array.pushObjects(set);
      }, []);
    });

    return cohorts.reduce((array, set) => {
      return array.pushObjects(set.toArray());
    }, []);
  }).readOnly(),

  userRoleTitles: computed('model.roles.[]', async function(){
    const user = await this.get('model');
    if(!user) {
      return [];
    }
    const roles = await user.get('roles');
    return roles.map(role => role.get('title').toLowerCase());
  }),

  userIsCourseDirector: computed('useRoleTitles.[]', async function(){
    const roleTitles = await this.get('userRoleTitles');
    return roleTitles.includes('course director');
  }),

  userIsFaculty: computed('useRoleTitles.[]', async function(){
    const roleTitles = await this.get('userRoleTitles');
    return roleTitles.includes('faculty');
  }),

  userIsDeveloper: computed('useRoleTitles.[]', async function(){
    const roleTitles = await this.get('userRoleTitles');
    return roleTitles.includes('developer');

  }),
  userIsStudent: computed('useRoleTitles.[]', async function(){
    const roleTitles = await this.get('userRoleTitles');
    return roleTitles.includes('student');
  }),
  userIsPublic: computed('useRoleTitles.[]', async function(){
    const roleTitles = await this.get('userRoleTitles');
    return roleTitles.includes('public');
  }),
  userIsFormerStudent: computed('useRoleTitles.[]', async function(){
    const roleTitles = await this.get('userRoleTitles');
    return roleTitles.includes('former student');
  }),
  activeRelatedCoursesInThisYearAndLastYear: computed(
    'model',
    'model.instructedOfferings.[]',
    'model.instructorGroups.[]',
    'model.instructedLearnerGroups.[]',
    'model.directedCourses.[]',
    'model.instructorIlmSessions.[]',
    async function(){
      const user = await this.get('model');
      if(isEmpty(user)){
        return [];
      }
      let currentYear = moment().format('YYYY');
      const currentMonth = parseInt(moment().format('M'), 10);
      if(currentMonth < 6){
        currentYear--;
      }
      const previousYear = currentYear -1;
      const nextYear = currentYear +1;
      return await this.get('store').query('course', {
        my: true,
        filters: {
          year: [previousYear, currentYear, nextYear],
          locked: false,
          archived: false
        }
      });
    }
  ),
  getBooleanAttributeFromToken(attribute) {
    const session = this.get('session');
    if(isEmpty(session)){
      return false;
    }

    const jwt = session.get('data.authenticated.jwt');

    if(isEmpty(jwt)){
      return false;
    }
    const obj = jwtDecode(jwt);

    return !!get(obj, attribute);
  },
  isRoot: computed('session.data.authenticated.jwt', function(){
    return this.getBooleanAttributeFromToken('is_root');
  }),
  performsNonLearnerFunction: computed('session.data.authenticated.jwt', function(){
    return this.getBooleanAttributeFromToken('performs_non_learner_function');
  }),
  canCreateOrUpdateUserInAnySchool: computed('session.data.authenticated.jwt', function(){
    return this.getBooleanAttributeFromToken('can_create_or_update_user_in_any_school');
  }),
  canCreateCIReportInAnySchool: computed('session.data.authenticated.jwt', function(){
    return this.getBooleanAttributeFromToken('can_create_curriculum_inventory_report_in_any_school');
  }),
  schools: computed('model.schools', async function () {
    const model = await this.get('model');
    return model.get('schools');
  }),
  async isDirectingSchool(school) {
    const user = await this.get('model');
    const ids = user.hasMany('directedSchools').ids();
    return ids.includes(school.get('id'));
  },
  async isAdministeringSchool(school) {
    const user = await this.get('model');
    const ids = user.hasMany('administeredSchools').ids();
    return ids.includes(school.get('id'));
  },
  async isDirectingCourseInSchool(school) {
    const user = await this.get('model');
    const schoolCourseIds = school.hasMany('courses').ids();

    const ids = user.hasMany('directedCourses').ids();
    const matches = ids.filter(id => schoolCourseIds.includes(id));

    return matches.length > 0;
  },
  async isAdministeringCourseInSchool(school) {
    const user = await this.get('model');
    const schoolCourseIds = school.hasMany('courses').ids();

    const ids = user.hasMany('administeredCourses').ids();
    const matches = ids.filter(id => schoolCourseIds.includes(id));

    return matches.length > 0;
  },
  async isAdministeringSessionInSchool(school) {
    const user = await this.get('model');
    const schoolCourseIds = school.hasMany('courses').ids();

    const sessions = await user.get('administeredSessions');
    const matches = sessions.filter(session => schoolCourseIds.includes(session.belongsTo('course').id()));

    return matches.length > 0;
  },
  async isTeachingCourseInSchool(school) {
    const user = await this.get('model');
    const schoolCourseIds = school.hasMany('courses').ids();

    const courses = await user.get('allInstructedCourses');
    const matches = courses.filter(course => schoolCourseIds.includes(course.get('id')));

    return matches.length > 0;
  },
  async isAdministeringCurriculumInventoryReportInSchool(school) {
    const user = await this.get('model');
    const schoolProgramIds = school.hasMany('programs').ids();

    const reports = await user.get('administeredCurriculumInventoryReports');
    const matches = reports.filter(report => schoolProgramIds.includes(report.belongsTo('program').id()));

    return matches.length > 0;
  },
  async isDirectingCourse(course) {
    const user = await this.get('model');

    const ids = user.hasMany('directedCourses').ids();

    return ids.includes(course.get('id'));
  },
  async isAdministeringCourse(course) {
    const user = await this.get('model');

    const ids = user.hasMany('administeredCourses').ids();

    return ids.includes(course.get('id'));
  },
  async isAdministeringSessionInCourse(course) {
    const user = await this.get('model');

    const sessions = await user.get('administeredSessions');
    const matches = sessions.filter(session => course.get('id') === session.belongsTo('course').id());

    return matches.length > 0;
  },
  async isTeachingCourse(course) {
    const user = await this.get('model');

    const courses = await user.get('allInstructedCourses');
    const matches = courses.filterBy('id', course.get('id'));

    return matches.length > 0;
  },
  async isAdministeringSession(session) {
    const user = await this.get('model');

    const ids = user.hasMany('administeredSessions').ids();

    return ids.includes(session.get('id'));
  },
  async isTeachingSession(session) {
    const user = await this.get('model');

    const sessions = await user.get('allInstructedSessions');
    const matches = sessions.filterBy('id', session.get('id'));

    return matches.length > 0;
  },
  async isDirectingProgram(program) {
    const user = await this.get('model');

    const ids = user.hasMany('directedPrograms').ids();

    return ids.includes(program.get('id'));
  },
  async isDirectingProgramYearInProgram(program) {
    const user = await this.get('model');

    const programYears = await user.get('programYears');
    const matches = programYears.filter(programYear => program.get('id') === programYear.belongsTo('program').id());

    return matches.length > 0;
  },
  async isDirectingProgramYear(programYear) {
    const user = await this.get('model');

    const ids = user.hasMany('programYears').ids();

    return ids.includes(programYear.get('id'));
  },
  async isAdministeringCurriculumInventoryReport(report) {
    const user = await this.get('model');

    const ids = user.hasMany('administeredCurriculumInventoryReports').ids();

    return ids.includes(report.get('id'));
  },
  async getRolesInSchool(school) {
    let roles = [];
    if (await this.isDirectingSchool(school)) {
      roles.pushObject('SCHOOL_DIRECTOR');
    }
    if (await this.isAdministeringSchool(school)) {
      roles.pushObject('SCHOOL_ADMINISTRATOR');
    }
    if (await this.isDirectingCourseInSchool(school)) {
      roles.pushObject('COURSE_DIRECTOR');
    }
    if (await this.isAdministeringCourseInSchool(school)) {
      roles.pushObject('COURSE_ADMINISTRATOR');
    }
    if (await this.isAdministeringSessionInSchool(school)) {
      roles.pushObject('SESSION_ADMINISTRATOR');
    }
    if (await this.isTeachingCourseInSchool(school)) {
      roles.pushObject('COURSE_INSTRUCTOR');
    }
    if (await this.isAdministeringCurriculumInventoryReportInSchool(school)) {
      roles.pushObject('CURRICULUM_INVENTORY_REPORT_ADMINISTRATOR');
    }

    return roles;
  },
  async getRolesInCourse(course) {
    let roles = [];
    if (await this.isDirectingCourse(course)) {
      roles.pushObject('COURSE_DIRECTOR');
    }
    if (await this.isAdministeringCourse(course)) {
      roles.pushObject('COURSE_ADMINISTRATOR');
    }
    if (await this.isAdministeringSessionInCourse(course)) {
      roles.pushObject('SESSION_ADMINISTRATOR');
    }
    if (await this.isTeachingCourse(course)) {
      roles.pushObject('COURSE_INSTRUCTOR');
    }

    return roles;
  },
  async getRolesInSession(session) {
    let roles = [];
    if (await this.isAdministeringSession(session)) {
      roles.pushObject('SESSION_ADMINISTRATOR');
    }
    if (await this.isTeachingSession(session)) {
      roles.pushObject('COURSE_INSTRUCTOR');
    }

    return roles;
  },
  async getRolesInProgram(program) {
    let roles = [];
    if (await this.isDirectingProgram(program)) {
      roles.pushObject('PROGRAM_DIRECTOR');
    }
    if (await this.isDirectingProgramYearInProgram(program)) {
      roles.pushObject('PROGRAM_YEAR_DIRECTOR');
    }

    return roles;
  },
  async getRolesInProgramYear(programYear) {
    let roles = [];
    if (await this.isDirectingProgramYear(programYear)) {
      roles.pushObject('PROGRAM_YEAR_DIRECTOR');
    }

    return roles;
  },
  async getRolesInCurriculumInventoryReport(report) {
    let roles = [];
    if (await this.isAdministeringCurriculumInventoryReport(report)) {
      roles.pushObject('CURRICULUM_INVENTORY_REPORT_ADMINISTRATOR');
    }

    return roles;
  },
});
<|endoftext|>


<commit_before>var currentX = 50;
var currentY = 50;
function setup() {
  createCanvas(windowWidth,windowHeight);

}

function draw() {

  if (frameCount%3&&frameCount%5) {
    fill(255,0,255);
  }
  else if (frameCount%3) {
    fill(255,0,0);
  }
  else if (frameCount%5) {
    fill(0,0,255);
  }
  else{
    fill(255);
  }
  ellipse(currentX,currentY,100,100);
  currentX = currentX + random(-10,10);
  currentY = currentY + random(-10,10);
}
<commit_msg>changed start point<commit_after>var currentX = 0;
var currentY = 0;
function setup() {
  createCanvas(windowWidth,windowHeight);
  currentX = width/2;
  currentY = height/2;
}

function draw() {

  if (frameCount%3&&frameCount%5) {
    fill(255,0,255);
  }
  else if (frameCount%3) {
    fill(255,0,0);
  }
  else if (frameCount%5) {
    fill(0,0,255);
  }
  else{
    fill(255);
  }
  ellipse(currentX,currentY,100,100);
  currentX = currentX + random(-10,10);
  currentY = currentY + random(-10,10);
}
<|endoftext|>


<commit_before>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

import Newsticker from 'react-native-newsticker';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
} = React;

var NewstickerProject = React.createClass({
  getInitialState: function() {
    return {
      is_begin: false,
    };
  },
  render: function() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Newsticker Example</Text>
        <Newsticker
          style={styles.alignLeft}
          typeInterval={100}
          blinkInterval={500}
          start={this.state.is_begin}
          text={'This is a really awesome Newsticker !!'}
        />

      <TouchableOpacity
        style={styles.button}
        onPress={()=>{this.setState({is_begin: true})}}
        >
        <Text style={styles.buttonText}>Start Newsticker</Text>
      </TouchableOpacity>

      </View>
    );
  }
});

var styles = StyleSheet.create({
  alignLeft: {
    textAlign: 'left',
  },
  button: {
    height: 30,
    marginTop: 30,
    paddingTop: 6,
    paddingBottom: 6,
    borderRadius: 3,
    borderWidth: 1,
    backgroundColor: '#007AFF',
    borderColor: 'transparent',
  },
  buttonText: {
    color: '#fff',
    textAlign: 'center',
  },
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingHorizontal: 80,
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('NewstickerProject', () => NewstickerProject);
<commit_msg>update example<commit_after>/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

import Newsticker from 'react-native-newsticker';

var React = require('react-native');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
} = React;

var NewstickerProject = React.createClass({
  getInitialState: function() {
    return {
      is_begin: false,
    };
  },
  onFinish: function() {
    console.log('Newsticker Finished')
  },
  render: function() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Newsticker Example</Text>
        <Newsticker
          style={styles.alignLeft}
          typeInterval={100}
          blinkInterval={500}
          onFinish={this.onFinish.bind(this)}
          start={this.state.is_begin}
          text={'This is a really awesome Newsticker !!'}
        />

        <TouchableOpacity
          style={styles.button}
          onPress={()=>{this.setState({is_begin: !this.state.is_begin})}}
          >
          <Text style={styles.buttonText}>{this.state.is_begin ? 'Stop' : 'Start'} Newsticker</Text>
        </TouchableOpacity>

      </View>
    );
  }
});

var styles = StyleSheet.create({
  alignLeft: {
    textAlign: 'left',
  },
  button: {
    height: 30,
    marginTop: 30,
    paddingTop: 6,
    paddingBottom: 6,
    borderRadius: 3,
    borderWidth: 1,
    backgroundColor: '#007AFF',
    borderColor: 'transparent',
  },
  buttonText: {
    color: '#fff',
    textAlign: 'center',
  },
  container: {
    flex: 1,
    justifyContent: 'center',
    paddingHorizontal: 80,
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('NewstickerProject', () => NewstickerProject);
<|endoftext|>


<commit_before>'use strict';

// const _ = require('underscore');
// const Promise = require('bluebird');
const Firebase = require('firebase');

var dbRef = {};
dbRef.root = new Firebase('https://dazzling-heat-3394.firebaseio.com/');
// .then(function (ref) {
//   dbRef.imgTickets = ref;
//   return dbRef.root.child(ticketsInfo.ticketsPool);
// })
// .then(function (ref) {
//   dbRef.taskTicketsPool = ref;
//   return dbRef.root.child(ticketsInfo.ticketsReq);
// })
// .then(function (ref) {
//   dbRef.taskTicketsReq = ref;
//   return dbRef.root.child(ticketsInfo.ticketsRes);
// })
// .then(function (ref) {
//   dbRef.taskTicketsRes = ref;
//   loadScript('tasks/' + taskInfo.taskName + '.js', function () {
//     console.log('loaded task: ' + taskInfo.taskName);
//   });
// })
// .catch(function (err) {
//   console.log(err);
// });

// return dbRef.root.child('img_ref');

var taskData = {};
var taskInfo = {};
var ticketsInfo = {};

// helper
function isTicketInReqAndNotExpired (ticket) {
  for (var reqTicketUID in taskData.taskTicketsReq) {
    var reqTicket = taskData.taskTicketsReq[reqTicketUID];
    var poolTicket = taskData.taskTicketsPool[reqTicket[ticketsInfo.ticketsPool_uid]];
    console.log('isTicketInReqAndNotExpired', poolTicket, ticket);
    if (poolTicket && (poolTicket.uid === ticket.uid) && (!isReqTicketExpired(reqTicket))) return true;
  }
  return false;
}

// helper
function isTicketInRes (ticket) {
  for (var resTicketUID in taskData.taskTicketsRes) {
    var resTicket = taskData.taskTicketsRes[resTicketUID];
    var reqTicket = taskData.taskTicketsReq[resTicket[ticketsInfo.ticketsReq_uid]];
    var poolTicket = taskData.taskTicketsPool[reqTicket[ticketsInfo.ticketsPool_uid]];
    console.log('isTicketInRes', poolTicket, ticket);
    if (poolTicket && poolTicket.uid === ticket.uid) return true;
  }
  return false;
}

// helper
function isReqTicketExpired (reqTicket) {
  return (getNow() - reqTicket.timeSubmitted) > reqTicket.taskDuration; // TODO create these keys, normalize taskDuration and reference it back from jobs bucket
}

// helper
function remainsOpen (poolTicket) {
  console.log('remainsOpen?');
  if (isTicketInRes(poolTicket) || (isTicketInReqAndNotExpired(poolTicket))) return false;
  else return true;
}

// API
function getTickets (taskName, maxCount) {
  taskInfo.taskName = taskName;
  ticketsInfo.ticketsPool = taskInfo.taskName + '_tickets_pool',
  ticketsInfo.ticketsReq = taskInfo.taskName + '_tickets_req',
  ticketsInfo.ticketsRes = taskInfo.taskName + '_tickets_res',
  ticketsInfo.ticketsPool_uid = ticketsInfo.ticketsPool + '_uid';
  ticketsInfo.ticketsReq_uid = ticketsInfo.ticketsReq + '_uid';

  return new Promise(function(resolve, reject) {
    dbRef.root.once('value', wholeDbSnapshot => {
      taskData.all = wholeDbSnapshot.val();
      taskData.imgTickets = taskData.all.img_ref;
      taskData.taskTicketsPool = taskData.all[ticketsInfo.ticketsPool];
      taskData.taskTicketsReq = taskData.all[ticketsInfo.ticketsReq] || {};
      taskData.taskTicketsRes = taskData.all[ticketsInfo.ticketsRes] || {};
      resolve()
    }, err => { reject(err); });
  })
  .then(() => {
    var ticketsToServe = [];
    for (var poolTicketUID in taskData.taskTicketsPool) {
      var poolTicket = taskData.taskTicketsPool[poolTicketUID];
      if (ticketsToServe.length === maxCount) break;
      if (remainsOpen(poolTicket)) {
        dbRef.taskTicketsReq = dbRef.root.child(ticketsInfo.ticketsReq);
        console.log('found open ticket');
        ticketsToServe.push(dbRef.taskTicketsReq.push(poolTicket)
        .then(function (pushedReqTicketRef) {
          console.log('pushedReqTicketRef', pushedReqTicketRef);
          this[ticketsInfo.ticketsPool_uid] = this.uid;
          this.uid = pushedReqTicketRef.path.u[1];
          this.timeSubmitted = getNow();
          this.taskDuration = minToMs(taskInfo.taskDuration); // TODO add this via reference to job entry?
          delete this.img_ref_uid;

          var pushObj = {};
          pushObj[ticketsInfo.ticketsPool_uid] = this[ticketsInfo.ticketsPool_uid];
          pushObj.uid = this.uid;
          pushObj.timeSubmitted = this.timeSubmitted;
          pushObj.taskDuration = this.taskDuration;
          pushedReqTicketRef.set(pushObj);

          return this;
        }.bind(_.deepClone(poolTicket)))
        .catch(function (err) {
          throw err;
        }));
      }
    }
    taskInfo.ticketsReceived = ticketsToServe.length;
    console.log('ticketsToServe', ticketsToServe);
    return Promise.all(ticketsToServe);
  })
  .catch(err => {
    sendErr(err);
  });
}

// helper
function getImage (reqTicket) {
  var ticketsPoolKey = reqTicket[ticketsInfo.ticketsPool_uid];
  var ticketsPoolTask = taskData.taskTicketsPool[ticketsPoolKey];
  var gottenImg = taskData.imgTickets[ticketsPoolTask.img_ref_uid];
  return gottenImg;
}

// helper
function pushAndAddUID (targetRef, sourceObj) {
  var item = sourceObj;
  targetRef.push(item)
  .then(function (tempRef) {
    item.uid = tempRef.path.u[1];
    return tempRef.update({uid: item.uid});
  })
  .then(function () {
    console.log('item at ' + targetRef.path.u[0] + '/' + item.uid + 'updated');
  })
  .catch(function (err) { throw (err); });
}

function sendErr (err) {
  console.log(err);
  return err;
}

function getNow() {
  return new Date().getTime();
}

module.exports = {
  getTickets: getTickets,
}
<commit_msg>Refactor for Fb queries but scrapping bc changing schema design<commit_after>'use strict'

const _ = require('../scripts/helpers/utils.js');
const Promise = require('bluebird');
const Firebase = require('firebase');

var dbRef = {};
dbRef.root = new Firebase('https://dazzling-heat-3394.firebaseio.com/');
// .then(function (ref) {
//   dbRef.imgTickets = ref;
//   return dbRef.root.child(ticketsInfo.ticketsPool);
// })
// .then(function (ref) {
//   dbRef.taskTicketsPool = ref;
//   return dbRef.root.child(ticketsInfo.ticketsReq);
// })
// .then(function (ref) {
//   dbRef.taskTicketsReq = ref;
//   return dbRef.root.child(ticketsInfo.ticketsRes);
// })
// .then(function (ref) {
//   dbRef.taskTicketsRes = ref;
//   loadScript('tasks/' + taskInfo.taskName + '.js', function () {
//     console.log('loaded task: ' + taskInfo.taskName);
//   });
// })
// .catch(function (err) {
//   console.log(err);
// });

// return dbRef.root.child('img_ref');

var taskData = {};
var taskInfo = {};
var ticketsInfo = {};

getOpenTickets('task_img_verification_trinary', 30, 15)
.then(tickets => {
  console.log('GOT TICKETS');
  console.log(tickets);
})
.catch(err => {
  console.log('err');
  console.log(err);
});

// helper
// if a ticket is in req and not expired, it's considered actively in process, so don't serve it
function isInReqAndNotExpired (poolTicketToMatch) {
  let fbQuery = dbRef.taskTicketsReq.orderByChild(ticketsInfo.ticketsPool_uid).equalTo(poolTicketToMatch.uid);
  return new Promise((resolve, reject) => {
    fbQuery.once('value', matchedReqTickets => {
      matchedReqTickets = matchedReqTickets.val();

      for (var key in matchedReqTickets) {
        let matchedReqTicket = matchedReqTickets[key];
        if (isNotExpired(matchedReqTicket)) {
          // console.log('in req and not expired!')
          return resolve(true);
        }
      }
      // console.log('not in req or expired!');
      resolve(false);
    });
  });
}

// helper
function isInRes (poolTicketToMatch) {
  let fbQuery = dbRef.taskTicketsRes.orderByChild(ticketsInfo.ticketsPool_uid).equalTo(poolTicketToMatch.uid);
  return new Promise((resolve, reject) => {
    fbQuery.once('value', matchedResTickets => {
      matchedResTickets = matchedResTickets.val();
      console.log('matchedResTickets', matchedResTickets);
      matchedResTickets ? resolve(true) : resolve(false);
    });
  });
}

// helper
function isNotExpired (reqTicket) {
  return (_.getNow() - reqTicket.timeSubmitted) > reqTicket.taskDuration; // TODO create these keys, normalize taskDuration and reference it back from jobs bucket
}

// helper
function isOpen (poolTicket) {
  // console.log('isOpen?');
  return Promise.all([isInRes(poolTicket), isInReqAndNotExpired(poolTicket)])
  .then(resultsBoolArr => {
    return resultsBoolArr.reduce((prevBool, currBool, i, o) => {
      return prevBool && currBool;
    }, true);
  })
}

// API
function getOpenTickets (taskName, maxCount, taskDuration) { // TODO can remove taskDuration from server, client, and db here once refactored probably
  taskInfo.taskName = taskName;
  taskInfo.maxTicketsToGet = Number(maxCount);
  taskInfo.taskDuration = Number(taskDuration);

  ticketsInfo.ticketsPool = taskInfo.taskName + '_tickets_pool',
  ticketsInfo.ticketsReq = taskInfo.taskName + '_tickets_req',
  ticketsInfo.ticketsRes = taskInfo.taskName + '_tickets_res',
  ticketsInfo.ticketsPool_uid = ticketsInfo.ticketsPool + '_uid';
  ticketsInfo.ticketsReq_uid = ticketsInfo.ticketsReq + '_uid';

  dbRef.imgRef = dbRef.root.child('img_ref');
  dbRef.taskTicketsPool = dbRef.root.child(ticketsInfo.ticketsPool);
  dbRef.taskTicketsReq = dbRef.root.child(ticketsInfo.ticketsReq);
  dbRef.taskTicketsRes = dbRef.root.child(ticketsInfo.ticketsRes);

  // console.log(taskInfo)
  // console.log(ticketsInfo)

  return new Promise(function(resolve, reject) {
    // get unexpired tickets

    dbRef.root.child(ticketsInfo.ticketsPool)

    dbRef.root.once('value', wholeDbSnapshot => {
      taskData.all = wholeDbSnapshot.val();
      taskData.imgTickets = taskData.all.img_ref;
      taskData.taskTicketsPool = taskData.all[ticketsInfo.ticketsPool];
      taskData.taskTicketsReq = taskData.all[ticketsInfo.ticketsReq] || {};
      taskData.taskTicketsRes = taskData.all[ticketsInfo.ticketsRes] || {};

      _.each(taskData, (item, key) => {
        console.log(key, Object.keys(item).length);
      });

      resolve(taskData.taskTicketsPool)
    }, err => { reject(err); });
  })
  .then(() => {
    var ticketsToServe = [];
    for (var poolTicketUID in taskData.taskTicketsPool) {
      var poolTicket = taskData.taskTicketsPool[poolTicketUID];
      if (ticketsToServe.length === maxCount) break;
      isOpen (poolTicket)
      .then(result => {
        // console.log('found open ticket');
        ticketsToServe.push(dbRef.taskTicketsReq.push(poolTicket)
        .then(function (pushedReqTicketRef) {
          // console.log('pushedReqTicketRef', pushedReqTicketRef);
          this[ticketsInfo.ticketsPool_uid] = this.uid;
          this.uid = pushedReqTicketRef.path.u[1];
          this.timeSubmitted = _.getNow();
          // this.taskDuration = _.minToMs(taskInfo.taskDuration); // TODO add this via reference to job entry?
          delete this.img_ref_uid;

          var pushObj = {};
          pushObj[ticketsInfo.ticketsPool_uid] = this[ticketsInfo.ticketsPool_uid];
          pushObj.uid = this.uid;
          pushObj.timeSubmitted = this.timeSubmitted;
          pushObj.taskDuration = this.taskDuration;
          // console.log('pushObj', pushObj);
          pushedReqTicketRef.set(pushObj);

          return this;
        }.bind(_.deepClone(poolTicket)))
        .catch(function (err) {
          throw err;
        }));

      });
    }
    taskInfo.ticketsReceived = ticketsToServe.length;
    console.log('ticketsToServe.length', ticketsToServe.length);
    return Promise.all(ticketsToServe);
  })
  .catch(err => {
    sendErr(err);
  });
}

// helper
function getImage (reqTicket) {
  var ticketsPoolKey = reqTicket[ticketsInfo.ticketsPool_uid];
  var ticketsPoolTask = taskData.taskTicketsPool[ticketsPoolKey];
  var gottenImg = taskData.imgTickets[ticketsPoolTask.img_ref_uid];
  return gottenImg;
}

// helper
function pushAndAddUID (targetRef, sourceObj) {
  var item = sourceObj;
  targetRef.push(item)
  .then(function (tempRef) {
    item.uid = tempRef.path.u[1];
    return tempRef.update({uid: item.uid});
  })
  .then(function () {
    // console.log('item at ' + targetRef.path.u[0] + '/' + item.uid + 'updated');
  })
  .catch(function (err) { throw (err); });
}

function sendErr (err) {
  console.log(err);
  return err;
}

module.exports = {
  getOpenTickets: getOpenTickets,
}
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.View.extend({
  /**
   * run when the view is loaded to enable the fullpage.js abilities
   */
  initFullpage: function () {
    "use strict";
    var selector = this.get('fullpageSelector'), $element;
    Ember.Logger.debug('fullpage view -> initFullpage!');
    if (Ember.isNone(selector)) {
      $element = this.$();
    } else {
      $element = this.$(selector);
    }
    $element.fullpage(this.get('fullpageOptions'));
    this.customInitilization();
  }.on('didInsertElement'),
  removeFullpage: function () {
    "use strict";
    Ember.Logger.debug('fullpage view -> removeFullpage!');

    /*
     * NOTE: the following section is to be checked when fullpage.js is updated!
     * Strongly related to how fullpage.js setup its listener
     */
    //remove the side navigation is any
    //Ember.$('#fp-nav').remove();
    ////remove the global fullpage.js scrolling controls
    //Ember.$.fn.fullpage.setAllowScrolling(false);
    //Ember.$.fn.fullpage.setKeyboardScrolling(false);
    ////remove the global listener from fullpage.js
    //Ember.$(window).off('hashchange');
    //Ember.$(document).off('click', '#fullPage-nav a');
    //Ember.$('.section').off('click', '.toSlide');
    //Ember.$(document).off('click', '.fullPage-slidesNav a');

    Ember.$.fn.fullpage.destroy('all');

    this.customRemoval();
  }.on('willDestroyElement'),
  /**
   * contains the options that should be passed on to fullpage.js when initializing it.
   */
  fullpageOptions: {},
  /**
   * contains the selector that should host the fullpage initialization.
   */
  fullpageSelector: null,
  /**
   * function to override in case extra customization is required when loading initializing the view
   */
  customInitilization: function () {},
  /**
   * function to override in case extra customization is required when removing the view
   */
  customRemoval: function () {}
});
<commit_msg>somehow the removal wasn't working<commit_after>import Ember from 'ember';

export default Ember.View.extend({
  /**
   * run when the view is loaded to enable the fullpage.js abilities
   */
  initFullpage: function () {
    "use strict";
    var selector = this.get('fullpageSelector'), $element;
    Ember.Logger.debug('fullpage view -> initFullpage!');
    if (Ember.isNone(selector)) {
      $element = this.$();
    } else {
      $element = this.$(selector);
    }
    $element.fullpage(this.get('fullpageOptions'));
    this.customInitilization();
  }.on('didInsertElement'),
  removeFullpage: function () {
    "use strict";
    Ember.Logger.debug('fullpage view -> removeFullpage!');

    /*
     * NOTE: the following section is to be checked when fullpage.js is updated!
     * Strongly related to how fullpage.js setup its listener
     */
    //remove the side navigation is any
    //Ember.$('#fp-nav').remove();
    ////remove the global fullpage.js scrolling controls
    //Ember.$.fn.fullpage.setAllowScrolling(false);
    //Ember.$.fn.fullpage.setKeyboardScrolling(false);
    ////remove the global listener from fullpage.js
    //Ember.$(window).off('hashchange');
    //Ember.$(document).off('click', '#fullPage-nav a');
    //Ember.$('.section').off('click', '.toSlide');
    //Ember.$(document).off('click', '.fullPage-slidesNav a');

    // Ember.$.fn.fullpage.destroy('all');
    Ember.$.fn.fullpage.destroy();

    this.customRemoval();
  }.on('willDestroyElement'),
  /**
   * contains the options that should be passed on to fullpage.js when initializing it.
   */
  fullpageOptions: {},
  /**
   * contains the selector that should host the fullpage initialization.
   */
  fullpageSelector: null,
  /**
   * function to override in case extra customization is required when loading initializing the view
   */
  customInitilization: function () {},
  /**
   * function to override in case extra customization is required when removing the view
   */
  customRemoval: function () {}
});
<|endoftext|>