<commit_before>define( ['dojo/_base/declare',
         'dojo/_base/array'
        ],
        function( declare, array ) {

var Feature = declare( null,

/**
 * @lends JBrowse.Store.BAM.Feature
 */
{

    /**
     * Feature object used for the JBrowse BAM backend.
     * @param args.store the BAM store this feature comes from
     * @param args.record optional BAM record (a plain object) containing the data for this feature
     * @constructs
     */
    constructor: function( args ) {
        this.store = args.store;

        var data = args.record ? dojo.clone( args.record ) : args.data;

        // figure out start and end
        data.start = data.start || data.pos;
        data.end = data.end || ( data.lref ? data.pos + data.lref : data.seq ? data.pos + data.seq.length : undefined );

        /*  can extract "SEQ reverse complement" from bitwise flag,
         *    but that gives orientation of the _read sequence_ relative to the reference,
         *    whereas feat[STRAND] is intended to indicate orientation of the _template_
         *        (in the case of RNA-Seq, the RNA that the read is derived from) relative to the reference
         *   for some BAM sources (such as TopHat), an optional field "XS" is used to to indicate RNA orientation
         *        relative to ref.  'XS' values are '+' or '-' (any others?),
         *        for some sources, lack of 'XS' is meant to indicate plus strand, only minus strand are specifically tagged
         *   for more on strandedness, see seqanswers.com/forums/showthread.php?t=9303
         *   TODO: really need to determine whether to look at bitwise flag, or XS, or something else based
         *           on the origin of the BAM data (type of sequencer or program name, etc.)
         *           for now using XS based on honeybee BAM data
         */
        // trying to determine orientation from 'XS' optional field
        data.strand = ('XS' in data )                ? ( data.XS == '-' ? -1 : 1 ) :
                       data.seq_reverse_complemented ? -1                          :
                                                       1;

        data.score = data.mapping_quality || data.MQ || data.mq;
        data.type = data.type || 'match';
        data.source = args.store.source;
        data.seq_id = data.segment;
        delete data.segment;

        if( data.qual && data.qual.join )
            data.qual = data.qual.join(' ');

        if( data.readName ) {
            data.name = data.readName;
            delete data.readName;
        }
        delete data.pos;

        this.data = data;
        this._subCounter = 0;
        this._uniqueID = args.parent ? args.parent._uniqueID + '-' + ++args.parent._subCounter
                                     : this.data.name+' at '+ data.seq_id + ':' + data.start + '..' + data.end;

        var cigar = data.CIGAR || data.cigar;
        this.data.subfeatures = [];
        if( cigar ) {
            this.data.Gap = this._cigarToGap( cigar );
            this.data.subfeatures.push.apply( this.data.subfeatures, this._cigarToSubfeats( cigar, this ) );
        }
    },

    _parseCigar: function( cigar ) {
        return array.map( cigar.match(/\d+\D/g), function( op ) {
           return [ op.match(/\D/)[0].toUpperCase(), parseInt( op ) ];
        });
    },

    /**
     *  take a cigar string, and initial position, return an array of subfeatures
     */
    _cigarToSubfeats: function(cigar, parent)    {
        var subfeats = [];
        var min = parent.get('start');
        var max;
        var ops = this._parseCigar( cigar );
        for (var i = 0; i < ops.length; i++)  {
            var lop = ops[i][1];
            var op = ops[i][0];  // operation type
            // converting "=" to "E" to avoid possible problems later with non-alphanumeric type name
            if (op === "=")  { op = "E"; }

            switch (op) {
            case 'M':
            case 'D':
            case 'N':
            case 'E':
            case 'X':
                max = min + lop;
                break;
            case 'I':
                max = min;
                break;
            case 'P':  // not showing padding deletions (possibly change this later -- could treat same as 'I' ?? )
            case 'H':  // not showing hard clipping (since it's unaligned, and offset arg meant to be beginning of aligned part)
            case 'S':  // not showing soft clipping (since it's unaligned, and offset arg meant to be beginning of aligned part)
                break;
                // other possible cases
            }
            var subfeat = new Feature({
                store: this.store,
                data: {
                    type: 'match_part',
                    start: min,
                    end: max,
                    strand: parent.get('strand'),
                    cigar_op: lop+op
                },
                parent: this
            });
            if (op !== 'N')  {
                subfeats.push(subfeat);
            }
            min = max;
        }
        return subfeats;
    },

    /**
     * Takes a CIGAR string, translates to a GFF3 Gap attribute
     */
    _cigarToGap: function(cigar)    {
        return array.map( this._parseCigar( cigar ), function( op ) {
            return ( {
                         // map the CIGAR operations to the less-descriptive
                         // GFF3 gap operations
                         M: 'M',
                         I: 'I',
                         D: 'D',
                         N: 'D',
                         S: 'M',
                         H: 'M',
                         P: 'I'
                     }[op[0]] || op[0]
                   )+op[1];
        }).join(' ');
    },

    get: function(name) {
        return this.data[ name ];
    },

    tags: function() {
        var t = [];
        var d = this.data;
        for( var k in d ) {
            if( d.hasOwnProperty( k ) )
                t.push( k );
        }
        return t;
    }

});

return Feature;
});
<commit_msg>don't rename segment to seq_id in BAM features, causes confusion with the seq_* attributes<commit_after>define( ['dojo/_base/declare',
         'dojo/_base/array'
        ],
        function( declare, array ) {

var Feature = declare( null,

/**
 * @lends JBrowse.Store.BAM.Feature
 */
{

    /**
     * Feature object used for the JBrowse BAM backend.
     * @param args.store the BAM store this feature comes from
     * @param args.record optional BAM record (a plain object) containing the data for this feature
     * @constructs
     */
    constructor: function( args ) {
        this.store = args.store;

        var data = args.record ? dojo.clone( args.record ) : args.data;

        // figure out start and end
        data.start = data.start || data.pos;
        data.end = data.end || ( data.lref ? data.pos + data.lref : data.seq ? data.pos + data.seq.length : undefined );

        /*  can extract "SEQ reverse complement" from bitwise flag,
         *    but that gives orientation of the _read sequence_ relative to the reference,
         *    whereas feat[STRAND] is intended to indicate orientation of the _template_
         *        (in the case of RNA-Seq, the RNA that the read is derived from) relative to the reference
         *   for some BAM sources (such as TopHat), an optional field "XS" is used to to indicate RNA orientation
         *        relative to ref.  'XS' values are '+' or '-' (any others?),
         *        for some sources, lack of 'XS' is meant to indicate plus strand, only minus strand are specifically tagged
         *   for more on strandedness, see seqanswers.com/forums/showthread.php?t=9303
         *   TODO: really need to determine whether to look at bitwise flag, or XS, or something else based
         *           on the origin of the BAM data (type of sequencer or program name, etc.)
         *           for now using XS based on honeybee BAM data
         */
        // trying to determine orientation from 'XS' optional field
        data.strand = ('XS' in data )                ? ( data.XS == '-' ? -1 : 1 ) :
                       data.seq_reverse_complemented ? -1                          :
                                                       1;

        data.score = data.mapping_quality || data.MQ || data.mq;
        data.type = data.type || 'match';
        data.source = args.store.source;
        data.segment = data.segment;

        if( data.qual && data.qual.join )
            data.qual = data.qual.join(' ');

        if( data.readName ) {
            data.name = data.readName;
            delete data.readName;
        }
        delete data.pos;

        this.data = data;
        this._subCounter = 0;
        this._uniqueID = args.parent ? args.parent._uniqueID + '-' + ++args.parent._subCounter
                                     : this.data.name+' at '+ data.segment + ':' + data.start + '..' + data.end;

        var cigar = data.CIGAR || data.cigar;
        this.data.subfeatures = [];
        if( cigar ) {
            this.data.Gap = this._cigarToGap( cigar );
            this.data.subfeatures.push.apply( this.data.subfeatures, this._cigarToSubfeats( cigar, this ) );
        }
    },

    _parseCigar: function( cigar ) {
        return array.map( cigar.match(/\d+\D/g), function( op ) {
           return [ op.match(/\D/)[0].toUpperCase(), parseInt( op ) ];
        });
    },

    /**
     *  take a cigar string, and initial position, return an array of subfeatures
     */
    _cigarToSubfeats: function(cigar, parent)    {
        var subfeats = [];
        var min = parent.get('start');
        var max;
        var ops = this._parseCigar( cigar );
        for (var i = 0; i < ops.length; i++)  {
            var lop = ops[i][1];
            var op = ops[i][0];  // operation type
            // converting "=" to "E" to avoid possible problems later with non-alphanumeric type name
            if (op === "=")  { op = "E"; }

            switch (op) {
            case 'M':
            case 'D':
            case 'N':
            case 'E':
            case 'X':
                max = min + lop;
                break;
            case 'I':
                max = min;
                break;
            case 'P':  // not showing padding deletions (possibly change this later -- could treat same as 'I' ?? )
            case 'H':  // not showing hard clipping (since it's unaligned, and offset arg meant to be beginning of aligned part)
            case 'S':  // not showing soft clipping (since it's unaligned, and offset arg meant to be beginning of aligned part)
                break;
                // other possible cases
            }
            var subfeat = new Feature({
                store: this.store,
                data: {
                    type: 'match_part',
                    start: min,
                    end: max,
                    strand: parent.get('strand'),
                    cigar_op: lop+op
                },
                parent: this
            });
            if (op !== 'N')  {
                subfeats.push(subfeat);
            }
            min = max;
        }
        return subfeats;
    },

    /**
     * Takes a CIGAR string, translates to a GFF3 Gap attribute
     */
    _cigarToGap: function(cigar)    {
        return array.map( this._parseCigar( cigar ), function( op ) {
            return ( {
                         // map the CIGAR operations to the less-descriptive
                         // GFF3 gap operations
                         M: 'M',
                         I: 'I',
                         D: 'D',
                         N: 'D',
                         S: 'M',
                         H: 'M',
                         P: 'I'
                     }[op[0]] || op[0]
                   )+op[1];
        }).join(' ');
    },

    get: function(name) {
        return this.data[ name ];
    },

    tags: function() {
        var t = [];
        var d = this.data;
        for( var k in d ) {
            if( d.hasOwnProperty( k ) )
                t.push( k );
        }
        return t;
    }

});

return Feature;
});
<|endoftext|>


<commit_before>import { Types } from 'mongoose';
import Promise from 'bluebird';

import Attraction from './attraction.model';
// return all attractions
export function list(req, res, next) {
  Attraction.find()
    .then((attractions) => {
      res.json(attractions);
    })
    .catch(next);
}

// return the list of currently used categories
export function categories(req, res, next) {
   Attraction.find().distinct('category').exec( function (err, docs) {
    if (err)
        res.send(err);
    res.json(docs);
  });
}

// return the list of attractions of a given category
export function category(req, res, next) {
  Attraction.find({category: req.params.category}).exec( function (err, docs) {
   if (err)
       res.send(err);
   res.json(docs);
   });
}

// return a list containing "limit"-number of attractions of a given category in descending order
export function top(req, res, next) {
  Attraction.find({category: req.params.category}).sort({'rating.quality.rating': -1}).limit(parseInt(req.params.limit)).exec( function (err, docs) {
   if (err)
       res.send(err);
   res.json(docs);
   });
}

// return the list of the top attractions for a given number
export function best(req, res, next) {
  Attraction.find().sort({'rating.quality.rating': -1}).limit(parseInt(req.params.limit)).exec( function (err, docs) {
   if (err)
       res.send(err);
   res.json(docs);
   });
}
// return the list of all attrations ordered by quality
export function all(req, res, next) {
  Attraction.find().sort({'rating.quality.rating': -1}).exec( function (err, docs) {
   if (err)
       res.send(err);
   res.json(docs);
   });
}

exports.get = function(req, res){
  Attraction.find().exec(function(err, attraction){
    res.jsonp(attraction);
  });
};

// get a list of attractions belonging to one city, sorted by most popular
export function getAllFromCityId(req, res, next) {
  Attraction.find({ city: req.params.city }).sort({ 'rating.quality.rating': -1 })
    .then((attractions) => {
      res.json(attractions);
    })
    .catch(next);
}

function newRating(currentRating, amount, newRating) {
  return (newRating/(amount + 1)) + (currentRating * amount/(amount+1));
}

// TO-DO put rating and updating
export function rateAttractions(req, res, next) {
  // Mocka: en liste av nye ratings, en bruker rater en hel reise av gangen
  const ratings = [{ attractionId: '56aa0dc353c8040f4cc54637', quality: 2, popularity: 2 }, { attractionId: '56ca0db353d8040f4cc54638', quality: 5, popularity: 5 }]

  // For hver attraction: Oppdater rating
  Promise.map(ratings, rating =>
    Attraction.findOne(
      { _id: rating.attractionId }
    ).then((attraction) => {
      console.log(attraction);
      attraction.rating.quality.rating = newRating(
        attraction.rating.quality.rating,
        attraction.rating.quality.amount,
        rating.quality);
      attraction.rating.quality.amount += 1;

      attraction.rating.popularity.rating = newRating(
        attraction.rating.popularity.rating,
        attraction.rating.popularity.amount,
        rating.popularity);
      attraction.rating.popularity.amount += 1;

      return attraction.save();
    })).then(
      res.sendStatus(200)
    ).catch(next);
}
<commit_msg>read object from request body<commit_after>import { Types } from 'mongoose';
import Promise from 'bluebird';

import Attraction from './attraction.model';
// return all attractions
export function list(req, res, next) {
  Attraction.find()
    .then((attractions) => {
      res.json(attractions);
    })
    .catch(next);
}

// return the list of currently used categories
export function categories(req, res, next) {
   Attraction.find().distinct('category').exec( function (err, docs) {
    if (err)
        res.send(err);
    res.json(docs);
  });
}

// return the list of attractions of a given category
export function category(req, res, next) {
  Attraction.find({category: req.params.category}).exec( function (err, docs) {
   if (err)
       res.send(err);
   res.json(docs);
   });
}

// return a list containing "limit"-number of attractions of a given category in descending order
export function top(req, res, next) {
  Attraction.find({category: req.params.category}).sort({'rating.quality.rating': -1}).limit(parseInt(req.params.limit)).exec( function (err, docs) {
   if (err)
       res.send(err);
   res.json(docs);
   });
}

// return the list of the top attractions for a given number
export function best(req, res, next) {
  Attraction.find().sort({'rating.quality.rating': -1}).limit(parseInt(req.params.limit)).exec( function (err, docs) {
   if (err)
       res.send(err);
   res.json(docs);
   });
}
// return the list of all attrations ordered by quality
export function all(req, res, next) {
  Attraction.find().sort({'rating.quality.rating': -1}).exec( function (err, docs) {
   if (err)
       res.send(err);
   res.json(docs);
   });
}

exports.get = function(req, res){
  Attraction.find().exec(function(err, attraction){
    res.jsonp(attraction);
  });
};

// get a list of attractions belonging to one city, sorted by most popular
export function getAllFromCityId(req, res, next) {
  Attraction.find({ city: req.params.city }).sort({ 'rating.quality.rating': -1 })
    .then((attractions) => {
      res.json(attractions);
    })
    .catch(next);
}

function newRating(currentRating, amount, newRating) {
  return (newRating/(amount + 1)) + (currentRating * amount/(amount+1));
}

// TO-DO put rating and updating
export function rateAttractions(req, res, next) {
  // Mocka: en liste av nye ratings, en bruker rater en hel reise av gangen
  // const ratings = [{ attractionId: '56aa0dc353c8040f4cc54637', quality: 2, popularity: 2 }, { attractionId: '56ca0db353d8040f4cc54638', quality: 5, popularity: 5 }]
  const ratings = req.body.ratings;
  // For hver attraction: Oppdater rating
  Promise.map(ratings, rating =>
    Attraction.findOne(
      { _id: rating.attractionId }
    ).then((attraction) => {
      console.log(attraction);
      attraction.rating.quality.rating = newRating(
        attraction.rating.quality.rating,
        attraction.rating.quality.amount,
        rating.quality);
      attraction.rating.quality.amount += 1;

      attraction.rating.popularity.rating = newRating(
        attraction.rating.popularity.rating,
        attraction.rating.popularity.amount,
        rating.popularity);
      attraction.rating.popularity.amount += 1;

      return attraction.save();
    })).then(
      res.sendStatus(200)
    ).catch(next);
}
<|endoftext|>


<commit_before>b6ad6f86-973a-11e6-b514-8086f2004150<commit_msg>Initial commit.13<commit_after>b6b19606-973a-11e6-b514-8086f2004150<|endoftext|>


<commit_before>( function( mw, $ ) {

mw.addFreeWheelControler = function( embedPlayer, config, callback ) {
	embedPlayer.freeWheelAds = new mw.freeWheelControler({
		'embedPlayer' : embedPlayer,
		'config' : config,
		'callback' :  callback
	});
	mw.freeWheelGlobalContextInstance = embedPlayer.freeWheelAds;
};

mw.freeWheelControler = function( opt ){
	return this.init( opt );
};

mw.freeWheelControler.prototype = {

	// The freeWheel adManager
	adManager: null,

	// The ad Context:
	adContext: null,

	// The ad data requested
	adDataRequested : false,

	// The pre video url
	contentVideoURL : null,

	// prerollSlots
	prerollSlots : [],

	// midroll_overlaySlots
	midroll_overlaySlots : [],

	// postrollSlots
	postrollSlots: [],

	// slotPlaying
	slotPlaying: false,

	/**
	 * Initialize the adMannager javascript and setup adds
	 *
	 * @param {Object} opt Object
	 * {
	 * 	'embedPlayer' {object} the embedPlayer instance
	 * 	'config' {object} any freewheel configuration
	 * 	'callback' {function} called on load complete
	 * }
	 * @return
	 */
	init: function( opt ){
		var _this = this;
		$.extend( this, opt);

		// XXX temporary override config for testing
		this.config = {
			'networkId' :'96749',
			'serverUrl' : 'http://sdnyadvip1-d.fwmrm.net/ad/g/1',
			'videoAssetId' : 'DemoVideoGroup.01',
			'videoDuration' : 500
		};

		// Load the ad manager url:
		// XXX todo we should be able to read this from "adManagerUrl"
		var AdManagerUrl = mw.getConfig( 'FreeWheel.AdManagerUrl' );

		//$.getScript(AdManagerUrl, function(){
		// For debugging use local copy:
		mw.load( 'tv.freewheel.SDK', function(){
			_this.setupAds();
		});
	},
	/**
	 * Setup ads, main freeWheel control flow
	 * @return
	 */
	setupAds: function(){
		var _this = this;

		// Add key-values for ad targeting.
		this.addContextKeyValues();

		// Listen to AdManager Events
		this.addContextListners();

		// Set context timeout
		this.setContextTimeout();

		// Add the temporal slots for this "player"
		this.addTemporalSlots();

		// Add local companion targets
		this.addCompanionBindings();

		// FreeWheel sets SVLads003 as the response?
		window['SVLads003'] = true;
		// Load add data ( will call onRequestComplete once ready )
		mw.log("freeWheelController::submitRequest>");
		this.getContext().submitRequest();
	},
	/**
	 * Called on the completion of freeWheel add loading
	 * @param event
	 * @return
	 */
	onRequestComplete: function( event ){
		var _this = mw.freeWheelGlobalContextInstance;
		mw.log("freeWheelController::onRequestComplete>");
		if ( event.success ){
			var fwTemporalSlots = _this.getContext().getTemporalSlots();
			for (var i=0; i < fwTemporalSlots.length; i++){
				var slot = fwTemporalSlots[i];
				switch ( slot.getTimePositionClass() ){
					case tv.freewheel.SDK.TIME_POSITION_CLASS_PREROLL:
						_this.prerollSlots.push(slot);
						break;
					case tv.freewheel.SDK.TIME_POSITION_CLASS_MIDROLL:
					case tv.freewheel.SDK.TIME_POSITION_CLASS_OVERLAY:
						_this.midroll_overlaySlots.push(slot);
						break;
					case tv.freewheel.SDK.TIME_POSITION_CLASS_POSTROLL:
						_this.postrollSlots.push(slot);
						break;
				}
			}
			if( _this.prerollSlots[0] )
				_this.prerollSlots[0].play();
		}
		// issue the "ready callback"
		mw.freeWheelGlobalContextInstance.callback();
	},
	/**
	 * Adds local companion targets ( if they  exists ) for easy passing across iframe
	 * @return
	 */
	addCompanionBindings: function(){
		var _this = this;
		mw.log("freeWheelController::addCompanionBindings>");
		// Add some hidden companion targets if we are running in an iframe
		if( !mw.getConfig('EmbedPlayer.IsIframeServer') ){
			return ;
		}
		// Setup the embedPlayer server setFreeWheelAddCompanions method
		this.embedPlayer.setFreeWheelAddCompanions = function( companionSet ){
			_this.addCompanionTargets( companionSet );
		};

		// Trigger the adding of any server side bindings:
		$( this.embedPlayer ).trigger( 'FreeWheel_GetAddCompanions' );
		// we now monitor for companion html changes and pass that across the iframe
		this.monitorForCompanionChanges();
	},
	monitorForCompanionChanges: function(){
		var _this = this;
		var companionStateCache = {};
		setInterval(function(){
			$('#fw_companion_container').find( '._fwph').each(function(inx, node){
				var id = $(node).attr('id');
				var curHtml = $('#_fw_container_' + id ).html();
				if( curHtml && companionStateCache[ id ] != curHtml){
					$( _this.embedPlayer ).trigger('FreeWheel_UpdateCompanion', {
						'id' : id,
						'content' : curHtml
					});
					companionStateCache[ id ] = curHtml;
				}
			});
		},1000);
	},
	/**
	 * Add hidden companion targets for companions to be passed overt the iframe
	 * @param companionSet
	 * @return
	 */
	addCompanionTargets: function( companionSet ){
		if(! $('#fw_companion_container').length ){
			$('body').append( $('<div />').attr('id', 'fw_companion_container' ) );
		}

		$.each(companionSet, function(inx, companion){
			var id =  companion.id;
			$('#fw_companion_container').append(
				$('<span />').attr('id', id ).addClass( '_fwph' )
				.css('display', 'none')
				.append(
					$('<form />').attr('id', '_fw_form_' + id )
					.append(
						$('<input type="hidden"/>').attr({
							'name' : '_fw_input_' + id,
							'id' : '_fw_input_' + id
						})
					),
					$('<span />').attr('id', '_fw_container_' + id )
				)
			);
		});
		mw.log( 'freeWheelController:: addCompanionTargets: Added:' + $('#fw_companion_container ._fwph').length + ' targets' );
	},
	/**
	 * Gets a property from config if possible
	 * @param propId
	 * @return
	 */
	getProperty: function( propId ){
		// Check if the property was set in config:
		if( this.config[propId] ){
			return this.config[propId];
		}
		mw.log( "freeWheelController:: getProperty: " + propId + ' unset' );
		// XXX some default copied from freeWheelSample.html
		// TODO don't use these values!
		switch( propId ){
			case 'profileId':
				return 'global-js';
				break;
			case 'displayBaseId':
				return 'displayBase';
				break;
			case 'siteSectionId' :
				return 'DemoSiteGroup.01';
				default:

			break;
		}
	},
	getAdManager: function(){
		if( !this.adManager ){
			this.adManager = new tv.freewheel.SDK.AdManager();
			this.adManager.setNetwork( this.getProperty( 'networkId' ) );
			this.adManager.setServer( this.getProperty('serverUrl') );
		}
		return this.adManager;
	},
	getContext: function(){
		if( !this.adContext ){
			this.adContext = this.getAdManager().newContext();

			this.adContext.registerVideoDisplayBase( 'videoContainer' );
			this.adContext.setProfile( this.getProperty( 'profileId' ) );

			this.adContext.setVideoAsset(
					this.getProperty( 'videoAssetId' ),
					this.getProperty( 'videoDuration' ),
					this.getProperty( 'networkId' )
			);
			this.adContext.setSiteSection(
					this.getProperty('siteSectionId') ,
					this.getProperty( 'networkId' )
			);
		}
		return this.adContext;
	},
	addContextKeyValues: function(){
		mw.log("freeWheelController::freeWheelController>")
		// XXX todo read key value pairs from plugin config ?
		var context = this.getContext();
		context.addKeyValue("module","DemoPlayer");
		context.addKeyValue("feature","trackingURLs");
		context.addKeyValue("feature", "simpleAds");

	},
	addContextListners: function(){
		mw.log("freeWheelController::addContextListners>" );
		this.getContext().addEventListener( tv.freewheel.SDK.EVENT_REQUEST_COMPLETE, this.onRequestComplete );
		this.getContext().addEventListener( tv.freewheel.SDK.EVENT_SLOT_ENDED, this.onSlotEnded );
	},
	setContextTimeout: function(){
		mw.log("freeWheelController::setContextTimeout>" );
		// To make sure video ad playback in poor network condition, set video ad timeout parameters.
		this.getContext().setParameter(tv.freewheel.SDK.PARAMETER_RENDERER_VIDEO_START_DETECT_TIMEOUT,10000,tv.freewheel.SDK.PARAMETER_LEVEL_GLOBAL);
		this.getContext().setParameter(tv.freewheel.SDK.PARAMETER_RENDERER_VIDEO_PROGRESS_DETECT_TIMEOUT,10000,tv.freewheel.SDK.PARAMETER_LEVEL_GLOBAL);
	},
	addTemporalSlots: function(){
		mw.log("freeWheelController::addTemporalSlots>")
		var context = this.getContext();
		//Add 1 preroll, 1 midroll, 2 overlay, 1 postroll slot
		context.addTemporalSlot("Preroll_1", tv.freewheel.SDK.ADUNIT_PREROLL, 0);
		context.addTemporalSlot("Midroll_1", tv.freewheel.SDK.ADUNIT_MIDROLL, 5);
		context.addTemporalSlot("Overlay_1", tv.freewheel.SDK.ADUNIT_OVERLAY, 10);
		context.addTemporalSlot("Overlay_2", tv.freewheel.SDK.ADUNIT_OVERLAY, 15);
		context.addTemporalSlot("Postroll_1", tv.freewheel.SDK.ADUNIT_POSTROLL, 60);
	},
	onSlotEnded: function ( event ){
		var _this = this;
		var slotTimePositionClass = event.slot.getTimePositionClass();
		mw.log("freeWheelControl:: onSlotEnded slotTimePositionClass: " + slotTimePositionClass );
		switch (slotTimePositionClass)
		{
			case tv.freewheel.SDK.TIME_POSITION_CLASS_PREROLL:
				if ( this.prerollSlots.length ){
					this.prerollSlots.shift();
					if ( this.prerollSlots.length )
						this.prerollSlots[0].play();
					else{
						// restore player
						/*
						$('#videoPlayer').bind('ended', onContentVideoEnded);
						$('#videoPlayer').bind('timeupdate', onContentVideoTimeUpdated);
						$('#videoPlayer').attr('controls', true);
						$('#videoPlayer').attr('src', contentVideoURL);
						$('#videoPlayer')[0].play();
						*/
						this.getContext().setVideoState(tv.freewheel.SDK.VIDEO_STATE_PLAYING);
					}
				}
				break;
			case tv.freewheel.SDK.TIME_POSITION_CLASS_MIDROLL:
			case tv.freewheel.SDK.TIME_POSITION_CLASS_OVERLAY:
				this.slotPlaying = false;
				break;
			case tv.freewheel.SDK.TIME_POSITION_CLASS_POSTROLL:
				if ( this.postrollSlots.length ){
					this.postrollSlots.shift();
					if ( this.postrollSlots.length ){
						postrollSlots[0].play();
					} else {
						_this.getContext().setVideoState(tv.freewheel.SDK.VIDEO_STATE_COMPLETED);
						$("#start").attr('disabled', false);
					}
				}
				break;
		}
	}
};

} )( window.mw, window.jQuery );<commit_msg>removed global instance ref<commit_after>( function( mw, $ ) {

mw.addFreeWheelControler = function( embedPlayer, config, callback ) {
	embedPlayer.freeWheelAds = new mw.freeWheelControler({
		'embedPlayer' : embedPlayer,
		'config' : config,
		'callback' :  callback
	});
	mw.freeWheelGlobalContextInstance = embedPlayer.freeWheelAds;
};

mw.freeWheelControler = function( opt ){
	return this.init( opt );
};

mw.freeWheelControler.prototype = {

	// The freeWheel adManager
	adManager: null,

	// The ad Context:
	adContext: null,

	// The ad data requested
	adDataRequested : false,

	// The pre video url
	contentVideoURL : null,

	// prerollSlots
	prerollSlots : [],

	// midroll_overlaySlots
	midroll_overlaySlots : [],

	// postrollSlots
	postrollSlots: [],

	// slotPlaying
	slotPlaying: false,

	/**
	 * Initialize the adMannager javascript and setup adds
	 *
	 * @param {Object} opt Object
	 * {
	 * 	'embedPlayer' {object} the embedPlayer instance
	 * 	'config' {object} any freewheel configuration
	 * 	'callback' {function} called on load complete
	 * }
	 * @return
	 */
	init: function( opt ){
		var _this = this;
		$.extend( this, opt);

		// XXX temporary override config for testing
		this.config = {
			'networkId' :'96749',
			'serverUrl' : 'http://sdnyadvip1-d.fwmrm.net/ad/g/1',
			'videoAssetId' : 'DemoVideoGroup.01',
			'videoDuration' : 500
		};

		// Load the ad manager url:
		// XXX todo we should be able to read this from "adManagerUrl"
		var AdManagerUrl = mw.getConfig( 'FreeWheel.AdManagerUrl' );

		//$.getScript(AdManagerUrl, function(){
		// For debugging use local copy:
		mw.load( 'tv.freewheel.SDK', function(){
			_this.setupAds();
		});
	},
	/**
	 * Setup ads, main freeWheel control flow
	 * @return
	 */
	setupAds: function(){
		var _this = this;

		// Add key-values for ad targeting.
		this.addContextKeyValues();

		// Listen to AdManager Events
		this.addContextListners();

		// Set context timeout
		this.setContextTimeout();

		// Add the temporal slots for this "player"
		this.addTemporalSlots();

		// Add local companion targets
		this.addCompanionBindings();

		// XXX FreeWheel sets SVLads003 as the response?
		window['SVLads003'] = true;

		// Load add data ( will call onRequestComplete once ready )
		mw.log("freeWheelController::submitRequest>");
		this.getContext().submitRequest();
	},
	/**
	 * Called on the completion of freeWheel add loading
	 * @param event
	 * @return
	 */
	onRequestComplete: function( event ){
		var _this = this;
		mw.log("freeWheelController::onRequestComplete>");
		if ( event.success ){
			var fwTemporalSlots = _this.getContext().getTemporalSlots();
			for (var i=0; i < fwTemporalSlots.length; i++){
				var slot = fwTemporalSlots[i];
				switch ( slot.getTimePositionClass() ){
					case tv.freewheel.SDK.TIME_POSITION_CLASS_PREROLL:
						_this.prerollSlots.push(slot);
						break;
					case tv.freewheel.SDK.TIME_POSITION_CLASS_MIDROLL:
					case tv.freewheel.SDK.TIME_POSITION_CLASS_OVERLAY:
						_this.midroll_overlaySlots.push(slot);
						break;
					case tv.freewheel.SDK.TIME_POSITION_CLASS_POSTROLL:
						_this.postrollSlots.push(slot);
						break;
				}
			}
			if( _this.prerollSlots[0] )
				_this.prerollSlots[0].play();
		}
		// issue the "ready callback"
		_this.callback();
	},
	/**
	 * Adds local companion targets ( if they  exists ) for easy passing across iframe
	 * @return
	 */
	addCompanionBindings: function(){
		var _this = this;
		mw.log("freeWheelController::addCompanionBindings>");
		// Add some hidden companion targets if we are running in an iframe
		if( !mw.getConfig('EmbedPlayer.IsIframeServer') ){
			return ;
		}
		// Setup the embedPlayer server setFreeWheelAddCompanions method
		this.embedPlayer.setFreeWheelAddCompanions = function( companionSet ){
			_this.addCompanionTargets( companionSet );
		};

		// Trigger the adding of any server side bindings:
		$( this.embedPlayer ).trigger( 'FreeWheel_GetAddCompanions' );
		// we now monitor for companion html changes and pass that across the iframe
		this.monitorForCompanionChanges();
	},
	monitorForCompanionChanges: function(){
		var _this = this;
		var companionStateCache = {};
		setInterval(function(){
			$('#fw_companion_container').find( '._fwph').each(function(inx, node){
				var id = $(node).attr('id');
				var curHtml = $('#_fw_container_' + id ).html();
				if( curHtml && companionStateCache[ id ] != curHtml){
					$( _this.embedPlayer ).trigger('FreeWheel_UpdateCompanion', {
						'id' : id,
						'content' : curHtml
					});
					companionStateCache[ id ] = curHtml;
				}
			});
		},1000);
	},
	/**
	 * Add hidden companion targets for companions to be passed overt the iframe
	 * @param companionSet
	 * @return
	 */
	addCompanionTargets: function( companionSet ){
		if(! $('#fw_companion_container').length ){
			$('body').append( $('<div />').attr('id', 'fw_companion_container' ) );
		}

		$.each(companionSet, function(inx, companion){
			var id =  companion.id;
			$('#fw_companion_container').append(
				$('<span />').attr('id', id ).addClass( '_fwph' )
				.css('display', 'none')
				.append(
					$('<form />').attr('id', '_fw_form_' + id )
					.append(
						$('<input type="hidden"/>').attr({
							'name' : '_fw_input_' + id,
							'id' : '_fw_input_' + id
						})
					),
					$('<span />').attr('id', '_fw_container_' + id )
				)
			);
		});
		mw.log( 'freeWheelController:: addCompanionTargets: Added:' + $('#fw_companion_container ._fwph').length + ' targets' );
	},
	/**
	 * Gets a property from config if possible
	 * @param propId
	 * @return
	 */
	getProperty: function( propId ){
		// Check if the property was set in config:
		if( this.config[propId] ){
			return this.config[propId];
		}
		mw.log( "freeWheelController:: getProperty: " + propId + ' unset' );
		// XXX some default copied from freeWheelSample.html
		// TODO don't use these values!
		switch( propId ){
			case 'profileId':
				return 'global-js';
				break;
			case 'displayBaseId':
				return 'displayBase';
				break;
			case 'siteSectionId' :
				return 'DemoSiteGroup.01';
				default:

			break;
		}
	},
	getAdManager: function(){
		if( !this.adManager ){
			this.adManager = new tv.freewheel.SDK.AdManager();
			this.adManager.setNetwork( this.getProperty( 'networkId' ) );
			this.adManager.setServer( this.getProperty('serverUrl') );
		}
		return this.adManager;
	},
	getContext: function(){
		if( !this.adContext ){
			this.adContext = this.getAdManager().newContext();

			this.adContext.registerVideoDisplayBase( 'videoContainer' );
			this.adContext.setProfile( this.getProperty( 'profileId' ) );

			this.adContext.setVideoAsset(
					this.getProperty( 'videoAssetId' ),
					this.getProperty( 'videoDuration' ),
					this.getProperty( 'networkId' )
			);
			this.adContext.setSiteSection(
					this.getProperty('siteSectionId') ,
					this.getProperty( 'networkId' )
			);
		}
		return this.adContext;
	},
	addContextKeyValues: function(){
		mw.log("freeWheelController::freeWheelController>")
		// XXX todo read key value pairs from plugin config ?
		var context = this.getContext();
		context.addKeyValue("module","DemoPlayer");
		context.addKeyValue("feature","trackingURLs");
		context.addKeyValue("feature", "simpleAds");

	},
	addContextListners: function(){
		var _this = this;
		mw.log("freeWheelController::addContextListners>" );
		this.getContext().addEventListener( tv.freewheel.SDK.EVENT_REQUEST_COMPLETE, function( event ){
			_this.onRequestComplete( event );
		});
		this.getContext().addEventListener( tv.freewheel.SDK.EVENT_SLOT_ENDED, this.onSlotEnded );
	},
	setContextTimeout: function(){
		mw.log("freeWheelController::setContextTimeout>" );
		// To make sure video ad playback in poor network condition, set video ad timeout parameters.
		this.getContext().setParameter(tv.freewheel.SDK.PARAMETER_RENDERER_VIDEO_START_DETECT_TIMEOUT,10000,tv.freewheel.SDK.PARAMETER_LEVEL_GLOBAL);
		this.getContext().setParameter(tv.freewheel.SDK.PARAMETER_RENDERER_VIDEO_PROGRESS_DETECT_TIMEOUT,10000,tv.freewheel.SDK.PARAMETER_LEVEL_GLOBAL);
	},
	addTemporalSlots: function(){
		mw.log("freeWheelController::addTemporalSlots>")
		var context = this.getContext();
		//Add 1 preroll, 1 midroll, 2 overlay, 1 postroll slot
		context.addTemporalSlot("Preroll_1", tv.freewheel.SDK.ADUNIT_PREROLL, 0);
		context.addTemporalSlot("Midroll_1", tv.freewheel.SDK.ADUNIT_MIDROLL, 5);
		context.addTemporalSlot("Overlay_1", tv.freewheel.SDK.ADUNIT_OVERLAY, 10);
		context.addTemporalSlot("Overlay_2", tv.freewheel.SDK.ADUNIT_OVERLAY, 15);
		context.addTemporalSlot("Postroll_1", tv.freewheel.SDK.ADUNIT_POSTROLL, 60);
	},
	onSlotEnded: function ( event ){
		var _this = this;
		var slotTimePositionClass = event.slot.getTimePositionClass();
		mw.log("freeWheelControl:: onSlotEnded slotTimePositionClass: " + slotTimePositionClass );
		switch (slotTimePositionClass)
		{
			case tv.freewheel.SDK.TIME_POSITION_CLASS_PREROLL:
				if ( this.prerollSlots.length ){
					this.prerollSlots.shift();
					if ( this.prerollSlots.length )
						this.prerollSlots[0].play();
					else{
						// restore player
						/*
						$('#videoPlayer').bind('ended', onContentVideoEnded);
						$('#videoPlayer').bind('timeupdate', onContentVideoTimeUpdated);
						$('#videoPlayer').attr('controls', true);
						$('#videoPlayer').attr('src', contentVideoURL);
						$('#videoPlayer')[0].play();
						*/
						this.getContext().setVideoState(tv.freewheel.SDK.VIDEO_STATE_PLAYING);
					}
				}
				break;
			case tv.freewheel.SDK.TIME_POSITION_CLASS_MIDROLL:
			case tv.freewheel.SDK.TIME_POSITION_CLASS_OVERLAY:
				this.slotPlaying = false;
				break;
			case tv.freewheel.SDK.TIME_POSITION_CLASS_POSTROLL:
				if ( this.postrollSlots.length ){
					this.postrollSlots.shift();
					if ( this.postrollSlots.length ){
						postrollSlots[0].play();
					} else {
						_this.getContext().setVideoState(tv.freewheel.SDK.VIDEO_STATE_COMPLETED);
						$("#start").attr('disabled', false);
					}
				}
				break;
		}
	}
};

} )( window.mw, window.jQuery );<|endoftext|>


<commit_before>// @flow

import {loadFiles, loadTerm} from '@gob/worker-load-data'
import {IS_WORKER} from './lib'

import type {LoadDataMessage} from './load-data'

declare var self: DedicatedWorkerGlobalScope

function checkIdbInWorkerSupport() {
	if ((self: any).IDBCursor) {
		return true
	}
	return false
}

function sendMessage(params: {id: string, [key: string]: mixed}) {
	let {id, type, ...args} = params
	let strMessage = JSON.stringify({id, type, ...args})
	self.postMessage(strMessage)
}

async function main({data}) {
	let message = JSON.parse(data)

	switch (message.type) {
		case 'check-idb-in-worker-support': {
			let supportState = await checkIdbInWorkerSupport()
			await sendMessage({id: message.id, supported: supportState})
			return
		}
		case 'load-from-info': {
			let {url, path} = message
			await loadFiles(url, path)
			break
		}
		case 'load-term-data': {
			let {term, courseInfoUrl, path} = message
			await loadTerm(term, courseInfoUrl, path)
			break
		}
		case 'dispatch': {
			break
		}
		default: {
			;(message.type: empty)
		}
	}

	sendMessage({id: message.id})
}

if (IS_WORKER) {
	// $FlowFixMe {data} is not in event… except that it is
	self.addEventListener('message', main)
}

class PointlessExportForTestingAndFlow {
	addEventListener(_1: string, _2: Function) {}
	removeEventListener(_1: string, _2: Function) {}
	postMessage(_: string) {}
}

export default PointlessExportForTestingAndFlow
<commit_msg>remove unused import<commit_after>// @flow

import {loadFiles, loadTerm} from '@gob/worker-load-data'
import {IS_WORKER} from './lib'

declare var self: DedicatedWorkerGlobalScope

function checkIdbInWorkerSupport() {
	if ((self: any).IDBCursor) {
		return true
	}
	return false
}

function sendMessage(params: {id: string, [key: string]: mixed}) {
	let {id, type, ...args} = params
	let strMessage = JSON.stringify({id, type, ...args})
	self.postMessage(strMessage)
}

async function main({data}) {
	let message = JSON.parse(data)

	switch (message.type) {
		case 'check-idb-in-worker-support': {
			let supportState = await checkIdbInWorkerSupport()
			await sendMessage({id: message.id, supported: supportState})
			return
		}
		case 'load-from-info': {
			let {url, path} = message
			await loadFiles(url, path)
			break
		}
		case 'load-term-data': {
			let {term, courseInfoUrl, path} = message
			await loadTerm(term, courseInfoUrl, path)
			break
		}
		case 'dispatch': {
			break
		}
		default: {
			;(message.type: empty)
		}
	}

	sendMessage({id: message.id})
}

if (IS_WORKER) {
	// $FlowFixMe {data} is not in event… except that it is
	self.addEventListener('message', main)
}

class PointlessExportForTestingAndFlow {
	addEventListener(_1: string, _2: Function) {}
	removeEventListener(_1: string, _2: Function) {}
	postMessage(_: string) {}
}

export default PointlessExportForTestingAndFlow
<|endoftext|>


<commit_before>var MiniBrowser = function(dictionary)
{
	this.url = dictionary.url;
	this.barColor = (dictionary.barColor) ? dictionary.barColor : Ti.UI.currentWindow.barColor;
	this.modal = (dictionary.modal) ? dictionary.modal : false;

	var winBase;
	var nav;
	var windowBrowser;
	var webViewBrowser;
	var buttonCloseWindow;
	var activityIndicator;

	var toolbarButtons;
	var buttonBack;
	var buttonForward;
	var buttonStop;
	var buttonRefresh;
	var buttonAction;
	var buttonSpace;

	var actionDialog;

	this.initToolbar = function()
	{
		toolbarButtons = Ti.UI.iOS.createToolbar({
			barColor:this.barColor,
			bottom:0,
			height:44
		});

		buttonBack = Ti.UI.createButton({
			image:"modules/mini-browser/Icon-Back.png",
			enabled:false
		});
		buttonBack.addEventListener("click", function() {
			webViewBrowser.goBack();
		});

		buttonForward = Ti.UI.createButton({
			image:"modules/mini-browser/Icon-Forward.png",
			enabled:false
		});
		buttonForward.addEventListener("click", function() {
			webViewBrowser.goForward();
		});

		buttonStop = Ti.UI.createButton({
			systemButton:Titanium.UI.iPhone.SystemButton.STOP
		});
		buttonStop.addEventListener("click", function() {

			activityIndicator.hide();

			webViewBrowser.stopLoading();

			buttonBack.enabled = webViewBrowser.canGoBack();
			buttonForward.enabled = webViewBrowser.canGoForward();
			buttonAction.enabled = true;

			actionsDialog.title = webViewBrowser.url;

			toolbarButtons.items = [
				buttonBack,
				buttonSpace,
				buttonForward,
				buttonSpace,
				buttonRefresh,
				buttonSpace,
				buttonAction
			];

		});

		buttonRefresh = Ti.UI.createButton({
			systemButton:Titanium.UI.iPhone.SystemButton.REFRESH
		});
		buttonRefresh.addEventListener("click", function() {
			webViewBrowser.reload();
		});

		buttonAction = Ti.UI.createButton({
			systemButton:Titanium.UI.iPhone.SystemButton.ACTION,
			enabled:false
		});
		buttonAction.addEventListener("click", function() {
			actionsDialog.show();
		});

		buttonSpace = Ti.UI.createButton({
			systemButton:Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE
		});

		this.initActions();

		windowBrowser.add(toolbarButtons);
	},

	this.initActions = function()
	{
		actionsDialog = Ti.UI.createOptionDialog({
			options:["Copiar Link","Abrir no Safari","Enviar Link por e-mail","Cancelar"],
			cancel:3
		});

		actionsDialog.addEventListener("click", function(e) {
			switch(e.index) {
				case 0:
					Titanium.UI.Clipboard.setText(webViewBrowser.url);
					break;
				case 1:
					if (Titanium.Platform.canOpenURL(webViewBrowser.url)) {
						Titanium.Platform.openURL(webViewBrowser.url);
					}
					break;
				case 2:
					var emailDialog = Titanium.UI.createEmailDialog({
						barColor:windowBrowser.barColor
					});

					emailDialog.subject = windowBrowser.title;
					emailDialog.messageBody = webViewBrowser.url;
					emailDialog.open();
					break;
				default:
					break;
			}
		});

	}

	(function() {
		windowBrowser = Ti.UI.createWindow({
			barColor:this.barColor,
			backgroundColor:"#FFF"
		});

		if (this.modal == true)
		{
			winBase = Ti.UI.createWindow({
				navBarHidden:true,
				modal:true
			});
			nav = Ti.UI.iPhone.createNavigationGroup({
				window:windowBrowser
			});
			winBase.add(nav);

			buttonCloseWindow = Ti.UI.createButton({
				title:"Fechar",
				style:Ti.UI.iPhone.SystemButtonStyle.DONE
			});
			windowBrowser.leftNavButton = buttonCloseWindow;

			buttonCloseWindow.addEventListener("click", function() {
				winBase.close();
			});

			winBase.addEventListener("close", function()
			{
				windowBrowser = null;
				nav = null;
				buttonCloseWindow = null;
				webViewBrowser = null;

				toolbarButtons = null;
				buttonBack = null;
				buttonForward = null;
				buttonStop = null;
				buttonRefresh = null;
				buttonAction = null;
				buttonSpace = null;

				winBase = null;
			});
		}

		webViewBrowser = Ti.UI.createWebView({
			url:this.url,
			left:0,
			top:0,
			bottom:44,
			width:"100%",
			loading:false
		});
		windowBrowser.add(webViewBrowser);

		webViewBrowser.addEventListener("load", function() {

			activityIndicator.hide();

			windowBrowser.title = webViewBrowser.evalJS("document.title");

			buttonBack.enabled = webViewBrowser.canGoBack();
			buttonForward.enabled = webViewBrowser.canGoForward();
			buttonAction.enabled = true;

			actionsDialog.title = webViewBrowser.url;

			toolbarButtons.items = [
				buttonBack,
				buttonSpace,
				buttonForward,
				buttonSpace,
				buttonRefresh,
				buttonSpace,
				buttonAction
			];

		});

		webViewBrowser.addEventListener("beforeload", function() {

			activityIndicator.show();

			buttonAction.enabled = false;

			toolbarButtons.items = [
				buttonBack,
				buttonSpace,
				buttonForward,
				buttonSpace,
				buttonStop,
				buttonSpace,
				buttonAction
			];

		});

		webViewBrowser.addEventListener("error", function() {

			activityIndicator.hide();

			buttonBack.enabled = webViewBrowser.canGoBack();
			buttonForward.enabled = webViewBrowser.canGoForward();
			buttonAction.enabled = true;

			actionsDialog.title = webViewBrowser.url;

			toolbarButtons.items = [
				buttonBack,
				buttonSpace,
				buttonForward,
				buttonSpace,
				buttonRefresh,
				buttonSpace,
				buttonAction
			];

		});

		activityIndicator = Ti.UI.createActivityIndicator({
			style:Titanium.UI.iPhone.ActivityIndicatorStyle.PLAIN
		});
		windowBrowser.rightNavButton = activityIndicator;

		this.initToolbar();

		return (this.modal == true) ? winBase : windowBrowser;
	)();

}
<commit_msg>New feature: Internationalization<commit_after>var MiniBrowser = function(dictionary)
{
	this.url = dictionary.url;
	this.barColor = (dictionary.barColor) ? dictionary.barColor : Ti.UI.currentWindow.barColor;
	this.modal = (dictionary.modal) ? dictionary.modal : false;

	var winBase;
	var nav;
	var windowBrowser;
	var webViewBrowser;
	var buttonCloseWindow;
	var activityIndicator;

	var toolbarButtons;
	var buttonBack;
	var buttonForward;
	var buttonStop;
	var buttonRefresh;
	var buttonAction;
	var buttonSpace;

	var actionDialog;

	this.initToolbar = function()
	{
		toolbarButtons = Ti.UI.iOS.createToolbar({
			barColor:this.barColor,
			bottom:0,
			height:44
		});

		buttonBack = Ti.UI.createButton({
			image:"modules/mini-browser/Icon-Back.png",
			enabled:false
		});
		buttonBack.addEventListener("click", function() {
			webViewBrowser.goBack();
		});

		buttonForward = Ti.UI.createButton({
			image:"modules/mini-browser/Icon-Forward.png",
			enabled:false
		});
		buttonForward.addEventListener("click", function() {
			webViewBrowser.goForward();
		});

		buttonStop = Ti.UI.createButton({
			systemButton:Titanium.UI.iPhone.SystemButton.STOP
		});
		buttonStop.addEventListener("click", function() {

			activityIndicator.hide();

			webViewBrowser.stopLoading();

			buttonBack.enabled = webViewBrowser.canGoBack();
			buttonForward.enabled = webViewBrowser.canGoForward();
			buttonAction.enabled = true;

			actionsDialog.title = webViewBrowser.url;

			toolbarButtons.items = [
				buttonBack,
				buttonSpace,
				buttonForward,
				buttonSpace,
				buttonRefresh,
				buttonSpace,
				buttonAction
			];

		});

		buttonRefresh = Ti.UI.createButton({
			systemButton:Titanium.UI.iPhone.SystemButton.REFRESH
		});
		buttonRefresh.addEventListener("click", function() {
			webViewBrowser.reload();
		});

		buttonAction = Ti.UI.createButton({
			systemButton:Titanium.UI.iPhone.SystemButton.ACTION,
			enabled:false
		});
		buttonAction.addEventListener("click", function() {
			actionsDialog.show();
		});

		buttonSpace = Ti.UI.createButton({
			systemButton:Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE
		});

		this.initActions();

		windowBrowser.add(toolbarButtons);
	},

	this.initActions = function()
	{
		actionsDialog = Ti.UI.createOptionDialog({
			options:[
				L("copy_link", "Copy link"),
				L("open_safari", "Open in the Safari"),
				L("send_by_email","Send by email"),
				L("cancel","Cancel")
			],
			cancel:3
		});

		actionsDialog.addEventListener("click", function(e) {
			switch(e.index) {
				case 0:
					Titanium.UI.Clipboard.setText(webViewBrowser.url);
					break;
				case 1:
					if (Titanium.Platform.canOpenURL(webViewBrowser.url)) {
						Titanium.Platform.openURL(webViewBrowser.url);
					}
					break;
				case 2:
					var emailDialog = Titanium.UI.createEmailDialog({
						barColor:windowBrowser.barColor
					});

					emailDialog.subject = windowBrowser.title;
					emailDialog.messageBody = webViewBrowser.url;
					emailDialog.open();
					break;
				default:
					break;
			}
		});

	}

	(function() {
		windowBrowser = Ti.UI.createWindow({
			barColor:this.barColor,
			backgroundColor:"#FFF"
		});

		if (this.modal == true)
		{
			winBase = Ti.UI.createWindow({
				navBarHidden:true,
				modal:true
			});
			nav = Ti.UI.iPhone.createNavigationGroup({
				window:windowBrowser
			});
			winBase.add(nav);

			buttonCloseWindow = Ti.UI.createButton({
				title:L("close","Close"),
				style:Ti.UI.iPhone.SystemButtonStyle.DONE
			});
			windowBrowser.leftNavButton = buttonCloseWindow;

			buttonCloseWindow.addEventListener("click", function() {
				winBase.close();
			});

			winBase.addEventListener("close", function()
			{
				windowBrowser = null;
				nav = null;
				buttonCloseWindow = null;
				webViewBrowser = null;

				toolbarButtons = null;
				buttonBack = null;
				buttonForward = null;
				buttonStop = null;
				buttonRefresh = null;
				buttonAction = null;
				buttonSpace = null;

				winBase = null;
			});
		}

		webViewBrowser = Ti.UI.createWebView({
			url:this.url,
			left:0,
			top:0,
			bottom:44,
			width:"100%",
			loading:false
		});
		windowBrowser.add(webViewBrowser);

		webViewBrowser.addEventListener("load", function() {

			activityIndicator.hide();

			windowBrowser.title = webViewBrowser.evalJS("document.title");

			buttonBack.enabled = webViewBrowser.canGoBack();
			buttonForward.enabled = webViewBrowser.canGoForward();
			buttonAction.enabled = true;

			actionsDialog.title = webViewBrowser.url;

			toolbarButtons.items = [
				buttonBack,
				buttonSpace,
				buttonForward,
				buttonSpace,
				buttonRefresh,
				buttonSpace,
				buttonAction
			];

		});

		webViewBrowser.addEventListener("beforeload", function() {

			activityIndicator.show();

			buttonAction.enabled = false;

			toolbarButtons.items = [
				buttonBack,
				buttonSpace,
				buttonForward,
				buttonSpace,
				buttonStop,
				buttonSpace,
				buttonAction
			];

		});

		webViewBrowser.addEventListener("error", function() {

			activityIndicator.hide();

			buttonBack.enabled = webViewBrowser.canGoBack();
			buttonForward.enabled = webViewBrowser.canGoForward();
			buttonAction.enabled = true;

			actionsDialog.title = webViewBrowser.url;

			toolbarButtons.items = [
				buttonBack,
				buttonSpace,
				buttonForward,
				buttonSpace,
				buttonRefresh,
				buttonSpace,
				buttonAction
			];

		});

		activityIndicator = Ti.UI.createActivityIndicator({
			style:Titanium.UI.iPhone.ActivityIndicatorStyle.PLAIN
		});
		windowBrowser.rightNavButton = activityIndicator;

		this.initToolbar();

		return (this.modal == true) ? winBase : windowBrowser;
	)();

}
<|endoftext|>


<commit_before>// @flow

import PropTypes from 'prop-types';
import * as React from 'react';
import Icon from 'react-native-vector-icons/Ionicons';

import { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';
import { connect } from 'lib/utils/redux-utils';

import Button from '../components/button.react';
import { ThreadSettingsRouteName } from '../navigation/route-names';
import type { AppState } from '../redux/redux-setup';
import { styleSelector } from '../themes/colors';
import type { ChatNavigationProp } from './chat.react';

type Props = {|
  threadInfo: ThreadInfo,
  navigate: $PropertyType<ChatNavigationProp<'MessageList'>, 'navigate'>,
  // Redux state
  styles: typeof styles,
|};
class ThreadSettingsButton extends React.PureComponent<Props> {
  static propTypes = {
    threadInfo: threadInfoPropType.isRequired,
    navigate: PropTypes.func.isRequired,
    styles: PropTypes.objectOf(PropTypes.object).isRequired,
  };

  render() {
    return (
      <Button onPress={this.onPress} androidBorderlessRipple={true}>
        <Icon name="md-settings" size={30} style={this.props.styles.button} />
      </Button>
    );
  }

  onPress = () => {
    const threadInfo = this.props.threadInfo;
    this.props.navigate({
      name: ThreadSettingsRouteName,
      params: { threadInfo },
      key: `${ThreadSettingsRouteName}${threadInfo.id}`,
    });
  };
}

const styles = {
  button: {
    color: 'link',
    paddingHorizontal: 10,
  },
};
const stylesSelector = styleSelector(styles);

export default connect((state: AppState) => ({
  styles: stylesSelector(state),
}))(ThreadSettingsButton);
<commit_msg>[native] Use hook instead of connect functions and HOC in ThreadSettingsButton.<commit_after>// @flow

import * as React from 'react';
import Icon from 'react-native-vector-icons/Ionicons';

import { type ThreadInfo } from 'lib/types/thread-types';

import Button from '../components/button.react';
import { ThreadSettingsRouteName } from '../navigation/route-names';
import { useStyles } from '../themes/colors';
import type { ChatNavigationProp } from './chat.react';

type BaseProps = {|
  +threadInfo: ThreadInfo,
  +navigate: $PropertyType<ChatNavigationProp<'MessageList'>, 'navigate'>,
|};
type Props = {|
  ...BaseProps,
  +styles: typeof unboundStyles,
|};

class ThreadSettingsButton extends React.PureComponent<Props> {
  render() {
    return (
      <Button onPress={this.onPress} androidBorderlessRipple={true}>
        <Icon name="md-settings" size={30} style={this.props.styles.button} />
      </Button>
    );
  }

  onPress = () => {
    const threadInfo = this.props.threadInfo;
    this.props.navigate({
      name: ThreadSettingsRouteName,
      params: { threadInfo },
      key: `${ThreadSettingsRouteName}${threadInfo.id}`,
    });
  };
}

const unboundStyles = {
  button: {
    color: 'link',
    paddingHorizontal: 10,
  },
};

export default React.memo<BaseProps>(function ConnectedThreadSettingsButton(
  props: BaseProps,
) {
  const styles = useStyles(unboundStyles);

  return <ThreadSettingsButton {...props} styles={styles} />;
});
<|endoftext|>


<commit_before>angular.module('npact')
  .controller('npactGraphContainerCtrl', function($scope, $element, $window, $log, $timeout,
                                           npactConstants, Utils, GraphConfig, Evt,
                                           GraphingCalculator) {
    'use strict';

    var getWidth = function() {
      return $element.width() - 15; //from style.css `.graph`
    };

    //The baseOpts are the graph options that are the same for every graph
    var baseOpts = { width: getWidth() },
        updateMetrics = function() {
          baseOpts.m = GraphingCalculator.chart(baseOpts);
        };
    this.graphOptions = function(idx) {
      // This function builds the specific options for a graph; as
      // many graph rows will never be drawn this only generates the
      // object for a row when needed.
      var start = $scope.graphSpecs[idx];
      return angular.extend({ startBase: start }, baseOpts);
    };

    var ready = function() {
          return GraphConfig.nucleotides && GraphConfig.nucleotides.length &&
            baseOpts.m;
        },
        draw = function() { $scope.$broadcast(Evt.DRAW); },
        redraw = function() {
          if (!ready()) return;  //too early to do anything
          $scope.$broadcast(Evt.REDRAW);
        },
        rebuild = function() {
          if (!ready()) return;  //too early to do anything
          $scope.$broadcast(Evt.REBUILD);
        };

    /*** Watch the config for changes we care about ***/
    $scope.$watchCollection(
      function() { return [GraphConfig.basesPerGraph,
                    GraphConfig.offset, GraphConfig.startBase, GraphConfig.endBase]; },
      function() {
        // basic row geometry changed, repartition and rebuild
        if(isNaN(GraphConfig.startBase) ||
           isNaN(GraphConfig.endBase) ||
           isNaN(GraphConfig.basesPerGraph)) { return; }
        baseOpts.basesPerGraph = GraphConfig.basesPerGraph;
        $scope.graphSpecs = GraphingCalculator.partition(GraphConfig);
        updateMetrics();
        $log.log('Partitioned into', $scope.graphSpecs.length, 'rows.');
        updateVisibility(); //number of rows might have changed.
        $timeout(rebuild);
      });

    $scope.$watch(function() { return GraphConfig.nucleotides; }, function() {
      $scope.$broadcast('n-profile');
    }, true);
    $scope.$watch(function() { return GraphConfig.colorBlindFriendly; }, redraw);

    $scope.$watch(GraphConfig.activeTracks, function(val) {
      //Find headers and headerY
      baseOpts.tracks = val;
      updateMetrics();
      updateRowHeight(baseOpts.m.height);
      redraw();
    }, true);

    /***  Scrolling and Graph Visibility management ***/
    var $win = angular.element($window),
        winHeight = $win.height(),
        slack = 20, // how many pixels outside of viewport to render
        topOffset = 0,
        topIdx = 0, bottomIdx = 0,
        graphRowHeight = 0,
        updateRowHeight = function(height) {
          topOffset = Math.floor($element.offset().top + _.parseInt($element.css('padding-top')));
          $log.log('topOffset:', topOffset);
          $scope.graphHeight = height;
          try {
             graphRowHeight = angular.element('#graph_0', $element).outerHeight();
          }
          catch(e) {
            graphRowHeight = 0; // There are no rows
          }
          updateVisibility();
        },
        scrollToBase = function(base) {
          if(isNaN(base)) return;
          var idx = Math.floor(base / GraphConfig.basesPerGraph);
          var id = '#graph_' + idx;
          $timeout(function() {
            $log.log('scrolling to', id);
            $window.scrollTo(0, $(id).offset().top);
          }, 40);
        },
        updateVisibility = function() {
          if(!baseOpts.m) return;
          var scrollDist = $window.scrollY - topOffset - slack;
          topIdx = Math.floor(scrollDist / graphRowHeight);
          bottomIdx = topIdx + Math.ceil((winHeight + 2* slack) / graphRowHeight);
        },
        onScroll = function() {
          updateVisibility();
          draw();
        },
        onResize = function() {
          winHeight = $win.height();
          if(getWidth() !== baseOpts.width) {
            topOffset = $element.offset().top;
            baseOpts.width = getWidth();
            updateMetrics();
            updateVisibility();
            redraw();
          }
          else {
            //If the width didn't change then its the same as scrolling
            onScroll();
          }
        },
        onKeyDown = _.throttle(function(event) {
          var keyCode = event.which, delta;
          switch(keyCode) {
          case 37: // left key
            delta = -GraphConfig.basesPerGraph / 100;
            GraphConfig.offset += delta;
            $scope.$broadcast('offset', delta);
            break;
          case 39: // right key
            delta = GraphConfig.basesPerGraph / 100;
            GraphConfig.offset += delta;
            $scope.$broadcast('offset', delta);
            break;
          }
        }, 40, {leading:true}),
        onKeyUp = _.debounce(function(event) {
          var keyCode = event.which;
          switch(keyCode) {
          case 37: // left key
          case 39: // right key
            $scope.$apply();
            break;
          }
        }, 800);
    $scope.$watch(function() { return GraphConfig.gotoBase; }, scrollToBase);

    this.visible = function(idx) { return idx >= topIdx && idx <= bottomIdx; };
    $win.on('resize', onResize);
    $win.on('scroll', onScroll);
    $win.on('keydown', onKeyDown);
    $win.on('keyup', onKeyUp);
    $scope.$on('$destroy', function() {
      $win.off('resize', onResize);
      $win.off('scroll', onScroll);
      $win.off('keydown', onKeyDown);
      $win.off('keyup', onKeyUp);
    });
  })
  .directive('npactGraphContainer', function(STATIC_BASE_URL) {
    return {
      restrict: 'A',
      scope: {},
      templateUrl: STATIC_BASE_URL + 'js/graphs/graph-container.html',
      controller: 'npactGraphContainerCtrl as ctrl'
    };
  })

  .directive('npactGraph', function (Grapher, Evt, GraphingCalculator, GraphConfig,
                              $log, $timeout) {
    'use strict';
    return {
      restrict: 'A',
      require: '^npactGraphContainer',
      link: function($scope, $element, $attrs, ctrl) {
        var g = null,
            visible = ctrl.visible,
            idx = $attrs.idx,
            el = $element[0],
            // redraw gets set for all graphs once (e.g. a new track
            // triggers broadcasts redraw), but only gets cleared as
            // the currently visible ones are drawn
            redraw = false,
            draw = function(force) {
              if(!redraw || (!force && !visible(idx))) { return null; }
              var opts = ctrl.graphOptions(idx);
              //However long it actually takes to draw, we have the
              //latest options as of this point
              redraw = false;
              return (g || (g = new Grapher(el, opts)))
                    .redraw(opts)
                    .catch(function() {
                      //something went wrong, we will still need to redraw this
                      redraw = true;
                    });
            },
            schedule = function(force) {
              if(!redraw || (!force && !visible(idx))) { return null; }
              return $timeout(_.partial(draw, force), 0, false);
            },
            discard = function() {
              if(g) { g.destroy(); g = null; }
            };
        $scope.$on(Evt.DRAW, _.partial(schedule, false));
        $scope.$on(Evt.REDRAW, function() { redraw = true; schedule();});
        $scope.$on(Evt.REBUILD, function() { discard(); redraw = true; schedule(); });
        $scope.$on('n-profile', function() {
          redraw = true;
          if(g) { g.clearProfilePoints(); }
          schedule();
        });
        $scope.$on('offset', function(event, dx) {
          if(g && g.offset && visible(idx)) {
            g.offset(dx);
          }
        });
        $scope.$on('$destroy', discard);

        $scope.$on('print', function(evt, callback) {
          var p = schedule(true);
          if(p) {
            callback(p.then(function() { return g.replaceWithImage(); }));
          }
          else { callback(g.replaceWithImage()); }
        });
        $scope.$watch(function() { return GraphConfig.gotoBase; }, function(gotoBase, fromBase) {
          var start = idx * GraphConfig.basesPerGraph,
              end = start + GraphConfig.basesPerGraph;
          if (gotoBase && start <= gotoBase && gotoBase <= end) {
            $log.log('gotoBase triggered redraw:', gotoBase);
            redraw = true;
            schedule(true);
          }
          else if(fromBase && start <= fromBase && fromBase <= end) {
            redraw = true;
          }
        });
      }
    };
  })
  .directive('npactExtract', function(STATIC_BASE_URL, GraphConfig, NProfiler,
                               $log, Translater) {
    return {
      restrict: 'A',
      scope: { extract: '=npactExtract'},
      templateUrl: STATIC_BASE_URL + 'js/graphs/extract.html',
      link: function($scope, $element, $attrs, ctrl) {
        $log.log(NProfiler);
        window.currentScope = $scope;
        $scope.NProfiler = NProfiler;
        // TODO: if extract.complement, reverse the string
        // ?Maybe we get results either way?

        // I *think* we need to subtract 1 because coming from C/NCBI
        // the DNA is treated as 1 indexed
        // at least we got no results till we did this.
        $scope.ddna = NProfiler.ddna.slice($scope.extract.start - 1, $scope.extract.end - 1);
        Translater($scope.ddna, GraphConfig.mycoplasma, $scope.extract.complement)
          .then(function(res) {
            $scope.ddnaP = res.data && res.data.seq;
            $scope.ddnaRC = res.data && res.data.complement;
            $scope.query = $scope.extract.complement ? $scope.ddnaRC : $scope.ddna;
          });
        //window.NProfiler = NProfiler; window.GraphConfig = GraphConfig;
        $scope.config = GraphConfig;
      }
    };
  })
;
<commit_msg>TODO on element width<commit_after>angular.module('npact')
  .controller('npactGraphContainerCtrl', function($scope, $element, $window, $log, $timeout,
                                           npactConstants, Utils, GraphConfig, Evt,
                                           GraphingCalculator) {
    'use strict';

    var getWidth = function() {
      //TODO: Probably need to use $element.innerWidth();
      return $element.width() - 15; //from style.css `.graph`
    };

    //The baseOpts are the graph options that are the same for every graph
    var baseOpts = { width: getWidth() },
        updateMetrics = function() {
          baseOpts.m = GraphingCalculator.chart(baseOpts);
        };
    this.graphOptions = function(idx) {
      // This function builds the specific options for a graph; as
      // many graph rows will never be drawn this only generates the
      // object for a row when needed.
      var start = $scope.graphSpecs[idx];
      return angular.extend({ startBase: start }, baseOpts);
    };

    var ready = function() {
          return GraphConfig.nucleotides && GraphConfig.nucleotides.length &&
            baseOpts.m;
        },
        draw = function() { $scope.$broadcast(Evt.DRAW); },
        redraw = function() {
          if (!ready()) return;  //too early to do anything
          $scope.$broadcast(Evt.REDRAW);
        },
        rebuild = function() {
          if (!ready()) return;  //too early to do anything
          $scope.$broadcast(Evt.REBUILD);
        };

    /*** Watch the config for changes we care about ***/
    $scope.$watchCollection(
      function() { return [GraphConfig.basesPerGraph,
                    GraphConfig.offset, GraphConfig.startBase, GraphConfig.endBase]; },
      function() {
        // basic row geometry changed, repartition and rebuild
        if(isNaN(GraphConfig.startBase) ||
           isNaN(GraphConfig.endBase) ||
           isNaN(GraphConfig.basesPerGraph)) { return; }
        baseOpts.basesPerGraph = GraphConfig.basesPerGraph;
        $scope.graphSpecs = GraphingCalculator.partition(GraphConfig);
        updateMetrics();
        $log.log('Partitioned into', $scope.graphSpecs.length, 'rows.');
        updateVisibility(); //number of rows might have changed.
        $timeout(rebuild);
      });

    $scope.$watch(function() { return GraphConfig.nucleotides; }, function() {
      $scope.$broadcast('n-profile');
    }, true);
    $scope.$watch(function() { return GraphConfig.colorBlindFriendly; }, redraw);

    $scope.$watch(GraphConfig.activeTracks, function(val) {
      //Find headers and headerY
      baseOpts.tracks = val;
      updateMetrics();
      updateRowHeight(baseOpts.m.height);
      redraw();
    }, true);

    /***  Scrolling and Graph Visibility management ***/
    var $win = angular.element($window),
        winHeight = $win.height(),
        slack = 20, // how many pixels outside of viewport to render
        topOffset = 0,
        topIdx = 0, bottomIdx = 0,
        graphRowHeight = 0,
        updateRowHeight = function(height) {
          topOffset = Math.floor($element.offset().top + _.parseInt($element.css('padding-top')));
          $log.log('topOffset:', topOffset);
          $scope.graphHeight = height;
          try {
             graphRowHeight = angular.element('#graph_0', $element).outerHeight();
          }
          catch(e) {
            graphRowHeight = 0; // There are no rows
          }
          updateVisibility();
        },
        scrollToBase = function(base) {
          if(isNaN(base)) return;
          var idx = Math.floor(base / GraphConfig.basesPerGraph);
          var id = '#graph_' + idx;
          $timeout(function() {
            $log.log('scrolling to', id);
            $window.scrollTo(0, $(id).offset().top);
          }, 40);
        },
        updateVisibility = function() {
          if(!baseOpts.m) return;
          var scrollDist = $window.scrollY - topOffset - slack;
          topIdx = Math.floor(scrollDist / graphRowHeight);
          bottomIdx = topIdx + Math.ceil((winHeight + 2* slack) / graphRowHeight);
        },
        onScroll = function() {
          updateVisibility();
          draw();
        },
        onResize = function() {
          winHeight = $win.height();
          if(getWidth() !== baseOpts.width) {
            topOffset = $element.offset().top;
            baseOpts.width = getWidth();
            updateMetrics();
            updateVisibility();
            redraw();
          }
          else {
            //If the width didn't change then its the same as scrolling
            onScroll();
          }
        },
        onKeyDown = _.throttle(function(event) {
          var keyCode = event.which, delta;
          switch(keyCode) {
          case 37: // left key
            delta = -GraphConfig.basesPerGraph / 100;
            GraphConfig.offset += delta;
            $scope.$broadcast('offset', delta);
            break;
          case 39: // right key
            delta = GraphConfig.basesPerGraph / 100;
            GraphConfig.offset += delta;
            $scope.$broadcast('offset', delta);
            break;
          }
        }, 40, {leading:true}),
        onKeyUp = _.debounce(function(event) {
          var keyCode = event.which;
          switch(keyCode) {
          case 37: // left key
          case 39: // right key
            $scope.$apply();
            break;
          }
        }, 800);
    $scope.$watch(function() { return GraphConfig.gotoBase; }, scrollToBase);

    this.visible = function(idx) { return idx >= topIdx && idx <= bottomIdx; };
    $win.on('resize', onResize);
    $win.on('scroll', onScroll);
    $win.on('keydown', onKeyDown);
    $win.on('keyup', onKeyUp);
    $scope.$on('$destroy', function() {
      $win.off('resize', onResize);
      $win.off('scroll', onScroll);
      $win.off('keydown', onKeyDown);
      $win.off('keyup', onKeyUp);
    });
  })
  .directive('npactGraphContainer', function(STATIC_BASE_URL) {
    return {
      restrict: 'A',
      scope: {},
      templateUrl: STATIC_BASE_URL + 'js/graphs/graph-container.html',
      controller: 'npactGraphContainerCtrl as ctrl'
    };
  })

  .directive('npactGraph', function (Grapher, Evt, GraphingCalculator, GraphConfig,
                              $log, $timeout) {
    'use strict';
    return {
      restrict: 'A',
      require: '^npactGraphContainer',
      link: function($scope, $element, $attrs, ctrl) {
        var g = null,
            visible = ctrl.visible,
            idx = $attrs.idx,
            el = $element[0],
            // redraw gets set for all graphs once (e.g. a new track
            // triggers broadcasts redraw), but only gets cleared as
            // the currently visible ones are drawn
            redraw = false,
            draw = function(force) {
              if(!redraw || (!force && !visible(idx))) { return null; }
              var opts = ctrl.graphOptions(idx);
              //However long it actually takes to draw, we have the
              //latest options as of this point
              redraw = false;
              return (g || (g = new Grapher(el, opts)))
                    .redraw(opts)
                    .catch(function() {
                      //something went wrong, we will still need to redraw this
                      redraw = true;
                    });
            },
            schedule = function(force) {
              if(!redraw || (!force && !visible(idx))) { return null; }
              return $timeout(_.partial(draw, force), 0, false);
            },
            discard = function() {
              if(g) { g.destroy(); g = null; }
            };
        $scope.$on(Evt.DRAW, _.partial(schedule, false));
        $scope.$on(Evt.REDRAW, function() { redraw = true; schedule();});
        $scope.$on(Evt.REBUILD, function() { discard(); redraw = true; schedule(); });
        $scope.$on('n-profile', function() {
          redraw = true;
          if(g) { g.clearProfilePoints(); }
          schedule();
        });
        $scope.$on('offset', function(event, dx) {
          if(g && g.offset && visible(idx)) {
            g.offset(dx);
          }
        });
        $scope.$on('$destroy', discard);

        $scope.$on('print', function(evt, callback) {
          var p = schedule(true);
          if(p) {
            callback(p.then(function() { return g.replaceWithImage(); }));
          }
          else { callback(g.replaceWithImage()); }
        });
        $scope.$watch(function() { return GraphConfig.gotoBase; }, function(gotoBase, fromBase) {
          var start = idx * GraphConfig.basesPerGraph,
              end = start + GraphConfig.basesPerGraph;
          if (gotoBase && start <= gotoBase && gotoBase <= end) {
            $log.log('gotoBase triggered redraw:', gotoBase);
            redraw = true;
            schedule(true);
          }
          else if(fromBase && start <= fromBase && fromBase <= end) {
            redraw = true;
          }
        });
      }
    };
  })
  .directive('npactExtract', function(STATIC_BASE_URL, GraphConfig, NProfiler,
                               $log, Translater) {
    return {
      restrict: 'A',
      scope: { extract: '=npactExtract'},
      templateUrl: STATIC_BASE_URL + 'js/graphs/extract.html',
      link: function($scope, $element, $attrs, ctrl) {
        $log.log(NProfiler);
        window.currentScope = $scope;
        $scope.NProfiler = NProfiler;
        // TODO: if extract.complement, reverse the string
        // ?Maybe we get results either way?

        // I *think* we need to subtract 1 because coming from C/NCBI
        // the DNA is treated as 1 indexed
        // at least we got no results till we did this.
        $scope.ddna = NProfiler.ddna.slice($scope.extract.start - 1, $scope.extract.end - 1);
        Translater($scope.ddna, GraphConfig.mycoplasma, $scope.extract.complement)
          .then(function(res) {
            $scope.ddnaP = res.data && res.data.seq;
            $scope.ddnaRC = res.data && res.data.complement;
            $scope.query = $scope.extract.complement ? $scope.ddnaRC : $scope.ddna;
          });
        //window.NProfiler = NProfiler; window.GraphConfig = GraphConfig;
        $scope.config = GraphConfig;
      }
    };
  })
;
<|endoftext|>


<commit_before>var missingData = {
    urls: {
        survey: '/static/sample_data/survey.json',
        teams: '/static/sample_data/teams.json',
        states: '/static/sample_data/states.json',
        collectableData: '/static/sample_data/collectable_data.json'
    },
    initiate: function() {
        jQuery('#missing_data_teams,#missing_data_states').selectmenu({
            change: missingData.changeStateOrTeam
        });
        dataGetter.addNew(missingData.urls.teams, missingData.fillTeamsList, false);
        dataGetter.addNew(missingData.urls.states, missingData.fillStatesList, false);
        dataGetter.addNew(missingData.urls.survey, missingData.listChildren, true);
        dataGetter.addNew(missingData.urls.survey, missingData.listWomen, true);
        dataGetter.addNew(missingData.urls.collectableData, missingData.listChildren, false);
        dataGetter.addNew(missingData.urls.collectableData, missingData.listWomen, false);
    },
    fillTeamsList: function(data) {
        _.each(data.teams, function(names, id) {
            jQuery('#missing_data_teams').append(missingData.teamOptionTmp({
                id: id,
                names: names
            }));
        });
    },
    teamOptionTmp: _.template('<option value="<%- id %>"><%- names %></option>'),
    fillStatesList: function(data) {
        _.each(data.states.sort(), function(state) {
            jQuery('#missing_data_states').append(missingData.stateOptionTmp({
                state: state
            }));
        });
    },
    stateOptionTmp: _.template('<option value="<%- state %>" ><%- state %></option>'),
    changeStateOrTeam: function() {
        var data = dataGetter.downloads[missingData.urls.survey].data,
            team = jQuery('#missing_data_teams').val(),
            state = jQuery('#missing_data_states').val();
        missingData.listChildren(data, team, state);
        missingData.listWomen(data, team, state);
    },
    listTmp: _.template('
<%- detail.charAt(0).toUpperCase() + detail.slice(1).replace("_"," ") %>:<%= percentage %>%
'),
    listWomen: function(data, team, state) {
        if (!dataGetter.checkAll([missingData.urls.survey, missingData.urls.collectableData])) {
            /* Check that all the relative data has been downloaded, else cancel.
            See home.js. */
            return false;
        }
        var collectableData = dataGetter.downloads[missingData.urls.collectableData].data.collectable_data,
            surveyData = dataGetter.downloads[missingData.urls.survey].data.survey_data,
            womenTotal = 0,
            womenDetails = {},
            percentages = [];

        _.each(collectableData.women, function(detail) {
            womenDetails[detail] = 0;
        });

        _.each(surveyData, function(survey) {

            if (team && team > 0 && team != survey.team) {
                return true;
            }
            if (state && state != 'All states' && state != clusterInfo.findState(survey.cluster)) {
                return true;
            }

            _.each(survey.members, function(member) {
                if (member.gender == 'F' && member.age > 15 && member.age < 45) {
                    womenTotal++;
                }
            });

            _.each(survey.women_surveys, function(woman) {
                _.each(collectableData.women, function(detail) {
                    if (detail in woman) {
                        womenDetails[detail] ++;
                    }
                });
            });
        });

        if (womenTotal > 0) {
            _.each(collectableData.women, function(detail) {
                percentages.push({
                    detail: detail,
                    percentage: Math.round((womenTotal - womenDetails[detail]) / womenTotal * 100 * 10) /10
                });
            });
        }

        percentages = _.sortBy(percentages, 'detail');

        jQuery('#missing_data_women_list').empty();

        _.each(percentages, function(percentage) {
            jQuery('#missing_data_women_list').append(missingData.listTmp(percentage));
        });
    },
    listChildren: function(data, team, state) {
        if (!dataGetter.checkAll([missingData.urls.survey, missingData.urls.collectableData])) {
            /* Check that all the relative data has been downloaded, else cancel.
            See home.js. */
            return false;
        }
        var collectableData = dataGetter.downloads[missingData.urls.collectableData].data.collectable_data,
            surveyData = dataGetter.downloads[missingData.urls.survey].data.survey_data,
            childrenTotal = 0,
            childDetails = {},
            percentages = [];

        _.each(collectableData.children, function(detail) {
            childDetails[detail] = 0;
        });

        _.each(surveyData, function(survey) {

            if (team && team > 0 && team != survey.team) {
                return true;
            }
            if (state && state != 'All states' && state != clusterInfo.findState(survey.cluster)) {
                return true;
            }

            _.each(survey.members, function(member) {
                if (member.age < 5) {
                    childrenTotal++;
                }
            });

            _.each(survey.child_surveys, function(child) {
                _.each(collectableData.children, function(detail) {
                    if (detail in child) {
                        childDetails[detail] ++;
                    }
                });
            });
        });

        if (childrenTotal > 0) {
            _.each(collectableData.children, function(detail) {
                percentages.push({
                    detail: detail,
                    percentage: Math.round((childrenTotal - childDetails[detail]) / childrenTotal * 100 * 10) /10
                });
            });
        }

        percentages = _.sortBy(percentages, 'detail');

        jQuery('#missing_data_children_list').empty();
        _.each(percentages, function(percentage) {
            jQuery('#missing_data_children_list').append(missingData.listTmp(percentage));
        });
    }
};
missingData.initiate();
<commit_msg>set women age to: 14 > X > 50<commit_after>var missingData = {
    urls: {
        survey: '/static/sample_data/survey.json',
        teams: '/static/sample_data/teams.json',
        states: '/static/sample_data/states.json',
        collectableData: '/static/sample_data/collectable_data.json'
    },
    initiate: function() {
        jQuery('#missing_data_teams,#missing_data_states').selectmenu({
            change: missingData.changeStateOrTeam
        });
        dataGetter.addNew(missingData.urls.teams, missingData.fillTeamsList, false);
        dataGetter.addNew(missingData.urls.states, missingData.fillStatesList, false);
        dataGetter.addNew(missingData.urls.survey, missingData.listChildren, true);
        dataGetter.addNew(missingData.urls.survey, missingData.listWomen, true);
        dataGetter.addNew(missingData.urls.collectableData, missingData.listChildren, false);
        dataGetter.addNew(missingData.urls.collectableData, missingData.listWomen, false);
    },
    fillTeamsList: function(data) {
        _.each(data.teams, function(names, id) {
            jQuery('#missing_data_teams').append(missingData.teamOptionTmp({
                id: id,
                names: names
            }));
        });
    },
    teamOptionTmp: _.template('<option value="<%- id %>"><%- names %></option>'),
    fillStatesList: function(data) {
        _.each(data.states.sort(), function(state) {
            jQuery('#missing_data_states').append(missingData.stateOptionTmp({
                state: state
            }));
        });
    },
    stateOptionTmp: _.template('<option value="<%- state %>" ><%- state %></option>'),
    changeStateOrTeam: function() {
        var data = dataGetter.downloads[missingData.urls.survey].data,
            team = jQuery('#missing_data_teams').val(),
            state = jQuery('#missing_data_states').val();
        missingData.listChildren(data, team, state);
        missingData.listWomen(data, team, state);
    },
    listTmp: _.template('
<%- detail.charAt(0).toUpperCase() + detail.slice(1).replace("_"," ") %>:<%= percentage %>%
'),
    listWomen: function(data, team, state) {
        if (!dataGetter.checkAll([missingData.urls.survey, missingData.urls.collectableData])) {
            /* Check that all the relative data has been downloaded, else cancel.
            See home.js. */
            return false;
        }
        var collectableData = dataGetter.downloads[missingData.urls.collectableData].data.collectable_data,
            surveyData = dataGetter.downloads[missingData.urls.survey].data.survey_data,
            womenTotal = 0,
            womenDetails = {},
            percentages = [];

        _.each(collectableData.women, function(detail) {
            womenDetails[detail] = 0;
        });

        _.each(surveyData, function(survey) {

            if (team && team > 0 && team != survey.team) {
                return true;
            }
            if (state && state != 'All states' && state != clusterInfo.findState(survey.cluster)) {
                return true;
            }

            _.each(survey.members, function(member) {
                if (member.gender == 'F' && member.age > 14 && member.age < 50) {
                    womenTotal++;
                }
            });

            _.each(survey.women_surveys, function(woman) {
                _.each(collectableData.women, function(detail) {
                    if (detail in woman) {
                        womenDetails[detail] ++;
                    }
                });
            });
        });

        if (womenTotal > 0) {
            _.each(collectableData.women, function(detail) {
                percentages.push({
                    detail: detail,
                    percentage: Math.round((womenTotal - womenDetails[detail]) / womenTotal * 100 * 10) /10
                });
            });
        }

        percentages = _.sortBy(percentages, 'detail');

        jQuery('#missing_data_women_list').empty();

        _.each(percentages, function(percentage) {
            jQuery('#missing_data_women_list').append(missingData.listTmp(percentage));
        });
    },
    listChildren: function(data, team, state) {
        if (!dataGetter.checkAll([missingData.urls.survey, missingData.urls.collectableData])) {
            /* Check that all the relative data has been downloaded, else cancel.
            See home.js. */
            return false;
        }
        var collectableData = dataGetter.downloads[missingData.urls.collectableData].data.collectable_data,
            surveyData = dataGetter.downloads[missingData.urls.survey].data.survey_data,
            childrenTotal = 0,
            childDetails = {},
            percentages = [];

        _.each(collectableData.children, function(detail) {
            childDetails[detail] = 0;
        });

        _.each(surveyData, function(survey) {

            if (team && team > 0 && team != survey.team) {
                return true;
            }
            if (state && state != 'All states' && state != clusterInfo.findState(survey.cluster)) {
                return true;
            }

            _.each(survey.members, function(member) {
                if (member.age < 5) {
                    childrenTotal++;
                }
            });

            _.each(survey.child_surveys, function(child) {
                _.each(collectableData.children, function(detail) {
                    if (detail in child) {
                        childDetails[detail] ++;
                    }
                });
            });
        });

        if (childrenTotal > 0) {
            _.each(collectableData.children, function(detail) {
                percentages.push({
                    detail: detail,
                    percentage: Math.round((childrenTotal - childDetails[detail]) / childrenTotal * 100 * 10) /10
                });
            });
        }

        percentages = _.sortBy(percentages, 'detail');

        jQuery('#missing_data_children_list').empty();
        _.each(percentages, function(percentage) {
            jQuery('#missing_data_children_list').append(missingData.listTmp(percentage));
        });
    }
};
missingData.initiate();
<|endoftext|>


<commit_before>var body = document.body;
var html = document.documentElement;
var body = html.getElementsByTagName("body")[0];
var table = body.getElementsByTagName("table")[0];
var size = 20; // Size of cell

// Credit to http://stackoverflow.com/questions/1145850/how-to-get-height-of-entire-document-with-javascript
var height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
var width = Math.max(body.scrollWidth, body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth);
width -= 10; // Make the table a little smaller so there's a valid border.
height -= 10;
width = Math.floor(width/size);
height = Math.floor(height/size);
console.log("Width: "+width, " Height: "+height);
table.setAttribute("height", height*size + "px");
table.setAttribute("width", width*size + "px");
for (var i=0; i<height; i+=1) {
	var row = table.insertRow(i);
	for (var j=0; j<width; j+=1) {
		var cell = row.insertCell(j);
		cell.setAttribute("class", "emptycell");
		cell.setAttribute("name", j+"_"+i);
		var btn = document.createElement("button");
		btn.setAttribute("class", "foodcell");
		btn.setAttribute("onclick", "placeFood("+j+","+i+")");
		cell.appendChild(btn);
	}
}

function updateBoard(snake) {
	for (var r=0, row; r<table.rows.length; r++) {
		for (var c=0; c<table.rows[r].cells.length; c++) {
			var cell = table.rows[r].cells[c];
			var isSnakeCell = false;
			for (var s=0; s<snake.length; s++) {
				if (cell.getAttribute("name") == snake[s][0]+"_"+snake[s][1]) {
					isSnakeCell = true;
					break;
				}
			}
			if (isSnakeCell) {
				cell.setAttribute("class", "snakecell");
			} else {
				cell.setAttribute("class", "emptycell");
			}
		}
	}
}<commit_msg>Change back to invis<commit_after>var body = document.body;
var html = document.documentElement;
var body = html.getElementsByTagName("body")[0];
var table = body.getElementsByTagName("table")[0];
var size = 20; // Size of cell

// Credit to http://stackoverflow.com/questions/1145850/how-to-get-height-of-entire-document-with-javascript
var height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
var width = Math.max(body.scrollWidth, body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth);
width -= 10; // Make the table a little smaller so there's a valid border.
height -= 10;
width = Math.floor(width/size);
height = Math.floor(height/size);
console.log("Width: "+width, " Height: "+height);
table.setAttribute("height", height*size + "px");
table.setAttribute("width", width*size + "px");
for (var i=0; i<height; i+=1) {
	var row = table.insertRow(i);
	for (var j=0; j<width; j+=1) {
		var cell = row.insertCell(j);
		cell.setAttribute("class", "emptycell");
		cell.setAttribute("name", j+"_"+i);
		var btn = document.createElement("button");
		btn.setAttribute("class", "invisible");
		btn.setAttribute("onclick", "placeFood("+j+","+i+")");
		cell.appendChild(btn);
	}
}

function updateBoard(snake) {
	for (var r=0, row; r<table.rows.length; r++) {
		for (var c=0; c<table.rows[r].cells.length; c++) {
			var cell = table.rows[r].cells[c];
			var isSnakeCell = false;
			for (var s=0; s<snake.length; s++) {
				if (cell.getAttribute("name") == snake[s][0]+"_"+snake[s][1]) {
					isSnakeCell = true;
					break;
				}
			}
			if (isSnakeCell) {
				cell.setAttribute("class", "snakecell");
			} else {
				cell.setAttribute("class", "emptycell");
			}
		}
	}
}<|endoftext|>