<commit_before>/* global goog, lime, obacht */
/* jshint strict: false, devel:true */

goog.provide('obacht.Collision');
goog.require('obacht.themes');
//goog.require('obacht.Game');

/**
 * Collision Detector
 *
 * @constructor
 */
obacht.Collision = function (player, trap) {
    "use strict";
    this.object1pos = player.character.getPosition();
    this.object2pos = trap.character.getPosition();

    /*Size Object1*/
    this.obj1w = player.character.getSize().width;
    this.obj1h = player.character.getSize().height;

    /*Left Top Corner Player*/
    this.obj1x = Math.round(this.object1pos.x / 10) * 10 - (this.obj1w / 2);
    this.obj1y = Math.round(this.object1pos.y / 10) * 10 - (this.obj1h / 2);

    /*Size Object2*/
    this.obj2w = trap.character.getSize().width;
    this.obj2h = trap.character.getSize().height;

    /*Left Top Corner Trap*/
    this.obj2x = Math.round(this.object2pos.x / 10) * 10 - (this.obj2w / 2);
    this.obj2y = Math.round(this.object2pos.y / 10) * 10 - (this.obj2h / 2);

    /*Request BoundingBoxes | Name = BoundingBoxes Object 2*/
    this.bbobj1 = player.boundingBoxes;
    this.bbobj2 = trap.boundingBoxes;

    var state = false;
    var i = 0;
    while (i < trap.boundingBoxes.length) {

        //New Player i==0
        this.obj1x = this.obj1x - this.bbobj1[0].x;
        this.obj1y = this.obj1y + this.bbobj1[0].y;

        this.obj1w = this.bbobj1[0].width;
        this.obj1h = this.bbobj1[0].height;

        //New Trap
        this.obj2x = this.obj2x - this.bbobj2[i].x;
        this.obj2y = this.obj2y + this.bbobj2[i].y;

        this.obj2w = this.bbobj2[i].width;
        this.obj2h = this.bbobj2[i].height;

        if (this.obj1x < this.obj2x + this.obj2w  &&
            this.obj2x < this.obj1x + this.obj1w  &&
            this.obj1y < this.obj2y + this.obj2h &&
            this.obj2y < this.obj1y + this.obj1h === true){
        state=true;
        }

        //console.log(i);
        i = i + 1;
    }
};

obacht.Collision.prototype = {

    rect: function () {
        "use strict";
        return this.state;

    }
};
<commit_msg>Bugfix  Collision.js (Still without crouch)<commit_after>/* global goog, lime, obacht */
/* jshint strict: false, devel:true */

goog.provide('obacht.Collision');
goog.require('obacht.themes');
//goog.require('obacht.Game');

/**
 * Collision Detector
 *
 * @constructor
 */
obacht.Collision = function (player, trap) {
    "use strict";
    this.object1pos = player.character.getPosition();
    this.object2pos = trap.character.getPosition();

    /*Size Object1*/
    this.obj1w = player.character.getSize().width;
    this.obj1h = player.character.getSize().height;

    /*Left Top Corner Player*/
    this.obj1x = Math.round(this.object1pos.x / 10) * 10 + (this.obj1w / 2);
    this.obj1y = Math.round(this.object1pos.y / 10) * 10 - (this.obj1h / 2);

    /*Size Object2*/
    this.obj2w = trap.character.getSize().width;
    this.obj2h = trap.character.getSize().height;

    /*Left Top Corner Trap*/
    this.obj2x = Math.round(this.object2pos.x / 10) * 10 + (this.obj2w / 2);
    this.obj2y = Math.round(this.object2pos.y / 10) * 10 - (this.obj2h / 2);

    /*Request BoundingBoxes | Name = BoundingBoxes Object 2*/
    this.bbobj1 = player.boundingBoxes;
    this.bbobj2 = trap.boundingBoxes;

    var state = false;
    var i = 0;
    while (i < trap.boundingBoxes.length) {

        //New Player i==0
        this.obj1x = this.obj1x - this.bbobj1[0].x;
        this.obj1y = this.obj1y + this.bbobj1[0].y;

        this.obj1w = this.bbobj1[0].width;
        this.obj1h = this.bbobj1[0].height;

        //New Trap
        this.obj2x = this.obj2x - this.bbobj2[i].x;
        this.obj2y = this.obj2y + this.bbobj2[i].y;

        this.obj2w = this.bbobj2[i].width;
        this.obj2h = this.bbobj2[i].height;

        if (this.obj1x < this.obj2x + this.obj2w  &&
            this.obj2x < this.obj1x + this.obj1w  &&
            this.obj1y < this.obj2y + this.obj2h &&
            this.obj2y < this.obj1y + this.obj1h === true){
        state=true;
        }

        //console.log(i);
        i = i + 1;
    }
};

obacht.Collision.prototype = {

    rect: function () {
        "use strict";
        return this.state;

    }
};
<|endoftext|>


<commit_before>var setupAvatar = require('./avatar');
var voxelEngine = require('../voxelEngine');
var skin = require('minecraft-skin');

module.exports = {
  init: function(socket) {
    var self = this;
    this.lerpPercent = 0.1;
    self.playerId = socket.id;
    this.others = {};

    function sendState() {
      if (!socket.connected) {
        return;
      }
      var player = voxelEngine.engine.controls.target();
      var state = {
        position: player.yaw.position,
        rotation: {
          y: player.yaw.rotation.y,
          x: player.pitch.rotation.x
        }
      };
      socket.emit('state', state);
    }

    voxelEngine.engine.controls.on('data', function(state) {
      var interacting = false;
      Object.keys(state).map(function(control) {
        if (state[control] > 0) {
          interacting = true;
        }
      });

      if (interacting) {
        sendState();
      }
    });

    // setTimeout is because three.js seems to throw errors if you add stuff too soon
    setTimeout(function() {
      socket.on('update', function(updates) {
        Object.keys(updates.positions).map(function(player) {
          var update = updates.positions[player];
          if (player === self.playerId) {
            return self.onServerUpdate(update); // local player
          }
          self.updatePlayerPosition(player, update); // other players
        })
      })
    }, 1000)

    socket.on('leave', function(id) {
      if (!self.others[id]) {
        return;
      }
      self.engine.scene.remove(self.others[id].mesh);
      delete self.others[id];
    });

    setupAvatar();
  },
  onServerUpdate: function(update) {
    // TODO use server sent location
  },
  updatePlayerPosition: function(id, update) {
    function scale( x, fromLow, fromHigh, toLow, toHigh ) {
      return ( x - fromLow ) * ( toHigh - toLow ) / ( fromHigh - fromLow ) + toLow;
    }

    var pos = update.position;
    var player = this.others[id];
    if (!player) {
      var playerSkin = skin(voxelEngine.engine.THREE, 'assets/avatars/player.png', {
        scale: new voxelEngine.engine.THREE.Vector3(0.04, 0.04, 0.04)
      });
      var playerMesh = playerSkin.mesh;
      this.others[id] = playerSkin;
      playerMesh.children[0].position.y = 10;
      voxelEngine.engine.scene.add(playerMesh);
    }

    var playerSkin = this.others[id];
    var playerMesh = playerSkin.mesh;
    playerMesh.position.copy(playerMesh.position.lerp(pos, this.lerpPercent));

    playerMesh.children[0].rotation.y = update.rotation.y + (Math.PI / 2);
    playerSkin.head.rotation.z = scale(update.rotation.x, -1.5, 1.5, -0.75, 0.75);
  }
};
<commit_msg>fixing a bug in playerSync<commit_after>var setupAvatar = require('./avatar');
var voxelEngine = require('../voxelEngine');
var skin = require('minecraft-skin');

module.exports = {
  init: function(socket) {
    var self = this;
    this.lerpPercent = 0.1;
    self.playerId = socket.id;
    this.others = {};

    function sendState() {
      if (!socket.connected) {
        return;
      }
      var player = voxelEngine.engine.controls.target();
      var state = {
        position: player.yaw.position,
        rotation: {
          y: player.yaw.rotation.y,
          x: player.pitch.rotation.x
        }
      };
      socket.emit('state', state);
    }

    voxelEngine.engine.controls.on('data', function(state) {
      var interacting = false;
      Object.keys(state).map(function(control) {
        if (state[control] > 0) {
          interacting = true;
        }
      });

      if (interacting) {
        sendState();
      }
    });

    // setTimeout is because three.js seems to throw errors if you add stuff too soon
    setTimeout(function() {
      socket.on('update', function(updates) {
        Object.keys(updates.positions).map(function(player) {
          var update = updates.positions[player];
          if (player === self.playerId) {
            return self.onServerUpdate(update); // local player
          }
          self.updatePlayerPosition(player, update); // other players
        })
      })
    }, 1000)

    socket.on('leave', function(id) {
      if (!self.others[id]) {
        return;
      }
      voxelEngine.engine.scene.remove(self.others[id].mesh);
      delete self.others[id];
    });

    setupAvatar();
  },
  onServerUpdate: function(update) {
    // TODO use server sent location
  },
  updatePlayerPosition: function(id, update) {
    function scale( x, fromLow, fromHigh, toLow, toHigh ) {
      return ( x - fromLow ) * ( toHigh - toLow ) / ( fromHigh - fromLow ) + toLow;
    }

    var pos = update.position;
    var player = this.others[id];
    if (!player) {
      var playerSkin = skin(voxelEngine.engine.THREE, 'assets/avatars/player.png', {
        scale: new voxelEngine.engine.THREE.Vector3(0.04, 0.04, 0.04)
      });
      var playerMesh = playerSkin.mesh;
      this.others[id] = playerSkin;
      playerMesh.children[0].position.y = 10;
      voxelEngine.engine.scene.add(playerMesh);
    }

    var playerSkin = this.others[id];
    var playerMesh = playerSkin.mesh;
    playerMesh.position.copy(playerMesh.position.lerp(pos, this.lerpPercent));

    playerMesh.children[0].rotation.y = update.rotation.y + (Math.PI / 2);
    playerSkin.head.rotation.z = scale(update.rotation.x, -1.5, 1.5, -0.75, 0.75);
  }
};
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import 'react-mdl/extra/css/material.deep_orange-orange.min.css';
import 'react-mdl-extra/dist/react-mdl-extra.min.css';
import 'normalize.css/normalize.css';
import { NavigationBar, Footer, ImageGallery } from '../components';
import Background from '../assets/main_background.png';
import '../styles/image-gallery.css';
import styles from '../styles/MainScene.scss';

export default class App extends Component {
  render() {
    const images = [{
        original: `${Background}`,
        thumbnail: '',
      }, {
        original: `${Background}`,
        thumbnail: ''
      },
    ];

    return (

        <NavigationBar />

          <ImageGallery
            showFullscreenButton={false}
            showThumbnails={false}
            showPlayButton={false}
            items={images}
            slideInterval={2000}
          />

              SLib.io is a C++ cross-platform framework built for speed.

              MAKE IT FASTER

              <svg width='200px' height='40px' viewBox='0 0 200 37'>
                <g strokeWidth='2' fill='none' fillRule='evenodd'>
                  <polygon stroke='#FBAF3F' points='199 36 1 36 1 1 182 1' />
                </g>
              </svg>

GETTING STARTED

              <svg width='200px' height='40px' viewBox='0 0 200 37'>
                <g strokeWidth='2' fill='none' fillRule='evenodd'>
                  <polygon fill='#00A79D' points='0 0 18.5209434 37 200 37 200 0' />
                </g>
              </svg>

SHOWCASE

    );
  }
}
<commit_msg>update<commit_after>import React, { Component } from 'react';
import 'react-mdl/extra/css/material.deep_orange-orange.min.css';
import 'react-mdl-extra/dist/react-mdl-extra.min.css';
import 'normalize.css/normalize.css';
import { NavigationBar, Footer, ImageGallery } from '../components';
import Background from '../assets/main_background.png';
import '../styles/image-gallery.css';
import styles from '../styles/MainScene.scss';

export default class App extends Component {
  render() {
    const images = [{
        original: `${Background}`,
        thumbnail: '',
      }, {
        original: `${Background}`,
        thumbnail: ''
      },
    ];

    return (

        <NavigationBar />

          <ImageGallery
            showFullscreenButton={false}
            showThumbnails={false}
            showPlayButton={false}
            items={images}
            slideInterval={2000}
          />

              SLib is a C++ cross-platform framework built for speed.

              MAKE IT FASTER

              <svg width='200px' height='40px' viewBox='0 0 200 37'>
                <g strokeWidth='2' fill='none' fillRule='evenodd'>
                  <polygon stroke='#FBAF3F' points='199 36 1 36 1 1 182 1' />
                </g>
              </svg>

GETTING STARTED

              <svg width='200px' height='40px' viewBox='0 0 200 37'>
                <g strokeWidth='2' fill='none' fillRule='evenodd'>
                  <polygon fill='#00A79D' points='0 0 18.5209434 37 200 37 200 0' />
                </g>
              </svg>

SHOWCASE

    );
  }
}
<|endoftext|>


<commit_before>Template.Collection.created = function() {
    var self = this;
    self._selected = new ReactiveVar();
    self._loading = new ReactiveVar();
    self._progress = new ReactiveVar();
    self.load = function(song, action) {
        options = {};
        if(!_.isEqual(action, undefined)) {
            self._collection = self.data.collection;
            if(_.isEqual(action, true)) {
                _.extend(options, {
                    action: 'download',
                    progress: function(data, n, total) {
                        self._progress.set({ value: n, max: total });
                    }
                });
            }
        }
        self._loading.set(song);
        AudioPlayer.load(song, function() {
            self._loading.set(null);
            self._progress.set(null);
        }, function(error) {
            UIkit.notify(error.message, 'warning');
        }, options);
    }
    self.loadNext = function() {
        var song = Session.get('currentSong');
        if(!song) {
        } else {
            self.load(self.findNext(song, 1));
        }
    },
    self.loadPrevious = function() {
        var song = Session.get('currentSong');
        if(!song) {
        } else {
            self.load(self.findNext(song, -1));
        }
    },
    self.selectNext = function() {
        var song = self._selected.get();
        if(!song) {
        } else {
            self._selected.set(self.findNext(song, 1));
        }
    }
    self.selectPrevious = function() {
        var song = self._selected.get();
        if(!song) {
        } else {
            self._selected.set(self.findNext(song, -1));
        }
    }
    self.findNext = function(song, order, sort) {
        if(!order) order = 1;
        var query = {}, sort = _.extend({}, sort ? sort : self.data.sort);
        var index = 0, lastIndex = _.size(sort) -1;
        var field;
        for(field in sort) {
            var value = song[field];
            var operator = sort[field] == order ? '$gt' : '$lt';
            if(!value) {
                continue; // TODO
            } else if(++index < lastIndex) {
                query[field] = value;
            } else {
                query[field] = {};
                query[field][operator] = value;
            }
        }
        var collection = null;
        if(song != self._selected.get()) {
            collection = self._collection;
        } else {
            collection = self.data.collection;
            _.extend(query, self.searchQuery());
        }
        var nextSong = collection.findOne(query, { sort: _.object(_.map(self.data.sort, function(value, key) {
            return [key, value * order];
        })), fields: self.data.fields });
        if(!nextSong) {
            delete sort[field];
            nextSong = self.findNext(song, order, sort);
        }
        return nextSong;
    }
    self.searchQuery = function() {
        var query = {};
        var search = Session.get('search');
        if(typeof search == 'string') {
            var regexp = new RegExp(search.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'), 'i');
            _.extend(query, { '$or': [{ 'artist': regexp }, { 'album': regexp }, { 'title': regexp }]});
        }
        return query;
    }
    _.extend(AudioPlayer, { loadNext: self.loadNext, loadPrevious: self.loadPrevious });
}

Template.Collection.rendered = function() {
    var self = this;
    self.$('table').focus();
}

Template.Collection.helpers({
    'model': function() {
        var self = Template.instance();
        return this.collection.find(self.searchQuery(), { fields: this.fields, sort: this.sort });
    },
    'rowAttributes': function() {
        var self = Template.instance();
        var attributes = {};
        if(!AudioPlayer.canPlay(this)) {
            _.extend(attributes, { disabled: 'disabled' });
        }
        if(_.isEqual(self._selected.get(), this)) {
            _.extend(attributes, { selected: 'selected' });
        }
        if(_.isEqual(self._loading.get(), this)) {
            _.extend(attributes, { role: 'loading' });
        }
        if(_.isEqual(Session.get('currentSong'), this)) {
            _.extend(attributes, { class: 'uk-active' });
        }
        return attributes;
    },
    'progress': function() {
        var self = Template.instance();
        var progress = self._progress.get();
        if(_.isEqual(self._loading.get(), this) && progress) {
            return progress;
        }

    },
    'search': function() {
        var self = Template.instance();
        return Session.get('search');
    }
});

Template.Collection.events({
    'input aside input[type="search"]': function(event, template) {
        var self = template;
        Session.set('search', event.target.value);
    },
    'change table thead tr th input[type="checkbox"]': function(event, template) {
        var self = template;
        var checked = self.$(event.target).prop('checked');
        self.$('td input[type="checkbox"]').each(function() {
            self.$(this).prop('checked', checked);
        });
    },
    'change table tbody tr td input[type="checkbox"]': function(event, template) {
        var self = template;
        var allChecked = true;
        self.$('td input[type="checkbox"]').each(function() {
            allChecked = self.$(this).prop('checked');
            return allChecked;
        });
        self.$('th input[type="checkbox"]').prop('checked', allChecked);
    },
    'click table tbody tr': function(event, template) {
        var self = template;
        self._selected.set(this);
    },
    'dblclick table tbody tr': function(event, template) {
        var self = template;
        self.load(this, event.shiftKey);
    },
    'keydown table tbody': function(event, template) {
        var self = template;
        switch(event.keyCode) {
            case 13: // <return>
                self.load(self._selected.get(), event.shiftKey);
                break;
            case 38: // <up>
                self.selectPrevious();
                break;
            case 40: // <down>
                self.selectNext();
                break;
            default:
                return;
        }
        return false;
    }
})
<commit_msg>Block form submition in collection template helper<commit_after>Template.Collection.created = function() {
    var self = this;
    self._selected = new ReactiveVar();
    self._loading = new ReactiveVar();
    self._progress = new ReactiveVar();
    self.load = function(song, action) {
        options = {};
        if(!_.isEqual(action, undefined)) {
            self._collection = self.data.collection;
            if(_.isEqual(action, true)) {
                _.extend(options, {
                    action: 'download',
                    progress: function(data, n, total) {
                        self._progress.set({ value: n, max: total });
                    }
                });
            }
        }
        self._loading.set(song);
        AudioPlayer.load(song, function() {
            self._loading.set(null);
            self._progress.set(null);
        }, function(error) {
            UIkit.notify(error.message, 'warning');
        }, options);
    }
    self.loadNext = function() {
        var song = Session.get('currentSong');
        if(!song) {
        } else {
            self.load(self.findNext(song, 1));
        }
    },
    self.loadPrevious = function() {
        var song = Session.get('currentSong');
        if(!song) {
        } else {
            self.load(self.findNext(song, -1));
        }
    },
    self.selectNext = function() {
        var song = self._selected.get();
        if(!song) {
        } else {
            self._selected.set(self.findNext(song, 1));
        }
    }
    self.selectPrevious = function() {
        var song = self._selected.get();
        if(!song) {
        } else {
            self._selected.set(self.findNext(song, -1));
        }
    }
    self.findNext = function(song, order, sort) {
        if(!order) order = 1;
        var query = {}, sort = _.extend({}, sort ? sort : self.data.sort);
        var index = 0, lastIndex = _.size(sort) -1;
        var field;
        for(field in sort) {
            var value = song[field];
            var operator = sort[field] == order ? '$gt' : '$lt';
            if(!value) {
                continue; // TODO
            } else if(++index < lastIndex) {
                query[field] = value;
            } else {
                query[field] = {};
                query[field][operator] = value;
            }
        }
        var collection = null;
        if(song != self._selected.get()) {
            collection = self._collection;
        } else {
            collection = self.data.collection;
            _.extend(query, self.searchQuery());
        }
        var nextSong = collection.findOne(query, { sort: _.object(_.map(self.data.sort, function(value, key) {
            return [key, value * order];
        })), fields: self.data.fields });
        if(!nextSong) {
            delete sort[field];
            nextSong = self.findNext(song, order, sort);
        }
        return nextSong;
    }
    self.searchQuery = function() {
        var query = {};
        var search = Session.get('search');
        if(typeof search == 'string') {
            var regexp = new RegExp(search.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'), 'i');
            _.extend(query, { '$or': [{ 'artist': regexp }, { 'album': regexp }, { 'title': regexp }]});
        }
        return query;
    }
    _.extend(AudioPlayer, { loadNext: self.loadNext, loadPrevious: self.loadPrevious });
}

Template.Collection.rendered = function() {
    var self = this;
    self.$('table').focus();
}

Template.Collection.helpers({
    'model': function() {
        var self = Template.instance();
        return this.collection.find(self.searchQuery(), { fields: this.fields, sort: this.sort });
    },
    'rowAttributes': function() {
        var self = Template.instance();
        var attributes = {};
        if(!AudioPlayer.canPlay(this)) {
            _.extend(attributes, { disabled: 'disabled' });
        }
        if(_.isEqual(self._selected.get(), this)) {
            _.extend(attributes, { selected: 'selected' });
        }
        if(_.isEqual(self._loading.get(), this)) {
            _.extend(attributes, { role: 'loading' });
        }
        if(_.isEqual(Session.get('currentSong'), this)) {
            _.extend(attributes, { class: 'uk-active' });
        }
        return attributes;
    },
    'progress': function() {
        var self = Template.instance();
        var progress = self._progress.get();
        if(_.isEqual(self._loading.get(), this) && progress) {
            return progress;
        }

    },
    'search': function() {
        var self = Template.instance();
        return Session.get('search');
    }
});

Template.Collection.events({
    'submit form': function(event, template) {
        return false;
    },
    'input aside input[type="search"]': function(event, template) {
        var self = template;
        Session.set('search', event.target.value);
    },
    'change table thead tr th input[type="checkbox"]': function(event, template) {
        var self = template;
        var checked = self.$(event.target).prop('checked');
        self.$('td input[type="checkbox"]').each(function() {
            self.$(this).prop('checked', checked);
        });
    },
    'change table tbody tr td input[type="checkbox"]': function(event, template) {
        var self = template;
        var allChecked = true;
        self.$('td input[type="checkbox"]').each(function() {
            allChecked = self.$(this).prop('checked');
            return allChecked;
        });
        self.$('th input[type="checkbox"]').prop('checked', allChecked);
    },
    'click table tbody tr': function(event, template) {
        var self = template;
        self._selected.set(this);
    },
    'dblclick table tbody tr': function(event, template) {
        var self = template;
        self.load(this, event.shiftKey);
    },
    'keydown table tbody': function(event, template) {
        var self = template;
        switch(event.keyCode) {
            case 13: // <return>
                self.load(self._selected.get(), event.shiftKey);
                break;
            case 38: // <up>
                self.selectPrevious();
                break;
            case 40: // <down>
                self.selectNext();
                break;
            default:
                return;
        }
        return false;
    }
})
<|endoftext|>


<commit_before>import ClockAct from '../acts/Clock'
import Manager from './Manager'

const manager = new Manager({display: [4]}, new ClockAct())

export default manager
<commit_msg>✨ Expose defaultAct<commit_after>import ClockAct from '../acts/Clock'
import Manager from './Manager'

const defaultAct = new ClockAct()

const manager = new Manager({display: [4]}, defaultAct)

export default manager
export {defaultAct}
<|endoftext|>


<commit_before>import React from 'react';
import { Form } from 'semantic-ui-react';

export const ListingTitle = ({title, onChange}) => {
  return (
    <Form onSubmit={e => this.onSubmit(e)}>
      <Form.Field width="8">
        <label htmlFor="firstName">Title</label>
        <input
          placeholder="Insert Title here"
          name="title"
          value={title}
          onChange={e => onChange(e)}
        />
      </Form.Field>
    </Form>
  )
}<commit_msg>separate add listing title into own component<commit_after>import React from 'react';
import { Form } from 'semantic-ui-react';

export const ListingTitle = ({ title, onChange }) => {
  return (
    <Form.TextArea
      rows="1"
      className="ui center aligned grid"
      label="Title"
      placeholder="Insert title of job here"
      name="title"
      value={title}
      onChange={e => onChange(e)}
    />
  );
};

<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import User from '../components/reports/user'
import { viewTimeReportBy } from '../actions/session'

class UserContainer extends Component {

  render () {
    const { data } = this.props
    const { id } = this.props.params
    const user = data.users.find(x => x.username == id) || {}
    return (

      <User user={user} data={data} id={this.props.params.id} />

    )
  }
}

function mapStateToProps (state) {
  return {
    data: state.reports.data
  }
}

export default connect(
  mapStateToProps,
  {viewTimeReportBy}
)(UserContainer)
<commit_msg>fixed red screen when reloading on the user page<commit_after>import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import User from '../components/reports/user'
import { viewTimeReportBy } from '../actions/session'

class UserContainer extends Component {

  render () {
    const { data } = this.props
    const { id } = this.props.params
    const user = data.users.find(x => x.username == id) || {metrics:[]}
    return (

      <User user={user} data={data} id={this.props.params.id} />

    )
  }
}

function mapStateToProps (state) {
  return {
    data: state.reports.data
  }
}

export default connect(
  mapStateToProps,
  {viewTimeReportBy}
)(UserContainer)
<|endoftext|>


<commit_before>import { moduleFor, test } from 'ember-qunit';
import Ember from 'ember';

moduleFor('service:ember-cli', 'Unit | Service | ember cli', {
  // Specify the other units that are required for this test.
  needs: ['model:gist','model:gistFile', 'service:dependency-resolver']
});

test('compiling a gist works', function(assert) {
  assert.expect(7);
  var service = this.subject();
  assert.ok(service);

  var gist = Ember.Object.create({
    files: Ember.A([
      Ember.Object.create({
        filePath: 'templates/application.hbs',
        extension: '.hbs',
        content: '
Hi, I\'m{{appName}}
'
      }),
      Ember.Object.create({
        filePath: 'controllers/application.js',
        extension: '.js',
        content: 'import Ember from "ember";\n\nexport default Ember.Controller.extend({appName:"foo"});'
      })
    ])
  });

  Ember.run(function() {
    service.compileGist(gist).then(function(output) {
      output = output.replace(/define\('([a-z0-9\-\/]+)'/gi,'define("$1"');
      assert.ok(output.indexOf('define("demo-app/router"')>-1, 'build contains router');
      assert.ok(output.indexOf('define("demo-app/initializers/router"')>-1, 'build contains router initializer');
      assert.ok(output.indexOf('define("demo-app/app"')>-1, 'build contains app');
      assert.ok(output.indexOf('define("demo-app/templates/application"')>-1, 'build contains template');
      assert.ok(output.indexOf('define("demo-app/controllers/application"')>-1, 'build contains controller');
      assert.ok(output.indexOf('define("demo-app/config/environment"')>-1, 'build contains config');
    });
  });
});

test("getTwiddleJson() resolves dependencies", function(assert) {
  var service = this.subject();

  var gist = Ember.Object.create({
    files: Ember.A([Ember.Object.create({
      filePath: 'twiddle.json',
      content: `
        {
          "dependencies": {
            "ember": "1.13.9",
            "ember-template-compiler": "2.0.1",
            "ember-data": "1.12.1",
            "jquery": "//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js"
          }
        }
      `
    })])
  });

  var twiddleJson = service.getTwiddleJson(gist);

  assert.deepEqual(twiddleJson.dependencies, {
    'ember': "//cdnjs.cloudflare.com/ajax/libs/ember.js/1.13.9/ember.debug.js",
    'ember-template-compiler': "//cdnjs.cloudflare.com/ajax/libs/ember.js/2.0.1/ember-template-compiler.js",
    'ember-data': "//cdnjs.cloudflare.com/ajax/libs/ember-data.js/1.12.1/ember-data.js",
    'jquery': "//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js"
  });
});

test("updateDependencyVersion() updates the version of the dependency in twiddle.json", function(assert) {
  assert.expect(2);

  var service = this.subject();

  var gist = Ember.Object.create({
    files: Ember.A([Ember.Object.create({
      filePath: 'twiddle.json',
      content: `
        {
          "dependencies": {
            "ember": "1.13.9"
          }
        }
      `
    })])
  });

  service.updateDependencyVersion(gist, 'ember', 'release').then(function() {
    var updatedContent = gist.get('files').findBy('filePath', 'twiddle.json').get('content');
    var parsed = JSON.parse(updatedContent);

    assert.equal(parsed.dependencies.ember, 'release');
    assert.equal(parsed.dependencies.hasOwnProperty('ember-template-compiler'), false, "does not automatically add an ember-template-compiler dependency, when ember is updated");
  });
});

test("updateDependencyVersion() updates the version of ember-template-compiler if ember is updated", function(assert) {
  assert.expect(2);

  var service = this.subject();

  var gist = Ember.Object.create({
    files: Ember.A([Ember.Object.create({
      filePath: 'twiddle.json',
      content: `
        {
          "dependencies": {
            "ember": "1.13.9",
            "ember-template-compiler": "1.13.9"
          }
        }
      `
    })])
  });

  service.updateDependencyVersion(gist, 'ember', 'release').then(function() {
    var updatedContent = gist.get('files').findBy('filePath', 'twiddle.json').get('content');
    var parsed = JSON.parse(updatedContent);

    assert.equal(parsed.dependencies.ember, 'release');
    assert.equal(parsed.dependencies['ember-template-compiler'], 'release');
  });
});

test("buildProperties() works as expected without replacements", function (assert) {
  assert.expect(3);

  var service = this.subject();
  var props = service.buildProperties('helper');

  assert.equal(props.filePath, 'helpers/my-helper.js', 'filePath set');
  assert.ok(props.content, 'has content');
  assert.ok(props.content.indexOf('<%=') === -1, 'No replacement tags in content');
});

test("buildProperties() works as expected with replacements", function (assert) {
  assert.expect(5);

  var service = this.subject();
  var props = service.buildProperties('helper', {
    camelizedModuleName: 'myHelper'
  });

  assert.equal(props.filePath, 'helpers/my-helper.js', 'filePath set');
  assert.ok(props.content, 'has content');
  assert.ok(props.content.indexOf('<%=') === -1, 'No replacement tags in content');
  assert.ok(props.content.indexOf('myHelper(params') !== -1, 'Replacements worked');
  assert.ok(props.content.indexOf('helper(myHelper)') !== -1, 'Replacements worked if multiple');
});

test('compileHbs includes moduleName', function(assert) {
  var service = this.subject();
  var result = service.compileHbs('foo', 'somePath/here.hbs');

  assert.ok(result.indexOf('moduleName: "demo-app/somePath/here"') > -1, 'moduleName included');
});

test('compileHbs can include backticks', function(assert) {
  var template = "`stuff`";
  var service = this.subject();
  var result = service.compileHbs(template, 'some-path');

  assert.ok(result.indexOf(template) > -1, 'original template included');
});

test("buildHtml works when testing not enabled", function(assert) {
  var service = this.subject();

  service.getTwiddleJson = function() {
    return {
      "version": "0.5.0",
      "EmberENV": {
        "FEATURES": {}
      },
      "options": {
        "enable-testing": false
      },
      "dependencies": {
        "jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.js"
      }
    };
  };

  var gist = Ember.Object.create({
    initialRoute: "/"
  });

  var output = service.buildHtml(gist, '/* app */', '/* styles */');

  assert.ok(output.indexOf("window.location.hash='/';") > 0, "output sets initialRoute");
  assert.ok(output.indexOf('EmberENV = {"FEATURES":{}}') > 0, "output contains feature flags");
  assert.ok(output.indexOf('') > 0, "output includes dependency");
  assert.ok(output.indexOf('') > 0, "output includes styles");
  assert.ok(output.indexOf('') > 0, "output includes dependency");
  assert.ok(output.indexOf('


<commit_before>// FL-13-May-2013 Created
// FL-13-May-2013 Changed

// Logging with dojox.analytics for analysis of user behavior.

<script type="text/javascript" src="dojotoolkit/dojo/dojo.js"
   data-dojo-config="parseOnLoad: true, sendInterval: 5000, analyticsUrl: 'http://server/path/to/dataLogger'"></script>

<script language="JavaScript" type="text/javascript">
   // include the analytics system
   dojo.require("dojox.analytics");

   // this plugin returns the information dojo collects when it launches
   dojo.require("dojox.analytics.plugins.dojo");

   // this plugin return the information the window has when it launches
   // and it also ties to a few events such as window.option
   dojo.require("dojox.analytics.plugins.window");

   // this plugin tracks console. message, It logs console.error, warn, and
   // info messages to the tracker.  It also defines console.rlog() which
   // can be used to log only to the server.  Note that if isDebug() is disabled
   // you will still see the console messages on the sever, but not in the actual
   // browser console.
   dojo.require("dojox.analytics.plugins.consoleMessages");

   // tracks where a mouse is on a page an what it is over, periodically sampling
   // and storing this data
   dojo.require("dojox.analytics.plugins.mouseOver");

   // tracks mouse clicks on the page
   dojo.require("dojox.analytics.plugins.mouseClick");

   // tracks when the user has gone idle
   dojo.require("dojox.analytics.plugins.idle");

 </script>

// [eof]
<commit_msg>Removing unused analytics js<commit_after><|endoftext|>


<commit_before>module.exports.register = function (context) {

  var TheGraph = context.TheGraph;

  TheGraph.config.nodeMenuPort = {
    container: {},
    backgroundRect: {
      rx: TheGraph.config.nodeRadius,
      ry: TheGraph.config.nodeRadius,
      height: TheGraph.contextPortSize - 1
    },
    circle: {
      r: 10
    },
    text: {}
  };

  TheGraph.factories.nodeMenuPort = {
    createNodeMenuPortGroup: TheGraph.factories.createGroup,
    createNodeMenuBackgroundRect: TheGraph.factories.createRect,
    createNodeMenuPortCircle: TheGraph.factories.createCircle,
    createNodeMenuPortText: TheGraph.factories.createText
  };

  TheGraph.NodeMenuPort = React.createFactory( React.createClass({
    displayName: "TheGraphNodeMenuPort",
    componentDidMount: function () {
      ReactDOM.findDOMNode(this).addEventListener("up", this.edgeStart);
    },
    edgeStart: function (event) {
      // Don't tap graph
      event.stopPropagation();

      var port = {
        process: this.props.processKey,
        port: this.props.label,
        type: this.props.port.type
      };

      var edgeStartEvent = new CustomEvent('the-graph-edge-start', {
        detail: {
          isIn: this.props.isIn,
          port: port,
          route: this.props.route
        },
        bubbles: true
      });
      ReactDOM.findDOMNode(this).dispatchEvent(edgeStartEvent);
    },
    render: function() {
      var labelLen = this.props.label.length;
      var bgWidth = (labelLen>12 ? labelLen*8+40 : 120);
      // Highlight compatible port
      var highlightPort = this.props.highlightPort;
      var highlight = (highlightPort && highlightPort.isIn === this.props.isIn && highlightPort.type === this.props.port.type);

      var rectOptions = {
        className: "context-port-bg"+(highlight ? " highlight" : ""),
        x: this.props.x + (this.props.isIn ? -bgWidth : 0),
        y: this.props.y - TheGraph.contextPortSize/2,
        width: bgWidth
      };

      rectOptions = TheGraph.merge(TheGraph.config.nodeMenuPort.backgroundRect, rectOptions);
      var rect = TheGraph.factories.nodeMenuPort.createNodeMenuBackgroundRect.call(this, rectOptions);

      var circleOptions = {
        className: "context-port-hole stroke route"+this.props.route,
        cx: this.props.x,
        cy: this.props.y,
      };
      circleOptions = TheGraph.merge(TheGraph.config.nodeMenuPort.circle, circleOptions);
      var circle = TheGraph.factories.nodeMenuPort.createNodeMenuPortCircle.call(this, circleOptions);

      var textOptions = {
        className: "context-port-label fill route"+this.props.route,
        x: this.props.x + (this.props.isIn ? -20 : 20),
        y: this.props.y,
        children: this.props.label.replace(/(.*)\/(.*)(_.*)\.(.*)/, '$2.$4')
      };

      textOptions = TheGraph.merge(TheGraph.config.nodeMenuPort.text, textOptions);
      var text = TheGraph.factories.nodeMenuPort.createNodeMenuPortText.call(this, textOptions);

      var containerContents = [rect, circle, text];

      var containerOptions = TheGraph.merge(TheGraph.config.nodeMenuPort.container, { className: "context-port click context-port-"+(this.props.isIn ? "in" : "out") });
      return TheGraph.factories.nodeMenuPort.createNodeMenuPortGroup.call(this, containerOptions, containerContents);

    }
  }));

};
<commit_msg>Fix node menu port click listener<commit_after>module.exports.register = function (context) {

  var TheGraph = context.TheGraph;

  TheGraph.config.nodeMenuPort = {
    container: {},
    backgroundRect: {
      rx: TheGraph.config.nodeRadius,
      ry: TheGraph.config.nodeRadius,
      height: TheGraph.contextPortSize - 1
    },
    circle: {
      r: 10
    },
    text: {}
  };

  TheGraph.factories.nodeMenuPort = {
    createNodeMenuPortGroup: TheGraph.factories.createGroup,
    createNodeMenuBackgroundRect: TheGraph.factories.createRect,
    createNodeMenuPortCircle: TheGraph.factories.createCircle,
    createNodeMenuPortText: TheGraph.factories.createText
  };

  TheGraph.NodeMenuPort = React.createFactory( React.createClass({
    displayName: "TheGraphNodeMenuPort",
    componentDidMount: function () {
      ReactDOM.findDOMNode(this).addEventListener("tap", this.edgeStart);
    },
    edgeStart: function (event) {
      // Don't tap graph
      event.stopPropagation();

      var port = {
        process: this.props.processKey,
        port: this.props.label,
        type: this.props.port.type
      };

      var edgeStartEvent = new CustomEvent('the-graph-edge-start', {
        detail: {
          isIn: this.props.isIn,
          port: port,
          route: this.props.route
        },
        bubbles: true
      });
      ReactDOM.findDOMNode(this).dispatchEvent(edgeStartEvent);
    },
    render: function() {
      var labelLen = this.props.label.length;
      var bgWidth = (labelLen>12 ? labelLen*8+40 : 120);
      // Highlight compatible port
      var highlightPort = this.props.highlightPort;
      var highlight = (highlightPort && highlightPort.isIn === this.props.isIn && highlightPort.type === this.props.port.type);

      var rectOptions = {
        className: "context-port-bg"+(highlight ? " highlight" : ""),
        x: this.props.x + (this.props.isIn ? -bgWidth : 0),
        y: this.props.y - TheGraph.contextPortSize/2,
        width: bgWidth
      };

      rectOptions = TheGraph.merge(TheGraph.config.nodeMenuPort.backgroundRect, rectOptions);
      var rect = TheGraph.factories.nodeMenuPort.createNodeMenuBackgroundRect.call(this, rectOptions);

      var circleOptions = {
        className: "context-port-hole stroke route"+this.props.route,
        cx: this.props.x,
        cy: this.props.y,
      };
      circleOptions = TheGraph.merge(TheGraph.config.nodeMenuPort.circle, circleOptions);
      var circle = TheGraph.factories.nodeMenuPort.createNodeMenuPortCircle.call(this, circleOptions);

      var textOptions = {
        className: "context-port-label fill route"+this.props.route,
        x: this.props.x + (this.props.isIn ? -20 : 20),
        y: this.props.y,
        children: this.props.label.replace(/(.*)\/(.*)(_.*)\.(.*)/, '$2.$4')
      };

      textOptions = TheGraph.merge(TheGraph.config.nodeMenuPort.text, textOptions);
      var text = TheGraph.factories.nodeMenuPort.createNodeMenuPortText.call(this, textOptions);

      var containerContents = [rect, circle, text];

      var containerOptions = TheGraph.merge(TheGraph.config.nodeMenuPort.container, { className: "context-port click context-port-"+(this.props.isIn ? "in" : "out") });
      return TheGraph.factories.nodeMenuPort.createNodeMenuPortGroup.call(this, containerOptions, containerContents);

    }
  }));

};
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */

// There isn't a standard way to get line numbers reliably, we attempt to
// parse out a few formats we have seen.
// Note we do not use e.lineNumber as it is not reliable (especially in the
// context of eval)
function getLineNumber(error) {
  try {
    // firefox
    const firefoxRegex = /eval:(\d+):\d+/;
    if (error.stack.match(firefoxRegex)) {
      const res = error.stack.match(firefoxRegex);
      return parseInt(res[1], 10);
    }

    // chrome
    const chromeRegex = /eval.+:(\d+):\d+/;
    if (error.stack.match(chromeRegex)) {
      const res = error.stack.match(chromeRegex);
      return parseInt(res[1], 10);
    }

  } catch (e) {
    return;
  }

  // We found nothing
  return;
}

async function executeCodeSnippet(consoleLogElement, codeSnippet) {
  consoleLogElement.innerText = '';
  var oldLog = console.log;
  console.log = function(...values) {
    let logStrs = [];
    for (let i = 0; i < values.length; i++) {
      const value = values[i];

      let logStr;
      if (value.toString == null) {
        logStr = value;
      } else {
        const toStr = value.toString();

        if (toStr === '[object Object]') {
          logStr = JSON.stringify(value, null, 2);
        } else {
          logStr = toStr;
        }
        logStrs.push(logStr);
      }
    }
    consoleLogElement.innerHTML += logStrs.join(' ') + '\n';
  };

  function reportError(e) {
    var errorMessage = '\n
An error occured';
    var lineNumber = getLineNumber(e);
    if (lineNumber !== undefined) {
      errorMessage += ' on line: ' + lineNumber + '';
    } else {
      errorMessage += ''
    }
    errorMessage += '
';
    errorMessage += '
' + e.message + '
';
    errorMessage += '
';

    console.log(errorMessage);
  }

  // It is important that codeSnippet and 'try {' be on the same line
  // in order to not modify the line number on an error.
  const evalString = '(async function runner() { try { ' + codeSnippet +
      '} catch (e) { reportError(e); } })()';

  if (window._tfengine && window._tfengine.startScope) {
    window._tfengine.startScope();
  } else {
    tf.ENV.engine.startScope()
  }

  // this outer try is for errors that prevent the snippet from being parsed.
  try {
    await eval(evalString).catch(function(e) {
      // This catch is for errors within promises within snippets
      reportError(e);
    });
  } catch (e) {
    reportError(e);
  }

  if (window._tfengine && window._tfengine.endScope) {
    window._tfengine.endScope();
  } else {
    tf.ENV.engine.endScope();
  }

  console.log = oldLog;
};

function makeEditable(codeBlock) {
  var parent = codeBlock.parentElement;
  var codeText = codeBlock.innerText;

  parent.innerHTML = '';
  var myCodeMirror = CodeMirror(parent, {
    value: codeText,
    theme: 'railscasts',
    mode: 'javascript',
    tabSize: 2,
    indentUnit: 2,
    viewportMargin: Infinity,
  });

  codeBlock.codeMirror = myCodeMirror;
}

function initCodeBlocks(selector) {
  // Find all the code blocks.
  var jsBlocks =
      Array.prototype.slice.call(document.querySelectorAll(selector));

  jsBlocks.forEach(function(block) {
    var consoleElement = document.createElement('div');
    consoleElement.className = 'snippet-console';

    var consoleRunElement = document.createElement('button');
    consoleRunElement.innerText = 'Run';
    consoleRunElement.className = 'snippet-run-button';

    var consoleEditElement = document.createElement('button');
    consoleEditElement.innerText = 'Edit';
    consoleEditElement.className = 'snippet-edit-button';

    var consoleLogElement = document.createElement('div');
    consoleLogElement.className = 'snippet-console-log';

    consoleElement.appendChild(consoleLogElement);
    consoleElement.appendChild(consoleEditElement);
    consoleElement.appendChild(consoleRunElement);

    block.parentElement.insertAdjacentElement('afterend', consoleElement);

    consoleRunElement.addEventListener('click', function() {
      var consoleLogElement =
          this.parentElement.querySelector('.snippet-console-log');

      var snippetText;
      if (block.codeMirror) {
        snippetText = block.codeMirror.getValue();
      } else {
        snippetText = this.parentElement.previousElementSibling.innerText;
      }

      executeCodeSnippet(consoleLogElement, snippetText);
    });

    consoleEditElement.addEventListener('click', function() {
      makeEditable(block);
      this.disabled = true;
    });
  });
}
<commit_msg>Snippets (#465)<commit_after>/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */

// There isn't a standard way to get line numbers reliably, we attempt to
// parse out a few formats we have seen.
// Note we do not use e.lineNumber as it is not reliable (especially in the
// context of eval)
function getLineNumber(error) {
  try {
    // firefox
    const firefoxRegex = /eval:(\d+):\d+/;
    if (error.stack.match(firefoxRegex)) {
      const res = error.stack.match(firefoxRegex);
      return parseInt(res[1], 10);
    }

    // chrome
    const chromeRegex = /eval.+:(\d+):\d+/;
    if (error.stack.match(chromeRegex)) {
      const res = error.stack.match(chromeRegex);
      return parseInt(res[1], 10);
    }

  } catch (e) {
    return;
  }

  // We found nothing
  return;
}

async function executeCodeSnippet(consoleLogElement, codeSnippet) {
  consoleLogElement.innerText = '';
  var oldLog = console.log;
  console.log = function(...values) {
    let logStrs = [];
    for (let i = 0; i < values.length; i++) {
      const value = values[i];

      let logStr;
      if (value.toString == null) {
        logStr = value;
      } else {
        const toStr = value.toString();

        if (toStr === '[object Object]') {
          logStr = JSON.stringify(value, null, 2);
        } else {
          logStr = toStr;
        }
        logStrs.push(logStr);
      }
    }
    consoleLogElement.innerHTML += logStrs.join(' ') + '\n';
  };

  function reportError(e) {
    var errorMessage = '\n
An error occured';
    var lineNumber = getLineNumber(e);
    if (lineNumber !== undefined) {
      errorMessage += ' on line: ' + lineNumber + '';
    } else {
      errorMessage += ''
    }
    errorMessage += '
';
    errorMessage += '
' + e.message + '
';
    errorMessage += '
';

    console.log(errorMessage);
  }

  // It is important that codeSnippet and 'try {' be on the same line
  // in order to not modify the line number on an error.
  const evalString = '(async function runner() { try { ' + codeSnippet +
    '\n} catch (e) { reportError(e); } })()';

  if (window._tfengine && window._tfengine.startScope) {
    window._tfengine.startScope();
  } else {
    tf.ENV.engine.startScope()
  }

  // this outer try is for errors that prevent the snippet from being parsed.
  try {
    await eval(evalString).catch(function(e) {
      // This catch is for errors within promises within snippets
      reportError(e);
    });
  } catch (e) {
    reportError(e);
  }

  if (window._tfengine && window._tfengine.endScope) {
    window._tfengine.endScope();
  } else {
    tf.ENV.engine.endScope();
  }

  console.log = oldLog;
};

function makeEditable(codeBlock) {
  var parent = codeBlock.parentElement;
  var codeText = codeBlock.innerText;

  parent.innerHTML = '';
  var myCodeMirror = CodeMirror(parent, {
    value: codeText,
    theme: 'railscasts',
    mode: 'javascript',
    tabSize: 2,
    indentUnit: 2,
    viewportMargin: Infinity,
  });

  codeBlock.codeMirror = myCodeMirror;
}

function initCodeBlocks(selector) {
  // Find all the code blocks.
  var jsBlocks =
    Array.prototype.slice.call(document.querySelectorAll(selector));

  jsBlocks.forEach(function(block) {
    var consoleElement = document.createElement('div');
    consoleElement.className = 'snippet-console';

    var consoleRunElement = document.createElement('button');
    consoleRunElement.innerText = 'Run';
    consoleRunElement.className = 'snippet-run-button';

    var consoleEditElement = document.createElement('button');
    consoleEditElement.innerText = 'Edit';
    consoleEditElement.className = 'snippet-edit-button';

    var consoleLogElement = document.createElement('div');
    consoleLogElement.className = 'snippet-console-log';

    consoleElement.appendChild(consoleLogElement);
    consoleElement.appendChild(consoleEditElement);
    consoleElement.appendChild(consoleRunElement);

    block.parentElement.insertAdjacentElement('afterend', consoleElement);

    consoleRunElement.addEventListener('click', function() {
      var consoleLogElement =
        this.parentElement.querySelector('.snippet-console-log');

      var snippetText;
      if (block.codeMirror) {
        snippetText = block.codeMirror.getValue();
      } else {
        snippetText = this.parentElement.previousElementSibling.innerText;
      }

      executeCodeSnippet(consoleLogElement, snippetText);
    });

    consoleEditElement.addEventListener('click', function() {
      makeEditable(block);
      this.disabled = true;
    });
  });
}
<|endoftext|>


<commit_before>/* eslint-disable no-restricted-syntax, no-invalid-this */
'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var isPositive = require( '@stdlib/assert/is-positive-number' ).isPrimitive;
var kurtosis = require( '@stdlib/math/base/dists/kumaraswamy/kurtosis' );
var mean = require( '@stdlib/math/base/dists/kumaraswamy/mean' );
var mode = require( '@stdlib/math/base/dists/kumaraswamy/mode' );
var skewness = require( '@stdlib/math/base/dists/kumaraswamy/skewness' );
var stdev = require( '@stdlib/math/base/dists/kumaraswamy/stdev' );
var variance = require( '@stdlib/math/base/dists/kumaraswamy/variance' );
var cdf = require( '@stdlib/math/base/dists/kumaraswamy/cdf' );
var logcdf = require( '@stdlib/math/base/dists/kumaraswamy/logcdf' );
var logpdf = require( '@stdlib/math/base/dists/kumaraswamy/logpdf' );
var pdf = require( '@stdlib/math/base/dists/kumaraswamy/pdf' );
var quantile = require( '@stdlib/math/base/dists/kumaraswamy/quantile' );

// FUNCTIONS //

/**
* Evaluates the cumulative distribution function (CDF).
*
* @private
* @param {number} x - input value
* @returns {number} evaluated CDF
*/
function kumaraswamyCDF( x ) {
	return cdf( x, this.a, this.b );
}

/**
* Evaluates the natural logarithm of the cumulative distribution function (CDF).
*
* @private
* @param {number} x - input value
* @returns {number} evaluated logCDF
*/
function kumaraswamyLogCDF( x ) {
	return logcdf( x, this.a, this.b );
}

/**
* Evaluates the natural logarithm of the probability density function (PDF).
*
* @private
* @param {number} x - input value
* @returns {number} evaluated logPDF
*/
function kumaraswamyLogPDF( x ) {
	return logpdf( x, this.a, this.b );
}

/**
* Evaluates the probability density function (PDF).
*
* @private
* @param {number} x - input value
* @returns {number} evaluated PDF
*/
function kumaraswamyPDF( x ) {
	return pdf( x, this.a, this.b );
}

/**
* Evaluates the quantile function.
*
* @private
* @param {Probability} p - input probability
* @returns {number} evaluated quantile function
*/
function kumaraswamyQuantile( p ) {
	return quantile( p, this.a, this.b );
}

// MAIN //

/**
* Kumaraswamy's double bounded distribution constructor.
*
* @constructor
* @param {PositiveNumber} [a=1.0] - first shape parameter
* @param {PositiveNumber} [b=1.0] - second shape parameter
* @throws {TypeError} `a` must be a positive number
* @throws {TypeError} `b` must be a positive number
* @returns {Kumaraswamy} distribution instance
*
* @example
* var kumaraswamy = new Kumaraswamy( 1.0, 1.0 );
*
* var y = kumaraswamy.cdf( 0.8 );
* // returns 0.8
*
* var mode = kumaraswamy.mode;
* // returns NaN
*/
function Kumaraswamy() {
	var a;
	var b;
	if ( !(this instanceof Kumaraswamy) ) {
		if ( arguments.length === 0 ) {
			return new Kumaraswamy();
		}
		return new Kumaraswamy( arguments[ 0 ], arguments[ 1 ] );
	}
	if ( arguments.length ) {
		a = arguments[ 0 ];
		b = arguments[ 1 ];
		if ( !isPositive( a ) ) {
			throw new TypeError( 'invalid input argument. First shape parameter `a` must be a positive number. Value: `' + a + '`' );
		}
		if ( !isPositive( b ) ) {
			throw new TypeError( 'invalid input argument. Second shape parameter `b` must be a positive number. Value: `' + b + '`' );
		}
	} else {
		a = 1.0;
		b = 1.0;
	}
	Object.defineProperty( this, 'a', {
		'configurable': false,
		'enumerable': true,
		'get': function get() {
			return a;
		},
		'set': function set( value ) {
			if ( !isPositive( value ) ) {
				throw new TypeError( 'invalid value. Must be a positive number. Value: `' + value + '`' );
			}
			a = value;
		}
	});
	Object.defineProperty( this, 'b', {
		'configurable': false,
		'enumerable': true,
		'get': function get() {
			return b;
		},
		'set': function set( value ) {
			if ( !isPositive( value ) ) {
				throw new TypeError( 'invalid value. Must be a positive number. Value: `' + value + '`' );
			}
			b = value;
		}
	});
	return this;
}

/**
* Kumaraswamy's double bounded distribution excess kurtosis.
*
* @memberof Kumaraswamy.prototype
* @name kurtosis
* @type {number}
* @see [kurtosis]{@link https://en.wikipedia.org/wiki/Kurtosis}
*
* @example
* var kumaraswamy = new Kumaraswamy( 4.0, 12.0 );
*
* var v = kumaraswamy.kurtosis;
* // returns ~2.704
*/
Object.defineProperty( Kumaraswamy.prototype, 'kurtosis', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return kurtosis( this.a, this.b );
	}
});

/**
* Kumaraswamy's double bounded distribution expected value.
*
* @memberof Kumaraswamy.prototype
* @name mean
* @type {number}
* @see [expected value]{@link https://en.wikipedia.org/wiki/Expected_value}
*
* @example
* var kumaraswamy = new Kumaraswamy( 4.0, 12.0 );
*
* var v = kumaraswamy.mean;
* // returns ~0.481
*/
Object.defineProperty( Kumaraswamy.prototype, 'mean', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return mean( this.a, this.b );
	}
});

/**
* Kumaraswamy's double bounded distribution mode.
*
* @memberof Kumaraswamy.prototype
* @name mode
* @type {number}
* @see [mode]{@link https://en.wikipedia.org/wiki/Mode_%28statistics%29}
*
* @example
* var kumaraswamy = new Kumaraswamy( 4.0, 12.0 );
*
* var v = kumaraswamy.mode;
* // returns ~0.503
*/
Object.defineProperty( Kumaraswamy.prototype, 'mode', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return mode( this.a, this.b );
	}
});

/**
* Kumaraswamy's double bounded distribution skewness.
*
* @memberof Kumaraswamy.prototype
* @name skewness
* @type {number}
* @see [skewness]{@link https://en.wikipedia.org/wiki/Skewness}
*
* @example
* var kumaraswamy = new Kumaraswamy( 4.0, 12.0 );
*
* var v = kumaraswamy.skewness;
* // returns ~-0.201
*/
Object.defineProperty( Kumaraswamy.prototype, 'skewness', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return skewness( this.a, this.b );
	}
});

/**
* Kumaraswamy's double bounded distribution standard deviation.
*
* @memberof Kumaraswamy.prototype
* @name stdev
* @type {PositiveNumber}
* @see [standard deviation]{@link https://en.wikipedia.org/wiki/Standard_deviation}
*
* @example
* var kumaraswamy = new Kumaraswamy( 4.0, 12.0 );
*
* var v = kumaraswamy.stdev;
* // returns ~0.13
*/
Object.defineProperty( Kumaraswamy.prototype, 'stdev', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return stdev( this.a, this.b );
	}
});

/**
* Kumaraswamy's double bounded distribution variance.
*
* @memberof Kumaraswamy.prototype
* @name variance
* @type {PositiveNumber}
* @see [variance]{@link https://en.wikipedia.org/wiki/Variance}
*
* @example
* var kumaraswamy = new Kumaraswamy( 4.0, 12.0 );
*
* var v = kumaraswamy.variance;
* // returns ~0.017
*/
Object.defineProperty( Kumaraswamy.prototype, 'variance', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return variance( this.a, this.b );
	}
});

/**
* Evaluates the cumulative distribution function (CDF).
*
* @memberof Kumaraswamy.prototype
* @name cdf
* @type {Function}
* @param {number} x - input value
* @returns {number} evaluated CDF
* @see [cdf]{@link https://en.wikipedia.org/wiki/Cumulative_distribution_function}
*
* @example
* var kumaraswamy = new Kumaraswamy( 2.0, 4.0 );
*
* var v = kumaraswamy.cdf( 0.5 );
* // returns ~0.684
*/
setReadOnly( Kumaraswamy.prototype, 'cdf', kumaraswamyCDF );

/**
* Evaluates the natural logarithm of the cumulative distribution function (CDF).
*
* @memberof Kumaraswamy.prototype
* @name logcdf
* @type {Function}
* @param {number} x - input value
* @returns {number} evaluated logCDF
* @see [cdf]{@link https://en.wikipedia.org/wiki/Cumulative_distribution_function}
*
* @example
* var kumaraswamy = new Kumaraswamy( 2.0, 4.0 );
*
* var v = kumaraswamy.logcdf( 0.5 );
* // returns ~-0.38
*/
setReadOnly( Kumaraswamy.prototype, 'logcdf', kumaraswamyLogCDF );

/**
* Evaluates the natural logarithm of the probability density function (PDF).
*
* @memberof Kumaraswamy.prototype
* @name logpdf
* @type {Function}
* @param {number} x - input value
* @returns {number} evaluated logPDF
* @see [pdf]{@link https://en.wikipedia.org/wiki/Probability_density_function}
*
* @example
* var kumaraswamy = new Kumaraswamy( 2.0, 4.0 );
*
* var v = kumaraswamy.logpdf( 0.9 );
* // returns ~-3.016
*/
setReadOnly( Kumaraswamy.prototype, 'logpdf', kumaraswamyLogPDF );

/**
* Evaluates the probability density function (PDF).
*
* @memberof Kumaraswamy.prototype
* @name pdf
* @type {Function}
* @param {number} x - input value
* @returns {number} evaluated PDF
* @see [pdf]{@link https://en.wikipedia.org/wiki/Probability_density_function}
*
* @example
* var kumaraswamy = new Kumaraswamy( 2.0, 4.0 );
*
* var v = kumaraswamy.pdf( 0.9 );
* // returns ~0.049
*/
setReadOnly( Kumaraswamy.prototype, 'pdf', kumaraswamyPDF );

/**
* Evaluates the quantile function.
*
* @memberof Kumaraswamy.prototype
* @name quantile
* @type {Function}
* @param {Probability} p - input probability
* @returns {number} evaluated quantile function
* @see [quantile function]{@link https://en.wikipedia.org/wiki/Quantile_function}
*
* @example
* var kumaraswamy = new Kumaraswamy( 2.0, 4.0 );
*
* var v = kumaraswamy.quantile( 0.5 );
* // returns ~0.399
*/
setReadOnly( Kumaraswamy.prototype, 'quantile', kumaraswamyQuantile );

// EXPORTS //

module.exports = Kumaraswamy;
<commit_msg>Re-arrange JSDoc tags<commit_after>/* eslint-disable no-restricted-syntax, no-invalid-this */
'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var isPositive = require( '@stdlib/assert/is-positive-number' ).isPrimitive;
var kurtosis = require( '@stdlib/math/base/dists/kumaraswamy/kurtosis' );
var mean = require( '@stdlib/math/base/dists/kumaraswamy/mean' );
var mode = require( '@stdlib/math/base/dists/kumaraswamy/mode' );
var skewness = require( '@stdlib/math/base/dists/kumaraswamy/skewness' );
var stdev = require( '@stdlib/math/base/dists/kumaraswamy/stdev' );
var variance = require( '@stdlib/math/base/dists/kumaraswamy/variance' );
var cdf = require( '@stdlib/math/base/dists/kumaraswamy/cdf' );
var logcdf = require( '@stdlib/math/base/dists/kumaraswamy/logcdf' );
var logpdf = require( '@stdlib/math/base/dists/kumaraswamy/logpdf' );
var pdf = require( '@stdlib/math/base/dists/kumaraswamy/pdf' );
var quantile = require( '@stdlib/math/base/dists/kumaraswamy/quantile' );

// FUNCTIONS //

/**
* Evaluates the cumulative distribution function (CDF).
*
* @private
* @param {number} x - input value
* @returns {number} evaluated CDF
*/
function kumaraswamyCDF( x ) {
	return cdf( x, this.a, this.b );
}

/**
* Evaluates the natural logarithm of the cumulative distribution function (CDF).
*
* @private
* @param {number} x - input value
* @returns {number} evaluated logCDF
*/
function kumaraswamyLogCDF( x ) {
	return logcdf( x, this.a, this.b );
}

/**
* Evaluates the natural logarithm of the probability density function (PDF).
*
* @private
* @param {number} x - input value
* @returns {number} evaluated logPDF
*/
function kumaraswamyLogPDF( x ) {
	return logpdf( x, this.a, this.b );
}

/**
* Evaluates the probability density function (PDF).
*
* @private
* @param {number} x - input value
* @returns {number} evaluated PDF
*/
function kumaraswamyPDF( x ) {
	return pdf( x, this.a, this.b );
}

/**
* Evaluates the quantile function.
*
* @private
* @param {Probability} p - input probability
* @returns {number} evaluated quantile function
*/
function kumaraswamyQuantile( p ) {
	return quantile( p, this.a, this.b );
}

// MAIN //

/**
* Kumaraswamy's double bounded distribution constructor.
*
* @constructor
* @param {PositiveNumber} [a=1.0] - first shape parameter
* @param {PositiveNumber} [b=1.0] - second shape parameter
* @throws {TypeError} `a` must be a positive number
* @throws {TypeError} `b` must be a positive number
* @returns {Kumaraswamy} distribution instance
*
* @example
* var kumaraswamy = new Kumaraswamy( 1.0, 1.0 );
*
* var y = kumaraswamy.cdf( 0.8 );
* // returns 0.8
*
* var mode = kumaraswamy.mode;
* // returns NaN
*/
function Kumaraswamy() {
	var a;
	var b;
	if ( !(this instanceof Kumaraswamy) ) {
		if ( arguments.length === 0 ) {
			return new Kumaraswamy();
		}
		return new Kumaraswamy( arguments[ 0 ], arguments[ 1 ] );
	}
	if ( arguments.length ) {
		a = arguments[ 0 ];
		b = arguments[ 1 ];
		if ( !isPositive( a ) ) {
			throw new TypeError( 'invalid input argument. First shape parameter `a` must be a positive number. Value: `' + a + '`' );
		}
		if ( !isPositive( b ) ) {
			throw new TypeError( 'invalid input argument. Second shape parameter `b` must be a positive number. Value: `' + b + '`' );
		}
	} else {
		a = 1.0;
		b = 1.0;
	}
	Object.defineProperty( this, 'a', {
		'configurable': false,
		'enumerable': true,
		'get': function get() {
			return a;
		},
		'set': function set( value ) {
			if ( !isPositive( value ) ) {
				throw new TypeError( 'invalid value. Must be a positive number. Value: `' + value + '`' );
			}
			a = value;
		}
	});
	Object.defineProperty( this, 'b', {
		'configurable': false,
		'enumerable': true,
		'get': function get() {
			return b;
		},
		'set': function set( value ) {
			if ( !isPositive( value ) ) {
				throw new TypeError( 'invalid value. Must be a positive number. Value: `' + value + '`' );
			}
			b = value;
		}
	});
	return this;
}

/**
* Kumaraswamy's double bounded distribution excess kurtosis.
*
* @name kurtosis
* @memberof Kumaraswamy.prototype
* @type {number}
* @see [kurtosis]{@link https://en.wikipedia.org/wiki/Kurtosis}
*
* @example
* var kumaraswamy = new Kumaraswamy( 4.0, 12.0 );
*
* var v = kumaraswamy.kurtosis;
* // returns ~2.704
*/
Object.defineProperty( Kumaraswamy.prototype, 'kurtosis', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return kurtosis( this.a, this.b );
	}
});

/**
* Kumaraswamy's double bounded distribution expected value.
*
* @name mean
* @memberof Kumaraswamy.prototype
* @type {number}
* @see [expected value]{@link https://en.wikipedia.org/wiki/Expected_value}
*
* @example
* var kumaraswamy = new Kumaraswamy( 4.0, 12.0 );
*
* var v = kumaraswamy.mean;
* // returns ~0.481
*/
Object.defineProperty( Kumaraswamy.prototype, 'mean', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return mean( this.a, this.b );
	}
});

/**
* Kumaraswamy's double bounded distribution mode.
*
* @name mode
* @memberof Kumaraswamy.prototype
* @type {number}
* @see [mode]{@link https://en.wikipedia.org/wiki/Mode_%28statistics%29}
*
* @example
* var kumaraswamy = new Kumaraswamy( 4.0, 12.0 );
*
* var v = kumaraswamy.mode;
* // returns ~0.503
*/
Object.defineProperty( Kumaraswamy.prototype, 'mode', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return mode( this.a, this.b );
	}
});

/**
* Kumaraswamy's double bounded distribution skewness.
*
* @name skewness
* @memberof Kumaraswamy.prototype
* @type {number}
* @see [skewness]{@link https://en.wikipedia.org/wiki/Skewness}
*
* @example
* var kumaraswamy = new Kumaraswamy( 4.0, 12.0 );
*
* var v = kumaraswamy.skewness;
* // returns ~-0.201
*/
Object.defineProperty( Kumaraswamy.prototype, 'skewness', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return skewness( this.a, this.b );
	}
});

/**
* Kumaraswamy's double bounded distribution standard deviation.
*
* @name stdev
* @memberof Kumaraswamy.prototype
* @type {PositiveNumber}
* @see [standard deviation]{@link https://en.wikipedia.org/wiki/Standard_deviation}
*
* @example
* var kumaraswamy = new Kumaraswamy( 4.0, 12.0 );
*
* var v = kumaraswamy.stdev;
* // returns ~0.13
*/
Object.defineProperty( Kumaraswamy.prototype, 'stdev', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return stdev( this.a, this.b );
	}
});

/**
* Kumaraswamy's double bounded distribution variance.
*
* @name variance
* @memberof Kumaraswamy.prototype
* @type {PositiveNumber}
* @see [variance]{@link https://en.wikipedia.org/wiki/Variance}
*
* @example
* var kumaraswamy = new Kumaraswamy( 4.0, 12.0 );
*
* var v = kumaraswamy.variance;
* // returns ~0.017
*/
Object.defineProperty( Kumaraswamy.prototype, 'variance', {
	'configurable': false,
	'enumerable': true,
	'get': function get() {
		return variance( this.a, this.b );
	}
});

/**
* Evaluates the cumulative distribution function (CDF).
*
* @name cdf
* @memberof Kumaraswamy.prototype
* @type {Function}
* @param {number} x - input value
* @returns {number} evaluated CDF
* @see [cdf]{@link https://en.wikipedia.org/wiki/Cumulative_distribution_function}
*
* @example
* var kumaraswamy = new Kumaraswamy( 2.0, 4.0 );
*
* var v = kumaraswamy.cdf( 0.5 );
* // returns ~0.684
*/
setReadOnly( Kumaraswamy.prototype, 'cdf', kumaraswamyCDF );

/**
* Evaluates the natural logarithm of the cumulative distribution function (CDF).
*
* @name logcdf
* @memberof Kumaraswamy.prototype
* @type {Function}
* @param {number} x - input value
* @returns {number} evaluated logCDF
* @see [cdf]{@link https://en.wikipedia.org/wiki/Cumulative_distribution_function}
*
* @example
* var kumaraswamy = new Kumaraswamy( 2.0, 4.0 );
*
* var v = kumaraswamy.logcdf( 0.5 );
* // returns ~-0.38
*/
setReadOnly( Kumaraswamy.prototype, 'logcdf', kumaraswamyLogCDF );

/**
* Evaluates the natural logarithm of the probability density function (PDF).
*
* @name logpdf
* @memberof Kumaraswamy.prototype
* @type {Function}
* @param {number} x - input value
* @returns {number} evaluated logPDF
* @see [pdf]{@link https://en.wikipedia.org/wiki/Probability_density_function}
*
* @example
* var kumaraswamy = new Kumaraswamy( 2.0, 4.0 );
*
* var v = kumaraswamy.logpdf( 0.9 );
* // returns ~-3.016
*/
setReadOnly( Kumaraswamy.prototype, 'logpdf', kumaraswamyLogPDF );

/**
* Evaluates the probability density function (PDF).
*
* @name pdf
* @memberof Kumaraswamy.prototype
* @type {Function}
* @param {number} x - input value
* @returns {number} evaluated PDF
* @see [pdf]{@link https://en.wikipedia.org/wiki/Probability_density_function}
*
* @example
* var kumaraswamy = new Kumaraswamy( 2.0, 4.0 );
*
* var v = kumaraswamy.pdf( 0.9 );
* // returns ~0.049
*/
setReadOnly( Kumaraswamy.prototype, 'pdf', kumaraswamyPDF );

/**
* Evaluates the quantile function.
*
* @name quantile
* @memberof Kumaraswamy.prototype
* @type {Function}
* @param {Probability} p - input probability
* @returns {number} evaluated quantile function
* @see [quantile function]{@link https://en.wikipedia.org/wiki/Quantile_function}
*
* @example
* var kumaraswamy = new Kumaraswamy( 2.0, 4.0 );
*
* var v = kumaraswamy.quantile( 0.5 );
* // returns ~0.399
*/
setReadOnly( Kumaraswamy.prototype, 'quantile', kumaraswamyQuantile );

// EXPORTS //

module.exports = Kumaraswamy;
<|endoftext|>


<commit_before>Components.utils.import("resource://greasemonkey/util.js");

function GM_xmlhttpRequester(wrappedContentWin, chromeWindow, originUrl) {
  this.wrappedContentWin = wrappedContentWin;
  this.chromeWindow = chromeWindow;
  this.originUrl = originUrl;
}

// this function gets called by user scripts in content security scope to
// start a cross-domain xmlhttp request.
//
// details should look like:
// {method,url,onload,onerror,onreadystatechange,headers,data}
// headers should be in the form {name:value,name:value,etc}
// can't support mimetype because i think it's only used for forcing
// text/xml and we can't support that
GM_xmlhttpRequester.prototype.contentStartRequest = function(details) {
  if (!GM_apiLeakCheck("GM_xmlhttpRequest")) {
    return;
  }

  try {
    // Validate and parse the (possibly relative) given URL.
    var uri = GM_util.uriFromUrl(details.url, this.originUrl);
    var url = uri.spec;
  } catch (e) {
    // A malformed URL won't be parsed properly.
    throw new Error("Invalid URL: " + details.url);
  }

  // This is important - without it, GM_xmlhttpRequest can be used to get
  // access to things like files and chrome. Careful.
  switch (uri.scheme) {
    case "http":
    case "https":
    case "ftp":
        var req = new this.chromeWindow.XMLHttpRequest();
        GM_util.hitch(this, "chromeStartRequest", url, details, req)();
      break;
    default:
      throw new Error("Disallowed scheme in URL: " + details.url);
  }

  var rv = { abort: function () { return req.abort(); } };
  if (!!details.synchronous) {
    rv.finalUrl = req.finalUrl;
    rv.readyState = req.readyState;
    rv.responseHeaders = req.getAllResponseHeaders();
    rv.responseText = req.responseText;
    rv.status = req.status;
    rv.statusText = req.statusText;
  }
  return rv;
};

// this function is intended to be called in chrome's security context, so
// that it can access other domains without security warning
GM_xmlhttpRequester.prototype.chromeStartRequest =
function(safeUrl, details, req) {
  this.setupReferer(details, req);

  var setupRequestEvent = GM_util.hitch(this, 'setupRequestEvent', this.wrappedContentWin);

  setupRequestEvent(req, "abort", details);
  setupRequestEvent(req, "error", details);
  setupRequestEvent(req, "load", details);
  setupRequestEvent(req, "progress", details);
  setupRequestEvent(req, "readystatechange", details);
  setupRequestEvent(req, "timeout", details);
  if (details.upload) {
    setupRequestEvent(req.upload, "abort", details.upload);
    setupRequestEvent(req.upload, "error", details.upload);
    setupRequestEvent(req.upload, "load", details.upload);
    setupRequestEvent(req.upload, "progress", details.upload);
  }

  req.mozBackgroundRequest = !!details.mozBackgroundRequest;

  req.open(details.method, safeUrl,
      !details.synchronous, details.user || "", details.password || "");

  if (details.overrideMimeType) {
    req.overrideMimeType(details.overrideMimeType);
  }
  if (details.timeout) {
    req.timeout = details.timeout;
  }

  if (details.headers) {
    var headers = details.headers;

    for (var prop in headers) {
      if (Object.prototype.hasOwnProperty.call(headers, prop)) {
        req.setRequestHeader(prop, headers[prop]);
      }
    }
  }

  var body = details.data ? details.data : null;
  if (details.binary) {
    req.sendAsBinary(body);
  } else {
    req.send(body);
  }
};

// sets the "Referer" HTTP header for this GM_XHR request.
// Firefox does not let chrome JS set the "Referer" HTTP heade via XHR
// directly. However, we can still set it indirectly via an
// http-on-modify-request observer.
GM_xmlhttpRequester.prototype.setupReferer =
function(details, req) {
  if (!details.headers || !details.headers.Referer) return;

  var observerService = Components.classes["@mozilla.org/observer-service;1"]
      .getService(Components.interfaces.nsIObserverService);
  var requestObserver = {};
  requestObserver.observe = function(subject, topic, data) {
      observerService.removeObserver(requestObserver, "http-on-modify-request");

      var channel = subject.QueryInterface(Components.interfaces.nsIChannel);
      if (channel == req.channel) {
        var httpChannel = subject.QueryInterface(
            Components.interfaces.nsIHttpChannel);
        httpChannel.setRequestHeader("Referer", details.headers.Referer, false);
      }
    };
  observerService.addObserver(requestObserver, "http-on-modify-request", false);
};

// arranges for the specified 'event' on xmlhttprequest 'req' to call the
// method by the same name which is a property of 'details' in the content
// window's security context.
GM_xmlhttpRequester.prototype.setupRequestEvent =
function(wrappedContentWin, req, event, details) {
  if (!details["on" + event]) return;

  req.addEventListener(event, function(evt) {
    var responseState = {
      // Can't support responseXML because security won't
      // let the browser call properties on it.
      responseText: req.responseText,
      readyState: req.readyState,
      responseHeaders: null,
      status: null,
      statusText: null,
      finalUrl: null
    };

    switch (event) {
      case "progress":
        responseState.lengthComputable = evt.lengthComputable;
        responseState.loaded = evt.loaded;
        responseState.total = evt.total;
        break;
      case "error":
        break;
      default:
        if (4 != req.readyState) break;
        responseState.responseHeaders = req.getAllResponseHeaders();
        responseState.status = req.status;
        responseState.statusText = req.statusText;
        responseState.finalUrl = req.channel.URI.spec;
        break;
    }

    if (GM_util.windowIsClosed(wrappedContentWin)) {
      return;
    }

    // Pop back onto browser thread and call event handler.
    // Have to use nested function here instead of GM_util.hitch because
    // otherwise details[event].apply can point to window.setTimeout, which
    // can be abused to get increased privileges.
    new XPCNativeWrapper(wrappedContentWin, "setTimeout()")
      .setTimeout(function(){ details["on" + event](responseState); }, 0);
  }, false);
};
<commit_msg>Specify __exposedProps__ for xmlhttprequester.<commit_after>Components.utils.import("resource://greasemonkey/util.js");

function GM_xmlhttpRequester(wrappedContentWin, chromeWindow, originUrl) {
  this.wrappedContentWin = wrappedContentWin;
  this.chromeWindow = chromeWindow;
  this.originUrl = originUrl;
}

// this function gets called by user scripts in content security scope to
// start a cross-domain xmlhttp request.
//
// details should look like:
// {method,url,onload,onerror,onreadystatechange,headers,data}
// headers should be in the form {name:value,name:value,etc}
// can't support mimetype because i think it's only used for forcing
// text/xml and we can't support that
GM_xmlhttpRequester.prototype.contentStartRequest = function(details) {
  if (!GM_apiLeakCheck("GM_xmlhttpRequest")) {
    return;
  }

  try {
    // Validate and parse the (possibly relative) given URL.
    var uri = GM_util.uriFromUrl(details.url, this.originUrl);
    var url = uri.spec;
  } catch (e) {
    // A malformed URL won't be parsed properly.
    throw new Error("Invalid URL: " + details.url);
  }

  // This is important - without it, GM_xmlhttpRequest can be used to get
  // access to things like files and chrome. Careful.
  switch (uri.scheme) {
    case "http":
    case "https":
    case "ftp":
        var req = new this.chromeWindow.XMLHttpRequest();
        GM_util.hitch(this, "chromeStartRequest", url, details, req)();
      break;
    default:
      throw new Error("Disallowed scheme in URL: " + details.url);
  }

  var rv = {
    __exposedProps__: {
        finalUrl: "r",
        readyState: "r",
        responseHeaders: "r",
        responseText: "r",
        status: "r",
        statusText: "r"
        },
    abort: function () { return req.abort(); }
  };
  if (!!details.synchronous) {
    rv.finalUrl = req.finalUrl;
    rv.readyState = req.readyState;
    rv.responseHeaders = req.getAllResponseHeaders();
    rv.responseText = req.responseText;
    rv.status = req.status;
    rv.statusText = req.statusText;
  }
  return rv;
};

// this function is intended to be called in chrome's security context, so
// that it can access other domains without security warning
GM_xmlhttpRequester.prototype.chromeStartRequest =
function(safeUrl, details, req) {
  this.setupReferer(details, req);

  var setupRequestEvent = GM_util.hitch(this, 'setupRequestEvent', this.wrappedContentWin);

  setupRequestEvent(req, "abort", details);
  setupRequestEvent(req, "error", details);
  setupRequestEvent(req, "load", details);
  setupRequestEvent(req, "progress", details);
  setupRequestEvent(req, "readystatechange", details);
  setupRequestEvent(req, "timeout", details);
  if (details.upload) {
    setupRequestEvent(req.upload, "abort", details.upload);
    setupRequestEvent(req.upload, "error", details.upload);
    setupRequestEvent(req.upload, "load", details.upload);
    setupRequestEvent(req.upload, "progress", details.upload);
  }

  req.mozBackgroundRequest = !!details.mozBackgroundRequest;

  req.open(details.method, safeUrl,
      !details.synchronous, details.user || "", details.password || "");

  if (details.overrideMimeType) {
    req.overrideMimeType(details.overrideMimeType);
  }
  if (details.timeout) {
    req.timeout = details.timeout;
  }

  if (details.headers) {
    var headers = details.headers;

    for (var prop in headers) {
      if (Object.prototype.hasOwnProperty.call(headers, prop)) {
        req.setRequestHeader(prop, headers[prop]);
      }
    }
  }

  var body = details.data ? details.data : null;
  if (details.binary) {
    req.sendAsBinary(body);
  } else {
    req.send(body);
  }
};

// sets the "Referer" HTTP header for this GM_XHR request.
// Firefox does not let chrome JS set the "Referer" HTTP heade via XHR
// directly. However, we can still set it indirectly via an
// http-on-modify-request observer.
GM_xmlhttpRequester.prototype.setupReferer =
function(details, req) {
  if (!details.headers || !details.headers.Referer) return;

  var observerService = Components.classes["@mozilla.org/observer-service;1"]
      .getService(Components.interfaces.nsIObserverService);
  var requestObserver = {};
  requestObserver.observe = function(subject, topic, data) {
      observerService.removeObserver(requestObserver, "http-on-modify-request");

      var channel = subject.QueryInterface(Components.interfaces.nsIChannel);
      if (channel == req.channel) {
        var httpChannel = subject.QueryInterface(
            Components.interfaces.nsIHttpChannel);
        httpChannel.setRequestHeader("Referer", details.headers.Referer, false);
      }
    };
  observerService.addObserver(requestObserver, "http-on-modify-request", false);
};

// arranges for the specified 'event' on xmlhttprequest 'req' to call the
// method by the same name which is a property of 'details' in the content
// window's security context.
GM_xmlhttpRequester.prototype.setupRequestEvent =
function(wrappedContentWin, req, event, details) {
  if (!details["on" + event]) return;

  req.addEventListener(event, function(evt) {
    var responseState = {
      __exposedProps__: {
          finalUrl: "r",
          readyState: "r",
          responseHeaders: "r",
          responseText: "r",
          status: "r",
          statusText: "r"
          },
      // Can't support responseXML because security won't
      // let the browser call properties on it.
      responseText: req.responseText,
      readyState: req.readyState,
      responseHeaders: null,
      status: null,
      statusText: null,
      finalUrl: null
    };

    switch (event) {
      case "progress":
        responseState.lengthComputable = evt.lengthComputable;
        responseState.loaded = evt.loaded;
        responseState.total = evt.total;
        break;
      case "error":
        break;
      default:
        if (4 != req.readyState) break;
        responseState.responseHeaders = req.getAllResponseHeaders();
        responseState.status = req.status;
        responseState.statusText = req.statusText;
        responseState.finalUrl = req.channel.URI.spec;
        break;
    }

    if (GM_util.windowIsClosed(wrappedContentWin)) {
      return;
    }

    // Pop back onto browser thread and call event handler.
    // Have to use nested function here instead of GM_util.hitch because
    // otherwise details[event].apply can point to window.setTimeout, which
    // can be abused to get increased privileges.
    new XPCNativeWrapper(wrappedContentWin, "setTimeout()")
      .setTimeout(function(){ details["on" + event](responseState); }, 0);
  }, false);
};
<|endoftext|>


<commit_before>/* This file is only loaded on Cordova-bundled apps and is used only in case
 * autoupdate package is used.
 * It checks if File plugin is installed and a newer version of the app code can
 * be found on persistent storage. In that case those files are dynamically
 * added to the page.
 * Otherwise a normal app code is loaded (shipped with the app initially).
 */

(function () {

  var loadedEvent = (function () {
    var usingEventConstructor = false;

    // some browsers don't support the Event constructor
    // eg Cordova on Android JellyBean
    if (window.Event) {
      usingEventConstructor = true;
    }

    var eventName = 'meteor-cordova-loaded';
    var event;
    if (usingEventConstructor) {
      event = new Event(eventName);
    } else {
      event = document.createEvent('Event');
      event.initEvent(eventName, true, true);
    }

    return {
      dispatch: function () {
        document.dispatchEvent(event);
      }
    };
  })();

  var readFile = function (url, cb) {
    window.resolveLocalFileSystemURL(url,
      function (fileEntry) {
        var success = function (file) {
          var reader = new FileReader();
          reader.onloadend = function (evt) {
            var result = evt.target.result;
            cb(null, result);
          };
          reader.onerror = fail;
          reader.readAsText(file);
        };
        var fail = function (evt) {
          cb(new Error("Failed to load entry"), null);
        };
        fileEntry.file(success, fail);
      },
      // error callback
      function (err) { cb(new Error("Failed to load entry"), null); }
    );
  };

  var each = function (array, f) {
    for (var i = 0; i < array.length; i++)
      f(array[i], i, array);
  };

  // To ensure that all our <script> tags are loaded in the correct order we add
  // them to DOM one by one.
  // The assumption here is that every element in the queue is a function that
  // calls loadScript only once. Because loadScript makes sure to call
  // launchNext after the async operation is done, it works as intended. We
  // allow the last function to be something different (like trigger the
  // document event).
  var queue = [];
  var launchNext = function () {
    if (! queue.length)
      return;
    var fun = queue.shift();
    fun();
  };

  var loadScript = function (url) {
    var scriptTag = document.createElement('script');
    scriptTag.type = "text/javascript";
    scriptTag.src = url;
    scriptTag.onload = launchNext;

    document.getElementsByTagName('head')[0].appendChild(scriptTag);
  };

  var loadStyle = function (url) {
    var styleTag = document.createElement('link');
    styleTag.rel = "stylesheet";
    styleTag.type = "text/css";
    styleTag.href = url;
    document.getElementsByTagName('head')[0].appendChild(styleTag);
  };

  var stripLeadingSlash = function (p) {
    if (p.charAt(0) !== '/')
      throw new Error("bad path: " + p);
    return p.slice(1);
  };

  var loadAssetsFromManifest = function (manifest, urlPrefix) {
    // Set the base href so that relative paths point to the correct version
    // of the app.
    var newBase = document.createElement("base");
    newBase.setAttribute("href", urlPrefix);
    document.getElementsByTagName("head")[0].appendChild(newBase);

    each(manifest, function (item) {
      // We want to use relative paths so that our base href is taken into
      // account.
      var url = item.url ? stripLeadingSlash(item.url) : '';
      if (item.type === 'js')
        queue.push(function () {
          loadScript(url);
        });
      else if (item.type === 'css')
        loadStyle(url);
    });

    queue.push(function () {
      loadedEvent.dispatch();
    });

    launchNext();
  };

  // Fallback to the bundled assets from the disk. If an error is passed as an
  // argument, then there was a problem reading from the manifest files. If
  // no error is passed, then we simply do not have any new versions.
  var fallback = function (err) {
    if (err) {
      console.log('Couldn\'t load from the manifest, ' +
                  'falling back to the bundled assets.');
    } else {
      console.log('No new versions saved to disk.');
    }

    loadAssetsFromManifest(__meteor_manifest__, '');
  };

  var cleanCache = function (url, cb) {
    var fail = function (err) {
      console.log("Clearing cache failed: ");
      console.log(err);
      cb();
    };
    window.resolveLocalFileSystemURL(url, function(entry) {
      entry.removeRecursively(function() {
        console.log("Cleared cache successfully.");
        cb();
      }, fail);
    }, fail);
  };

  var loadApp = function (localPathPrefix) {

    readFile(localPathPrefix + 'version',
      function (err, version) {
        if (err) {
          fallback();
          return;
        }

        var versionPrefix = localPathPrefix + version + '/';

        // We have a version string, now read the new version
        readFile(versionPrefix + 'manifest.json',
            function (err, res) {
          if (err) {
            fallback(err);
            return;
          }

          var program = JSON.parse(res);
          // update the version we are loading
          __meteor_runtime_config__.autoupdateVersionCordova = version;
          // update the public settings
          __meteor_runtime_config__.PUBLIC_SETTINGS = program.PUBLIC_SETTINGS;

          loadAssetsFromManifest(program.manifest, versionPrefix);
        });
    });
  };

  document.addEventListener("deviceready", function () {
    var localPathPrefix = cordova.file.applicationStorageDirectory +
                          'Documents/meteor/';
    if (__meteor_runtime_config__.cleanCache) {
      // If cleanCache is enabled, clean the cache and then load the app.
      cleanCache(localPathPrefix, function () {
        loadApp(localPathPrefix);
      });
    } else {
      loadApp(localPathPrefix);
    }
  }, false);
})();

<commit_msg>Clean up the cache folder on every startup, so we don't keep all versions of your app on disk forever.<commit_after>/* This file is only loaded on Cordova-bundled apps and is used only in case
 * autoupdate package is used.
 * It checks if File plugin is installed and a newer version of the app code can
 * be found on persistent storage. In that case those files are dynamically
 * added to the page.
 * Otherwise a normal app code is loaded (shipped with the app initially).
 */

(function () {

  var loadedEvent = (function () {
    var usingEventConstructor = false;

    // some browsers don't support the Event constructor
    // eg Cordova on Android JellyBean
    if (window.Event) {
      usingEventConstructor = true;
    }

    var eventName = 'meteor-cordova-loaded';
    var event;
    if (usingEventConstructor) {
      event = new Event(eventName);
    } else {
      event = document.createEvent('Event');
      event.initEvent(eventName, true, true);
    }

    return {
      dispatch: function () {
        document.dispatchEvent(event);
      }
    };
  })();

  var readFile = function (url, cb) {
    window.resolveLocalFileSystemURL(url,
      function (fileEntry) {
        var success = function (file) {
          var reader = new FileReader();
          reader.onloadend = function (evt) {
            var result = evt.target.result;
            cb(null, result);
          };
          reader.onerror = fail;
          reader.readAsText(file);
        };
        var fail = function (evt) {
          cb(new Error("Failed to load entry"), null);
        };
        fileEntry.file(success, fail);
      },
      // error callback
      function (err) { cb(new Error("Failed to load entry"), null); }
    );
  };

  var each = function (array, f) {
    for (var i = 0; i < array.length; i++)
      f(array[i], i, array);
  };

  // To ensure that all our <script> tags are loaded in the correct order we add
  // them to DOM one by one.
  // The assumption here is that every element in the queue is a function that
  // calls loadScript only once. Because loadScript makes sure to call
  // launchNext after the async operation is done, it works as intended. We
  // allow the last function to be something different (like trigger the
  // document event).
  var queue = [];
  var launchNext = function () {
    if (! queue.length)
      return;
    var fun = queue.shift();
    fun();
  };

  var loadScript = function (url) {
    var scriptTag = document.createElement('script');
    scriptTag.type = "text/javascript";
    scriptTag.src = url;
    scriptTag.onload = launchNext;

    document.getElementsByTagName('head')[0].appendChild(scriptTag);
  };

  var loadStyle = function (url) {
    var styleTag = document.createElement('link');
    styleTag.rel = "stylesheet";
    styleTag.type = "text/css";
    styleTag.href = url;
    document.getElementsByTagName('head')[0].appendChild(styleTag);
  };

  var stripLeadingSlash = function (p) {
    if (p.charAt(0) !== '/')
      throw new Error("bad path: " + p);
    return p.slice(1);
  };

  var loadAssetsFromManifest = function (manifest, urlPrefix) {
    // Set the base href so that relative paths point to the correct version
    // of the app.
    var newBase = document.createElement("base");
    newBase.setAttribute("href", urlPrefix);
    document.getElementsByTagName("head")[0].appendChild(newBase);

    each(manifest, function (item) {
      // We want to use relative paths so that our base href is taken into
      // account.
      var url = item.url ? stripLeadingSlash(item.url) : '';
      if (item.type === 'js')
        queue.push(function () {
          loadScript(url);
        });
      else if (item.type === 'css')
        loadStyle(url);
    });

    queue.push(function () {
      loadedEvent.dispatch();
    });

    launchNext();
  };

  // Fallback to the bundled assets from the disk. If an error is passed as an
  // argument, then there was a problem reading from the manifest files. If
  // no error is passed, then we simply do not have any new versions.
  var fallback = function (err) {
    if (err) {
      console.log('Couldn\'t load from the manifest, ' +
                  'falling back to the bundled assets.');
    } else {
      console.log('No new versions saved to disk.');
    }

    loadAssetsFromManifest(__meteor_manifest__, '');
  };

  var listDirectory = function (url, options, cb) {
    if (typeof options === 'function')
      cb = options, options = {};

    var fail = function (err) { cb(err); };
    window.resolveLocalFileSystemURL(url, function (entry) {
      var reader = entry.createReader();
      reader.readEntries(function (entries) {
        var names = [];
        each(entries, function (entry) {
          if (! options.dirsOnly || entry.isDirectory)
            names.push(entry.name);
        });
        cb(null, names);
      }, fail);
    }, fail);
  };

  var removeDirectory = function (url, cb) {
    var fail = function (err) {
      cb(err);
    };
    window.resolveLocalFileSystemURL(url, function (entry) {
      entry.removeRecursively(function () {
        cb();
      }, fail);
    }, fail);
  };

  var loadVersion = function (version, localPathPrefix) {
    var versionPrefix = localPathPrefix + version + '/';
    // We have a version string, now read the new version
    readFile(versionPrefix + 'manifest.json',
        function (err, res) {
      if (err) {
        fallback(err);
        return;
      }

      var program = JSON.parse(res);
      // update the version we are loading
      __meteor_runtime_config__.autoupdateVersionCordova = version;
      // update the public settings
      __meteor_runtime_config__.PUBLIC_SETTINGS = program.PUBLIC_SETTINGS;

      loadAssetsFromManifest(program.manifest, versionPrefix);
    });
  };

  var loadApp = function (localPathPrefix) {
    readFile(localPathPrefix + 'version',
      function (err, version) {
        if (err) {
          fallback();
          return;
        }

        // Try to clean up our cache directory, make sure to scan the directory
        // *before* loading the actual app. This ordering will prevent race
        // conditions when the app code tries to download a new version before
        // the old-cache removal has scanned the cache folder.
        listDirectory(localPathPrefix, {dirsOnly: true}, function (err, names) {
          loadVersion(version, localPathPrefix);

          if (err) return;
          each(names, function (name) {
            // Skip the folder with the latest version
            if (name === version)
              return;

            // remove everything else, as we don't want to keep too much cache
            // around on disk
            removeDirectory(localPathPrefix + name + '/', function (err) {
              if (err) {
                console.log('Failed to remove an old cache folder '
                            + name + ':' + err.message);
              } else {
                console.log('Successfully removed an old cache folder ' + name);
              }
            });
          });
        });
    });
  };

  document.addEventListener("deviceready", function () {
    var localPathPrefix = cordova.file.applicationStorageDirectory +
                          'Documents/meteor/';
    if (__meteor_runtime_config__.cleanCache) {
      // If cleanCache is enabled, clean the cache and then load the app.
      removeDirectory(localPathPrefix, function (err) {
        if (err) console.log('Failed to clear cache: ' + err.message);
        else console.log('Successfully cleared the cache.');

        loadApp(localPathPrefix);
      });
    } else {
      loadApp(localPathPrefix);
    }
  }, false);
})();

<|endoftext|>