<commit_before>elation.require([ ], function() {
  elation.extend("engine.systems.sound", function(args) {
    elation.implement(this, elation.engine.systems.system);

    this.enabled = true;
    this.canPlaySound = false;
    this.volume = 100;

    Object.defineProperty(this, 'volume', {get: function() { return this.reallistener.getMasterVolume(); }, set: function(v) { this.reallistener.setMasterVolume(v); }});

    this.system_attach = function(ev) {
      console.log('INIT: sound');
    }
    this.engine_stop = function(ev) {
      console.log('SHUTDOWN: sound');
    }
    this.engine_frame = function(ev) {
    }
    this.setActiveListener = function(listener) {
      this.listener = listener;
      if (this.reallistener) {
        listener.add(this.reallistener);
      }
    }
    this.getActiveListener = function() {
      return this.listener;
    }
    this.getRealListener = function() {
      // Ideally, we'd show some UI element that indicates that this page will start playing sound when focused, and if we want to get
      // fancy, volume for the whole sound system should fade in from 0 to 1 over 3-5 seconds to give users a chance to adjust system volume
      // if needed
      if (!this.reallistener) {
        this.reallistener = new THREE.AudioListener();
        console.log('[sound] Creating audio context', this.reallistener);
        if (this.listener) {
          this.listener.add(this.reallistener);
        }
      }
      return this.reallistener;
    }
    this.mute = function(mutestate) {
      this.enabled = (typeof mutestate == 'undefined' ? false : !mutestate);
      if (this.enabled) {
        this.reallistener.context.resume();
      } else {
        this.reallistener.context.suspend();
      }
    }
    this.toggleMute = function() {
      this.mute(this.enabled);
    }
    this.setVolume = function(v) {
      this.reallistener.setMasterVolume(v / 100);
    }
    this.enableSound = function() {
      if (!this.canPlaySound) {
        this.canPlaySound = true;
        elation.events.fire({type: 'sound_enabled', element: this});
      }
    }
  });
  elation.component.add('engine.systems.sound.config', function() {
    this.init = function() {
        this.args.orientation = 'vertical'
        elation.engine.systems.render.config.extendclass.init.call(this);

        this.client = this.args.client;
        this.engine = this.client.engine;
        this.view = this.client.view;
        this.soundsystem = this.engine.systems.sound;

        var soundpanel = elation.ui.panel({
          orientation: 'vertical',
          classname: 'engine_config_section',
          append: this
        });

        // Sound Settings
        var soundlabel = elation.ui.labeldivider({
          append: soundpanel,
          label: '3D Sound Settings'
        });
        var mute = elation.ui.toggle({
          label: 'Mute',
          append: soundpanel,
          events: { toggle: elation.bind(this.soundsystem, this.soundsystem.toggleMute) }
        });
        var volume = elation.ui.slider({
          append: soundpanel,
          min: 1,
          max: 100,
          snap: 1,
          label: 'Volume',
          handles: [
            {
              name: 'handle_one_volume',
              value: this.soundsystem.volume,
              bindvar: [this.soundsystem, 'volume']
            }
          ],
          //events: { ui_slider_change: elation.bind(this.soundsystem, function() { this.setVolume(this.volume); }) }
        });

      // Capture Settings
/*
      var capturelabel = elation.ui.labeldivider({
        append: capturepanel,
        label: 'Capture Settings'
      });
      var codec = elation.ui.select({
        append: capturepanel,
        label: 'Codec',
        items: ['h264','gif']
      });
      var fps = elation.ui.select({
        append: capturepanel,
        label: 'FPS',
        items: [5,10,25,30,45,60]
      });
*/
    }
  }, elation.ui.panel);
});
<commit_msg>Added soundsystem.getRealListenerAsync() and getOutputChannel()<commit_after>elation.require([ ], function() {
  elation.extend("engine.systems.sound", function(args) {
    elation.implement(this, elation.engine.systems.system);

    this.enabled = true;
    this.canPlaySound = false;
    this.volume = 100;

    this.channels = {};

    Object.defineProperty(this, 'volume', {get: function() { return this.reallistener.getMasterVolume(); }, set: function(v) { this.reallistener.setMasterVolume(v); }});

    this.system_attach = function(ev) {
      console.log('INIT: sound');
    }
    this.engine_stop = function(ev) {
      console.log('SHUTDOWN: sound');
    }
    this.engine_frame = function(ev) {
    }
    this.setActiveListener = function(listener) {
      this.listener = listener;
      if (this.reallistener) {
        listener.add(this.reallistener);
      }
    }
    this.getActiveListener = function() {
      return this.listener;
    }
    this.getRealListener = function() {
      // Ideally, we'd show some UI element that indicates that this page will start playing sound when focused, and if we want to get
      // fancy, volume for the whole sound system should fade in from 0 to 1 over 3-5 seconds to give users a chance to adjust system volume
      // if needed
      if (!this.reallistener) {
        this.reallistener = new THREE.AudioListener();
        console.log('[sound] Creating audio context', this.reallistener);
        if (this.listener) {
          this.listener.add(this.reallistener);
        }
      }
      return this.reallistener;
    }
    this.getRealListenerAsync = async function() {
      return new Promise(resolve => {
        if (this.reallistener) {
          resolve(this.reallistener);
        } else {
          elation.events.add(this, 'sound_enabled', ev => {
            resolve(this.getRealListener());
          });
        }
      });
    }
    this.getOutputChannel = async function(channelname='main') {
      if (this.channels[channelname]) {
        return this.channels[channelname];
      }

      let listener = await this.getRealListenerAsync();

      let channel = listener.context.createGain();
      channel.connect(listener.getInput());

      this.channels[channelname] = channel;

      return channel;
    }
    this.mute = function(mutestate) {
      this.enabled = (typeof mutestate == 'undefined' ? false : !mutestate);
      if (this.enabled) {
        this.reallistener.context.resume();
      } else {
        this.reallistener.context.suspend();
      }
    }
    this.toggleMute = function() {
      this.mute(this.enabled);
    }
    this.setVolume = function(v) {
      this.reallistener.setMasterVolume(v / 100);
    }
    this.enableSound = function() {
      if (!this.canPlaySound) {
        this.canPlaySound = true;
        elation.events.fire({type: 'sound_enabled', element: this});
      }
    }
  });
  elation.component.add('engine.systems.sound.config', function() {
    this.init = function() {
        this.args.orientation = 'vertical'
        elation.engine.systems.render.config.extendclass.init.call(this);

        this.client = this.args.client;
        this.engine = this.client.engine;
        this.view = this.client.view;
        this.soundsystem = this.engine.systems.sound;

        var soundpanel = elation.ui.panel({
          orientation: 'vertical',
          classname: 'engine_config_section',
          append: this
        });

        // Sound Settings
        var soundlabel = elation.ui.labeldivider({
          append: soundpanel,
          label: '3D Sound Settings'
        });
        var mute = elation.ui.toggle({
          label: 'Mute',
          append: soundpanel,
          events: { toggle: elation.bind(this.soundsystem, this.soundsystem.toggleMute) }
        });
        var volume = elation.ui.slider({
          append: soundpanel,
          min: 1,
          max: 100,
          snap: 1,
          label: 'Volume',
          handles: [
            {
              name: 'handle_one_volume',
              value: this.soundsystem.volume,
              bindvar: [this.soundsystem, 'volume']
            }
          ],
          //events: { ui_slider_change: elation.bind(this.soundsystem, function() { this.setVolume(this.volume); }) }
        });

      // Capture Settings
/*
      var capturelabel = elation.ui.labeldivider({
        append: capturepanel,
        label: 'Capture Settings'
      });
      var codec = elation.ui.select({
        append: capturepanel,
        label: 'Codec',
        items: ['h264','gif']
      });
      var fps = elation.ui.select({
        append: capturepanel,
        label: 'FPS',
        items: [5,10,25,30,45,60]
      });
*/
    }
  }, elation.ui.panel);
});
<|endoftext|>


<commit_before>const splitByComma = require('../../vendor/splitByComma');

function propertyGroup(that, element, parent) {
  const tab = new Array((element.depth * that.tabSize) + 1).join(that.tabChar);

  let value = splitByComma(element.value);
  let padding;

  if (element.align) {
    value = value
      .map(function (a, i) {
        let align = new Array(element.align + 4).join(' ');
        return i === 0 ? a : tab + align + a;
      })
      .join(',\n');

    padding = new Array(element.align - element.name.length + 2).join(' ');

    return `${element.name} ${padding} : ${value};`;
  }

  return element.name + ': ' + element.value + ';';
}

module.exports = propertyGroup;
<commit_msg>Fixed extra space in 'padding'<commit_after>const splitByComma = require('../../vendor/splitByComma');

function propertyGroup(that, element, parent) {
  const tab = new Array((element.depth * that.tabSize) + 1).join(that.tabChar);

  let value = splitByComma(element.value);
  let padding;

  if (element.align) {
    value = value
      .map(function (a, i) {
        let align = new Array(element.align + 4).join(' ');
        return i === 0 ? a : tab + align + a;
      })
      .join(',\n');

    padding = new Array(element.align - element.name.length + 2).join(' ');

    return `${element.name}${padding}: ${value};`;
  }

  return element.name + ': ' + element.value + ';';
}

module.exports = propertyGroup;
<|endoftext|>


<commit_before>var AABB = function ()
{

	this.center = vec3.create();
	this.extents = vec3.create();

};

AABB.extend(
{

	fromVertices: function (vertices, stride)
	{
		if (stride == undefined)
		{
			stride = 3;
		}

		var min = vec3.fromValues(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
		var max = vec3.fromValues(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE);

		for(var i = 0; i < vertices.length / stride; i++)
		{
			var position = vec3.fromValues
			(
				vertices[i * stride + 0],
				vertices[i * stride + 1],
				vertices[i * stride + 2]
			);

			if (position[0] < min[0])
			{
				min[0] = position[0];
			}

			if (position[0] > max[0])
			{
				max[0] = position[0];
			}

			if (position[1] < min[1])
			{
				min[1] = position[1];
			}

			if (position[1] > max[1])
			{
				max[1] = position[1];
			}

			if (position[2] < min[2])
			{
				min[2] = position[2];
			}

			if (position[2] > max[2])
			{
				max[2] = position[2];
			}
		}

		var diff = vec3.create();
		vec3.subtract(diff, max, min);
		vec3.scale(diff, diff, 0.5);
		var center = vec3.create();
		vec3.add(center, min, diff);
		var extents = diff;

		var aabb = new AABB();
		aabb.center = center;
		aabb.extents = extents;
		return aabb;
	},

	transform: function (aabb, matrix)
	{
		var vertices = [];

		var pushVertex = function (v0, v1, v2)
		{
			vertices.push(v0);
			vertices.push(v1);
			vertices.push(v2);
		};

		var topLeft = vec3.create();
		vec3.subtract(topLeft, aabb.center, aabb.extents);

		var bottomRight = vec3.create();
		vec3.add(bottomRight, aabb.center, aabb.extents);

		pushVertex(topLeft[0], topLeft[1], topLeft[2]);
		pushVertex(topLeft[0], bottomRight[1], topLeft[2]);
		pushVertex(bottomRight[0], topLeft[1], topLeft[2]);
		pushVertex(bottomRight[0], bottomRight[1], topLeft[2]);

		pushVertex(topLeft[0], topLeft[1], bottomRight[2]);
		pushVertex(topLeft[0], bottomRight[1], bottomRight[2]);
		pushVertex(bottomRight[0], topLeft[1], bottomRight[2]);
		pushVertex(bottomRight[0], bottomRight[1], bottomRight[2]);

		return AABB.fromVertices(vertices, 3);
	},

});

AABB.prototype.extend(
{

	intersectRay: function (ray)
	{
		//acquire bbox min and max bounds
		var vmin = vec3.create();
		var vmax = vec3.create();
		vec3.subtract(vmin, this.center, this.extents);
		vec3.add(vmax, this.center, this.extents);

		var T_nearDist = vec3.create();
		var T_farDist = vec3.create(); // vectors to hold the T-values for every direction
    	var t_near = Number.MIN_VALUE; // limits as defined;
    	var t_far = Number.MAX_VALUE;

		for (var i = 0; i < 3; i++)
		{
		//we test slabs in every direction
    	    if (ray.direction[i] == 0)
        	{ // ray parallel to planes in this direction
            	if ((ray.origin[i] < vmin[i]) || (ray.origin[i] > vmax[i]))
            	{
            	    return { hit:false, nearDistance: 0.0}; // parallel AND outside box : no intersection possible
           	 	}
        	}
        	else
        	{ // ray not parallel to planes in this direction
            	T_nearDist[i] = (vmin[i] - ray.origin[i]) / ray.direction[i];
            	T_farDist[i] = (vmax[i] - ray.origin[i]) / ray.direction[i];

  	          if(T_nearDist[i] > T_farDist[i])
  	          {
  	          	var temp = vec3.clone(T_farDist);
                vec3.copy(T_farDist, T_nearDist);
                vec3.copy(T_nearDist, temp);
  	          } // we want T_nearDist to hold values for intersection with near plane
            	if (T_nearDist[i] > t_near)
            	{
              		t_near = T_nearDist[i];
           		}
            	if (T_farDist[i] < t_far)
            	{
                	t_far = T_farDist[i];
            	}
            	if((t_near > t_far) || (t_far < 0) )
            	{
                	return {hit:false, nearDistance: 0.0};
            	}
       		 }
   		}
   		//debugger;
		return {hit: true, nearDistance: vec3.length(T_nearDist)};
	},

	// expands the AABB to fit another AABB
	expandToFit: function (aabb)
	{
		var thisTopLeft = vec3.create();
		vec3.subtract(this.center, this.extents);

		var thisBottomRight = vec3.create();
		vec3.add(this.center, this.extents);

		var otherTopLeft = vec3.create();
		vec3.subtract(aabb.center, aabb.extents);

		var otherBottomRight = vec3.create();
		vec3.add(aabb.center, aabb.extents);

		var max = function (x, y)
		{
			return vec3.fromValues(Math.max(x[0], y[0]), Math.max(x[1], y[1]), Math.max(x[2], y[2]));
		}

		var min = function (x, y)
		{
			return vec3.fromValues(Math.min(x[0], y[0]), Math.min(x[1], y[1]), Math.min(x[2], y[2]));
		}

		var resultTopLeft = min(thisTopLeft, otherTopLeft);
		var resultBottomRight = max(thisBottomRight, otherBottomRight);

		vec3.subtract(this.extents, resultBottomRight, resultTopLeft);
		vec3.scale(this.extents, this.extents, 0.5);

		vec3.add(this.center, resultTopLeft, this.extents);
	},

});<commit_msg>reformatted AABB.intersectRay<commit_after>var AABB = function ()
{

	this.center = vec3.create();
	this.extents = vec3.create();

};

AABB.extend(
{

	fromVertices: function (vertices, stride)
	{
		if (stride == undefined)
		{
			stride = 3;
		}

		var min = vec3.fromValues(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
		var max = vec3.fromValues(Number.MIN_VALUE, Number.MIN_VALUE, Number.MIN_VALUE);

		for(var i = 0; i < vertices.length / stride; i++)
		{
			var position = vec3.fromValues
			(
				vertices[i * stride + 0],
				vertices[i * stride + 1],
				vertices[i * stride + 2]
			);

			if (position[0] < min[0])
			{
				min[0] = position[0];
			}

			if (position[0] > max[0])
			{
				max[0] = position[0];
			}

			if (position[1] < min[1])
			{
				min[1] = position[1];
			}

			if (position[1] > max[1])
			{
				max[1] = position[1];
			}

			if (position[2] < min[2])
			{
				min[2] = position[2];
			}

			if (position[2] > max[2])
			{
				max[2] = position[2];
			}
		}

		var diff = vec3.create();
		vec3.subtract(diff, max, min);
		vec3.scale(diff, diff, 0.5);
		var center = vec3.create();
		vec3.add(center, min, diff);
		var extents = diff;

		var aabb = new AABB();
		aabb.center = center;
		aabb.extents = extents;
		return aabb;
	},

	transform: function (aabb, matrix)
	{
		var vertices = [];

		var pushVertex = function (v0, v1, v2)
		{
			vertices.push(v0);
			vertices.push(v1);
			vertices.push(v2);
		};

		var topLeft = vec3.create();
		vec3.subtract(topLeft, aabb.center, aabb.extents);

		var bottomRight = vec3.create();
		vec3.add(bottomRight, aabb.center, aabb.extents);

		pushVertex(topLeft[0], topLeft[1], topLeft[2]);
		pushVertex(topLeft[0], bottomRight[1], topLeft[2]);
		pushVertex(bottomRight[0], topLeft[1], topLeft[2]);
		pushVertex(bottomRight[0], bottomRight[1], topLeft[2]);

		pushVertex(topLeft[0], topLeft[1], bottomRight[2]);
		pushVertex(topLeft[0], bottomRight[1], bottomRight[2]);
		pushVertex(bottomRight[0], topLeft[1], bottomRight[2]);
		pushVertex(bottomRight[0], bottomRight[1], bottomRight[2]);

		return AABB.fromVertices(vertices, 3);
	},

});

AABB.prototype.extend(
{

	intersectRay: function (ray)
	{
		//acquire bbox min and max bounds
		var vmin = vec3.create();
		var vmax = vec3.create();

		vec3.subtract(vmin, this.center, this.extents);
		vec3.add(vmax, this.center, this.extents);

		var T_nearDist = vec3.create();
		var T_farDist = vec3.create(); // vectors to hold the T-values for every direction
		var t_near = Number.MIN_VALUE; // limits as defined;
		var t_far = Number.MAX_VALUE;

		for (var i = 0; i < 3; i++)
		{
			//we test slabs in every direction
			if (ray.direction[i] == 0.0)
			{
				// ray parallel to planes in this direction
				if ((ray.origin[i] < vmin[i]) || (ray.origin[i] > vmax[i]))
				{
					return { hit: false, nearDistance: 0.0 }; // parallel AND outside box : no intersection possible
				}
			}
			else
			{
				// ray not parallel to planes in this direction
				T_nearDist[i] = (vmin[i] - ray.origin[i]) / ray.direction[i];
				T_farDist[i] = (vmax[i] - ray.origin[i]) / ray.direction[i];

				if(T_nearDist[i] > T_farDist[i])
				{
					var temp = vec3.clone(T_farDist);
					vec3.copy(T_farDist, T_nearDist);
					vec3.copy(T_nearDist, temp);
				}

				// we want T_nearDist to hold values for intersection with near plane
				if (T_nearDist[i] > t_near)
				{
					t_near = T_nearDist[i];
				}

				if (T_farDist[i] < t_far)
				{
					t_far = T_farDist[i];
				}

				if ((t_near > t_far) || (t_far < 0))
				{
					return { hit: false, nearDistance: 0.0 };
				}
			}
		}

		return { hit: true, nearDistance: vec3.length(T_nearDist) };
	},

	// expands the AABB to fit another AABB
	expandToFit: function (aabb)
	{
		var thisTopLeft = vec3.create();
		vec3.subtract(this.center, this.extents);

		var thisBottomRight = vec3.create();
		vec3.add(this.center, this.extents);

		var otherTopLeft = vec3.create();
		vec3.subtract(aabb.center, aabb.extents);

		var otherBottomRight = vec3.create();
		vec3.add(aabb.center, aabb.extents);

		var max = function (x, y)
		{
			return vec3.fromValues(Math.max(x[0], y[0]), Math.max(x[1], y[1]), Math.max(x[2], y[2]));
		}

		var min = function (x, y)
		{
			return vec3.fromValues(Math.min(x[0], y[0]), Math.min(x[1], y[1]), Math.min(x[2], y[2]));
		}

		var resultTopLeft = min(thisTopLeft, otherTopLeft);
		var resultBottomRight = max(thisBottomRight, otherBottomRight);

		vec3.subtract(this.extents, resultBottomRight, resultTopLeft);
		vec3.scale(this.extents, this.extents, 0.5);

		vec3.add(this.center, resultTopLeft, this.extents);
	},

});<|endoftext|>


<commit_before>var shanhaijing = shanhaijing || { 'settings': {} };

(function($) {

shanhaijing.url = function(path) {
    return shanhaijing.settings.base_url + '/' + path;
};

})(jQuery);
<commit_msg>Form sumbit button loading state.<commit_after>var shanhaijing = shanhaijing || { 'settings': {} };

(function($) {

shanhaijing.url = function(path) {
    return shanhaijing.settings.base_url + '/' + path;
};

$(function() {

    var forms = $('form');
    if (forms.length > 0) {
        forms.submit(function(event) {
            var $this = $(this);
            if ($this.attr('data-validate') == 'parsley' && !$this.parsley('isValid')) {
                return;
            }
            $this.find('submit, button[type=submit]').button('loading');
        });
    }

});

})(jQuery);
<|endoftext|>


<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

requirejs.config({
    baseUrl: '/vendor',
    paths: {
        jquery: 'AdminLTE/plugins/jQuery/jQuery-2.1.4.min',
        bootstrap: 'bootstrap/dist/js/bootstrap.min',
        smoothscroll: 'smooth-scroll/dist/js/smooth-scroll.min',
        app: '/js/app'
    },
    shim: {
        bootstrap: {
            deps: ['jquery']
        }
    }
});

define(['smoothscroll', 'jquery', 'bootstrap'], function (smoothScroll) {
    $(function () {

        $('.wrapper').fadeIn('slow');
        $("[data-spy='scroll']").scrollspy();

        require(['app/pages/site/site'], function (SiteModule) {

            SiteModule.init();

            /**
             * Arranjar uma solução decente algum dia
             * Hack para o smoothscroll
             */
            var numberOfAjaxCallsAtLoad = 1;
            $(document).ajaxStop(function () {
                numberOfAjaxCallsAtLoad--;
                if (numberOfAjaxCallsAtLoad === 0) {
                    smoothScroll.init();
                }
            });
        });
    });
});<commit_msg>Correção no spyscroll para retornar à sessão anterior, ao recarregar  a página, sem necessidade de clicar no menu.<commit_after>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

requirejs.config({
    baseUrl: '/vendor',
    paths: {
        jquery: 'AdminLTE/plugins/jQuery/jQuery-2.1.4.min',
        bootstrap: 'bootstrap/dist/js/bootstrap.min',
        smoothscroll: 'smooth-scroll/dist/js/smooth-scroll.min',
        app: '/js/app'
    },
    shim: {
        bootstrap: {
            deps: ['jquery']
        }
    }
});

define(['smoothscroll', 'jquery', 'bootstrap'], function (smoothScroll) {
    $(function () {

        $('.wrapper').fadeIn('slow');
        $("body").scrollspy();

        /**
         * Salva a sessão que o usuário passou,
         * caso ele recarregue o site a última sessão visitada será exibida
         */
        $("body").on('activate.bs.scrollspy', function (e) {
            history.replaceState({}, "", $("a[href^='#']", e.target).attr("href"));
        });

        require(['app/pages/site/site'], function (SiteModule) {

            SiteModule.init();

            /**
             * Arranjar uma solução decente algum dia
             * Hack para o smoothscroll
             */
            var numberOfAjaxCallsAtLoad = 1;
            $(document).ajaxStop(function () {
                numberOfAjaxCallsAtLoad--;
                if (numberOfAjaxCallsAtLoad === 0) {
                    smoothScroll.init();
                }
            });
        });
    });
});<|endoftext|>


<commit_before>var pageTitleElement = document.getElementById("page-title");
// Menyeleksi DOM berdasarkan Id element dan menampungnya ke dalam variabel. Isinya merupakan object HTML element
console.log(pageTitleElement);
var pageBoxElements = document.getElementsByClassName("page-box");
// Menyeleksi DOM berdasarkan nama class element dan menampungnya ke dalam variabel. Isinya merupakan array dari object HTML element, walau
 hanya ada 1.
console.log(pageBoxElements);
var pageHeadings = document.getElementsByTagName("h1");
// Menyeleksi DOM berdasarkan tag
 dan menampungnya ke dalam variabel. Isinya merupakan array dari object HTML element
console.log(pageHeadings);

var pageTitleElementsContent = pageTitleElement.innerHTML;
console.log('isi
 :' + pageTitleElementsContent);
// isi
 adalah Sample Page Title

var pageBoxElementsContent = pageBoxElements.innerHTML;
console.log('isi
 :' + pageBoxElementsContent);
// isi
 adalah undefined!
<commit_msg>ambil isi dari array of DOM<commit_after>var pageTitleElement = document.getElementById("page-title");
// Menyeleksi DOM berdasarkan Id element dan menampungnya ke dalam variabel. Isinya merupakan object HTML element
console.log(pageTitleElement);
var pageBoxElements = document.getElementsByClassName("page-box");
// Menyeleksi DOM berdasarkan nama class element dan menampungnya ke dalam variabel. Isinya merupakan array dari object HTML element, walau
 hanya ada 1.
console.log(pageBoxElements);
var pageHeadings = document.getElementsByTagName("h1");
// Menyeleksi DOM berdasarkan tag
 dan menampungnya ke dalam variabel. Isinya merupakan array dari object HTML element
console.log(pageHeadings);

var pageTitleElementsContent = pageTitleElement.innerHTML;
console.log('isi
 :' + pageTitleElementsContent);
// isi
 adalah Sample Page Title

// Mengambil isi elemen pageBoxElements yang pertama, yaitu index ke 0
var firstPageBoxElement         = pageBoxElements[0];
var firstpageBoxElementContent  = firstPageBoxElement.innerHTML;

// Mengambil isi elemen pageBoxElements yang kedua, yaitu index ke 1
var secondPageBoxElement         = pageBoxElements[1];
var secondpageBoxElementContent  = secondPageBoxElement.innerHTML;

// Mengambil isi elemen pageBoxElements yang ketiga, yaitu index ke 2
var thirdPageBoxElement         = pageBoxElements[2];
var thirdpageBoxElementContent  = thirdPageBoxElement.innerHTML;

// Menampilkan isi elemen dengan console.log
console.log('isi
 yang pertama:' + firstpageBoxElementContent);
console.log('isi
 yang kedua:' + secondpageBoxElementContent);
console.log('isi
 yang ketiga:' + thirdpageBoxElementContent);
<|endoftext|>


<commit_before>define(['jquery', 'appearanceUtils'], function($, utils) {
   return {
      // where
      selector: function(pull) {
         return pull.state == 'open';
      },
      // order by
      sort: function(pull) {
         return pull.created_at;
      },
      // Allows custom modifications of each pull's display
      adjust: function(pull, node) {
         // If the pull is over 30 days old...
         if (Date.now() - (new Date(pull.created_at)) > 2590000000 ) {
            // Mark it in red
            $(node).addClass('bg-warning');
         }
      },
      navbar: "#restore-buttons",
      // Functions to stick status information in indicators at the bottom of each pull
      indicators: {
         qa_remaining: function qa_remaining(pull, node) {
            var required = pull.status.qa_req;
            var completed = pull.status.QA.length;
            node.text("QA " + completed + "/" + required);
         },
         cr_remaining: function cr_remaining(pull, node) {
            var required = pull.status.cr_req;
            var completed = pull.status.CR.length;
            node.text("CR " + completed + "/" + required);
         },
         status: function status(pull, node) {
            if (pull.status.commit_status) {
            var commit_status = pull.status.commit_status.data;
               switch(commit_status.state) {
                  case 'pending':
                  node.append('');
                  break;
                  case 'success':
                  node.append('');
                  break;
                  case 'error':
                  node.append('');
                  break;
                  case 'failure':
                  node.append('');
                  break;
               }
            }
         },
         user_icon: function user_icon(pull, node) {
            if (pull.is_mine()) {
               node.append('');
            }
         }
      },
      columns: [
         {
            title: "Special Pulls",
            id: "uniqPulls",
            selector: function(pull) {
               return (pull.deploy_blocked() || pull.status.ready) && !pull.dev_blocked();
            },
            sort: function(pull) {
               return pull.deploy_blocked() ? 0 : 1;
            },
            adjust: function(pull, node) {
               if (pull.deploy_blocked()) {
                  node.addClass('list-group-item-danger');
               }
            },
            triggers: {
               onCreate: function(blob, container) {
                  blob.removeClass('panel-default').addClass('panel-primary');
               },
               onUpdate: function(blob, container) {
                  utils.hideIfEmpty(container, blob, '.pull');
               }
            },
            shrinkToButton: true
         },
         {
            title: "dev_blocked Pulls",
            id: "blockPulls",
            selector: function(pull) {
               return pull.dev_blocked();
            }
         },
         {
            title: "CR Pulls",
            id: "crPulls",
            selector: function(pull) {
               return !pull.cr_done() && !pull.dev_blocked();
            },
            indicators: {
               cr_remaining: function(pull, node) {
                  var required = pull.status.cr_req;
                  var remaining = required - pull.status.CR.length;

                  if (remaining === 1) {
                     node.addClass('label label-danger');
                  }
               },
               qa_remaining: function(pull, node) {
                  var required = pull.status.qa_req;
                  var remaining = required - pull.status.QA.length;

                  if (remaining === 0) {
                     node.addClass('label label-success');
                  }
               }
            }
         },
         {
            title: "QA Pulls",
            id: "qaPulls",
            selector: function(pull) {
               return !pull.qa_done() && !pull.dev_blocked();
            },
            indicators: {
               qa_remaining: function(pull, node) {
                  var required = pull.status.qa_req;
                  var remaining = required - pull.status.QA.length;

                  if (remaining === 1) {
                     node.addClass('label label-danger');
                  }
               },
               cr_remaining: function(pull, node) {
                  var required = pull.status.cr_req;
                  var remaining = required - pull.status.CR.length;

                  if (remaining === 0) {
                     node.addClass('label label-success');
                  }
               }
            }

         }
      ]
   };
});
<commit_msg>Make build status Glyphicons into links<commit_after>define(['jquery', 'appearanceUtils'], function($, utils) {
   return {
      // where
      selector: function(pull) {
         return pull.state == 'open';
      },
      // order by
      sort: function(pull) {
         return pull.created_at;
      },
      // Allows custom modifications of each pull's display
      adjust: function(pull, node) {
         // If the pull is over 30 days old...
         if (Date.now() - (new Date(pull.created_at)) > 2590000000 ) {
            // Mark it in red
            $(node).addClass('bg-warning');
         }
      },
      navbar: "#restore-buttons",
      // Functions to stick status information in indicators at the bottom of each pull
      indicators: {
         qa_remaining: function qa_remaining(pull, node) {
            var required = pull.status.qa_req;
            var completed = pull.status.QA.length;
            node.text("QA " + completed + "/" + required);
         },
         cr_remaining: function cr_remaining(pull, node) {
            var required = pull.status.cr_req;
            var completed = pull.status.CR.length;
            node.text("CR " + completed + "/" + required);
         },
         status: function status(pull, node) {
            if (pull.status.commit_status) {
            var commit_status = pull.status.commit_status.data;
               var title = commit_status.description;
               var url   = commit_status.target_url;
               var state = commit_status.state;

               var link = $('' + state + "")
               node.append(link);
               switch(commit_status.state) {
                  case 'pending':
                  link.append('');
                  break;
                  case 'success':
                  link.append('');
                  break;
                  case 'error':
                  link.append('');
                  break;
                  case 'failure':
                  link.append('');
                  break;
               }
            }
         },
         user_icon: function user_icon(pull, node) {
            if (pull.is_mine()) {
               node.append('');
            }
         }
      },
      columns: [
         {
            title: "Special Pulls",
            id: "uniqPulls",
            selector: function(pull) {
               return (pull.deploy_blocked() || pull.status.ready) && !pull.dev_blocked();
            },
            sort: function(pull) {
               return pull.deploy_blocked() ? 0 : 1;
            },
            adjust: function(pull, node) {
               if (pull.deploy_blocked()) {
                  node.addClass('list-group-item-danger');
               }
            },
            triggers: {
               onCreate: function(blob, container) {
                  blob.removeClass('panel-default').addClass('panel-primary');
               },
               onUpdate: function(blob, container) {
                  utils.hideIfEmpty(container, blob, '.pull');
               }
            },
            shrinkToButton: true
         },
         {
            title: "dev_blocked Pulls",
            id: "blockPulls",
            selector: function(pull) {
               return pull.dev_blocked();
            }
         },
         {
            title: "CR Pulls",
            id: "crPulls",
            selector: function(pull) {
               return !pull.cr_done() && !pull.dev_blocked();
            },
            indicators: {
               cr_remaining: function(pull, node) {
                  var required = pull.status.cr_req;
                  var remaining = required - pull.status.CR.length;

                  if (remaining === 1) {
                     node.addClass('label label-danger');
                  }
               },
               qa_remaining: function(pull, node) {
                  var required = pull.status.qa_req;
                  var remaining = required - pull.status.QA.length;

                  if (remaining === 0) {
                     node.addClass('label label-success');
                  }
               }
            }
         },
         {
            title: "QA Pulls",
            id: "qaPulls",
            selector: function(pull) {
               return !pull.qa_done() && !pull.dev_blocked();
            },
            indicators: {
               qa_remaining: function(pull, node) {
                  var required = pull.status.qa_req;
                  var remaining = required - pull.status.QA.length;

                  if (remaining === 1) {
                     node.addClass('label label-danger');
                  }
               },
               cr_remaining: function(pull, node) {
                  var required = pull.status.cr_req;
                  var remaining = required - pull.status.CR.length;

                  if (remaining === 0) {
                     node.addClass('label label-success');
                  }
               }
            }

         }
      ]
   };
});
<|endoftext|>


<commit_before>var BadgeStore = function(channel) {
  var self = this;

  $.ajax({
    url: 'https://api.twitch.tv/kraken/chat/' + channel + '/badges',
    success: function(data) {
      for (var key in data)
        self[key] = data[key].image;
    }
  })
}

var ChatAssetStore = function() {
  var self = this;

  this.emotes = {};
  this.badges = {};

  this.fetchBadges = function(channel) {
    this.badges[channel] = new BadgeStore(channel);
  }

  // Global emotes
  $.ajax({
    url: 'https://twitchemotes.com/api_cache/v2/global.json',
    success: function(data) {
      var template = data.template.small;

      for (var key in data.emotes) {
        var imageId = data.emotes[key].image_id.toString();
        self.emotes[key] = template.replace('{image_id}', imageId);
      }
    }
  });
  // Subscriber emotes
  $.ajax({
    url: 'https://twitchemotes.com/api_cache/v2/subscriber.json',
    success: function(data) {
      var template = data.template.small;

      for (var channel in data.channels) {
        var emotes = data.channels[channel].emotes;

        for (var i = 0; i < emotes.length; ++i) {
          var code = emotes[i].code;
          var imageId = emotes[i].image_id.toString();
          self.emotes[code] = template.replace('{image_id}', imageId);
        }
      }
    }
  });
  // BTTV emotes
  $.ajax({
    url: 'https://api.betterttv.net/2/emotes',
    success: function(data) {
      var template = data.urlTemplate;

      for (var i = 0; i < data.emotes.length; i++) {
        var emote = data.emotes[i];
        var code = emote.code;
        self.emotes[code] = template.replace('{{id}}', emote.id)
                                    .replace('{{image}}', '1x');
      }

      // Some more
      $.ajax({
        url: 'https://raw.githubusercontent.com/Jiiks/BetterDiscordApp/master/data/emotedata_bttv.json',
        success: function(data) {
          data = JSON.parse(data); // Not parsed for some reason. I guess headers

          for (var code in data) {
            self.emotes[code] = template.replace('{{id}}', data[code])
                                        .replace('{{image}}', '1x');
          }
        }
      })
    }
  });
}

var CHAT_DISPLAY_INTERVAL = 0.25; // seconds
var CHAT_CLEAR_INTERVAL = 10; // seconds
var CHAT_DELAY = 10; // seconds

var currentChannel = null;
var chatSocket = null;

var chatMessagesQueue = [];
var chatDisplayId = setInterval(displayMessages, CHAT_DISPLAY_INTERVAL * 1000);
var chatClearId = setInterval(clearChat, CHAT_CLEAR_INTERVAL * 1000);

var chatContainer = $('#chat');
var chatLines = $('#chat-lines');

var chatAssetStore = new ChatAssetStore();

function toggleChat(visible) {
  chatContainer.toggle(visible);
}

function displayChatRaw(text) {
  var line = $('
').text(text);
  chatLines.append(line);
}

function connectToChat(channel) {
  chatAssetStore.fetchBadges(channel);

  // Close any previous connection
  if (chatSocket)
    chatSocket.close();

  // Clear chat's content
  chatLines.empty();
  // Attempt to connect to the new channel
  displayChatRaw('Joining chat: ' + channel + ' ...');

  chatSocket = new WebSocket('ws://' + window.location.host + '/chat/' + channel);

  chatSocket.onopen = function(e) {
    currentChannel = channel;

    displayChatRaw('Successfully joined the channel!');
    displayChatRaw('Delaying chat for: ' + CHAT_DELAY + ' seconds')
  };

  chatSocket.onerror = function(e) {
    displayChatRaw('Error: ' + e.reason);
  };

  chatSocket.onmessage = function(e) {
    var message = makeChatLine(JSON.parse(e.data));
    chatMessagesQueue.push(message);
  };
}

function displayMessages() {
  var i = 0;
  var now = new Date().getTime();

  for (; i < chatMessagesQueue.length; ++i) {
    var message = chatMessagesQueue[i];

    if (now - message.stamp < CHAT_DELAY * 1000)
      break ;

    chatLines.append(message);
  }

  chatMessagesQueue = chatMessagesQueue.slice(i, chatMessagesQueue.length);

  chatContainer.scrollTop(chatContainer[0].scrollHeight);
}

function clearChat() {
  // Keeping the chat relatively small
  chatLines.find('li:lt(-100)').remove();
}

function makeChatLine(message) {
  var color = message.tags ? message.tags.color : 'blue';

  var line = $('
')
    .addClass('chat-line');
  var nameSpan = $('')
    .addClass('chat-line-sender')
    .text(message.sender)
    .css('color', color);
  var contentSpan = makeContentSpan(message.content);

  if (message.tags)
    prependBadges(message.tags, line);
  line.append(nameSpan);
  line.append(contentSpan);

  line.stamp = new Date().getTime();

  return line;
}

function makeContentSpan(content) {
  var htmlParts = content.split(' ').map(function(word) {
    if (word in chatAssetStore.emotes)
      return '';

    return word;
  });
  return $('').html(': ' + htmlParts.join(' '));
}

function prependBadges(tags, line) {
  var specialAttributes = ['mod', 'subscriber', 'turbo']
    .filter(function(attribute) {
      return (tags[attribute] == '1');
    });

  if (tags['user-type'])
    specialAttributes.push(tags['user-type']);

  if (specialAttributes.length > 0) {
    var badgeWrapper = $('')
      .addClass('badge-wrapper');
    var badgeContainer = $('
');

    $.unique(specialAttributes).forEach(function(attribute) {
      var badge = $('')
        .attr('src', chatAssetStore.badges[currentChannel][attribute]);
      badgeContainer.append(badge);
    })

    badgeWrapper.wrapInner(badgeContainer);
    line.append(badgeWrapper);
  }
}
<commit_msg>Changed the way chat was refreshed<commit_after>var BadgeStore = function(channel) {
  var self = this;

  $.ajax({
    url: 'https://api.twitch.tv/kraken/chat/' + channel + '/badges',
    success: function(data) {
      for (var key in data)
        self[key] = data[key].image;
    }
  })
}

var ChatAssetStore = function() {
  var self = this;

  this.emotes = {};
  this.badges = {};

  this.fetchBadges = function(channel) {
    this.badges[channel] = new BadgeStore(channel);
  }

  // Global emotes
  $.ajax({
    url: 'https://twitchemotes.com/api_cache/v2/global.json',
    success: function(data) {
      var template = data.template.small;

      for (var key in data.emotes) {
        var imageId = data.emotes[key].image_id.toString();
        self.emotes[key] = template.replace('{image_id}', imageId);
      }
    }
  });
  // Subscriber emotes
  $.ajax({
    url: 'https://twitchemotes.com/api_cache/v2/subscriber.json',
    success: function(data) {
      var template = data.template.small;

      for (var channel in data.channels) {
        var emotes = data.channels[channel].emotes;

        for (var i = 0; i < emotes.length; ++i) {
          var code = emotes[i].code;
          var imageId = emotes[i].image_id.toString();
          self.emotes[code] = template.replace('{image_id}', imageId);
        }
      }
    }
  });
  // BTTV emotes
  $.ajax({
    url: 'https://api.betterttv.net/2/emotes',
    success: function(data) {
      var template = data.urlTemplate;

      for (var i = 0; i < data.emotes.length; i++) {
        var emote = data.emotes[i];
        var code = emote.code;
        self.emotes[code] = template.replace('{{id}}', emote.id)
                                    .replace('{{image}}', '1x');
      }

      // Some more
      $.ajax({
        url: 'https://raw.githubusercontent.com/Jiiks/BetterDiscordApp/master/data/emotedata_bttv.json',
        success: function(data) {
          data = JSON.parse(data); // Not parsed for some reason. I guess headers

          for (var code in data) {
            self.emotes[code] = template.replace('{{id}}', data[code])
                                        .replace('{{image}}', '1x');
          }
        }
      })
    }
  });
}

var CHAT_DISPLAY_INTERVAL = 0.25; // seconds
var CHAT_CLEAR_INTERVAL = 10; // seconds
var CHAT_DELAY = 10; // seconds

var currentChannel = null;
var chatSocket = null;

var chatMessagesQueue = [];
var chatDisplayId = setTimeout(displayMessages, CHAT_DISPLAY_INTERVAL * 1000);
var chatClearId = setInterval(clearChat, CHAT_CLEAR_INTERVAL * 1000);

var chatContainer = $('#chat');
var chatLines = $('#chat-lines');

var chatAssetStore = new ChatAssetStore();

function toggleChat(visible) {
  chatContainer.toggle(visible);
}

function displayChatRaw(text) {
  var line = $('
').text(text);
  chatLines.append(line);
}

function connectToChat(channel) {
  chatAssetStore.fetchBadges(channel);

  // Close any previous connection
  if (chatSocket)
    chatSocket.close();

  // Clear chat's content
  chatLines.empty();
  // Attempt to connect to the new channel
  displayChatRaw('Joining chat: ' + channel + ' ...');

  chatSocket = new WebSocket('ws://' + window.location.host + '/chat/' + channel);

  chatSocket.onopen = function(e) {
    currentChannel = channel;

    displayChatRaw('Successfully joined the channel!');
    displayChatRaw('Delaying chat for: ' + CHAT_DELAY + ' seconds')
  };

  chatSocket.onerror = function(e) {
    displayChatRaw('Error: ' + e.reason);
  };

  chatSocket.onmessage = function(e) {
    var message = makeChatLine(JSON.parse(e.data));
    chatMessagesQueue.push(message);
  };
}

function displayMessages() {
  var i = 0;
  var now = new Date().getTime();

  for (; i < chatMessagesQueue.length; ++i) {
    var message = chatMessagesQueue[i];

    if (now - message.stamp < CHAT_DELAY * 1000)
      break ;

    chatLines.append(message);
  }

  chatMessagesQueue = chatMessagesQueue.slice(i, chatMessagesQueue.length);

  chatContainer.scrollTop(chatContainer[0].scrollHeight);

  setTimeout(displayMessages, CHAT_DISPLAY_INTERVAL * 1000);
}

function clearChat() {
  // Keeping the chat relatively small
  chatLines.find('li:lt(-100)').remove();
}

function makeChatLine(message) {
  var color = message.tags ? message.tags.color : 'blue';

  var line = $('
')
    .addClass('chat-line');
  var nameSpan = $('')
    .addClass('chat-line-sender')
    .text(message.sender)
    .css('color', color);
  var contentSpan = makeContentSpan(message.content);

  if (message.tags)
    prependBadges(message.tags, line);
  line.append(nameSpan);
  line.append(contentSpan);

  line.stamp = new Date().getTime();

  return line;
}

function makeContentSpan(content) {
  var htmlParts = content.split(' ').map(function(word) {
    if (word in chatAssetStore.emotes)
      return '';

    return word;
  });
  return $('').html(': ' + htmlParts.join(' '));
}

function prependBadges(tags, line) {
  var specialAttributes = ['mod', 'subscriber', 'turbo']
    .filter(function(attribute) {
      return (tags[attribute] == '1');
    });

  if (tags['user-type'])
    specialAttributes.push(tags['user-type']);

  if (specialAttributes.length > 0) {
    var badgeWrapper = $('')
      .addClass('badge-wrapper');
    var badgeContainer = $('
');

    $.unique(specialAttributes).forEach(function(attribute) {
      var badge = $('')
        .attr('src', chatAssetStore.badges[currentChannel][attribute]);
      badgeContainer.append(badge);
    })

    badgeWrapper.wrapInner(badgeContainer);
    line.append(badgeWrapper);
  }
}
<|endoftext|>


<commit_before>Qlb.globalEnvironment.merge({
  // general

  "رأس":          // head
  function(x) {
    return x[0];
  },

  "ذيل":    // tail
  function(x) {
    return x.slice(1);
  },

  "كونس":    // cons
  function(x, y) {
    return [x].concat(y)
  },

  "طول":    // cons
  function(lst) {
    return lst.length;
  },

  "حال":    // cond
  function() {
    for (var i = 0; i < arguments.length; i++) {
      var cond = Qlb.eval(arguments[i][0]),
          val = arguments[i][1];
    }
  },

  "كرر":
  function(n, fn) {
    for (var i = 0; i < n; i++) { fn(n); }
  },

  "عكس":
  function(l) {
    return l.reverse();
  },

  "عدم": // null
  function() {
    return [];
  },

  "عدم؟": // null?
  function(lst) {
    return lst instanceof Array && lst.length == 0;
  },

  "لائحة؟": // list?
  function(lst) {
    return lst instanceof Array;
  },

  "و":    // and
  function() {
    var args = Array.prototype.slice.call(arguments);
    return args.reduce(function(prv, cur, idx, ary) {
      if(idx > 0) return prv && !!cur;
      else return !!cur;
    });
  },

  "أو":    // or
  function() {
    var args = Array.prototype.slice.call(arguments);
    return args.reduce(function(prv, cur, idx, ary) {
      if(idx > 0) return prv || !!cur;
      else return !!cur;
    });
  },

  "طبق":    // map
  function(fn, lst) {
    return lst.map(fn);
  },

  "طبق-مع-مؤشر":    // map-with-index
  function(fn, lst) {
    var ary = [];
    for (var i = 0; i < lst.length; i++) {
      ary[i] = fn(lst[i], i)
    }
    return ary;
  },

  "أجل":
  function(fn, millis) {
    return window.setTimeout(fn, millis)
  },

  "عنصر":
  function(n, lst) {
    console.log(lst.length, n, lst)
    return n < 1 || n > lst.length ? 0 : lst[n-1];
  },

  // input/output

  "قول":    // say
  function(str) {
    Qlb.console.log(str);
    return str;
  },

  "ضمن":    // require
  function(url) {
    var code = Qlb.http.get("/lib/" + url.replace("\\", "/") + ".qlb");
    return Qlb.execute(code);
  },

  "ضمن-تمديد":    // require-extension
  function(url) {
    importScripts("/lib/tamdeed/" + url + "-worker.js");
  },

  // comparison

  "يساوي؟":     // equals
  function(a, b) {
    return a == b;
  },

  "أكبر؟":     // greater
  function(a, b) {
    return a > b;
  },

  "أكبر-أو-يساوي؟":     // greater or equal
  function(a, b) {
    return a >= b;
  },

  "أصغر؟":     // less
  function(a, b) {
    return a < b
  },

  "أصغر-أو-يساوي؟":     // less or equal
  function(a, b) {
    return a <= b;
  },

  // arithmetic

  "سقف":     // ceil
  function(x) {
    return Math.ceil(x)
  },

  "أرض":     // floor
  function(x) {
    return Math.floor(x)
  },

  "القيمة-المطلقة":     // abs
  function(x) {
    return Math.abs(x)
  },

  "الأكبر":     // max
  function() {
    var args = Array.prototype.slice.call(arguments);
    return args.reduce(function(prv, cur, idx, ary) {
      if(idx > 0) return cur > prv ? cur : prv
      else return cur
    });
  },

  "الأصغر":     // min
  function() {
    var args = Array.prototype.slice.call(arguments);
    return args.reduce(function(prv, cur, idx, ary) {
      if(idx > 0) return cur < prv ? cur : prv
      else return cur
    });
  },

  "جمع":     // add
  function() {
    var args = Array.prototype.slice.call(arguments);
    return args.reduce(function(prv, cur, idx, ary) {
      return prv + cur;
    });
  },

  "طرح":    // subtract
  function() {
    var args = Array.prototype.slice.call(arguments);
    return args.reduce(function(prv, cur, idx, ary) {
      return prv - cur;
    });
  },

  "ضرب":     // multiply
  function() {
    var args = Array.prototype.slice.call(arguments);
    return args.reduce(function(prv, cur, idx, ary) {
      return prv * cur;
    });
  },

  "قسم":     // divide
  function() {
    var args = Array.prototype.slice.call(arguments);
    return args.reduce(function(prv, cur, idx, ary) {
      return prv / cur;
    });
  }
});<commit_msg>Remove console.log call from web worker code<commit_after>Qlb.globalEnvironment.merge({
  // general

  "رأس":          // head
  function(x) {
    return x[0];
  },

  "ذيل":    // tail
  function(x) {
    return x.slice(1);
  },

  "كونس":    // cons
  function(x, y) {
    return [x].concat(y)
  },

  "طول":    // cons
  function(lst) {
    return lst.length;
  },

  "حال":    // cond
  function() {
    for (var i = 0; i < arguments.length; i++) {
      var cond = Qlb.eval(arguments[i][0]),
          val = arguments[i][1];
    }
  },

  "كرر":
  function(n, fn) {
    for (var i = 0; i < n; i++) { fn(n); }
  },

  "عكس":
  function(l) {
    return l.reverse();
  },

  "عدم": // null
  function() {
    return [];
  },

  "عدم؟": // null?
  function(lst) {
    return lst instanceof Array && lst.length == 0;
  },

  "لائحة؟": // list?
  function(lst) {
    return lst instanceof Array;
  },

  "و":    // and
  function() {
    var args = Array.prototype.slice.call(arguments);
    return args.reduce(function(prv, cur, idx, ary) {
      if(idx > 0) return prv && !!cur;
      else return !!cur;
    });
  },

  "أو":    // or
  function() {
    var args = Array.prototype.slice.call(arguments);
    return args.reduce(function(prv, cur, idx, ary) {
      if(idx > 0) return prv || !!cur;
      else return !!cur;
    });
  },

  "طبق":    // map
  function(fn, lst) {
    return lst.map(fn);
  },

  "طبق-مع-مؤشر":    // map-with-index
  function(fn, lst) {
    var ary = [];
    for (var i = 0; i < lst.length; i++) {
      ary[i] = fn(lst[i], i)
    }
    return ary;
  },

  "أجل":
  function(fn, millis) {
    return window.setTimeout(fn, millis)
  },

  "عنصر":
  function(n, lst) {
    return n < 1 || n > lst.length ? 0 : lst[n-1];
  },

  // input/output

  "قول":    // say
  function(str) {
    Qlb.console.log(str);
    return str;
  },

  "ضمن":    // require
  function(url) {
    var code = Qlb.http.get("/lib/" + url.replace("\\", "/") + ".qlb");
    return Qlb.execute(code);
  },

  "ضمن-تمديد":    // require-extension
  function(url) {
    importScripts("/lib/tamdeed/" + url + "-worker.js");
  },

  // comparison

  "يساوي؟":     // equals
  function(a, b) {
    return a == b;
  },

  "أكبر؟":     // greater
  function(a, b) {
    return a > b;
  },

  "أكبر-أو-يساوي؟":     // greater or equal
  function(a, b) {
    return a >= b;
  },

  "أصغر؟":     // less
  function(a, b) {
    return a < b
  },

  "أصغر-أو-يساوي؟":     // less or equal
  function(a, b) {
    return a <= b;
  },

  // arithmetic

  "سقف":     // ceil
  function(x) {
    return Math.ceil(x)
  },

  "أرض":     // floor
  function(x) {
    return Math.floor(x)
  },

  "القيمة-المطلقة":     // abs
  function(x) {
    return Math.abs(x)
  },

  "الأكبر":     // max
  function() {
    var args = Array.prototype.slice.call(arguments);
    return args.reduce(function(prv, cur, idx, ary) {
      if(idx > 0) return cur > prv ? cur : prv
      else return cur
    });
  },

  "الأصغر":     // min
  function() {
    var args = Array.prototype.slice.call(arguments);
    return args.reduce(function(prv, cur, idx, ary) {
      if(idx > 0) return cur < prv ? cur : prv
      else return cur
    });
  },

  "جمع":     // add
  function() {
    var args = Array.prototype.slice.call(arguments);
    return args.reduce(function(prv, cur, idx, ary) {
      return prv + cur;
    });
  },

  "طرح":    // subtract
  function() {
    var args = Array.prototype.slice.call(arguments);
    return args.reduce(function(prv, cur, idx, ary) {
      return prv - cur;
    });
  },

  "ضرب":     // multiply
  function() {
    var args = Array.prototype.slice.call(arguments);
    return args.reduce(function(prv, cur, idx, ary) {
      return prv * cur;
    });
  },

  "قسم":     // divide
  function() {
    var args = Array.prototype.slice.call(arguments);
    return args.reduce(function(prv, cur, idx, ary) {
      return prv / cur;
    });
  }
});<|endoftext|>


<commit_before>// dependencies: module.js, fav.js, display.js, history.js
var getSearchQueryURL = function () {
  var parameters = []
  if ($('#searchbox').val() != null) {
    parameters.push('search=' + $('#searchbox').val())
  }
  if ($('#semester').val() != null) {
    parameters.push('semester=' + $('#semester').val())
  }
  if ($('#sort').val() != null) {
    parameters.push('sort=' + $('#sort').val())
  }
  return '?' + parameters.join('&')

  // search += '&track=' + 'UGRD'
}

// update search results from the search box
var searchFromBox = function() {
  // query url
  var queryURL = getSearchQueryURL()

  var query = encodeURIComponent($('#searchbox').val())
  var semester = $('#semester').val()
  var sort = $('#sort').val()

  // save search into history
  history_search(queryURL)

  searchForCourses(query, semester, sort)
}

// function for updating search results
// -- noswipe to prevent swiping if on mobile
var searchForCourses = function (query, semester, sort, noswipe) {

  // construct search query
  var search = '/api/search/' + query
  search += '?semester=' + semester
  search += '&sort=' + sort
  // search += '&track=' + 'UGRD'

  // display search
  $('#searchbox').val(query)
  if (semester) $('#semester').val(semester)
  if (sort) $('#sort').val(sort)

  // stop if no query
  if (query === undefined || query === '') {
    $('#results').children().remove();
    $('#search-title').text('0 Search Results')
    document.lastSearch = ''
    return false
  }

  // go to search pane for mobile
  if (document.isMobile && noswipe !== true) $('#main-pane').slick('slickGoTo', 1)

  // don't search if it's the same!
  if (document.lastSearch === search) return;
  document.lastSearch = search

  // store search value used
  localStorage.setItem("sort", $('#sort').val())

  // search!
  $.get(search, function (results, success, xhr) {
    if (!success) {
      window.alert('An error occured and your search could not be completed.')
      return false
    }

    // Remove any search results already in the results pane
    $('#results').children().remove()

    var len = results.length

    // Update the search results sub-heading
    $('#search-title').text(len + ' Search Result' + (len !== 1 ? 's' : ''))

    // List the returned courses in the search results pane
    for (var index in results) {
      var result = results[index]
      if (result) {
        $('#results').append(newDOMResult(result, {"tags": 1}))
      }
    }

    displayActive() // update highlighting of active course
  })

}

// returns a DOM object for a search result
function newDOMResult(result, props) {
  if (result.type === 'instructor') return newDOMinstructorResult(result, props)
  /*if (result.type === 'course')*/ return newDOMcourseResult(result, props)
}

// returns a DOM object for a search result of an instructor
function newDOMinstructorResult(instructor, props) {
  var name = instructor.name.first + ' ' + instructor.name.last

  // html string for the DOM object
  var htmlString = (
    '
'
    + '
'
      + '
'
        + '' + name + ''
      + '
'
      + '
'
        + '' + instructor.courses.length + ' '
        + ''
      + '
'
    + '
'
    + '
'
    + '
'
  + '
'
  )

  var entry = $.parseHTML(htmlString)[0]  // create DOM object
  var icon = $(entry).find('i')[0]        // find icon
  var title = $(entry).find('.instructor-title')    // instructor name
  icon.instructorId = instructor._id      // attach instructor id
  var body = $(entry).find('ul')[0]       // body of instructor result
  $(icon).click(function() {toggleInstructor(icon, body, entry); return false})
  $(entry).click(function() {toggleInstructor(icon, body, entry); return false})

  return entry
}

// handles clicking the button to toggle instructors
// - icon: DOM object of toggling icon
// - body: DOM object of place to insert courses
// - entry: DOM object of whole entry
function toggleInstructor(icon, body, entry) {
  var isEmpty = $(body).is(':empty')

  if (isEmpty) {
    loadInstructor(icon, body, entry)
    return
  }

  var isVisible = $(body).css('display') !== 'none'

  $(icon).removeClass(isVisible ? 'fa-caret-up' : 'fa-caret-down')
  $(icon).addClass(isVisible ? 'fa-caret-down' : 'fa-caret-up')
  if (isVisible) $(entry).removeClass('instructor-list-item-opened')
  else $(entry).addClass('instructor-list-item-opened')
  $(body).slideToggle()
}

// handles loading instructor courses
// - icon: DOM object of toggling icon
// - body: DOM object of place to insert courses
// - entry: DOM object of whole entry
function loadInstructor(icon, body, entry) {
  $.get('/api/instructor/' + icon.instructorId, function (instructor) {
    var courses = instructor.courses;
    for (var index in courses) {
      var course = courses[index]
      $(body).append(newDOMcourseResult(course, {'tags' : 1, 'semester': 1}))
    }

    $(icon).removeClass('fa-caret-down')
    $(icon).addClass('fa-caret-up')
    $(entry).addClass('instructor-list-item-opened')
    displayActive()
    $(body).slideToggle()
  })
}

// returns a DOM object for a search or favorite result of a course
// includes:
//   -- course object linking
//   -- clicking to favorite/unfavorite (+ course id linking for icon)
// props: properties for conditional rendering:
//  - 'semester' is defined => displays semester name too
//  - 'tags' is defined => displays pdf/audit tags
function newDOMcourseResult(course, props) {
  var isFav = (document.favorites.indexOf(course["_id"]) !== -1)

  var hasScore = (course.hasOwnProperty('scores') && course.scores.hasOwnProperty('Overall Quality of the Course'))

  if (hasScore)
    var score = course.scores['Overall Quality of the Course']

  // append semester if appropriate
  var semester = props.hasOwnProperty('semester') ? '\xa0' + course.semester.name + '' : ''

  // tags: dist / pdf / audit
  var tags = ''
  if (props.hasOwnProperty('tags')) {
    if (course.distribution !== undefined) tags += ' ' + course.distribution + ''
    if (course.hasOwnProperty('pdf')) {
      if (course.pdf.hasOwnProperty('required') && course.pdf.required) tags += ' PDFO'
      else if (course.pdf.hasOwnProperty('permitted') && !course.pdf.permitted) tags += ' NPDF'
    }
    if (course.audit) tags += ' AUDIT'
    if (tags !== '') tags = '\xa0' + tags + ''
  }

  var isPast = course.hasOwnProperty('scoresFromPreviousSemester') && course.scoresFromPreviousSemester
  var tooltip = isPast ? ' title="An asterisk * indicates a score from a different semester"' : ''

  // is this a new course
  var isNew = course.hasOwnProperty('new') && course.new

  var badgeColor = '#ddd' /* light grey */
  if (hasScore) badgeColor = colorAt(score)
  else if (isNew) badgeColor = '#92D4E3' /* blue */

  var badgeText = 'N/A'
  if (hasScore) badgeText = score.toFixed(2)
  else if (isNew) badgeText = 'New'
  if (isPast) badgeText += '*'

  // html string for the DOM object
  var htmlString = (
    '
'
    + '
'
      + '
'
        + '' + mainListing(course) + crossListings(course) + tags + ''
      + '
'
      + '
'
        + ' '
        + ''
          + badgeText
        + ''
      + '
'
    + '
'
    + '
'
      + '
' + course.title + '
'
      + '
' + semester + '
'
    + '
'
  + '
'
  )

  var entry = $.parseHTML(htmlString)[0]                                     // create DOM object
  var icon = $(entry).find('i')[0]                                           // favorite icon
  entry.courseId = course._id                                                // attach course id to entry
  icon.courseId = course._id                                                 // attach course id to icon
  $(icon).click(toggleFav)                                                   // handle click to fav/unfav
  $(entry).click(displayResult)                                              // enable click to display

  return entry
}
<commit_msg>fix encoding<commit_after>// dependencies: module.js, fav.js, display.js, history.js
var getSearchQueryURL = function () {
  var parameters = []
  if ($('#searchbox').val() != null) {
    parameters.push('search=' + $('#searchbox').val())
  }
  if ($('#semester').val() != null) {
    parameters.push('semester=' + $('#semester').val())
  }
  if ($('#sort').val() != null) {
    parameters.push('sort=' + $('#sort').val())
  }
  return '?' + parameters.join('&')

  // search += '&track=' + 'UGRD'
}

// update search results from the search box
var searchFromBox = function() {
  // query url
  var queryURL = getSearchQueryURL()

  var query = encodeURIComponent($('#searchbox').val())
  var semester = $('#semester').val()
  var sort = $('#sort').val()

  // save search into history
  history_search(queryURL)

  searchForCourses(query, semester, sort)
}

// function for updating search results
// -- noswipe to prevent swiping if on mobile
var searchForCourses = function (query, semester, sort, noswipe) {

  // construct search query
  var search = '/api/search/' + query
  search += '?semester=' + semester
  search += '&sort=' + sort
  // search += '&track=' + 'UGRD'

  // display search
  $('#searchbox').val(decodeURIComponent(query))
  if (semester) $('#semester').val(semester)
  if (sort) $('#sort').val(sort)

  // stop if no query
  if (query === undefined || query === '') {
    $('#results').children().remove();
    $('#search-title').text('0 Search Results')
    document.lastSearch = ''
    return false
  }

  // go to search pane for mobile
  if (document.isMobile && noswipe !== true) $('#main-pane').slick('slickGoTo', 1)

  // don't search if it's the same!
  if (document.lastSearch === search) return;
  document.lastSearch = search

  // store search value used
  localStorage.setItem("sort", $('#sort').val())

  // search!
  $.get(search, function (results, success, xhr) {
    if (!success) {
      window.alert('An error occured and your search could not be completed.')
      return false
    }

    // Remove any search results already in the results pane
    $('#results').children().remove()

    var len = results.length

    // Update the search results sub-heading
    $('#search-title').text(len + ' Search Result' + (len !== 1 ? 's' : ''))

    // List the returned courses in the search results pane
    for (var index in results) {
      var result = results[index]
      if (result) {
        $('#results').append(newDOMResult(result, {"tags": 1}))
      }
    }

    displayActive() // update highlighting of active course
  })

}

// returns a DOM object for a search result
function newDOMResult(result, props) {
  if (result.type === 'instructor') return newDOMinstructorResult(result, props)
  /*if (result.type === 'course')*/ return newDOMcourseResult(result, props)
}

// returns a DOM object for a search result of an instructor
function newDOMinstructorResult(instructor, props) {
  var name = instructor.name.first + ' ' + instructor.name.last

  // html string for the DOM object
  var htmlString = (
    '
'
    + '
'
      + '
'
        + '' + name + ''
      + '
'
      + '
'
        + '' + instructor.courses.length + ' '
        + ''
      + '
'
    + '
'
    + '
'
    + '
'
  + '
'
  )

  var entry = $.parseHTML(htmlString)[0]  // create DOM object
  var icon = $(entry).find('i')[0]        // find icon
  var title = $(entry).find('.instructor-title')    // instructor name
  icon.instructorId = instructor._id      // attach instructor id
  var body = $(entry).find('ul')[0]       // body of instructor result
  $(icon).click(function() {toggleInstructor(icon, body, entry); return false})
  $(entry).click(function() {toggleInstructor(icon, body, entry); return false})

  return entry
}

// handles clicking the button to toggle instructors
// - icon: DOM object of toggling icon
// - body: DOM object of place to insert courses
// - entry: DOM object of whole entry
function toggleInstructor(icon, body, entry) {
  var isEmpty = $(body).is(':empty')

  if (isEmpty) {
    loadInstructor(icon, body, entry)
    return
  }

  var isVisible = $(body).css('display') !== 'none'

  $(icon).removeClass(isVisible ? 'fa-caret-up' : 'fa-caret-down')
  $(icon).addClass(isVisible ? 'fa-caret-down' : 'fa-caret-up')
  if (isVisible) $(entry).removeClass('instructor-list-item-opened')
  else $(entry).addClass('instructor-list-item-opened')
  $(body).slideToggle()
}

// handles loading instructor courses
// - icon: DOM object of toggling icon
// - body: DOM object of place to insert courses
// - entry: DOM object of whole entry
function loadInstructor(icon, body, entry) {
  $.get('/api/instructor/' + icon.instructorId, function (instructor) {
    var courses = instructor.courses;
    for (var index in courses) {
      var course = courses[index]
      $(body).append(newDOMcourseResult(course, {'tags' : 1, 'semester': 1}))
    }

    $(icon).removeClass('fa-caret-down')
    $(icon).addClass('fa-caret-up')
    $(entry).addClass('instructor-list-item-opened')
    displayActive()
    $(body).slideToggle()
  })
}

// returns a DOM object for a search or favorite result of a course
// includes:
//   -- course object linking
//   -- clicking to favorite/unfavorite (+ course id linking for icon)
// props: properties for conditional rendering:
//  - 'semester' is defined => displays semester name too
//  - 'tags' is defined => displays pdf/audit tags
function newDOMcourseResult(course, props) {
  var isFav = (document.favorites.indexOf(course["_id"]) !== -1)

  var hasScore = (course.hasOwnProperty('scores') && course.scores.hasOwnProperty('Overall Quality of the Course'))

  if (hasScore)
    var score = course.scores['Overall Quality of the Course']

  // append semester if appropriate
  var semester = props.hasOwnProperty('semester') ? '\xa0' + course.semester.name + '' : ''

  // tags: dist / pdf / audit
  var tags = ''
  if (props.hasOwnProperty('tags')) {
    if (course.distribution !== undefined) tags += ' ' + course.distribution + ''
    if (course.hasOwnProperty('pdf')) {
      if (course.pdf.hasOwnProperty('required') && course.pdf.required) tags += ' PDFO'
      else if (course.pdf.hasOwnProperty('permitted') && !course.pdf.permitted) tags += ' NPDF'
    }
    if (course.audit) tags += ' AUDIT'
    if (tags !== '') tags = '\xa0' + tags + ''
  }

  var isPast = course.hasOwnProperty('scoresFromPreviousSemester') && course.scoresFromPreviousSemester
  var tooltip = isPast ? ' title="An asterisk * indicates a score from a different semester"' : ''

  // is this a new course
  var isNew = course.hasOwnProperty('new') && course.new

  var badgeColor = '#ddd' /* light grey */
  if (hasScore) badgeColor = colorAt(score)
  else if (isNew) badgeColor = '#92D4E3' /* blue */

  var badgeText = 'N/A'
  if (hasScore) badgeText = score.toFixed(2)
  else if (isNew) badgeText = 'New'
  if (isPast) badgeText += '*'

  // html string for the DOM object
  var htmlString = (
    '
'
    + '
'
      + '
'
        + '' + mainListing(course) + crossListings(course) + tags + ''
      + '
'
      + '
'
        + ' '
        + ''
          + badgeText
        + ''
      + '
'
    + '
'
    + '
'
      + '
' + course.title + '
'
      + '
' + semester + '
'
    + '
'
  + '
'
  )

  var entry = $.parseHTML(htmlString)[0]                                     // create DOM object
  var icon = $(entry).find('i')[0]                                           // favorite icon
  entry.courseId = course._id                                                // attach course id to entry
  icon.courseId = course._id                                                 // attach course id to icon
  $(icon).click(toggleFav)                                                   // handle click to fav/unfav
  $(entry).click(displayResult)                                              // enable click to display

  return entry
}
<|endoftext|>


<commit_before>var mongodb = require('../../lib/bson').pure();

var testCase = require('nodeunit').testCase,
  mongoO = require('../../lib/bson').pure(),
  debug = require('util').debug,
  inspect = require('util').inspect,
  Buffer = require('buffer').Buffer,
  gleak = require('../../tools/gleak'),
  fs = require('fs'),
  BSON = mongoO.BSON,
  Code = mongoO.Code,
  Binary = mongoO.Binary,
  Timestamp = mongoO.Timestamp,
  Long = mongoO.Long,
  MongoReply = mongoO.MongoReply,
  ObjectID = mongoO.ObjectID,
  Symbol = mongoO.Symbol,
  DBRef = mongoO.DBRef,
  Double = mongoO.Double,
  MinKey = mongoO.MinKey,
  MaxKey = mongoO.MaxKey,
  BinaryParser = mongoO.BinaryParser,
  utils = require('./tools/utils');

var BSONSE = mongodb,
  BSONDE = mongodb;

// for tests
BSONDE.BSON_BINARY_SUBTYPE_DEFAULT = 0;
BSONDE.BSON_BINARY_SUBTYPE_FUNCTION = 1;
BSONDE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
BSONDE.BSON_BINARY_SUBTYPE_UUID = 3;
BSONDE.BSON_BINARY_SUBTYPE_MD5 = 4;
BSONDE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;

BSONSE.BSON_BINARY_SUBTYPE_DEFAULT = 0;
BSONSE.BSON_BINARY_SUBTYPE_FUNCTION = 1;
BSONSE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
BSONSE.BSON_BINARY_SUBTYPE_UUID = 3;
BSONSE.BSON_BINARY_SUBTYPE_MD5 = 4;
BSONSE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;

var hexStringToBinary = function(string) {
  var numberofValues = string.length / 2;
  var array = "";

  for(var i = 0; i < numberofValues; i++) {
    array += String.fromCharCode(parseInt(string[i*2] + string[i*2 + 1], 16));
  }
  return array;
}

var assertBuffersEqual = function(test, buffer1, buffer2) {
  if(buffer1.length != buffer2.length) test.fail("Buffers do not have the same length", buffer1, buffer2);

  for(var i = 0; i < buffer1.length; i++) {
    test.equal(buffer1[i], buffer2[i]);
  }
}

/**
 * Module for parsing an ISO 8601 formatted string into a Date object.
 */
var ISODate = function (string) {
  var match;

 if (typeof string.getTime === "function")
   return string;
 else if (match = string.match(/^(\d{4})(-(\d{2})(-(\d{2})(T(\d{2}):(\d{2})(:(\d{2})(\.(\d+))?)?(Z|((\+|-)(\d{2}):(\d{2}))))?)?)?$/)) {
   var date = new Date();
   date.setUTCFullYear(Number(match[1]));
   date.setUTCMonth(Number(match[3]) - 1 || 0);
   date.setUTCDate(Number(match[5]) || 0);
   date.setUTCHours(Number(match[7]) || 0);
   date.setUTCMinutes(Number(match[8]) || 0);
   date.setUTCSeconds(Number(match[10]) || 0);
   date.setUTCMilliseconds(Number("." + match[12]) * 1000 || 0);

   if (match[13] && match[13] !== "Z") {
     var h = Number(match[16]) || 0,
         m = Number(match[17]) || 0;

     h *= 3600000;
     m *= 60000;

     var offset = h + m;
     if (match[15] == "+")
       offset = -offset;

     date = new Date(date.valueOf() + offset);
   }

   return date;
 } else
   throw new Error("Invalid ISO 8601 date given.", __filename);
};

var _Uint8Array = null;

/**
 * Retrieve the server information for the current
 * instance of the db client
 *
 * @ignore
 */
exports.setUp = function(callback) {
  _Uint8Array = global.Uint8Array;
  delete global['Uint8Array'];
  callback();
}

/**
 * Retrieve the server information for the current
 * instance of the db client
 *
 * @ignore
 */
exports.tearDown = function(callback) {
  global['Uint8Array'] = _Uint8Array;
  callback();
}

// /**
//  * @ignore
//  */
// exports.shouldCorrectlyDeserializeUsingTypedArray = function(test) {
//   var motherOfAllDocuments = {
//     'string': '客家话',
//     'array': [1,2,3],
//     'hash': {'a':1, 'b':2},
//     'date': new Date(),
//     'oid': new ObjectID(),
//     'binary': new Binary(new Buffer("hello")),
//     'int': 42,
//     'float': 33.3333,
//     'regexp': /regexp/,
//     'boolean': true,
//     'long': Long.fromNumber(100),
//     'where': new Code('this.a > i', {i:1}),
//     'dbref': new DBRef('namespace', new ObjectID(), 'integration_tests_'),
//     'minkey': new MinKey(),
//     'maxkey': new MaxKey()
//   }
//
//   // Let's serialize it
//   var data = BSONSE.BSON.serialize(motherOfAllDocuments, true, true, false);
//   // Build a typed array
//   var arr = new Uint8Array(new ArrayBuffer(data.length));
//   // Iterate over all the fields and copy
//   for(var i = 0; i < data.length; i++) {
//     arr[i] = data[i]
//   }
//
//   // Deserialize the object
//   var object = BSONDE.BSON.deserialize(arr);
//   // Asserts
//   test.equal(motherOfAllDocuments.string, object.string);
//   test.deepEqual(motherOfAllDocuments.array, object.array);
//   test.deepEqual(motherOfAllDocuments.date, object.date);
//   test.deepEqual(motherOfAllDocuments.oid.toHexString(), object.oid.toHexString());
//   test.deepEqual(motherOfAllDocuments.binary.length(), object.binary.length());
//   // Assert the values of the binary
//   for(var i = 0; i < motherOfAllDocuments.binary.length(); i++) {
//     test.equal(motherOfAllDocuments.binary.value[i], object.binary[i]);
//   }
//   test.deepEqual(motherOfAllDocuments.int, object.int);
//   test.deepEqual(motherOfAllDocuments.float, object.float);
//   test.deepEqual(motherOfAllDocuments.regexp, object.regexp);
//   test.deepEqual(motherOfAllDocuments.boolean, object.boolean);
//   test.deepEqual(motherOfAllDocuments.long.toNumber(), object.long);
//   test.deepEqual(motherOfAllDocuments.where, object.where);
//   test.deepEqual(motherOfAllDocuments.dbref.oid.toHexString(), object.dbref.oid.toHexString());
//   test.deepEqual(motherOfAllDocuments.dbref.namespace, object.dbref.namespace);
//   test.deepEqual(motherOfAllDocuments.dbref.db, object.dbref.db);
//   test.deepEqual(motherOfAllDocuments.minkey, object.minkey);
//   test.deepEqual(motherOfAllDocuments.maxkey, object.maxkey);
//   test.done();
// }

/**
 * Should make sure that arrays by themselves can be either be properly
 * serialized and deserialized, or that serializing throws an error
 */
exports.shouldCorrectlyDeserializeArray = function(test) {
  var testArray = [1,2,3];
  var data = null;

  console.dir(BSONSE)

  try {
    data = BSONSE.BSON.serialize(testArray, true, false, false);
    test.ok(false);
  } catch(e) {
    test.done();
  }
};

/**
 * @ignore
 */
exports.shouldCorrectlySerializeUsingTypedArray = function(test) {
  var motherOfAllDocuments = {
    'string': 'hello',
    'array': [1,2,3],
    'hash': {'a':1, 'b':2},
    'date': new Date(),
    'oid': new ObjectID(),
    'binary': new Binary(new Buffer("hello")),
    'int': 42,
    'float': 33.3333,
    'regexp': /regexp/,
    'boolean': true,
    'long': Long.fromNumber(100),
    'where': new Code('this.a > i', {i:1}),
    'dbref': new DBRef('namespace', new ObjectID(), 'integration_tests_'),
    'minkey': new MinKey(),
    'maxkey': new MaxKey()
  }

  // Let's serialize it
  var data = BSONSE.BSON.serialize(motherOfAllDocuments, true, false, false);
  // And deserialize it again
  var object = BSONSE.BSON.deserialize(data);
  // Asserts
  test.equal(motherOfAllDocuments.string, object.string);
  test.deepEqual(motherOfAllDocuments.array, object.array);
  test.deepEqual(motherOfAllDocuments.date, object.date);
  test.deepEqual(motherOfAllDocuments.oid.toHexString(), object.oid.toHexString());
  test.deepEqual(motherOfAllDocuments.binary.length(), object.binary.length());
  // Assert the values of the binary
  for(var i = 0; i < motherOfAllDocuments.binary.length(); i++) {
    test.equal(motherOfAllDocuments.binary.value[i], object.binary[i]);
  }
  test.deepEqual(motherOfAllDocuments.int, object.int);
  test.deepEqual(motherOfAllDocuments.float, object.float);
  test.deepEqual(motherOfAllDocuments.regexp, object.regexp);
  test.deepEqual(motherOfAllDocuments.boolean, object.boolean);
  test.deepEqual(motherOfAllDocuments.long.toNumber(), object.long.toNumber());
  test.deepEqual(motherOfAllDocuments.where, object.where);
  test.deepEqual(motherOfAllDocuments.dbref.oid.toHexString(), object.dbref.oid.toHexString());
  test.deepEqual(motherOfAllDocuments.dbref.namespace, object.dbref.namespace);
  test.deepEqual(motherOfAllDocuments.dbref.db, object.dbref.db);
  test.deepEqual(motherOfAllDocuments.minkey, object.minkey);
  test.deepEqual(motherOfAllDocuments.maxkey, object.maxkey);
  test.done();
}

/**
 * Retrieve the server information for the current
 * instance of the db client
 *
 * @ignore
 */
exports.noGlobalsLeaked = function(test) {
  var leaks = gleak.detectNew();
  test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', '));
  test.done();
}<commit_msg>Added C++ extension test aswell #46<commit_after>var mongodb = require('../../lib/bson').pure();

var testCase = require('nodeunit').testCase,
  mongoO = require('../../lib/bson').pure(),
  mongoC = require('../../lib/bson').native(),
  debug = require('util').debug,
  inspect = require('util').inspect,
  Buffer = require('buffer').Buffer,
  gleak = require('../../tools/gleak'),
  fs = require('fs'),
  BSON = mongoO.BSON,
  Code = mongoO.Code,
  Binary = mongoO.Binary,
  Timestamp = mongoO.Timestamp,
  Long = mongoO.Long,
  MongoReply = mongoO.MongoReply,
  ObjectID = mongoO.ObjectID,
  Symbol = mongoO.Symbol,
  DBRef = mongoO.DBRef,
  Double = mongoO.Double,
  MinKey = mongoO.MinKey,
  MaxKey = mongoO.MaxKey,
  BinaryParser = mongoO.BinaryParser,
  utils = require('./tools/utils');

var bsonC = new mongoC.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]);

var BSONSE = mongodb,
  BSONDE = mongodb;

// for tests
BSONDE.BSON_BINARY_SUBTYPE_DEFAULT = 0;
BSONDE.BSON_BINARY_SUBTYPE_FUNCTION = 1;
BSONDE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
BSONDE.BSON_BINARY_SUBTYPE_UUID = 3;
BSONDE.BSON_BINARY_SUBTYPE_MD5 = 4;
BSONDE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;

BSONSE.BSON_BINARY_SUBTYPE_DEFAULT = 0;
BSONSE.BSON_BINARY_SUBTYPE_FUNCTION = 1;
BSONSE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
BSONSE.BSON_BINARY_SUBTYPE_UUID = 3;
BSONSE.BSON_BINARY_SUBTYPE_MD5 = 4;
BSONSE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;

var hexStringToBinary = function(string) {
  var numberofValues = string.length / 2;
  var array = "";

  for(var i = 0; i < numberofValues; i++) {
    array += String.fromCharCode(parseInt(string[i*2] + string[i*2 + 1], 16));
  }
  return array;
}

var assertBuffersEqual = function(test, buffer1, buffer2) {
  if(buffer1.length != buffer2.length) test.fail("Buffers do not have the same length", buffer1, buffer2);

  for(var i = 0; i < buffer1.length; i++) {
    test.equal(buffer1[i], buffer2[i]);
  }
}

/**
 * Module for parsing an ISO 8601 formatted string into a Date object.
 */
var ISODate = function (string) {
  var match;

 if (typeof string.getTime === "function")
   return string;
 else if (match = string.match(/^(\d{4})(-(\d{2})(-(\d{2})(T(\d{2}):(\d{2})(:(\d{2})(\.(\d+))?)?(Z|((\+|-)(\d{2}):(\d{2}))))?)?)?$/)) {
   var date = new Date();
   date.setUTCFullYear(Number(match[1]));
   date.setUTCMonth(Number(match[3]) - 1 || 0);
   date.setUTCDate(Number(match[5]) || 0);
   date.setUTCHours(Number(match[7]) || 0);
   date.setUTCMinutes(Number(match[8]) || 0);
   date.setUTCSeconds(Number(match[10]) || 0);
   date.setUTCMilliseconds(Number("." + match[12]) * 1000 || 0);

   if (match[13] && match[13] !== "Z") {
     var h = Number(match[16]) || 0,
         m = Number(match[17]) || 0;

     h *= 3600000;
     m *= 60000;

     var offset = h + m;
     if (match[15] == "+")
       offset = -offset;

     date = new Date(date.valueOf() + offset);
   }

   return date;
 } else
   throw new Error("Invalid ISO 8601 date given.", __filename);
};

var _Uint8Array = null;

/**
 * Retrieve the server information for the current
 * instance of the db client
 *
 * @ignore
 */
exports.setUp = function(callback) {
  _Uint8Array = global.Uint8Array;
  delete global['Uint8Array'];
  callback();
}

/**
 * Retrieve the server information for the current
 * instance of the db client
 *
 * @ignore
 */
exports.tearDown = function(callback) {
  global['Uint8Array'] = _Uint8Array;
  callback();
}

// /**
//  * @ignore
//  */
// exports.shouldCorrectlyDeserializeUsingTypedArray = function(test) {
//   var motherOfAllDocuments = {
//     'string': '客家话',
//     'array': [1,2,3],
//     'hash': {'a':1, 'b':2},
//     'date': new Date(),
//     'oid': new ObjectID(),
//     'binary': new Binary(new Buffer("hello")),
//     'int': 42,
//     'float': 33.3333,
//     'regexp': /regexp/,
//     'boolean': true,
//     'long': Long.fromNumber(100),
//     'where': new Code('this.a > i', {i:1}),
//     'dbref': new DBRef('namespace', new ObjectID(), 'integration_tests_'),
//     'minkey': new MinKey(),
//     'maxkey': new MaxKey()
//   }
//
//   // Let's serialize it
//   var data = BSONSE.BSON.serialize(motherOfAllDocuments, true, true, false);
//   // Build a typed array
//   var arr = new Uint8Array(new ArrayBuffer(data.length));
//   // Iterate over all the fields and copy
//   for(var i = 0; i < data.length; i++) {
//     arr[i] = data[i]
//   }
//
//   // Deserialize the object
//   var object = BSONDE.BSON.deserialize(arr);
//   // Asserts
//   test.equal(motherOfAllDocuments.string, object.string);
//   test.deepEqual(motherOfAllDocuments.array, object.array);
//   test.deepEqual(motherOfAllDocuments.date, object.date);
//   test.deepEqual(motherOfAllDocuments.oid.toHexString(), object.oid.toHexString());
//   test.deepEqual(motherOfAllDocuments.binary.length(), object.binary.length());
//   // Assert the values of the binary
//   for(var i = 0; i < motherOfAllDocuments.binary.length(); i++) {
//     test.equal(motherOfAllDocuments.binary.value[i], object.binary[i]);
//   }
//   test.deepEqual(motherOfAllDocuments.int, object.int);
//   test.deepEqual(motherOfAllDocuments.float, object.float);
//   test.deepEqual(motherOfAllDocuments.regexp, object.regexp);
//   test.deepEqual(motherOfAllDocuments.boolean, object.boolean);
//   test.deepEqual(motherOfAllDocuments.long.toNumber(), object.long);
//   test.deepEqual(motherOfAllDocuments.where, object.where);
//   test.deepEqual(motherOfAllDocuments.dbref.oid.toHexString(), object.dbref.oid.toHexString());
//   test.deepEqual(motherOfAllDocuments.dbref.namespace, object.dbref.namespace);
//   test.deepEqual(motherOfAllDocuments.dbref.db, object.dbref.db);
//   test.deepEqual(motherOfAllDocuments.minkey, object.minkey);
//   test.deepEqual(motherOfAllDocuments.maxkey, object.maxkey);
//   test.done();
// }

/**
 * Should make sure that arrays by themselves can be either be properly
 * serialized and deserialized, or that serializing throws an error
 */
exports.shouldCorrectlyDeserializeArray = function(test) {
  var testArray = [1,2,3];
  var data = null;

  try {
    data = BSONSE.BSON.serialize(testArray, true, false, false);
    test.ok(false);
  } catch(e) {
  }

  try {
    data = bsonC.serialize(testArray, true, false, false);
    test.ok(false);
  } catch(e) {
    test.done();
  }
};

/**
 * @ignore
 */
exports.shouldCorrectlySerializeUsingTypedArray = function(test) {
  var motherOfAllDocuments = {
    'string': 'hello',
    'array': [1,2,3],
    'hash': {'a':1, 'b':2},
    'date': new Date(),
    'oid': new ObjectID(),
    'binary': new Binary(new Buffer("hello")),
    'int': 42,
    'float': 33.3333,
    'regexp': /regexp/,
    'boolean': true,
    'long': Long.fromNumber(100),
    'where': new Code('this.a > i', {i:1}),
    'dbref': new DBRef('namespace', new ObjectID(), 'integration_tests_'),
    'minkey': new MinKey(),
    'maxkey': new MaxKey()
  }

  // Let's serialize it
  var data = BSONSE.BSON.serialize(motherOfAllDocuments, true, false, false);
  // And deserialize it again
  var object = BSONSE.BSON.deserialize(data);
  // Asserts
  test.equal(motherOfAllDocuments.string, object.string);
  test.deepEqual(motherOfAllDocuments.array, object.array);
  test.deepEqual(motherOfAllDocuments.date, object.date);
  test.deepEqual(motherOfAllDocuments.oid.toHexString(), object.oid.toHexString());
  test.deepEqual(motherOfAllDocuments.binary.length(), object.binary.length());
  // Assert the values of the binary
  for(var i = 0; i < motherOfAllDocuments.binary.length(); i++) {
    test.equal(motherOfAllDocuments.binary.value[i], object.binary[i]);
  }
  test.deepEqual(motherOfAllDocuments.int, object.int);
  test.deepEqual(motherOfAllDocuments.float, object.float);
  test.deepEqual(motherOfAllDocuments.regexp, object.regexp);
  test.deepEqual(motherOfAllDocuments.boolean, object.boolean);
  test.deepEqual(motherOfAllDocuments.long.toNumber(), object.long.toNumber());
  test.deepEqual(motherOfAllDocuments.where, object.where);
  test.deepEqual(motherOfAllDocuments.dbref.oid.toHexString(), object.dbref.oid.toHexString());
  test.deepEqual(motherOfAllDocuments.dbref.namespace, object.dbref.namespace);
  test.deepEqual(motherOfAllDocuments.dbref.db, object.dbref.db);
  test.deepEqual(motherOfAllDocuments.minkey, object.minkey);
  test.deepEqual(motherOfAllDocuments.maxkey, object.maxkey);
  test.done();
}

/**
 * Retrieve the server information for the current
 * instance of the db client
 *
 * @ignore
 */
exports.noGlobalsLeaked = function(test) {
  var leaks = gleak.detectNew();
  test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', '));
  test.done();
}<|endoftext|>


<commit_before>var passport = require('passport');
var SamlStrategy = require('passport-saml').Strategy;
var fs = require('fs');
var path = require('path');
var config = require('../../config/environment');
var User = require('../../api/user/user.model');

passport.serializeUser(function (user, done) {
  console.log('Serialize User');
  console.log(user);
  done(null, user);
});

passport.deserializeUser(function (user, done) {
  done(null, user);
});

var samlStrategy = new SamlStrategy({
  // URL that goes from the Identity Provider -> Service Provider
  callbackUrl: 'https://127.0.0.1:4343/auth/cwl/login/callback',
  // URL that goes from the Service Provider -> Identity Provider
  // entryPoint: 'https://authentication.ubc.ca',
  // entryPoint: 'https://authentication.stg.id.ubc.ca/idp/profile/SAML2/Redirect/SSO',
  entryPoint: 'https://idp.testshib.org/idp/profile/SAML2/Redirect/SSO',
  // Usually specified as `/shibboleth` from site root
  issuer: 'https://comped.cs.ubc.ca',
  identifierFormat: null,
  // Service Provider private key
  decryptionPvk: fs.readFileSync(path.join(__dirname, '/../../cert/key.pem'), 'utf8'),
  // Service Provider Certificate
  privateCert: fs.readFileSync(path.join(__dirname, '/../../cert/key.pem'), 'utf8'),
  // Identity Provider's public key
  cert: fs.readFileSync(path.join(__dirname, '/../../cert/idp_cert.pem'), 'utf8'),
  validateInResponseTo: false,
  disableRequestedAuthnContext: true
}, function (profile, done) {
  console.log(profile);
  return done(null,
    {
      id: 12093810238,
      email: 'test@example.com',
      displayName: 'Test Account',
      firstName: 'Test',
      lastName: 'Account'
    });
  /* User.findOne({
    email: profile.email.toLowerCase()
  }, function (err, user) {
    if (err) return done(err);

    if (!user) {
      return done(null, false, { message: 'This student number is not registered.' });
    }
    if (!user.authenticate(password)) {
      return done(null, false, { message: 'This password is not correct.' });
    }
    return done(null, user);
  });*/
});

passport.use(samlStrategy);

module.exports = samlStrategy;
<commit_msg>CWL staging<commit_after>var passport = require('passport');
var SamlStrategy = require('passport-saml').Strategy;
var fs = require('fs');
var path = require('path');
var config = require('../../config/environment');
var User = require('../../api/user/user.model');

passport.serializeUser(function (user, done) {
  console.log('Serialize User');
  console.log(user);
  done(null, user);
});

passport.deserializeUser(function (user, done) {
  done(null, user);
});

var samlStrategy = new SamlStrategy({
  // URL that goes from the Identity Provider -> Service Provider
  callbackUrl: 'https://127.0.0.1:4343/auth/cwl/login/callback',
  //callbackUrl: 'https://comped.cs.ubc.ca/auth/cwl/login/callback',
  // URL that goes from the Service Provider -> Identity Provider
  // entryPoint: 'https://authentication.ubc.ca',
  entryPoint: 'https://authentication.stg.id.ubc.ca/idp/profile/SAML2/Redirect/SSO',
  //entryPoint: 'https://idp.testshib.org/idp/profile/SAML2/Redirect/SSO',
  // Usually specified as `/shibboleth` from site root
  issuer: 'https://comped.cs.ubc.ca',
  identifierFormat: null,
  // Service Provider private key
  decryptionPvk: fs.readFileSync(path.join(__dirname, '/../../cert/key.pem'), 'utf8'),
  // Service Provider Certificate
  privateCert: fs.readFileSync(path.join(__dirname, '/../../cert/key.pem'), 'utf8'),
  // Identity Provider's public key
  cert: fs.readFileSync(path.join(__dirname, '/../../cert/idp_cert.pem'), 'utf8'),
  validateInResponseTo: false,
  disableRequestedAuthnContext: true
}, function (profile, done) {
  console.log(profile);
  return done(null,
    {
      id: 12093810238,
      email: 'test@example.com',
      displayName: 'Test Account',
      firstName: 'Test',
      lastName: 'Account'
    });
  /* User.findOne({
    email: profile.email.toLowerCase()
  }, function (err, user) {
    if (err) return done(err);

    if (!user) {
      return done(null, false, { message: 'This student number is not registered.' });
    }
    if (!user.authenticate(password)) {
      return done(null, false, { message: 'This password is not correct.' });
    }
    return done(null, user);
  });*/
});

passport.use(samlStrategy);

module.exports = samlStrategy;
<|endoftext|>


<commit_before>const {slugify} = require('transliteration');
class Book{
	constructor(data){
		this.id = data.id;
		this.name = data.name;
		this.slug = data.slug;

		this.volumes = {};
		Object.keys(data.volumes).forEach((v) => {
			volumes[v] = new Volume(this, v, data.volumes[v]);
		});
	}

	createSaveData(){
		let data = {};
		Object.keys(this).forEach((v) => {딩
			data[v] = this[v];
		});
		data.volumes = {};
		Object.keys(this.volumes).forEach((v) => {
			data.volumes[v] = this.volumes[v].createSaveData();
		});

		return data;
	}

	save(){
		return db
		.collection('book')
		.findOneAndUpdate({
			id: this.id
		}, {
			$set: this.createSaveData()
		});
	}

	static createBook(name, volumes){
		return new Promise((reject, resolve) => {
			db
			.collection('settings')
			.findOne({name: 'last-item'})
			.then((result) => {
				return db
				.collection('settings')
				.findOneAndUpdate({
					name: 'last-item'
				}, {
					$set: {
						value: result.value + 1
					}
				});
			}).then(() => {
				let book = new Book({
					id: result.value,
					name,
					slug: slugify(name),
					volumes
				});

				book.save().then(() => {
					resolve(book);
				}),catch((err) => {
					reject(err);
				});
			}).catch((err) => {
				reject(err);
			});
		});
	}

	static getById(id){

	}

	static getBySlug(slug){

	}
}

module.exports = Book;
<commit_msg>fix typo of 4235606<commit_after>const {slugify} = require('transliteration');
class Book{
	constructor(data){
		this.id = data.id;
		this.name = data.name;
		this.slug = data.slug;

		this.volumes = {};
		Object.keys(data.volumes).forEach((v) => {
			volumes[v] = new Volume(this, v, data.volumes[v]);
		});
	}

	createSaveData(){
		let data = {};
		Object.keys(this).forEach((v) => {
			data[v] = this[v];
		});
		data.volumes = {};
		Object.keys(this.volumes).forEach((v) => {
			data.volumes[v] = this.volumes[v].createSaveData();
		});

		return data;
	}

	save(){
		return db
		.collection('book')
		.findOneAndUpdate({
			id: this.id
		}, {
			$set: this.createSaveData()
		});
	}

	static createBook(name, volumes){
		return new Promise((reject, resolve) => {
			db
			.collection('settings')
			.findOne({name: 'last-item'})
			.then((result) => {
				return db
				.collection('settings')
				.findOneAndUpdate({
					name: 'last-item'
				}, {
					$set: {
						value: result.value + 1
					}
				});
			}).then(() => {
				let book = new Book({
					id: result.value,
					name,
					slug: slugify(name),
					volumes
				});

				book.save().then(() => {
					resolve(book);
				}),catch((err) => {
					reject(err);
				});
			}).catch((err) => {
				reject(err);
			});
		});
	}

	static getById(id){

	}

	static getBySlug(slug){

	}
}

module.exports = Book;
<|endoftext|>