<commit_before>/**
 * A very simple jQuery plugin to that changes the opacity of the items in a list (doesn't matter what they are)
 * to give them impression of a cross-fading slide show. To set up, position all of the slides absolutely within
 * their container. Create a class ("trans-spec" by default) that contains the transition styles. These will be
 * applied to the slides after initialization takes place. The call shiner like:
 *
 *  $('.myslides').shiner();
 *
 * Shiner will also take options like:
 *
 * $('.myslides').shiner({ transClass: 'fast', delay: 1000});
 *
 * Shiner will also take the commands "stop" and "go" like:
 *
 * $('.myslides').shiner("stop")
 * $('.myslides').shiner("go");
 */
(function($) {

	var defaults = {
			transClass: "trans-spec",		/* The class to apply to set the transition properties */
			delay: 5000 					/* The delay between the changes in slides */
	};

	var slideSetInformation = {};

	var cssTransitionSupport = (function(){

            // body element
        var body = document.body || document.documentElement,

            // transition events with names
            transEndEvents = {
                'transition'      : 'transitionend',
                'WebkitTransition': 'webkitTransitionEnd',
                'MozTransition'   : 'transitionend',
                'MsTransition'    : 'MSTransitionEnd',
                'OTransition'     : 'oTransitionEnd otransitionend'
            }, name;

        // check for each transition type
        for (name in transEndEvents){

            // if transition type is supported
            if (body.style[name] !== undefined) {

                // return transition end event name
                return transEndEvents[name];
            }
        }

        // css transitions are not supported
        return false;

    })();

	/**
	 * make the slide visible either by making it opaque if that's supported in the browser or
	 * making it not hidden
	 */
	function makeVisible(slide) {
		if(cssTransitionSupport) {
			slide.css('opacity', 1);
		}
		else {
			var oldvalue = $.data(slide, 'old-display');
			if(!oldvalue) {
				oldvalue = 'block';
			}
			slide.css('display', oldvalue);
		}

	}

	/**
	 * make the slide invisible either by making it transparent if that's supported in the browser or
	 * making it hidden
	 */
	function makeInvisible(slide) {
		if(cssTransitionSupport) {
			slide.css('opacity', 0);
		}
		else {
			var oldvalue = slide.css('display');
			if(oldvalue != 'none') {
				$.data(slide, 'old-display', oldvalue);
			}
			slide.css('display', 'none');
		}
	}

	/**
	 * Returns true if the slide is opaque (if that's supported by the browser) or not hidden if
	 * opacity is not supported.
	 */
	function isVisible(slide) {
		if(cssTransitionSupport) {
			return slide.css('opacity') == 1;
		}
		else {
			return slide.css('display') != 'none';
		}
	}

	/**
	 * Makes the currently visible slide invisible and makes the next slide in the sequence visible
	 */
	function goToNext(slidesSelector) {
		var last = false;
		var slides = $(slidesSelector);
		slides.each(function() {
			var slide = $(this);
			if(isVisible(slide)) {
				makeInvisible(slide);
				last = true;
			}
			else {
				if(last == true) {
					last = false;
					makeVisible(slide);
				}
			}

		});

		if(last) {
			// meaning the one we made transparent was the last one
			makeVisible(slides.first());
		}
	}

	/**
	 * Starts the slide show by setting up a timer to change the slides
	 */
	function shineOn(slidesSelector) {
		shineOff(slidesSelector);
		slideSetInformation[slidesSelector].intervalId = setInterval(function() { goToNext(slidesSelector) }, slideSetInformation[slidesSelector].delay);
	}

	/**
	 * Stops the timer and thus the slide show
	 */
	function shineOff(slidesSelector) {
		if(slideSetInformation[slidesSelector].intervalId) {
			clearInterval(slideSetInformation[slidesSelector].intervalId);
		}

		slideSetInformation[slidesSelector].intervalId = null;
	}

	/**
	 * sets up the slides by making them all invisible and then making the first one visible.
	 */
	function initShine(slidesSelector, options) {
		var slides = $(slidesSelector);

		slideSetInformation[slidesSelector] = $.extend({}, defaults, options);

		slides.each(function() { makeInvisible($(this)); } );
		makeVisible(slides.first());

		setTimeout(function() {
			slides.addClass(slideSetInformation[slidesSelector].transClass);
			shineOn(slidesSelector);
		}, 100);

	}

	$.fn.shiner = function(options) {

		var theselector = this.selector;

		if(!options) {
			initShine(theselector);
		}
		else if(typeof options === 'string') {
			if (options === 'stop') {
				shineOff(theselector);
			}
			else if (options === 'go') {
				shineOn(theselector);
			}
		}
		else if(typeof options === 'object') {
			initShine(theselector, options);
		}
	}
}
)(jQuery);<commit_msg>Update comments<commit_after>/**
A simple jQuery plugin that changes the opacity of the items in a list (doesn't matter what they are)
to give them impression of a cross-fading slide show. If opacity is not supported, display hidden is used for
a somewhat graceful degredation of function.

To set up, position all of the slides absolutely within
their container. Create a class ("trans-spec" by default) that contains the transition styles. These will be
applied to the slides after initialization takes place (otherwise the initial setup looks funky).

Then call shiner like:

> $('.myslides').shiner();

Shiner will also take options like:

> $('.myslides').shiner({ transClass: 'fast', delay: 1000});

Shiner will also take the commands "stop" and "go" like:

> $('.myslides').shiner("stop")
> $('.myslides').shiner("go");

One of the nice things about using this technique is that all of the slides can be placed behind
another element (see example.html) allowing you to "frame" a slideshow. Also, styles like max-width
can be used for images and overflow hidden can be used for the container. This makes it easy to show
slides of different sizes and slightly different aspect ratios.

Shiner works in modern browsers and in ie 7/8. It also works very well on android devices despite
their limited processing power (unlike other slide show tools I've tried).
 */
(function($) {

	var defaults = {
			transClass: "trans-spec",		/* The class to apply to set the transition properties */
			delay: 5000 					/* The delay between the changes in slides */
	};

	var slideSetInformation = {};

	var cssTransitionSupport = (function(){

            // body element
        var body = document.body || document.documentElement,

            // transition events with names
            transEndEvents = {
                'transition'      : 'transitionend',
                'WebkitTransition': 'webkitTransitionEnd',
                'MozTransition'   : 'transitionend',
                'MsTransition'    : 'MSTransitionEnd',
                'OTransition'     : 'oTransitionEnd otransitionend'
            }, name;

        // check for each transition type
        for (name in transEndEvents){

            // if transition type is supported
            if (body.style[name] !== undefined) {

                // return transition end event name
                return transEndEvents[name];
            }
        }

        // css transitions are not supported
        return false;

    })();

	/**
	 * make the slide visible either by making it opaque if that's supported in the browser or
	 * making it not hidden
	 */
	function makeVisible(slide) {
		if(cssTransitionSupport) {
			slide.css('opacity', 1);
		}
		else {
			var oldvalue = $.data(slide, 'old-display');
			if(!oldvalue) {
				oldvalue = 'block';
			}
			slide.css('display', oldvalue);
		}

	}

	/**
	 * make the slide invisible either by making it transparent if that's supported in the browser or
	 * making it hidden
	 */
	function makeInvisible(slide) {
		if(cssTransitionSupport) {
			slide.css('opacity', 0);
		}
		else {
			var oldvalue = slide.css('display');
			if(oldvalue != 'none') {
				$.data(slide, 'old-display', oldvalue);
			}
			slide.css('display', 'none');
		}
	}

	/**
	 * Returns true if the slide is opaque (if that's supported by the browser) or not hidden if
	 * opacity is not supported.
	 */
	function isVisible(slide) {
		if(cssTransitionSupport) {
			return slide.css('opacity') == 1;
		}
		else {
			return slide.css('display') != 'none';
		}
	}

	/**
	 * Makes the currently visible slide invisible and makes the next slide in the sequence visible
	 */
	function goToNext(slidesSelector) {
		var last = false;
		var slides = $(slidesSelector);
		slides.each(function() {
			var slide = $(this);
			if(isVisible(slide)) {
				makeInvisible(slide);
				last = true;
			}
			else {
				if(last == true) {
					last = false;
					makeVisible(slide);
				}
			}

		});

		if(last) {
			// meaning the one we made transparent was the last one
			makeVisible(slides.first());
		}
	}

	/**
	 * Starts the slide show by setting up a timer to change the slides
	 */
	function shineOn(slidesSelector) {
		shineOff(slidesSelector);
		slideSetInformation[slidesSelector].intervalId = setInterval(function() { goToNext(slidesSelector) }, slideSetInformation[slidesSelector].delay);
	}

	/**
	 * Stops the timer and thus the slide show
	 */
	function shineOff(slidesSelector) {
		if(slideSetInformation[slidesSelector].intervalId) {
			clearInterval(slideSetInformation[slidesSelector].intervalId);
		}

		slideSetInformation[slidesSelector].intervalId = null;
	}

	/**
	 * sets up the slides by making them all invisible and then making the first one visible.
	 */
	function initShine(slidesSelector, options) {
		var slides = $(slidesSelector);

		slideSetInformation[slidesSelector] = $.extend({}, defaults, options);

		slides.each(function() { makeInvisible($(this)); } );
		makeVisible(slides.first());

		setTimeout(function() {
			slides.addClass(slideSetInformation[slidesSelector].transClass);
			shineOn(slidesSelector);
		}, 100);

	}

	$.fn.shiner = function(options) {

		var theselector = this.selector;

		if(!options) {
			initShine(theselector);
		}
		else if(typeof options === 'string') {
			if (options === 'stop') {
				shineOff(theselector);
			}
			else if (options === 'go') {
				shineOn(theselector);
			}
		}
		else if(typeof options === 'object') {
			initShine(theselector, options);
		}
	}
}
)(jQuery);
<|endoftext|>


<commit_before>/* vim:set ts=2 sw=2 sts=2 expandtab */
/*jshint asi: true undef: true es5: true node: true browser: true devel: true
         forin: true latedef: false globalstrict: true */

'use strict';

var Name = require('name')
var Method = require('method')

var core = require('./core'),
    accumulate = core.accumulate,
    accumulated = core.accumulated, end = core.end

var emit = Method()

var close = Method()

var accumulator = Name()
var state = Name()
var closed = Name()

// Signals can be either open or closed. An open signal may `emit` new values.
// A signal that is not open may not emit.
//
// Define helper that allow you to test the state of a signal.
function isClosed(signal) {
  return !!signal[closed]
}
function isOpen(signal) {
  return !!signal[accumulator]
}

function Signal() {}
accumulate.define(Signal, function(signal, next, initial) {
  if (isOpen(signal)) throw Error('Signal is being consumed')
  if (isClosed(signal)) return next(end(), initial)
  signal[accumulator] = next
  signal[state] = initial
  return signal
})
emit.define(Signal, function(signal, value) {
  if (isClosed(signal)) throw Error('Signal is already closed')
  if (!isOpen(signal)) throw Error('Signal is not open')
  var result = signal[accumulator](value, signal[state])
  if (result && result.is === accumulated) {
    close(signal)
  } else {
    signal[state] = result
  }
  return signal
})
close.define(Signal, function(signal, value) {
  if (isClosed(signal)) throw Error('Signal is already closed')
  if (value !== undefined) emit(signal, value)
  var result = signal[state]
  var next = signal[accumulator]
  signal[closed] = true
  signal[accumulator] = null
  signal[state] = null
  next(end(), result)

  return signal
})

// Define a factory function for the `Signal` constructor.
// Assign other signal functions to the factory function object and export
// the result.
function signal() { return new Signal() }
signal.type = Signal
signal.isOpen = isOpen
signal.isClosed = isClosed
signal.emit = emit
signal.close = close

module.exports = signal

<commit_msg>Explain a signal may be reduced by only 1 consumer<commit_after>/* vim:set ts=2 sw=2 sts=2 expandtab */
/*jshint asi: true undef: true es5: true node: true browser: true devel: true
         forin: true latedef: false globalstrict: true */

'use strict';

var Name = require('name')
var Method = require('method')

var core = require('./core'),
    accumulate = core.accumulate,
    accumulated = core.accumulated, end = core.end

var emit = Method()

var close = Method()

var accumulator = Name()
var state = Name()
var closed = Name()

// Signals can be either open or closed. An open signal may `emit` new values.
// A signal that is not open may not emit.
//
// Define helper that allow you to test the state of a signal.
function isClosed(signal) {
  return !!signal[closed]
}
function isOpen(signal) {
  return !!signal[accumulator]
}

function Signal() {}

// Implement accumulate protocol on signals, making them reducible.
accumulate.define(Signal, function(signal, next, initial) {
  // Signals may only be reduced by one consumer function.
  // Other data types built on top of signal may allow for more consumers.
  if (isOpen(signal)) throw Error('Signal is being consumed')
  if (isClosed(signal)) return next(end(), initial)
  signal[accumulator] = next
  signal[state] = initial
  return signal
})

emit.define(Signal, function(signal, value) {
  if (isClosed(signal)) throw Error('Signal is already closed')
  if (!isOpen(signal)) throw Error('Signal is not open')
  var result = signal[accumulator](value, signal[state])
  if (result && result.is === accumulated) {
    close(signal)
  } else {
    signal[state] = result
  }
  return signal
})

close.define(Signal, function(signal, value) {
  if (isClosed(signal)) throw Error('Signal is already closed')
  if (value !== undefined) emit(signal, value)
  var result = signal[state]
  var next = signal[accumulator]
  signal[closed] = true
  signal[accumulator] = null
  signal[state] = null
  next(end(), result)

  return signal
})

// Define a factory function for the `Signal` constructor.
// Assign other signal functions to the factory function object and export
// the result.
function signal() { return new Signal() }
signal.type = Signal
signal.isOpen = isOpen
signal.isClosed = isClosed
signal.emit = emit
signal.close = close

module.exports = signal

<|endoftext|>


<commit_before>$(function() {
  // run the currently selected effect
    function runEffect() {
      // get effect type from
      var selectedEffect = $( "#effectTypes" ).val();

      // most effect types need no options passed by default
      var options = {};
      // some effects have required parameters
      if ( selectedEffect === "scale" ) {
        options = { percent: 60 };
      } else if ( selectedEffect === "size" ) {
        options = { to: { width: 480, height: 385 } };
      }
       // run the effect
      $( "#effect" ).show( selectedEffect, options, 1100, callback );
    };

    //callback function to bring a hidden box back
    function callback() {
      setTimeout(function() {
        $( "#effect:visible" ).removeAttr( "style" ).fadeOut();
        }, 10000 );
    };

    // set effect from select menu value
    $( "#button" ).click(function() {
      runEffect();
    });

    $( "#effect" ).hide();

    //hide v_nav_bar
     //$( "#v_nav_bar").show();

    $(function() {
      $( "#accordion" ).accordion();
      })
    });
<<<<<<< Updated upstream
=======
<<<<<<< HEAD
<<<<<<< HEAD
   // $("#accordion").hide();
=======
>>>>>>> origin/master
=======
>>>>>>> origin/master
>>>>>>> Stashed changes

    $( "#clickme" ).click(function() {
      $( "#back" ).slideToggle( "slow", function() {
    // Animation complete.
  });
});
<<<<<<< Updated upstream
=======
<<<<<<< HEAD
<<<<<<< HEAD

  // It took me two consecutive days to lift my jaws up again,
  //so the third day after recovering a bit I started to hack.

=======
>>>>>>> origin/master
=======
>>>>>>> origin/master
>>>>>>> Stashed changes
<commit_msg>Update siisen.js<commit_after>$(function() {
  // run the currently selected effect
    function runEffect() {
      // get effect type from
      var selectedEffect = $( "#effectTypes" ).val();

      // most effect types need no options passed by default
      var options = {};
      // some effects have required parameters
      if ( selectedEffect === "scale" ) {
        options = { percent: 60 };
      } else if ( selectedEffect === "size" ) {
        options = { to: { width: 480, height: 385 } };
      }
       // run the effect
      $( "#effect" ).show( selectedEffect, options, 1100, callback );
    };

    //callback function to bring a hidden box back
    function callback() {
      setTimeout(function() {
        $( "#effect:visible" ).removeAttr( "style" ).fadeOut();
        }, 10000 );
    };

    // set effect from select menu value
    $( "#button" ).click(function() {
      runEffect();
    });

    $( "#effect" ).hide();

    //hide v_nav_bar
     //$( "#v_nav_bar").show();

    $(function() {
      $( "#accordion" ).accordion();
      })
    });
   // $("#accordion").hide();
    $( "#clickme" ).click(function() {
      $( "#back" ).slideToggle( "slow", function() {
    // Animation complete.
  });
});
<|endoftext|>


<commit_before>define("solver", ["util"], function(util) {

    function getPlayerCardMap(game) {
        /* structure:
        {
            player id: {
                known: [card, card...],
                some: [[card, card...], [card, card...]...],
                none: [card, card...]
            },
            ...
        }
        */
        var map = {};
        for (var i = 0; i < game.players.length; i++) {
            map[i] = {known: [], some: [], none: []};
        }

        game.log.forEach(function(entry) {
            if (entry.card) {
                map[entry.has.some].known.push(entry.card);
                return;
            }
            cards = ['w' + entry.guess.weapon, 'p' + entry.guess.player, 'r' + entry.guess.room];
            if (entry.has.some !== undefined)
                map[entry.has.some].some.push(cards);
            entry.has.none.forEach(function(p) {
                util.setExtend(map[p].none, cards);
            });
        });
        return map;
    }

    function getCardMatrix(game, cardMap) {
        var baseEntry = {};
        for (var i = 0; i < game.gameData.players.length; i++)
            baseEntry['p' + i] = 'unknown';
        for (var i = 0; i < game.gameData.weapons.length; i++)
            baseEntry['w' + i] = 'unknown';
        for (var i = 0; i < game.gameData.rooms.length; i++)
            baseEntry['r' + i] = 'unknown';

        var matrix = game.players.map(function(_, i) {
            var entry = $.extend({}, baseEntry);

            cardMap[i].some.forEach(function(cards) {
                cards.forEach(function(card) {
                    entry[card] = 'maybe';
                })
            });

            cardMap[i].none.forEach(function(card) {
                entry[card] = 'no';
            });

            cardMap[i].known.forEach(function(card) {
                entry[card] = 'yes';
            });

            return entry;
        });

        return matrix;
    }

    function solve(game) {
        var changed;
        var cardMap = getPlayerCardMap(game);

        do {
            changed = false;

            for (var pi = 0; pi < game.players.length; pi++) {
                // remove any entries that appear in "none" from "some"
                for (var ni = 0; ni < cardMap[pi].none.length; ni++) {
                    for (var si = 0; si < cardMap[pi].some.length; si++) {
                        changed = changed || util.arrayRemove(cardMap[pi].some[si], cardMap[pi].none[ni]);
                    }
                }

                // move any one-element arrays from "some" to "known"
                for (var si = 0; si < cardMap[pi].some.length; si++) {
                    var some = cardMap[pi].some;
                    if (some[si].length == 1) {
                        changed = true;
                        util.setExtend(cardMap[pi].known, some[si]);
                        // remove from "some" and adjust loop index
                        some.splice(si, 1);
                        si--;
                    }
                }
            }

        } while (changed);

        return cardMap;
    }

    return {
        getPlayerCardMap: getPlayerCardMap,
        getCardMatrix: getCardMatrix,
        solve: solve,
    }
});
<commit_msg>Account for known cards when solving<commit_after>define("solver", ["util"], function(util) {

    function getPlayerCardMap(game) {
        /* structure:
        {
            player id: {
                known: [card, card...],
                some: [[card, card...], [card, card...]...],
                none: [card, card...]
            },
            ...
        }
        */
        var map = {};
        for (var i = 0; i < game.players.length; i++) {
            map[i] = {known: [], some: [], none: []};
        }

        game.log.forEach(function(entry) {
            if (entry.card) {
                map[entry.has.some].known.push(entry.card);
                return;
            }
            cards = ['w' + entry.guess.weapon, 'p' + entry.guess.player, 'r' + entry.guess.room];
            if (entry.has.some !== undefined)
                map[entry.has.some].some.push(cards);
            entry.has.none.forEach(function(p) {
                util.setExtend(map[p].none, cards);
            });
        });
        return map;
    }

    function getCardMatrix(game, cardMap) {
        var baseEntry = {};
        for (var i = 0; i < game.gameData.players.length; i++)
            baseEntry['p' + i] = 'unknown';
        for (var i = 0; i < game.gameData.weapons.length; i++)
            baseEntry['w' + i] = 'unknown';
        for (var i = 0; i < game.gameData.rooms.length; i++)
            baseEntry['r' + i] = 'unknown';

        var matrix = game.players.map(function(_, i) {
            var entry = $.extend({}, baseEntry);

            cardMap[i].some.forEach(function(cards) {
                cards.forEach(function(card) {
                    entry[card] = 'maybe';
                })
            });

            cardMap[i].none.forEach(function(card) {
                entry[card] = 'no';
            });

            cardMap[i].known.forEach(function(card) {
                entry[card] = 'yes';
            });

            return entry;
        });

        return matrix;
    }

    function solve(game) {
        var changed;
        var cardMap = getPlayerCardMap(game);

        do {
            changed = false;

            // add known cards to everyone else's "none"
            // (only do this once!)
            for (var pi = 0; pi < game.players.length; pi++) {
                for (var ki = 0; ki < cardMap[pi].known.length; ki++) {
                    for (var pi2 = 0; pi2 < game.players.length; pi2++) {
                        if (pi != pi2) {
                            util.setExtend(cardMap[pi2].none, [cardMap[pi].known[ki]]);
                        }
                    }
                }
            }

            for (var pi = 0; pi < game.players.length; pi++) {
                // remove any entries that appear in "none" from "some"
                for (var ni = 0; ni < cardMap[pi].none.length; ni++) {
                    for (var si = 0; si < cardMap[pi].some.length; si++) {
                        changed = changed || util.arrayRemove(cardMap[pi].some[si], cardMap[pi].none[ni]);
                    }
                }

                // move any one-element arrays from "some" to "known"
                for (var si = 0; si < cardMap[pi].some.length; si++) {
                    var some = cardMap[pi].some;
                    if (some[si].length == 1) {
                        changed = true;
                        util.setExtend(cardMap[pi].known, some[si]);
                        // remove from "some" and adjust loop index
                        some.splice(si, 1);
                        si--;
                    }
                }
            }

        } while (changed);

        return cardMap;
    }

    return {
        getPlayerCardMap: getPlayerCardMap,
        getCardMatrix: getCardMatrix,
        solve: solve,
    }
});
<|endoftext|>


<commit_before>(function (Q, $, window, undefined) {

    /**
     * Streams/webrtc/preview tool.
     * Renders a tool to preview Streams/webrtc
     * @class Streams/webrtc/preview
     * @constructor
     * @param {Object} [options] options to pass besides the ones to Streams/preview tool
     */
    Q.Tool.define("Streams/webrtc/preview", ["Streams/preview"], function _Streams_webrtc_preview (options, preview) {
            var tool = this;
            var state = this.state;
            tool.preview = preview;

			preview.state.editable = false;

            //preview.state.creatable.preprocess = tool.composer.bind(this);

            //Q.addStylesheet('{{Streams}}/css/tools/webrtcPreview.css', { slotName: 'Streams' });

            Q.Text.get('Streams/content', function (err, text) {
                var msg = Q.firstErrorMessage(err);
                if (msg) {
                    return console.warn(msg);
                }

                tool.text = text;
                preview.state.onRefresh.add(tool.refresh.bind(tool));
            });
        },

        {
			templates: {
				view: {
					name: 'Streams/webrtc/preview/view',
					fields: { alt: 'icon', titleClass: '', titleTag: 'h3' }
				}
			}
        },

{
        refresh: function (stream) {
            var tool = this;
            var state = this.state;
            var $toolElement = $(tool.element);

            if (!Q.Streams.isStream(stream)) {
                return;
            }

            tool.stream = stream;

            // retain with stream
            Q.Streams.retainWith(tool).get(stream.fields.publisherId, stream.fields.name);

			var fields = Q.extend({}, state.templates.view.fields, {
				alt: 'icon',
				title: stream.fields.title,
				inplace: inplace,
				preamble: Q.getObject('webtc.preview.preamble', text) || 'Meeting'
			});
			Q.Template.render(
				'Streams/webrtc/preview/view',
				fields,
				function (err, html) {
					if (err) return;
					tool.element.innerHTML = html;
					Q.activate(tool, function () {
						// load the icon
						// TODO: make this use flexbox instead
						var jq = tool.$('img.Streams_preview_icon');
						tool.preview.icon(jq[0], p.fill('icon'));
						var $pc = tool.$('.Streams_preview_contents');
						if ($pc.parent().is(":visible")) {
							$pc.width(0).width($pc[0].remainingWidth());
						}
						Q.onLayout(tool.element).set(function () {
							var $pc = tool.$('.Streams_preview_contents');
							if ($pc.parent().is(':visible')) {
								$pc.width(0).width($pc[0].remainingWidth());
							}
						}, tool);
						Q.handle(state.onRender, tool);
					});
				},
				state.templates[tpl]
			);

            setTimeout(function () {
                $toolElement.tool("Streams/preview", {
                    publisherId: state.publisherId,
                    streamName: state.streamName
                }).tool("Streams/default/preview").activate();
            }, 0);

            $toolElement.on(Q.Pointer.fastclick, function () {
                var WebConference = Q.Streams.WebRTC();
                WebConference.start({
                    element: document.body,
                    roomId: stream.fields.name.split('/').pop(),
                    roomPublisherId: stream.fields.publisherId,
                    mode: 'node',
                    startWith: {video: false, audio: true},
                    onWebRTCRoomCreated: function() {
                        console.log('onWebRTCRoomCreated', this);
                    },
                    onWebrtcControlsCreated: function() {
                        console.log('onWebrtcControlsCreated', this);
                    }
                });
            });
        }
    });

Q.Template.set('Streams/webrtc/preview/view',
	'
'
	+ ''
	+ '
'
	+ '<{{titleTag}} class="Streams_preview_preamble">{{preamble}}</{{titleTag}}'
	+ '<{{titleTag}} class="Streams_preview_title">{{title}}</{{titleTag}}>'
	+ '
{{size}}
'
	+ '

'
);

})(Q, Q.$, window);<commit_msg>Fixing small errors in previous commit<commit_after>(function (Q, $, window, undefined) {

    /**
     * Streams/webrtc/preview tool.
     * Renders a tool to preview Streams/webrtc
     * @class Streams/webrtc/preview
     * @constructor
     * @param {Object} [options] options to pass besides the ones to Streams/preview tool
     */
    Q.Tool.define("Streams/webrtc/preview", ["Streams/preview"], function _Streams_webrtc_preview (options, preview) {
            var tool = this;
            var state = this.state;
            tool.preview = preview;

			preview.state.editable = false;

            //preview.state.creatable.preprocess = tool.composer.bind(this);

            //Q.addStylesheet('{{Streams}}/css/tools/webrtcPreview.css', { slotName: 'Streams' });

            Q.Text.get('Streams/content', function (err, text) {
                var msg = Q.firstErrorMessage(err);
                if (msg) {
                    return console.warn(msg);
                }

                tool.text = text;
                preview.state.onRefresh.add(tool.refresh.bind(tool));
            });
        },

        {
			templates: {
				view: {
					name: 'Streams/webrtc/preview/view',
					fields: { alt: 'icon', titleClass: '', titleTag: 'h3' }
				}
			}
        },

{
        refresh: function (stream) {
            var tool = this;
            var state = this.state;
            var $toolElement = $(tool.element);

            if (!Q.Streams.isStream(stream)) {
                return;
            }

            tool.stream = stream;

            // retain with stream
            Q.Streams.retainWith(tool).get(stream.fields.publisherId, stream.fields.name);

			var fields = Q.extend({}, state.templates.view.fields, {
				alt: 'icon',
				title: stream.fields.title,
				preamble: Q.getObject('webtc.preview.preamble', text) || 'Meeting'
			});
			Q.Template.render(
				'Streams/webrtc/preview/view',
				fields,
				function (err, html) {
					if (err) return;
					tool.element.innerHTML = html;
					Q.activate(tool, function () {
						// load the icon
						// TODO: make this use flexbox instead
						var jq = tool.$('img.Streams_preview_icon');
						tool.preview.icon(jq[0], p.fill('icon'));
						var $pc = tool.$('.Streams_preview_contents');
						if ($pc.parent().is(":visible")) {
							$pc.width(0).width($pc[0].remainingWidth());
						}
						Q.onLayout(tool.element).set(function () {
							var $pc = tool.$('.Streams_preview_contents');
							if ($pc.parent().is(':visible')) {
								$pc.width(0).width($pc[0].remainingWidth());
							}
						}, tool);
						Q.handle(state.onRender, tool);
					});
				},
				state.templates[tpl]
			);

            setTimeout(function () {
                $toolElement.tool("Streams/preview", {
                    publisherId: state.publisherId,
                    streamName: state.streamName
                }).tool("Streams/default/preview").activate();
            }, 0);

            $toolElement.on(Q.Pointer.fastclick, function () {
                var WebConference = Q.Streams.WebRTC();
                WebConference.start({
                    element: document.body,
                    roomId: stream.fields.name.split('/').pop(),
                    roomPublisherId: stream.fields.publisherId,
                    mode: 'node',
                    startWith: {video: false, audio: true},
                    onWebRTCRoomCreated: function() {
                        console.log('onWebRTCRoomCreated', this);
                    },
                    onWebrtcControlsCreated: function() {
                        console.log('onWebrtcControlsCreated', this);
                    }
                });
            });
        }
    });

Q.Template.set('Streams/webrtc/preview/view',
	'
'
	+ ''
	+ '
'
	+ '<{{titleTag}} class="Streams_preview_preamble">{{preamble}}</{{titleTag}}'
	+ '<{{titleTag}} class="Streams_preview_title">{{title}}</{{titleTag}}>'
	+ '
{{size}}
'
	+ '

'
);

})(Q, Q.$, window);<|endoftext|>


<commit_before>var Player = function(ui) {
	var player = ui._context.createElement('video')
	player.dom.preload = "metadata"

	this.element = player
	this.ui = ui
	this.setEventListeners()

	ui.element.remove()
	ui.element = player
	ui.parent.element.append(ui.element)

	this._xhr = new XMLHttpRequest()
	this._xhr.addEventListener('load', ui._context.wrapNativeCallback(this.parseManifest).bind(this))
}

Player.prototype.setEventListeners = function() {
	var player = this.element
	var dom = player.dom
	var ui = this.ui
	player.on('play', function() { ui.waiting = false; ui.paused = dom.paused }.bind(ui))
	player.on('pause', function() { ui.paused = dom.paused }.bind(ui))
	player.on('ended', function() { ui.finished() }.bind(ui))
	player.on('seeked', function() { log("seeked"); ui.seeking = false; ui.waiting = false }.bind(ui))
	player.on('canplay', function() { log("canplay", dom.readyState); ui.ready = dom.readyState }.bind(ui))
	player.on('seeking', function() { log("seeking"); ui.seeking = true; ui.waiting = true }.bind(ui))
	player.on('waiting', function() { log("waiting"); ui.waiting = true }.bind(ui))
	player.on('stalled', function() { log("Was stalled", dom.networkState); ui.stalled = true }.bind(ui))
	player.on('emptied', function() { log("Was emptied", dom.networkState); }.bind(ui))
	player.on('volumechange', function() { ui.muted = dom.muted }.bind(ui))
	player.on('canplaythrough', function() { log("ready to play"); ui.paused = dom.paused }.bind(ui))
	player.on('suspend', function() { log('suspended'); ui.paused = true })

	player.on('error', function() {
		log("Player error occurred", dom.error, "src", ui.source)

		if (!dom.error || !ui.source)
			return

		var msg = ""
		switch (dom.error.code) {
		case 1:
			msg = "MEDIA_ERR_ABORTED error occurred"
			break;
		case 2:
			msg = "MEDIA_ERR_NETWORK error occurred"
			break;
		case 3:
			msg = "MEDIA_ERR_DECODE error occurred"
			break;
		case 4:
			msg = "MEDIA_ERR_SRC_NOT_SUPPORTED error occurred"
			break;
		default:
			msg = "UNDEFINED error occurred"
			break;
		}
		log("Error", msg)
		if (!dom.error.message)
			dom.error.message = msg
		ui.error(dom.error)
	}.bind(ui))

	player.on('timeupdate', function() {
		ui.waiting = false
		ui.stalled = false
		if (!ui.seeking)
			ui.progress = dom.currentTime
	}.bind(ui))

	player.on('durationchange', function() {
		var d = dom.duration
		log("Duration", d)
		ui.duration = isFinite(d) ? d : 0
	}.bind(ui))

	player.on('progress', function() {
		var last = dom.buffered.length - 1
		ui.waiting = false
		if (last >= 0)
			ui.buffered = dom.buffered.end(last) - dom.buffered.start(last)
	}.bind(ui))

	this.setOption("autoplay", ui.autoPlay)
}

Player.prototype.parseManifest = function(data) {
	var lines = data.target.responseText.split('\n');
	var url = this.ui.source
	var path = url.substring(0, url.lastIndexOf('/') + 1)
	var idx = 0
	this._videoTracks = [ { "name": "auto", "url": this.ui.source, "id": idx } ]
	this._totalTracks = {}
	this._audioTracksInfo = []
	for (var i = 0; i < lines.length - 1; ++i) {
		var line = lines[i]
		var nextLine = lines[i + 1]
		if (line.indexOf('#EXT-X-STREAM-INF') == 0) {
			var attributes = line.split(',');
			var track = {
				url: nextLine.indexOf("http") === 0 ? nextLine : (path + nextLine)
			}
			for (var j = 0; j < attributes.length; ++j) {
				var param = attributes[j].split('=');
				if (param.length > 1) {
					switch (param[0].trim().toLowerCase()) {
						case "bandwidth":
							track.bandwidth = param[1].trim()
							break
						case "audio":
							track.audio = param[1].trim().replace(/"/g, "")
							break
						case "resolution":
							var size = param[1].split("x")
							track.width = size[0]
							track.height = size[1]
							break
					}
				}
			}
			var key = track.width + "x" + track.height
			if (!this._totalTracks[key]) {
				this._totalTracks[key] = []
			}
			this._totalTracks[key].push(track)
		} else if (line.indexOf('#EXT-X-MEDIA:TYPE=AUDIO') == 0) {
			var attributes = line.split(',');
			var audioTrack = {}
			for (var j = 0; j < attributes.length; ++j) {
				var param = attributes[j].split('=');
				if (param.length > 1) {
					switch (param[0].trim().toLowerCase()) {
						case "group-id":
							audioTrack.id = param[1].trim().replace(/"/g, "")
							break
						case "name":
							audioTrack.label = param[1].trim().replace(/"/g, "")
							break
						case "language":
							audioTrack.language = param[1].trim().replace(/"/g, "")
							break
						case "uri":
							audioTrack.url = param[1].trim()
							break
					}
				}
			}
			this._audioTracksInfo.push(audioTrack)
		}
	}

	for (var i in this._totalTracks) {
		var tmpTrack = this._totalTracks[i][0]
		tmpTrack.id = ++idx
		this._videoTracks.push(tmpTrack)
	}
}

Player.prototype.getFileExtension = function(filePath) {
	if (!filePath)
		return ""
	var urlLower = filePath.toLowerCase()
	var querryIndex = filePath.indexOf("?")
	if (querryIndex >= 0)
		urlLower = urlLower.substring(0, querryIndex)
	var extIndex = urlLower.lastIndexOf(".")
	return urlLower.substring(extIndex, urlLower.length)
}

Player.prototype.setSource = function(url) {
	this.ui.ready = false
	this._extension = this.getFileExtension(url)
	if (url && this._xhr && (this._extension === ".m3u8" || this._extension === ".m3u")) {
		this._xhr.open('GET', url);
		this._xhr.send()
	}

	var source = url
	if (this.ui.startPosition)
		source += "#t=" + this.ui.startPosition
	this.element.dom.src = source
}

Player.prototype.play = function() {
	this.element.dom.play()
}

Player.prototype.pause = function() {
	this.element.dom.pause()
}

Player.prototype.stop = function() {
	//where is no 'stop' method in html5 video player just pause instead
	this.pause()
}

Player.prototype.seek = function(delta) {
	this.element.dom.currentTime += delta
}

Player.prototype.seekTo = function(tp) {
	this.element.dom.currentTime = tp
}

Player.prototype.setVolume = function(volume) {
	this.element.dom.volume = volume
}

Player.prototype.setMute = function(muted) {
	this.element.dom.muted = muted
}

Player.prototype.setLoop = function(loop) {
	this.element.dom.loop = loop
}

Player.prototype.setOption = function(name, value) {
	if (name === "autoplay") {
		if (value)
			this.element.dom.setAttribute("autoplay", "")
		else
			this.element.dom.removeAttribute("autoplay");
	} else {
		this.element.dom.setAttribute(name, value)
	}
}

Player.prototype.setRect = function(l, t, r, b) {
	//not needed in this port
}

Player.prototype.setVisibility = function(visible) {
	log('VISIBILITY LOGIC MISSING HERE, visible:', visible)
}

Player.prototype.setupDrm = function(type, options, callback, error) {
	log('Not implemented')
}

Player.prototype.getAudioTracks = function() {
	log('Not implemented')
	return []
}

Player.prototype.getVideoTracks = function() {
	return this._videoTracks || []
}

Player.prototype.getAudioTracks = function() {
	var audioTracks = this.element.dom.audioTracks
	var result = []
	for (var i = 0; i < audioTracks.length; ++i) {
		var track = audioTracks[i]
		var info = this._audioTracksInfo[i]
		result.push({
			"id": i,
			"name": track.label ? track.label : info.name,
			"language": track.language ? track.language : info.language
		})
	}
	log("getAudioTracks", result)
	return result
}

Player.prototype.setAudioTrack = function(trackId) {
	var audioTracks = this.element.dom.audioTracks
	if (trackId < 0 || trackId >= audioTracks.length) {
		log("Where is no track", trackId)
		return
	}
	log("Set audio track", audioTracks[trackId])

	var result = []
	for (var i = 0; i < audioTracks.length; ++i)
		audioTracks[i].enabled = i === trackId
}

Player.prototype.setVideoTrack = function(trackId) {
	if (!this._videoTracks || this._videoTracks.length <= 0) {
		log("There is no available video track", this._videoTracks)
		return
	}
	if (trackId < 0 || trackId >= this._videoTracks.length) {
		log("Track with id", trackId, "not found")
		return
	}
	this.ui.waiting = true
	var progress = this.ui.progress
	log("Set video", this._videoTracks[trackId])
	this.element.dom.src = this._videoTracks[trackId].url
	this.seekTo(progress)
}

Player.prototype.setVideoTrack = function(trackId) {
	if (!this._videoTracks || this._videoTracks.length <= 0) {
		log("There is no available video track", this._videoTracks)
		return
	}
	if (trackId < 0 || trackId >= this._videoTracks.length) {
		log("Track with id", trackId, "not found")
		return
	}
	this.ui.waiting = true
	var progress = this.ui.progress
	log("Set video", this._videoTracks[trackId])
	this.element.dom.src = this._videoTracks[trackId].url
	this.seekTo(progress)
}

Player.prototype.setBackgroundColor = function(color) {
	var Color = _globals.core.Color
	this.element.dom.style.backgroundColor = new Color(color).rgba()
}

exports.createPlayer = function(ui) {
	return new Player(ui)
}

exports.probeUrl = function(url) {
	return 50
}

exports.Player = Player
<commit_msg>Revert "Add message in player error event if its not exist"<commit_after>var Player = function(ui) {
	var player = ui._context.createElement('video')
	player.dom.preload = "metadata"

	this.element = player
	this.ui = ui
	this.setEventListeners()

	ui.element.remove()
	ui.element = player
	ui.parent.element.append(ui.element)

	this._xhr = new XMLHttpRequest()
	this._xhr.addEventListener('load', ui._context.wrapNativeCallback(this.parseManifest).bind(this))
}

Player.prototype.setEventListeners = function() {
	var player = this.element
	var dom = player.dom
	var ui = this.ui
	player.on('play', function() { ui.waiting = false; ui.paused = dom.paused }.bind(ui))
	player.on('pause', function() { ui.paused = dom.paused }.bind(ui))
	player.on('ended', function() { ui.finished() }.bind(ui))
	player.on('seeked', function() { log("seeked"); ui.seeking = false; ui.waiting = false }.bind(ui))
	player.on('canplay', function() { log("canplay", dom.readyState); ui.ready = dom.readyState }.bind(ui))
	player.on('seeking', function() { log("seeking"); ui.seeking = true; ui.waiting = true }.bind(ui))
	player.on('waiting', function() { log("waiting"); ui.waiting = true }.bind(ui))
	player.on('stalled', function() { log("Was stalled", dom.networkState); ui.stalled = true }.bind(ui))
	player.on('emptied', function() { log("Was emptied", dom.networkState); }.bind(ui))
	player.on('volumechange', function() { ui.muted = dom.muted }.bind(ui))
	player.on('canplaythrough', function() { log("ready to play"); ui.paused = dom.paused }.bind(ui))
	player.on('suspend', function() { log('suspended'); ui.paused = true })

	player.on('error', function() {
		log("Player error occurred", dom.error, "src", ui.source)

		if (!dom.error || !ui.source)
			return

		ui.error(dom.error)

		log("player.error", dom.error)
		switch (dom.error.code) {
		case 1:
			log("MEDIA_ERR_ABORTED error occurred")
			break;
		case 2:
			log("MEDIA_ERR_NETWORK error occurred")
			break;
		case 3:
			log("MEDIA_ERR_DECODE error occurred")
			break;
		case 4:
			log("MEDIA_ERR_SRC_NOT_SUPPORTED error occurred")
			break;
		default:
			log("UNDEFINED error occurred")
			break;
		}
	}.bind(ui))

	player.on('timeupdate', function() {
		ui.waiting = false
		ui.stalled = false
		if (!ui.seeking)
			ui.progress = dom.currentTime
	}.bind(ui))

	player.on('durationchange', function() {
		var d = dom.duration
		log("Duration", d)
		ui.duration = isFinite(d) ? d : 0
	}.bind(ui))

	player.on('progress', function() {
		var last = dom.buffered.length - 1
		ui.waiting = false
		if (last >= 0)
			ui.buffered = dom.buffered.end(last) - dom.buffered.start(last)
	}.bind(ui))

	this.setOption("autoplay", ui.autoPlay)
}

Player.prototype.parseManifest = function(data) {
	var lines = data.target.responseText.split('\n');
	var url = this.ui.source
	var path = url.substring(0, url.lastIndexOf('/') + 1)
	var idx = 0
	this._videoTracks = [ { "name": "auto", "url": this.ui.source, "id": idx } ]
	this._totalTracks = {}
	this._audioTracksInfo = []
	for (var i = 0; i < lines.length - 1; ++i) {
		var line = lines[i]
		var nextLine = lines[i + 1]
		if (line.indexOf('#EXT-X-STREAM-INF') == 0) {
			var attributes = line.split(',');
			var track = {
				url: nextLine.indexOf("http") === 0 ? nextLine : (path + nextLine)
			}
			for (var j = 0; j < attributes.length; ++j) {
				var param = attributes[j].split('=');
				if (param.length > 1) {
					switch (param[0].trim().toLowerCase()) {
						case "bandwidth":
							track.bandwidth = param[1].trim()
							break
						case "audio":
							track.audio = param[1].trim().replace(/"/g, "")
							break
						case "resolution":
							var size = param[1].split("x")
							track.width = size[0]
							track.height = size[1]
							break
					}
				}
			}
			var key = track.width + "x" + track.height
			if (!this._totalTracks[key]) {
				this._totalTracks[key] = []
			}
			this._totalTracks[key].push(track)
		} else if (line.indexOf('#EXT-X-MEDIA:TYPE=AUDIO') == 0) {
			var attributes = line.split(',');
			var audioTrack = {}
			for (var j = 0; j < attributes.length; ++j) {
				var param = attributes[j].split('=');
				if (param.length > 1) {
					switch (param[0].trim().toLowerCase()) {
						case "group-id":
							audioTrack.id = param[1].trim().replace(/"/g, "")
							break
						case "name":
							audioTrack.label = param[1].trim().replace(/"/g, "")
							break
						case "language":
							audioTrack.language = param[1].trim().replace(/"/g, "")
							break
						case "uri":
							audioTrack.url = param[1].trim()
							break
					}
				}
			}
			this._audioTracksInfo.push(audioTrack)
		}
	}

	for (var i in this._totalTracks) {
		var tmpTrack = this._totalTracks[i][0]
		tmpTrack.id = ++idx
		this._videoTracks.push(tmpTrack)
	}
}

Player.prototype.getFileExtension = function(filePath) {
	if (!filePath)
		return ""
	var urlLower = filePath.toLowerCase()
	var querryIndex = filePath.indexOf("?")
	if (querryIndex >= 0)
		urlLower = urlLower.substring(0, querryIndex)
	var extIndex = urlLower.lastIndexOf(".")
	return urlLower.substring(extIndex, urlLower.length)
}

Player.prototype.setSource = function(url) {
	this.ui.ready = false
	this._extension = this.getFileExtension(url)
	if (url && this._xhr && (this._extension === ".m3u8" || this._extension === ".m3u")) {
		this._xhr.open('GET', url);
		this._xhr.send()
	}

	var source = url
	if (this.ui.startPosition)
		source += "#t=" + this.ui.startPosition
	this.element.dom.src = source
}

Player.prototype.play = function() {
	this.element.dom.play()
}

Player.prototype.pause = function() {
	this.element.dom.pause()
}

Player.prototype.stop = function() {
	//where is no 'stop' method in html5 video player just pause instead
	this.pause()
}

Player.prototype.seek = function(delta) {
	this.element.dom.currentTime += delta
}

Player.prototype.seekTo = function(tp) {
	this.element.dom.currentTime = tp
}

Player.prototype.setVolume = function(volume) {
	this.element.dom.volume = volume
}

Player.prototype.setMute = function(muted) {
	this.element.dom.muted = muted
}

Player.prototype.setLoop = function(loop) {
	this.element.dom.loop = loop
}

Player.prototype.setOption = function(name, value) {
	if (name === "autoplay") {
		if (value)
			this.element.dom.setAttribute("autoplay", "")
		else
			this.element.dom.removeAttribute("autoplay");
	} else {
		this.element.dom.setAttribute(name, value)
	}
}

Player.prototype.setRect = function(l, t, r, b) {
	//not needed in this port
}

Player.prototype.setVisibility = function(visible) {
	log('VISIBILITY LOGIC MISSING HERE, visible:', visible)
}

Player.prototype.setupDrm = function(type, options, callback, error) {
	log('Not implemented')
}

Player.prototype.getAudioTracks = function() {
	log('Not implemented')
	return []
}

Player.prototype.getVideoTracks = function() {
	return this._videoTracks || []
}

Player.prototype.getAudioTracks = function() {
	var audioTracks = this.element.dom.audioTracks
	var result = []
	for (var i = 0; i < audioTracks.length; ++i) {
		var track = audioTracks[i]
		var info = this._audioTracksInfo[i]
		result.push({
			"id": i,
			"name": track.label ? track.label : info.name,
			"language": track.language ? track.language : info.language
		})
	}
	log("getAudioTracks", result)
	return result
}

Player.prototype.setAudioTrack = function(trackId) {
	var audioTracks = this.element.dom.audioTracks
	if (trackId < 0 || trackId >= audioTracks.length) {
		log("Where is no track", trackId)
		return
	}
	log("Set audio track", audioTracks[trackId])

	var result = []
	for (var i = 0; i < audioTracks.length; ++i)
		audioTracks[i].enabled = i === trackId
}

Player.prototype.setVideoTrack = function(trackId) {
	if (!this._videoTracks || this._videoTracks.length <= 0) {
		log("There is no available video track", this._videoTracks)
		return
	}
	if (trackId < 0 || trackId >= this._videoTracks.length) {
		log("Track with id", trackId, "not found")
		return
	}
	this.ui.waiting = true
	var progress = this.ui.progress
	log("Set video", this._videoTracks[trackId])
	this.element.dom.src = this._videoTracks[trackId].url
	this.seekTo(progress)
}

Player.prototype.setVideoTrack = function(trackId) {
	if (!this._videoTracks || this._videoTracks.length <= 0) {
		log("There is no available video track", this._videoTracks)
		return
	}
	if (trackId < 0 || trackId >= this._videoTracks.length) {
		log("Track with id", trackId, "not found")
		return
	}
	this.ui.waiting = true
	var progress = this.ui.progress
	log("Set video", this._videoTracks[trackId])
	this.element.dom.src = this._videoTracks[trackId].url
	this.seekTo(progress)
}

Player.prototype.setBackgroundColor = function(color) {
	var Color = _globals.core.Color
	this.element.dom.style.backgroundColor = new Color(color).rgba()
}

exports.createPlayer = function(ui) {
	return new Player(ui)
}

exports.probeUrl = function(url) {
	return 50
}

exports.Player = Player
<|endoftext|>


<commit_before>var Player = function(ui) {
	var player = ui._context.createElement('video')
	player.dom.preload = "metadata"

	var dom = player.dom
	player.on('play', function() { ui.waiting = false; ui.paused = dom.paused }.bind(ui))
	player.on('pause', function() { ui.paused = dom.paused }.bind(ui))
	player.on('ended', function() { ui.finished() }.bind(ui))
	player.on('seeked', function() { log("seeked"); ui.seeking = false; ui.waiting = false }.bind(ui))
	player.on('canplay', function() { log("canplay", dom.readyState); ui.ready = dom.readyState }.bind(ui))
	player.on('seeking', function() { log("seeking"); ui.seeking = true; ui.waiting = true }.bind(ui))
	player.on('waiting', function() { log("waiting"); ui.waiting = true }.bind(ui))
	player.on('stalled', function() { log("Was stalled", dom.networkState); }.bind(ui))
	player.on('emptied', function() { log("Was emptied", dom.networkState); }.bind(ui))
	player.on('volumechange', function() { ui.muted = dom.muted }.bind(ui))
	player.on('canplaythrough', function() { log("ready to play"); ui.paused = dom.paused }.bind(ui))

	player.on('error', function() {
		log("Player error occured", dom.error, "src", ui.source)

		if (!dom.error || !ui.source)
			return

		ui.error(dom.error)

		log("player.error", dom.error)
		switch (dom.error.code) {
		case 1:
			log("MEDIA_ERR_ABORTED error occured")
			break;
		case 2:
			log("MEDIA_ERR_NETWORK error occured")
			break;
		case 3:
			log("MEDIA_ERR_DECODE error occured")
			break;
		case 4:
			log("MEDIA_ERR_SRC_NOT_SUPPORTED error occured")
			break;
		default:
			log("UNDEFINED error occured")
			break;
		}
	}.bind(ui))

	player.on('timeupdate', function() {
		ui.waiting = false
		if (!ui.seeking)
			ui.progress = dom.currentTime
	}.bind(ui))

	player.on('durationchange', function() {
		var d = dom.duration
		log("Duration", d)
		ui.duration = isFinite(d) ? d : 0
	}.bind(ui))

	player.on('progress', function() {
		var last = dom.buffered.length - 1
		ui.waiting = false
		if (last >= 0)
			ui.buffered = dom.buffered.end(last) - dom.buffered.start(last)
	}.bind(ui))

	this.element = player
	this.ui = ui

	ui.element.remove()
	ui.element = player
	ui.parent.element.append(ui.element)

	this.setAutoPlay(ui.autoPlay)
}

Player.prototype.setSource = function(url) {
	this.ui.ready = false
	this.element.dom.src = url
}

Player.prototype.play = function() {
	this.element.dom.play()
}

Player.prototype.pause = function() {
	this.element.dom.pause()
}

Player.prototype.stop = function() {
	//where is no 'stop' method in html5 video player just pause instead
	this.pause()
}

Player.prototype.seek = function(delta) {
	this.element.dom.currentTime += delta
}

Player.prototype.seekTo = function(tp) {
	this.element.dom.currentTime = tp
}

Player.prototype.setVolume = function(volume) {
	this.element.dom.volume = volume
}

Player.prototype.setMute = function(muted) {
	this.element.dom.muted = muted
}

Player.prototype.setLoop = function(loop) {
	this.element.dom.loop = loop
}

Player.prototype.setAutoPlay = function(autoPlay) {
	if (autoPlay)
		this.element.dom.setAttribute("autoplay", "")
	else
		this.element.dom.removeAttribute("autoplay");
}

Player.prototype.setRect = function(l, t, r, b) {
	//not needed in this port
}

Player.prototype.setVisibility = function(visible) {
	log('VISIBILITY LOGIC MISSING HERE, visible:', visible)
}

Player.prototype.setupDrm = function(type, options, callback, error) {
	log('Not implemented')
}

Player.prototype.getAudioTracks = function() {
	log('Not implemented')
	return []
}

Player.prototype.getVideoTracks = function() {
	log('Not implemented')
	return []
}

Player.prototype.setAudioTracks = function() {
	log('Not implemented')
}

Player.prototype.setVideoTracks = function() {
	log('Not implemented')
}

Player.prototype.setBackgroundColor = function(color) {
	var Color = _globals.core.Color
	this.element.dom.style.backgroundColor = new Color(color).rgba()
}

exports.createPlayer = function(ui) {
	return new Player(ui)
}

exports.probeUrl = function(url) {
	return 50
}

exports.Player = Player
<commit_msg>Implement video and audio track setting<commit_after>var Player = function(ui) {
	var player = ui._context.createElement('video')
	player.dom.preload = "metadata"

	var dom = player.dom
	player.on('play', function() { ui.waiting = false; ui.paused = dom.paused }.bind(ui))
	player.on('pause', function() { ui.paused = dom.paused }.bind(ui))
	player.on('ended', function() { ui.finished() }.bind(ui))
	player.on('seeked', function() { log("seeked"); ui.seeking = false; ui.waiting = false }.bind(ui))
	player.on('canplay', function() { log("canplay", dom.readyState); ui.ready = dom.readyState }.bind(ui))
	player.on('seeking', function() { log("seeking"); ui.seeking = true; ui.waiting = true }.bind(ui))
	player.on('waiting', function() { log("waiting"); ui.waiting = true }.bind(ui))
	player.on('stalled', function() { log("Was stalled", dom.networkState); }.bind(ui))
	player.on('emptied', function() { log("Was emptied", dom.networkState); }.bind(ui))
	player.on('volumechange', function() { ui.muted = dom.muted }.bind(ui))
	player.on('canplaythrough', function() { log("ready to play"); ui.paused = dom.paused }.bind(ui))

	player.on('error', function() {
		log("Player error occured", dom.error, "src", ui.source)

		if (!dom.error || !ui.source)
			return

		ui.error(dom.error)

		log("player.error", dom.error)
		switch (dom.error.code) {
		case 1:
			log("MEDIA_ERR_ABORTED error occured")
			break;
		case 2:
			log("MEDIA_ERR_NETWORK error occured")
			break;
		case 3:
			log("MEDIA_ERR_DECODE error occured")
			break;
		case 4:
			log("MEDIA_ERR_SRC_NOT_SUPPORTED error occured")
			break;
		default:
			log("UNDEFINED error occured")
			break;
		}
	}.bind(ui))

	player.on('timeupdate', function() {
		ui.waiting = false
		if (!ui.seeking)
			ui.progress = dom.currentTime
	}.bind(ui))

	player.on('durationchange', function() {
		var d = dom.duration
		log("Duration", d)
		ui.duration = isFinite(d) ? d : 0
	}.bind(ui))

	player.on('progress', function() {
		var last = dom.buffered.length - 1
		ui.waiting = false
		if (last >= 0)
			ui.buffered = dom.buffered.end(last) - dom.buffered.start(last)
	}.bind(ui))

	this.element = player
	this.ui = ui

	ui.element.remove()
	ui.element = player
	ui.parent.element.append(ui.element)

	this.setAutoPlay(ui.autoPlay)

	this._xhr = new XMLHttpRequest()
	this._xhr.addEventListener('load', this.parseManifest.bind(this))
}

Player.prototype.parseManifest = function(data) {
	var lines = data.target.responseText.split('\n');
	var url = this.ui.source
	var path = url.substring(0, url.lastIndexOf('/') + 1)
	var idx = 0
	this._videoTracks = [ { "name": "auto", "url": this.ui.source, "id": idx } ]
	this._totalTracks = {}
	this._audioTracksInfo = []
	for (var i = 0; i < lines.length - 1; ++i) {
		var line = lines[i]
		var nextLine = lines[i + 1]
		if (line.indexOf('#EXT-X-STREAM-INF') == 0) {
			var attributes = line.split(',');
			var track = {
				url: nextLine.indexOf("http") === 0 ? nextLine : (path + nextLine)
			}
			for (var j = 0; j < attributes.length; ++j) {
				var param = attributes[j].split('=');
				if (param.length > 1) {
					switch (param[0].trim().toLowerCase()) {
						case "bandwidth":
							track.bandwidth = param[1].trim()
							break
						case "audio":
							track.audio = param[1].trim().replace(/"/g, "")
							break
						case "resolution":
							var size = param[1].split("x")
							track.width = size[0]
							track.height = size[1]
							break
					}
				}
			}
			var key = track.width + "x" + track.height
			if (!this._totalTracks[key]) {
				this._totalTracks[key] = []
			}
			this._totalTracks[key].push(track)
		} else if (line.indexOf('#EXT-X-MEDIA:TYPE=AUDIO') == 0) {
			var attributes = line.split(',');
			var audioTrack = {}
			for (var j = 0; j < attributes.length; ++j) {
				var param = attributes[j].split('=');
				if (param.length > 1) {
					switch (param[0].trim().toLowerCase()) {
						case "group-id":
							audioTrack.id = param[1].trim().replace(/"/g, "")
							break
						case "name":
							audioTrack.label = param[1].trim().replace(/"/g, "")
							break
						case "language":
							audioTrack.language = param[1].trim().replace(/"/g, "")
							break
						case "uri":
							audioTrack.url = param[1].trim()
							break
					}
				}
			}
			this._audioTracksInfo.push(audioTrack)
		}
	}

	for (var i in this._totalTracks) {
		var tmpTrack = this._totalTracks[i][0]
		tmpTrack.id = ++idx
		this._videoTracks.push(tmpTrack)
	}
}

Player.prototype.getFileExtension = function(filePath) {
	if (!filePath)
		return ""
	var urlLower = filePath.toLowerCase()
	var querryIndex = filePath.indexOf("?")
	if (querryIndex >= 0)
		urlLower = urlLower.substring(0, querryIndex)
	var extIndex = urlLower.lastIndexOf(".")
	return urlLower.substring(extIndex, urlLower.length)
}

Player.prototype.setSource = function(url) {
	this.ui.ready = false
	this._extension = this.getFileExtension(url)
	if (url && (this._extension === ".m3u8" || this._extension === ".m3u")) {
		this._xhr.open('GET', url);
		this._xhr.send()
	}
	this.element.dom.src = url
}

Player.prototype.play = function() {
	this.element.dom.play()
}

Player.prototype.pause = function() {
	this.element.dom.pause()
}

Player.prototype.stop = function() {
	//where is no 'stop' method in html5 video player just pause instead
	this.pause()
}

Player.prototype.seek = function(delta) {
	this.element.dom.currentTime += delta
}

Player.prototype.seekTo = function(tp) {
	this.element.dom.currentTime = tp
}

Player.prototype.setVolume = function(volume) {
	this.element.dom.volume = volume
}

Player.prototype.setMute = function(muted) {
	this.element.dom.muted = muted
}

Player.prototype.setLoop = function(loop) {
	this.element.dom.loop = loop
}

Player.prototype.setAutoPlay = function(autoPlay) {
	if (autoPlay)
		this.element.dom.setAttribute("autoplay", "")
	else
		this.element.dom.removeAttribute("autoplay");
}

Player.prototype.setRect = function(l, t, r, b) {
	//not needed in this port
}

Player.prototype.setVisibility = function(visible) {
	log('VISIBILITY LOGIC MISSING HERE, visible:', visible)
}

Player.prototype.setupDrm = function(type, options, callback, error) {
	log('Not implemented')
}

Player.prototype.getAudioTracks = function() {
	log('Not implemented')
	return []
}

Player.prototype.getVideoTracks = function() {
	return this._videoTracks || []
}

Player.prototype.getAudioTracks = function() {
	var audioTracks = this.element.dom.audioTracks
	var result = []
	for (var i = 0; i < audioTracks.length; ++i) {
		var track = audioTracks[i]
		var info = this._audioTracksInfo[i]
		result.push({
			"id": i,
			"name": track.label ? track.label : info.name,
			"language": track.language ? track.language : info.language
		})
	}
	log("getAudioTracks", result)
	return result
}

Player.prototype.setAudioTrack = function(trackId) {
	var audioTracks = this.element.dom.audioTracks
	if (trackId < 0 || trackId >= audioTracks.length) {
		log("Where is no track", trackId)
		return
	}
	log("Set audio track", audioTracks[trackId])

	var result = []
	for (var i = 0; i < audioTracks.length; ++i)
		audioTracks[i].enabled = i === trackId
}

Player.prototype.setVideoTrack = function(trackId) {
	if (!this._videoTracks || this._videoTracks.length <= 0) {
		log("There is no available video track", this._videoTracks)
		return
	}
	if (trackId < 0 || trackId >= this._videoTracks.length) {
		log("Track with id", trackId, "not found")
		return
	}
	this.ui.waiting = true
	var progress = this.ui.progress
	log("Set video", this._videoTracks[trackId])
	this.element.dom.src = this._videoTracks[trackId].url
	this.seekTo(progress)
}

Player.prototype.setVideoTrack = function(trackId) {
	if (!this._videoTracks || this._videoTracks.length <= 0) {
		log("There is no available video track", this._videoTracks)
		return
	}
	if (trackId < 0 || trackId >= this._videoTracks.length) {
		log("Track with id", trackId, "not found")
		return
	}
	this.ui.waiting = true
	var progress = this.ui.progress
	log("Set video", this._videoTracks[trackId])
	this.element.dom.src = this._videoTracks[trackId].url
	this.seekTo(progress)
}

Player.prototype.setBackgroundColor = function(color) {
	var Color = _globals.core.Color
	this.element.dom.style.backgroundColor = new Color(color).rgba()
}

exports.createPlayer = function(ui) {
	return new Player(ui)
}

exports.probeUrl = function(url) {
	return 50
}

exports.Player = Player
<|endoftext|>


<commit_before>// Check RCPT TO domain is in host list

exports.hook_rcpt = function(next, connection, params) {
    var rcpt = params[0];
    // Check for RCPT TO without an @ first - ignore those here
    if (!rcpt.host) {
        return next();
    }

    connection.logdebug(this, "Checking if " + rcpt + " host is in host_lists");

    var domain          = rcpt.host.toLowerCase();
    var host_list       = this.config.get('host_list', 'list');
    var host_list_regex = this.config.get('host_list_regex', 'list');

    var i = 0;
    for (i in host_list) {
        connection.logdebug(this, "checking " + domain + " against " + host_list[i]);

        // normal matches
        if (host_list[i].toLowerCase() === domain) {
            if (connection.transaction.results) {
                connection.transaction.results(plugin, {pass: 'in_host_list'});
            }
            return next(OK);
        }
    }

    if (host_list_regex.length) {
        var regex = new RegExp ('^(?:' + host_list_regex.join('|') + ')$', 'i');

        connection.logdebug(this, "checking " + domain + " against regexp " + regex.source);

        // regex matches
        if (domain.match(regex)) {
            if (connection.transaction.results) {
                connection.transaction.results(plugin, {pass: 'in_host_list'});
            }
            return next(OK);
        }
    }

    if (connection.transaction.results) {
        connection.transaction.results(plugin, {fail: 'in_host_list'});
    }

    next();
}
<commit_msg>in_host_list: defined 'plugin'<commit_after>// Check RCPT TO domain is in host list

exports.hook_rcpt = function(next, connection, params) {
    var rcpt = params[0];
    // Check for RCPT TO without an @ first - ignore those here
    if (!rcpt.host) {
        return next();
    }

    connection.logdebug(this, "Checking if " + rcpt + " host is in host_lists");

    var domain          = rcpt.host.toLowerCase();
    var host_list       = this.config.get('host_list', 'list');
    var host_list_regex = this.config.get('host_list_regex', 'list');

    var i = 0;
    for (i in host_list) {
        connection.logdebug(this, "checking " + domain + " against " + host_list[i]);

        // normal matches
        if (host_list[i].toLowerCase() === domain) {
            connection.transaction.results.add(this, {pass: 'in_host_list'});
            return next(OK);
        }
    }

    if (host_list_regex.length) {
        var regex = new RegExp ('^(?:' + host_list_regex.join('|') + ')$', 'i');

        connection.logdebug(this, "checking " + domain + " against regexp " + regex.source);

        // regex matches
        if (domain.match(regex)) {
            connection.transaction.results.add(this, {pass: 'in_host_list'});
            return next(OK);
        }
    }

    connection.transaction.results.add(this, {fail: 'in_host_list'});
    return next();
}
<|endoftext|>


<commit_before>/**
 * Alloy
 * Copyright (c) 2012 by Appcelerator, Inc. All Rights Reserved.
 * See LICENSE for more information on licensing.
 */

exports.cliVersion = '>=3.X';

exports.init = function (logger, config, cli, appc) {
	var path = require('path'),
		fs = require('fs'),
		afs = appc.fs,
		i18n = appc.i18n(__dirname),
		__ = i18n.__,
		__n = i18n.__n,
		pkginfo = appc.pkginfo.package(module),
		exec = require('child_process').exec,
		spawn = require('child_process').spawn,
		parallel = appc.async.parallel;

	function run(deviceFamily, deployType, target, finished) {
		var appDir = path.join(cli.argv['project-dir'], 'app');
		if (!afs.exists(appDir)) {
			logger.info(__('Project not an Alloy app, continuing'));
			finished();
			return;
		}
		logger.info(__('Found Alloy app in %s', appDir.cyan));

		// TODO: Make this check specific to a TiSDK version
		// create a .alloynewcli file to tell old plugins not to run
		var buildDir = path.join(cli.argv['project-dir'], 'build');
		if (!afs.exists(buildDir)) {
			fs.mkdirSync(buildDir);
		}
		fs.writeFileSync(path.join(buildDir, '.alloynewcli'), '');

		var cRequire = afs.resolvePath(__dirname, '..', 'Alloy', 'commands', 'compile', 'index.js'),
			config = {
				platform: /(?:iphone|ipad)/.test(cli.argv.platform) ? 'ios' : cli.argv.platform,
				version: '0',
				simtype: 'none',
				devicefamily: /(?:iphone|ios)/.test(cli.argv.platform) ? deviceFamily : 'none',
				deploytype: deployType || cli.argv['deploy-type'] || 'development',
				target: target
			};

		config = Object.keys(config).map(function (c) {
			return c + '=' + config[c];
		}).join(',');

		if (afs.exists(cRequire)) {
			// we're being invoked from the actual alloy directory!
			// no need to subprocess, just require() and run
			var origLimit = Error.stackTraceLimit;
			Error.stackTraceLimit = Infinity;
			try {
				require(cRequire)({}, {
					config: config,
					outputPath: cli.argv['project-dir'],
					_version: pkginfo.version
				});
			} catch (e) {
				logger.error(__('Alloy compiler failed'));
				e.toString().split('\n').forEach(function (line) {
					if (line) { logger.error(line); }
				});
				process.exit(1);
			}
			Error.stackTraceLimit = origLimit;
			finished();
		} else {
			// we have no clue where alloy is installed, so we're going to subprocess
			// alloy and hope it's in the system path or a well known place
			var paths = {};
			parallel(this, ['alloy', 'node'].map(function (bin) {
				return function (done) {
					var envName = 'ALLOY_' + (bin === 'node' ? 'NODE_' : '') + 'PATH';

					paths[bin] = process.env[envName];
					if (paths[bin]) {
						done();
					} else if (process.platform === 'win32') {
						paths.alloy = 'alloy.cmd';
						done();
					} else {
						exec('which ' + bin, function (err, stdout, strerr) {
							if (!err) {
								paths[bin] = stdout.trim();
								done();
							} else {
								parallel(this, [
									'/usr/local/bin/' + bin,
									'/opt/local/bin/' + bin,
									path.join(process.env.HOME, 'local/bin', bin),
									'/opt/bin/' + bin,
									'/usr/bin/' + bin
								].map(function (p) {
									return function (cb) {
										if (afs.exists(p)) { paths[bin] = p; }
										cb();
									};
								}), done);
							}
						});
					}
				};
			}), function () {
				var cmd = [paths.node, paths.alloy, 'compile', appDir, '--config', config];
				if (cli.argv['no-colors'] || cli.argv['color'] === false) { cmd.push('--no-colors'); }
				if (process.platform === 'win32') { cmd.shift(); }
				logger.info(__('Executing Alloy compile: %s', cmd.join(' ').cyan));

				var child = (process.platform === 'win32') ? spawn(cmd.shift(), cmd, { stdio: 'inherit' }) : spawn(cmd.shift(), cmd);

				function checkLine(line) {
					var re = new RegExp(
						'(?:\u001b\\[\\d+m)?\\[?(' +
						logger.getLevels().join('|') +
						')\\]?\s*(?:\u001b\\[\\d+m)?(.*)', 'i'
					);
					if (line) {
						var m = line.match(re);
						if (m) {
							logger[m[1].toLowerCase()](m[2].trim());
						} else {
							logger.debug(line);
						}
					}
				}

				child.stdout !== null && child.stdout.on('data', function (data) {
					data.toString().split('\n').forEach(function (line) {
						checkLine(line);
					});
				});
				child.stderr !== null && child.stderr.on('data', function (data) {
					data.toString().split('\n').forEach(function (line) {
						checkLine(line);
					});
				});
				child !== null && child.on('exit', function (code) {
					if (code) {
						logger.error(__('Alloy compiler failed'));
						process.exit(1);
					} else {
						logger.info(__('Alloy compiler completed successfully'));
					}
					finished();
				});
			});
		}
	}

	cli.addHook('build.pre.compile', function (build, finished) {
		// TODO: Remove this workaround when the CLI reports the right deploy type for android
		var deployType = build.deployType;
		var target = build.target;

		if (cli.argv.platform === 'android') {
			switch(target) {
				case 'dist-playstore':
					deployType = 'production';
					break;
				case 'device':
					deployType = 'test';
					break;
				case 'emulator':
				default:
					deployType = 'development';
					break;
			}
		}
		run(build.deviceFamily, deployType, target, finished);
	});

	cli.addHook('codeprocessor.pre.run', function (build, finished) {
		run('none', 'development', undefined, finished);
	});
};
<commit_msg>fixed info spacing issue<commit_after>/**
 * Alloy
 * Copyright (c) 2012 by Appcelerator, Inc. All Rights Reserved.
 * See LICENSE for more information on licensing.
 */

exports.cliVersion = '>=3.X';

exports.init = function (logger, config, cli, appc) {
	var path = require('path'),
		fs = require('fs'),
		afs = appc.fs,
		i18n = appc.i18n(__dirname),
		__ = i18n.__,
		__n = i18n.__n,
		pkginfo = appc.pkginfo.package(module),
		exec = require('child_process').exec,
		spawn = require('child_process').spawn,
		parallel = appc.async.parallel;

	function run(deviceFamily, deployType, finished) {
		var appDir = path.join(cli.argv['project-dir'], 'app');
		if (!afs.exists(appDir)) {
			logger.info(__('Project not an Alloy app, continuing'));
			finished();
			return;
		}
		logger.info(__('Found Alloy app in %s', appDir.cyan));

		// TODO: Make this check specific to a TiSDK version
		// create a .alloynewcli file to tell old plugins not to run
		var buildDir = path.join(cli.argv['project-dir'], 'build');
		if (!afs.exists(buildDir)) {
			fs.mkdirSync(buildDir);
		}
		fs.writeFileSync(path.join(buildDir, '.alloynewcli'), '');

		var cRequire = afs.resolvePath(__dirname, '..', 'Alloy', 'commands', 'compile', 'index.js'),
			config = {
				platform: /(?:iphone|ipad)/.test(cli.argv.platform) ? 'ios' : cli.argv.platform,
				version: '0',
				simtype: 'none',
				devicefamily: /(?:iphone|ios)/.test(cli.argv.platform) ? deviceFamily : 'none',
				deploytype: deployType || cli.argv['deploy-type'] || 'development'
			};

		config = Object.keys(config).map(function (c) {
			return c + '=' + config[c];
		}).join(',');

		if (afs.exists(cRequire)) {
			// we're being invoked from the actual alloy directory!
			// no need to subprocess, just require() and run
			var origLimit = Error.stackTraceLimit;
			Error.stackTraceLimit = Infinity;
			try {
				require(cRequire)({}, {
					config: config,
					outputPath: cli.argv['project-dir'],
					_version: pkginfo.version
				});
			} catch (e) {
				logger.error(__('Alloy compiler failed'));
				e.toString().split('\n').forEach(function (line) {
					if (line) { logger.error(line); }
				});
				process.exit(1);
			}
			Error.stackTraceLimit = origLimit;
			finished();
		} else {
			// we have no clue where alloy is installed, so we're going to subprocess
			// alloy and hope it's in the system path or a well known place
			var paths = {};
			parallel(this, ['alloy', 'node'].map(function (bin) {
				return function (done) {
					var envName = 'ALLOY_' + (bin === 'node' ? 'NODE_' : '') + 'PATH';

					paths[bin] = process.env[envName];
					if (paths[bin]) {
						done();
					} else if (process.platform === 'win32') {
						paths.alloy = 'alloy.cmd';
						done();
					} else {
						exec('which ' + bin, function (err, stdout, strerr) {
							if (!err) {
								paths[bin] = stdout.trim();
								done();
							} else {
								parallel(this, [
									'/usr/local/bin/' + bin,
									'/opt/local/bin/' + bin,
									path.join(process.env.HOME, 'local/bin', bin),
									'/opt/bin/' + bin,
									'/usr/bin/' + bin
								].map(function (p) {
									return function (cb) {
										if (afs.exists(p)) { paths[bin] = p; }
										cb();
									};
								}), done);
							}
						});
					}
				};
			}), function () {
				var cmd = [paths.node, paths.alloy, 'compile', appDir, '--config', config];
				if (cli.argv['no-colors']) { cmd.push('--no-colors'); }
				if (process.platform === 'win32') { cmd.shift(); }
				logger.info(__('Executing Alloy compile: %s', cmd.join(' ').cyan));

				var child = spawn(cmd.shift(), cmd);

				function checkLine(line) {
					var re = new RegExp(
						'(?:\u001b\\[\\d+m)?\\[?(' +
						logger.getLevels().join('|') +
						')\\]?\s*(?:\u001b\\[\\d+m)?(.*)', 'i'
					);
					if (line) {
						var m = line.match(re);
						if (m) {
							logger[m[1].toLowerCase()](m[2].trim());
						} else {
							logger.debug(line);
						}
					}
				}

				child.stdout.on('data', function (data) {
					data.toString().split('\n').forEach(function (line) {
						checkLine(line);
					});
				});
				child.stderr.on('data', function (data) {
					data.toString().split('\n').forEach(function (line) {
						checkLine(line);
					});
				});
				child.on('exit', function (code) {
					if (code) {
						logger.error(__('Alloy compiler failed'));
						process.exit(1);
					} else {
						logger.info(__('Alloy compiler completed successfully'));
					}
					finished();
				});
			});
		}
	}

	cli.addHook('build.pre.compile', function (build, finished) {
		// TODO: Remove this workaround when the CLI reports the right deploy type for android
		var deployType = build.deployType;
		if (cli.argv.platform === 'android') {
			switch(cli.argv.target) {
				case 'dist-playstore':
					deployType = 'production';
					break;
				case 'device':
					deployType = 'test';
					break;
				case 'emulator':
				default:
					deployType = 'development';
					break;
			}
		}
		run(build.deviceFamily, deployType, finished);
	});

	cli.addHook('codeprocessor.pre.run', function (build, finished) {
		run('none', 'development', finished);
	});
};
<|endoftext|>


<commit_before>$(document).ready(parseSpells);

function parseSpells() {
	if (!localStorage['spells']) {
		console.log('getting spell data from server...');
		$.getScript('https://dl.dropboxusercontent.com/s/wneq3reu80vdlkb/spellData.json', function() {
				localStorage['spells'] = JSON.stringify(jsonSpellData);
				jsonSpellData.forEach(appendSpell);
				});
	} else {
		JSON.parse(localStorage['spells']).forEach(appendSpell);
	}

	$('#filters').change(filterSpells);
}

function appendSpell(spell) {
	var panel = $('

')
		.addClass('panel')
		.addClass('panel-default')
		;

	var attrs = parseAttrs(spell);
	var tags = [];
	for (var key in attrs) {
		if (attrs[key] === true) {
			tags.push(key);
		}
		addSpellAttr(panel, key, attrs[key]);
	}

	var heading = $('

')
		.addClass('panel-heading')
		.text(spell.name);

	var info = $('')
		.addClass('pull-right')
		.text(spell.level + ' ' + spell.school);
	heading.append(info);

	var body = $('

')
		.addClass('panel-body');

	var footer = $('

')
		.addClass('panel-footer')
		.text(tags.join(', '));

	body.append($.parseHTML(spell.desc));
	if (spell.higher_level) {
		body.append($.parseHTML(spell.higher_level));
	}
	heading.appendTo(panel);
	body.appendTo(panel);
	footer.appendTo(panel);
	panel.appendTo($('#spells'));
}

function parseAttrs(spell) {
	return {
		verbal: (spell.components.indexOf('V') !== -1),
		somantic: (spell.components.indexOf('S') !== -1), // motion
		material: (spell.components.indexOf('M') !== -1),
		ritual: (spell.ritual == 'yes'),
		concentration: (spell.concentration == 'yes'),
		level: (spell.level.substr(0, 1) == 'C') ? 0 : spell.level.substr(0, 1),
		classes: spell.class.split(', '),
		school: spell.school
	};
}

function addSpellAttr(panel, key, val) {
	if (typeof val == 'object'){
		val.forEach(function(attr) {
			panel.attr('data-' + attr.toLowerCase().replace(' ', '-'), true);
		});
	} else {
		panel.attr('data-' + key, val);
	}
}

function filterSpells() {
	$('.panel').hide();

	var classes = $('#classes').find(':checked').map(function() { return this.id; }).get();
	var levels = $('#levels').find(':checked').map(function() { return this.id.substr(3); }).get();
	$('.panel').filter(function() {
		if (!filterByClass(this, classes)) {
			return false;
		}

		if (!filterByLevel(this, levels)) {
			return false;
		}

		// you've reached the end and passed!
		return true;
	}).show();
}

function filterByClass(el, classes) {
	if (classes.length > 0) {
		var inClass = false;
		classes.forEach(function(className) {
			if ($(el).data(className) == true) {
				inClass = true;
				return true;
			}
		});
		return inClass;
	}
	return true;
}

function filterByLevel(el, levels) {
	if (levels.length > 0) {
		var inLevel = false;
		levels.forEach(function(lvl) {
			if ($(this).data('level') == lvl) {
				inLevel = true;
				return true;
			}
		}.bind(el));
		return inLevel;
	}
	return true;
}
<commit_msg>show classes as well<commit_after>$(document).ready(parseSpells);

function parseSpells() {
	if (!localStorage['spells']) {
		console.log('getting spell data from server...');
		$.getScript('https://dl.dropboxusercontent.com/s/wneq3reu80vdlkb/spellData.json', function() {
				localStorage['spells'] = JSON.stringify(jsonSpellData);
				jsonSpellData.forEach(appendSpell);
				});
	} else {
		JSON.parse(localStorage['spells']).forEach(appendSpell);
	}

	$('#filters').change(filterSpells);
}

function appendSpell(spell) {
	var panel = $('

')
		.addClass('panel')
		.addClass('panel-default')
		;

	var attrs = parseAttrs(spell);
	var tags = [];
	for (var key in attrs) {
		if (attrs[key] === true) {
			tags.push(key);
		}
		addSpellAttr(panel, key, attrs[key]);
	}

	var heading = $('

')
		.addClass('panel-heading')
		.text(spell.name);

	var info = $('')
		.addClass('pull-right')
		.text(spell.level + ' ' + spell.school);
	heading.append(info);

	var body = $('

')
		.addClass('panel-body');

	var footer = $('

')
		.addClass('panel-footer')
		.text(tags.concat(attrs.classes).join(', '));

	body.append($.parseHTML(spell.desc));
	if (spell.higher_level) {
		body.append($.parseHTML(spell.higher_level));
	}
	heading.appendTo(panel);
	body.appendTo(panel);
	footer.appendTo(panel);
	panel.appendTo($('#spells'));
}

function parseAttrs(spell) {
	return {
		verbal: (spell.components.indexOf('V') !== -1),
		somantic: (spell.components.indexOf('S') !== -1), // motion
		material: (spell.components.indexOf('M') !== -1),
		ritual: (spell.ritual == 'yes'),
		concentration: (spell.concentration == 'yes'),
		level: (spell.level.substr(0, 1) == 'C') ? 0 : spell.level.substr(0, 1),
		classes: spell.class.split(', '),
		school: spell.school
	};
}

function addSpellAttr(panel, key, val) {
	if (typeof val == 'object'){
		val.forEach(function(attr) {
			panel.attr('data-' + attr.toLowerCase().replace(' ', '-'), true);
		});
	} else {
		panel.attr('data-' + key, val);
	}
}

function filterSpells() {
	$('.panel').hide();

	var classes = $('#classes').find(':checked').map(function() { return this.id; }).get();
	var levels = $('#levels').find(':checked').map(function() { return this.id.substr(3); }).get();
	$('.panel').filter(function() {
		if (!filterByClass(this, classes)) {
			return false;
		}

		if (!filterByLevel(this, levels)) {
			return false;
		}

		// you've reached the end and passed!
		return true;
	}).show();
}

function filterByClass(el, classes) {
	if (classes.length > 0) {
		var inClass = false;
		classes.forEach(function(className) {
			if ($(el).data(className) == true) {
				inClass = true;
				return true;
			}
		});
		return inClass;
	}
	return true;
}

function filterByLevel(el, levels) {
	if (levels.length > 0) {
		var inLevel = false;
		levels.forEach(function(lvl) {
			if ($(this).data('level') == lvl) {
				inLevel = true;
				return true;
			}
		}.bind(el));
		return inLevel;
	}
	return true;
}
<|endoftext|>


<commit_before>require('dotenv').load();

//database stuff here
var mongoose = require('mongoose');

var connectionString = process.env.DATABASE_URL || process.env.MONGOLAB_URI;
console.log("-------------------------------Attempting to connect to Database");
mongoose.connect(connectionString);

mongoose.connection.on('connected', function() {
  console.log("Connected to Database >> specialist");
});

mongoose.connection.on('disconnected', function() {
  console.log("Disconneced From Database >> specialist")
});

mongoose.connection.on('error', function() {
  console.log('There was an error in the database!');
});
<commit_msg>another test<commit_after>require('dotenv').load();

//database stuff here
var mongoose = require('mongoose');
// var connectionString = 'mongodb://localhost/'
// if(process.env.NODE_ENV === 'production'){
//   connectionString = process.env.MONGOLAB_URI;
// }
var connectionString = process.env.DATABASE_URL || process.env.MONGOLAB_URI;
console.log("-------------------------------Attempting to connect to Database");
console.log(process.env.MONGOLAB_URI);
console.log(connectionString);
mongoose.connect(connectionString);

mongoose.connection.on('connected', function() {
  console.log("Connected to Database >> specialist");
});

mongoose.connection.on('disconnected', function() {
  console.log("Disconneced From Database >> specialist")
});

mongoose.connection.on('error', function() {
  console.log('There was an error in the database!');
});
<|endoftext|>


<commit_before>'use strict';

function Sprite(opt) {
    //config
    var index   = 0,
        frame   = -1,
        time    = null,
        playing = false,
        err     = opt.err,
        playErr = new Error('Animation is already playing'),
        rangeErr= new RangeError('Parameter must be between 1 and ' + frames),
        missing = new Error('Missing property'),
        rAF, rAF2, count, last, paused;

    //private settings
    var cvs     = document.getElementById(opt.id),
        x       = cvs.width = opt.width,
        y       = cvs.height = opt.height,
        ctx     = cvs.getContext('2d'),
        img     = new Image(),
        frames  = opt.image_width ? (opt.image_width / x) : (function (){throw missing}());

    img.src = opt.src;
    ctx.drawImage(img, index * x, 0, x, y, 0, 0, x, y);

    this.loop = function (fps, dir, n) {
        if (playing && err) throw playErr;
        if (fps == null) fps = 60;
        if (n !== null) count = 0;
        var delay = 1000 / fps;
        rAF = requestAnimationFrame(anim.bind(null, n, delay, dir));
        playing = true;
    };

    this.play = function (e) {
        if (playing && err) throw playErr;
        if (e.to > frames && err) throw rangeErr;
        if (e.from < 1 && err) throw rangeErr;
        if (e.fps == null) e.fps = 60;
        if (e.from == null) e.from = 0;
        if (e.to == null) e.to = frames - 1;
        if (e.n == null) e.n = 1;
        if (paused == null || !paused || count !== count || count == null) {
            if (e.to > e.from) count = 0;
            if (e.from > e.to) count = 1;
        }
        var delay = 1000 / e.fps;
        index = e.from - 1;
        e.from--;
        e.to--;
        playing = true;
        rAF2 = requestAnimationFrame(play.bind(null, e.from, e.to, e.n, delay));
        e.callback();
    }

    this.pause = function () {
        if (!playing && err) throw playErr;
        cancelAnimationFrame(rAF);
        cancelAnimationFrame(rAF2);
        playing = false;
        paused = true;
        frame = -1;
    };

    this.reset = function (to) {
        if (to == null) to = 0;
        cancelAnimationFrame(rAF);
        cancelAnimationFrame(rAF2);
        playing = false;
        frame = -1;
        index = to - 1;
        ctx.clearRect(0, 0, x, y);
        ctx.drawImage(img, (--to) * x, 0, x, y, 0, 0, x, y);
    };

    this.frame = function() {
        return index + 1;
    };

    var anim = function (n, delay, dir, timestamp) {
        if (time == null) time = timestamp;
        rAF = requestAnimationFrame(anim.bind(null, n, delay, dir));
        var current = Math.floor((timestamp - time) / delay);
        if (current > frame) {
            if (index == frames - 1) count++;
            frame = current;
            ctx.clearRect(0, 0, x, y);
            ctx.drawImage(img, index * x, 0, x, y, 0, 0, x, y);
            if (dir == 'backward') {
                if (index <= 0) {
                    index = frames;
                }
                index -= 1;
            } else {
                if (index >= frames - 1) {
                    index = 0;
                } else {
                    index++;
                }
            }//if dir backward
        }//if current> frame

        if (typeof n !== null && n > 0) {
            if (count == n && index == 1 && dir !== 'backward') {
                playing = false;
                paused = false;
                cancelAnimationFrame(rAF);
            }//if
            if (count == n && index == frames - 1 && dir == 'backward') {
                playing = false;
                paused = false;
                cancelAnimationFrame(rAF);
            }//if
        }//if typeof

    };//anim

    var play = function (from, to, n, delay, timestamp) {
        rAF2 = requestAnimationFrame(play.bind(null, from, to, n, delay));
        if (time === null) time = timestamp;
        var current = Math.floor((timestamp - time) / delay);
        if (current > frame) {
            frame = current;
            if (count >= n && index == last && n !== 0) {
                cancelAnimationFrame(rAF2);
                playing = false;
                paused = false;
            }
            ctx.clearRect(0, 0, x, y);
            ctx.drawImage(img, index * x, 0, x, y, 0, 0, x, y);
            if (to > from) {
                if (index >= to) {
                    index = from;
                } else {
                    index++;
                }
                last = to;
                if (index == to) count++;
            } else if (from > to) {
                if (index <= to) {
                    index = from;
                } else {
                    index--;
                }
                last = to;
                if (index == from) count++;
            }// else if

        } //current > frame
    };
}
<commit_msg>Changed dir<commit_after>'use strict';

function Sprite(opt) {
    //private settings
    var cvs     = document.getElementById(opt.id),
        x       = cvs.width = opt.width,
        y       = cvs.height = opt.height,
        ctx     = cvs.getContext('2d'),
        img     = new Image(),
        frames  = opt.image_width ? (opt.image_width / x) : (function (){throw missing}());

    //config
    var index   = 0,
        frame   = -1,
        time    = null,
        playing = false,
        err     = opt.err,
        playErr = new Error('Animation is already playing'),
        rangeErr= console.error(new RangeError('Parameter must be between 1 and ' + frames)),
        missing = new Error('Missing property'),
        rAF, count, paused;

    img.src = opt.src;
    ctx.drawImage(img, index * x, 0, x, y, 0, 0, x, y);

    this.play = function (e) {
        if (playing && err) throw playErr;
        if (e.to > frames && err) rangeErr;
        if (e.from < 1 && err) throw rangeErr;
        if (e.fps == null) e.fps = 60;
        if (e.from == null) e.from = 1;
        if (e.to == null) e.to = frames;
        if (e.n == null) e.n = 1;
        if (paused == null || !paused || count !== count || count == null) {
            if (e.to > e.from) count = 0;
            if (e.from > e.to) count = 1;
        }
        var delay = 1000 / e.fps;
        index = e.from - 1;
        e.from--;
        e.to--;
        playing = true;
        rAF = requestAnimationFrame(play.bind(null, e.from, e.to, e.n, delay, e.step, e.loop));
    }

    this.pause = function () {
        if (!playing && err) throw playErr;
        cancelAnimationFrame(rAF);
        playing = false;
        paused = true;
        frame = -1;
    };

    this.reset = function (to) {
        if (to == null) to = 0;
        cancelAnimationFrame(rAF);
        playing = false;
        frame = -1;
        index = to - 1;
        ctx.clearRect(0, 0, x, y);
        ctx.drawImage(img, (--to) * x, 0, x, y, 0, 0, x, y);
    };

    this.frame = function() {
        return index + 1;
    };

    var play = function (from, to, n, delay, callback1, callback2, timestamp) {
        rAF = requestAnimationFrame(play.bind(null, from, to, n, delay, callback1, callback2));
        if (time === null) time = timestamp;
        var current = Math.floor((timestamp - time) / delay);
        if (current > frame) {
            frame = current;
            if (count >= n && index == to && n !== 0) {
                playing = false;
                paused = false;
            }
            ctx.clearRect(0, 0, x, y);
            ctx.drawImage(img, index * x, 0, x, y, 0, 0, x, y);
            if (to > from) {
                if (index >= to) {
                    typeof callback1 === 'function' && callback1(index + 1);
                    index = from;
                } else {
                    typeof callback1 === 'function' && callback1(index + 1);
                    index++;
                }
                if (index == to) {
                    typeof callback2 === 'function' && callback2(count);
                    count++;
                }
            } else if (from > to) {
                if (index <= to) {
                    typeof callback1 === 'function' && callback1(index + 1);
                    index = from;
                } else {
                    typeof callback1 === 'function' && callback1(index + 1);
                    index--;
                }
                if (index == from) {
                    typeof callback2 === 'function' && callback2(count);
                    count++;
                }
            }// else if

        } //current > frame

    };
}
<|endoftext|>