<commit_before>/**!
 * Part of the jMediaelement-Project | http://github.com/aFarkas/jMediaelement
 * @author Alexander Farkas
 * Copyright 2010, Alexander Farkas
 * Dual licensed under the MIT or GPL Version 2 licenses.
 */
(function($){
	$.extend($.fn.mediaElementEmbed.defaults,
			{
				vlc: {}
			}
		)
	;

	var doc	 			= document,
		defaultAttrs 	= {
			pluginspage: 'http://www.videolan.org',
			version: 'VideoLAN.VLCPlugin.2',
			progid: 'VideoLAN.VLCPlugin.2',
			events: 'true',
			type: 'application/x-vlc-plugin'
		},
		activeXAttrs 	= {
			classid: 'clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921'
		}
	;
	function embedVlc(elem, id, attrs, params){
		var vlc;
		attrs = $.extend({}, defaultAttrs, attrs);
		if(!window.ActiveXObject){
			vlc = doc.createElement('object');
			$.each(attrs, function(name, val){
				vlc.setAttribute(name, val);
			});

			$.each(params, function(name, val){
				var param = doc.createElement('param');
				param.setAttribute('name', name);
				param.setAttribute('value', val);
				vlc.appendChild(param);
			});
			vlc.setAttribute('id', id);
			vlc.setAttribute('name', id);
			elem.parentNode.replaceChild(vlc, elem);
		} else if(elem.outerHTML){
			vlc = '<object';
			$.each($.extend({}, attrs, activeXAttrs), function(name, val){
				vlc += ' '+ name +'="'+ val +'"';
			});
			vlc += ' name="'+ id +'"';
			vlc += ' id="'+ id +'"';
			vlc += '>';
			$.each(params, function(name, val){
				vlc += ' <param name="'+ name +'" value="'+ val +'" />';
			});
			vlc += '</object>';
			elem.outerHTML = vlc;
			vlc = doc.getElementById(id);
		}
		return vlc;
	}
	var vlcMM = {
			isTechAvailable: function(){
				if($.support.vlc !== undefined){
					return $.support.vlc;
				}
				$.support.vlc = false;
				var navVLC = (navigator.plugins && navigator.plugins['VLC Multimedia Plug-in']);
				if(navVLC && parseFloat(((navVLC.description || '').match(/(\d+\.\d+)/) || '0.1'), 10) >= 0.9){
					$.support.vlc = true;
				} else if(window.ActiveXObject){
					try {
						if(new ActiveXObject('VideoLAN.VLCPlugin.2')){
							$.support.vlc = true;
						}
					} catch(e){}
				}
				return $.support.vlc;
			},
			_embed: function(src, id, api, dims, attrs, fn){
				var opts 	= api.embedOpts.vlc,
					vlcAttr = $.extend({}, dims, {src: src}),
					params 	= {
						src: src,
						ShowDisplay: 'true',
						AutoPlay: ''+ attrs.autoplay,//
						AutoLoop: ''+attrs.loop
					},
					vlc
				;
				$.extend(vlcAttr, params);
				vlc = $('<div />').css(dims).insertBefore(api.html5elem);
				vlc = $(embedVlc(vlc[0], id, vlcAttr, params)).css(dims);
				fn(vlc[0]);
			},
			canPlayCodecs: ['avc1.42E01E', 'mp4a.40.2', 'avc1.58A01E', 'avc1.4D401E', 'avc1.64001E', 'theora', 'vorbis'],
			canPlayContainer: ['video/x-msvideo', 'video/quicktime', 'video/x-m4v', 'video/mp4', 'video/m4p', 'video/x-flv', 'video/flv', 'audio/mpeg', 'audio/x-fla', 'audio/fla', 'video/ogg', 'video/x-ogg', 'audio/x-ogg', 'audio/ogg', 'application/ogg', 'application/x-ogg']
		}
	;

	$.multimediaSupport.add('vlc', 'video', vlcMM);
	$.multimediaSupport.add('vlc', 'audio', vlcMM);
})(jQuery);
<commit_msg>using lowercase instead of camelcase<commit_after>/**!
 * Part of the jMediaelement-Project | http://github.com/aFarkas/jMediaelement
 * @author Alexander Farkas
 * Copyright 2010, Alexander Farkas
 * Dual licensed under the MIT or GPL Version 2 licenses.
 */
(function($){
	$.extend($.fn.mediaElementEmbed.defaults,
			{
				vlc: {}
			}
		)
	;

	var doc	 			= document,
		defaultAttrs 	= {
			pluginspage: 'http://www.videolan.org',
			version: 'VideoLAN.VLCPlugin.2',
			progid: 'VideoLAN.VLCPlugin.2',
			events: 'true',
			type: 'application/x-vlc-plugin'
		},
		activeXAttrs 	= {
			classid: 'clsid:9BE31822-FDAD-461B-AD51-BE1D1C159921'
		}
	;
	function embedVlc(elem, id, attrs, params){
		var vlc;
		attrs = $.extend({}, defaultAttrs, attrs);
		if(!window.ActiveXObject){
			vlc = doc.createElement('object');
			$.each(attrs, function(name, val){
				vlc.setAttribute(name, val);
			});

			$.each(params, function(name, val){
				var param = doc.createElement('param');
				param.setAttribute('name', name);
				param.setAttribute('value', val);
				vlc.appendChild(param);
			});
			vlc.setAttribute('id', id);
			vlc.setAttribute('name', id);
			elem.parentNode.replaceChild(vlc, elem);
		} else if(elem.outerHTML){
			vlc = '<object';
			$.each($.extend({}, attrs, activeXAttrs), function(name, val){
				vlc += ' '+ name +'="'+ val +'"';
			});
			vlc += ' name="'+ id +'"';
			vlc += ' id="'+ id +'"';
			vlc += '>';
			$.each(params, function(name, val){
				vlc += ' <param name="'+ name +'" value="'+ val +'" />';
			});
			vlc += '</object>';
			elem.outerHTML = vlc;
			vlc = doc.getElementById(id);
		}
		return vlc;
	}
	var vlcMM = {
			isTechAvailable: function(){
				if($.support.vlc !== undefined){
					return $.support.vlc;
				}
				$.support.vlc = false;
				var navVLC = (navigator.plugins && navigator.plugins['VLC Multimedia Plug-in']);
				if(navVLC && parseFloat(((navVLC.description || '').match(/(\d+\.\d+)/) || '0.1'), 10) >= 0.9){
					$.support.vlc = true;
				} else if(window.ActiveXObject){
					try {
						if(new ActiveXObject('VideoLAN.VLCPlugin.2')){
							$.support.vlc = true;
						}
					} catch(e){}
				}
				return $.support.vlc;
			},
			_embed: function(src, id, api, dims, attrs, fn){
				var opts 	= api.embedOpts.vlc,
					vlcAttr = $.extend({}, dims, {src: src}),
					params 	= {
						src: src,
						showdisplay: 'true',
						autoplay: ''+ attrs.autoplay,//
						autoloop: ''+attrs.loop
					},
					vlc
				;
				$.extend(vlcAttr, params);
				vlc = $('<div />').css(dims).insertBefore(api.html5elem);
				vlc = $(embedVlc(vlc[0], id, vlcAttr, params)).css(dims);
				fn(vlc[0]);
			},
			canPlayCodecs: ['avc1.42E01E', 'mp4a.40.2', 'avc1.58A01E', 'avc1.4D401E', 'avc1.64001E', 'theora', 'vorbis'],
			canPlayContainer: ['video/x-msvideo', 'video/quicktime', 'video/x-m4v', 'video/mp4', 'video/m4p', 'video/x-flv', 'video/flv', 'audio/mpeg', 'audio/x-fla', 'audio/fla', 'video/ogg', 'video/x-ogg', 'audio/x-ogg', 'audio/ogg', 'application/ogg', 'application/x-ogg']
		}
	;

	$.multimediaSupport.add('vlc', 'video', vlcMM);
	$.multimediaSupport.add('vlc', 'audio', vlcMM);
})(jQuery);
<|endoftext|>


<commit_before><commit_msg>new seh data<commit_after><|endoftext|>


<commit_before>require('proof')(1, function (assert) {
    assert(require('../..'), 'require')
})
<commit_msg>Tidy `require.t.js`.<commit_after>require('proof')(1, prove)

function prove (assert) {
    assert(require('../..'), 'require')
}
<|endoftext|>


<commit_before>/*@cc_on@if(@_jscript_version<9){'video audio source track'.replace(/\w+/g,function(n){document.createElement(n)})}@end@*/

/**
* Kaltura html5 library loader
* For more info on mwEmbed / kaltura html5 library see:
* http://www.kaltura.org/project/HTML5_Video_Media_JavaScript_Library
*/

var kURID = '1.1t';
// Static script loader url:
var SCRIPT_LOADER_URL = 'http://html5.kaltura.org/ResourceLoader.php';
var SCRIPT_FORCE_DEBUG = false;

// These Lines are for local testing:
SCRIPT_FORCE_DEBUG = true;
SCRIPT_LOADER_URL = '../mwEmbed/ResourceLoader.php';
//kURID = new Date().getTime();

// Define mw ( if not already set )
if( !window['mw'] ){
	window['mw'] = {};
}

// Define the dom ready flag
var kAlreadyRunDomReadyFlag = false;

// Try and override the swfObject at runtime
// In case it was included before mwEmbedLoader and the embedSWF call is inline
kOverideSwfObject();

// Setup preMwEmbedReady queue
if( !preMwEmbedReady ){
	var preMwEmbedReady = [];
}
// Wrap mw.ready to preMwEmbedReady values
if( !mw.ready){
	mw.ready = function( fn ){
		preMwEmbedReady.push( fn );
		// Check if mw.ready was called after the dom is ready:
		if( kAlreadyRunDomReadyFlag ){
			kCheckAddScript();
		}
	}
}
// Setup a preMwEmbedConfig var
if( ! preMwEmbedConfig ) {
	var preMwEmbedConfig = [];
}
if( !mw.setConfig ){
	mw.setConfig = function( set, value ){
		var valueQueue = {};
		if( typeof value != 'undefined'  ) {
			preMwEmbedConfig[ set	] = value;
		} else if ( typeof set == 'object' ){
			for( var i in set ){
				preMwEmbedConfig[ i ] = set[i];
			}
		}
	}
}
// Test if swfObject exists, try and override its embed method to wrap html5 rewrite calls.
function kOverideSwfObject(){
	// Check if already override
	if( window['swfobject'] && window['swfobject']['originalEmbedSWF'] ){
		return ;
	}

	if( window['swfobject'] && window['swfobject']['embedSWF'] ){
		window['swfobject']['originalEmbedSWF'] = window['swfobject']['embedSWF'];
		// override embedObjec for our own ends
		window['swfobject']['embedSWF'] = function( swfUrlStr, replaceElemIdStr, widthStr,
				heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn)
		{
			var kEmbedSettings = kGetKalturaEmbedSettings( swfUrlStr, flashvarsObj);
			// Check if mobile safari:

			if( kBrowserAgentShouldUseHTML5() && kEmbedSettings.entryId ){
				// Make sure we have kaltura script:
				kAddScript();
				mw.ready(function(){
					var width = ( widthStr )? parseInt( widthStr ) : $j('#' + replaceElemIdStr ).width();
					var height = ( heightStr)? parseInt( heightStr ) : $j('#' + replaceElemIdStr ).height();

					var poster = 'http://cdnakmi.kaltura.com/p/' + kEmbedSettings.partnerId + '/sp/' +
						kEmbedSettings.partnerId + '00/thumbnail/entry_id/' + kEmbedSettings.entryId + '/width/' +
						height + '/height/' + width;
					$j('#' + replaceElemIdStr ).css({
						'width' : width,
						'height' : height
					}).embedPlayer({
						'poster': poster,
						'kentryid': kEmbedSettings.entryId,
						'kwidgetid' : kEmbedSettings.widgetId
					});
				});
			} else {
				// Else call the original EmbedSWF with all its arguments
				window['swfobject']['originalEmbedSWF']( swfUrlStr, replaceElemIdStr, widthStr,
						heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn )
			}
		}
	}
}

// Check dom for kaltura embeds ( fall forward )
// && html5 video tag ( for fallback & html5 player interface )
function kCheckAddScript(){
	// If user javascript is using mw.ready add script
	if( preMwEmbedReady.length ) {
		kAddScript();
		return ;
	}

	// If document includes audio or video tags
	if( document.getElementsByTagName('video').length != 0
		|| document.getElementsByTagName('audio').length != 0 ) {
		kAddScript();
		return ;
	}

	// If document includes kaltura embed tags && isMobile safari:
	if ( kBrowserAgentShouldUseHTML5() ) {
		// Check for kaltura objects in the page
		var usedIdSet = [];
		for(var i=0; i < document.getElementsByTagName('object').length; i++) {
			var embedTag = document.getElementsByTagName('object')[i];
			if( embedTag.getAttribute( 'name' ) == 'kaltura_player' ) {
				kAddScript();
				var kId = embedTag.getAttribute( 'id' );
				if( usedIdSet[ kId ] ) {
					// Update the id ( append index )
					embedTag.setAttribute( 'id',  kId + '_' + i);
				}
				usedIdSet[ embedTag.getAttribute( 'id' ) ] = true;
			}
		}
	}
}
function kBrowserAgentShouldUseHTML5(){
	return (  (navigator.userAgent.indexOf('iPhone') != -1) ||
	(navigator.userAgent.indexOf('iPod') != -1) ||
	(navigator.userAgent.indexOf('iPad') != -1) ||
	// to debug in chrome / desktop safari
	(document.URL.indexOf('forceMobileSafari') != -1 )
	);
}

// Add the kaltura html5 mwEmbed script
var kAddedScript = false;
function kAddScript(){
	if( kAddedScript ){
		return ;
	}
	kAddedScript = true;
	var url = SCRIPT_LOADER_URL + '?class=';

	if( typeof window.jQuery == 'undefined' ) {
		url+='window.jQuery,'
	}
	// Add mwEmbed and common style sheet
	url+= 'mwEmbed';

	// Add all the classes needed for video
	var jsPlayerRequest = [
		// core skin:
		'mw.style.mwCommon',
		'mw.style.ui_redmond',

		// embed player:
		'mw.EmbedPlayer',
		'mw.style.EmbedPlayer',
		'mw.PlayerControlBuilder',

		// default skin:
		'mw.PlayerSkinMvpcf',
		'mw.style.PlayerSkinMvpcf',

		// common playback methods:
		'mw.EmbedPlayerNative',
		'mw.EmbedPlayerKplayer',
		'mw.EmbedPlayerJava',

		// jQuery helpers
		'$j.ui',
		'$j.fn.hoverIntent',
		'$j.cookie',
		'JSON',
		'$j.ui.slider',
		'$j.fn.menu',
		'mw.style.jquerymenu',

		// Timed Text module
		'mw.TimedText',
		'mw.style.TimedText'
	];
	url+= ',' + jsPlayerRequest.join(',');

	url+='&urid=' + kURID;
	url+='&uselang=en';

	if ( SCRIPT_FORCE_DEBUG ){
		url+='&debug=true';
	}

	var script = document.createElement( 'script' );
	script.type = 'text/javascript';
	script.src = url;
	// no handlers:
	document.getElementsByTagName('body')[0].appendChild( script );
};

/**
* DOM-ready setup ( similar to jQuery.ready )
*/
function kRunMwDomReady(){
	kAlreadyRunDomReadyFlag  = true;
	kOverideSwfObject();
	kCheckAddScript();
}
// Check if already ready:
if ( document.readyState === "complete" ) {
	kRunMwDomReady();
}

// Cleanup functions for the document ready method
if ( document.addEventListener ) {
	DOMContentLoaded = function() {
		document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
		kRunMwDomReady();
	};

} else if ( document.attachEvent ) {
	DOMContentLoaded = function() {
		// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
		if ( document.readyState === "complete" ) {
			document.detachEvent( "onreadystatechange", DOMContentLoaded );
			kRunMwDomReady();
		}
	};
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
	// Use the handy event callback
	document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

	// A fallback to window.onload, that will always work
	window.addEventListener( "load", kRunMwDomReady, false );

// If IE event model is used
} else if ( document.attachEvent ) {
	// ensure firing before onload,
	// maybe late but safe also for iframes
	document.attachEvent("onreadystatechange", DOMContentLoaded);

	// A fallback to window.onload, that will always work
	window.attachEvent( "onload", kRunMwDomReady );

	// If IE and not a frame
	// continually check to see if the document is ready
	var toplevel = false;

	try {
		toplevel = window.frameElement == null;
	} catch(e) {}

	if ( document.documentElement.doScroll && toplevel ) {
		doScrollCheck();
	}
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
	if ( kAlreadyRunDomReadyFlag ) {
		return;
	}
	try {
		// If IE is used, use the trick by Diego Perini
		// http://javascript.nwbox.com/IEContentLoaded/
		document.documentElement.doScroll("left");
	} catch( error ) {
		setTimeout( doScrollCheck, 1 );
		return;
	}
	// and execute any waiting functions
	kRunMwDomReady();
}
// Copied from kalturaSupport loader mw.getKalturaEmbedSettingsFromUrl
kGetKalturaEmbedSettings = function( swfUrl, flashvars ){
	// If the url does not include kwidget or entry_id probably not a kaltura settings url:
	if( swfUrl.indexOf('kwidget') == -1 || swfUrl.indexOf('entry_id') == -1 ){
		return {};
	}
	if( !flashvars )
		flashvars= {};

	var dataUrlParts = swfUrl.split('/');
	var embedSettings = {};

	embedSettings.entryId =  dataUrlParts.pop();
	// Search backward for 'widgetId'
	var widgetId = false;
	while( dataUrlParts.length ){
		var curUrlPart =  dataUrlParts.pop();
		if( curUrlPart == 'wid'){
			widgetId = prevUrlPart;
			break;
		}
		prevUrlPart = curUrlPart;
	}
	if( widgetId ){
		embedSettings.widgetId = widgetId;
		// Also set the partner id;
		embedSettings.partnerId = widgetId.replace(/_/,'');
	}
	// Flash vars take precedence:
	for( var i in  flashvars){
		embedSettings[i] = flashvars[i];
	}
	return embedSettings;
};
<commit_msg>removed debug ref<commit_after>/*@cc_on@if(@_jscript_version<9){'video audio source track'.replace(/\w+/g,function(n){document.createElement(n)})}@end@*/

/**
* Kaltura html5 library loader
* For more info on mwEmbed / kaltura html5 library see:
* http://www.kaltura.org/project/HTML5_Video_Media_JavaScript_Library
*/

var kURID = '1.1t';
// Static script loader url:
var SCRIPT_LOADER_URL = 'http://html5.kaltura.org/ResourceLoader.php';
var SCRIPT_FORCE_DEBUG = false;

// These Lines are for local testing:
//SCRIPT_FORCE_DEBUG = true;
//SCRIPT_LOADER_URL = '../mwEmbed/ResourceLoader.php';
//kURID = new Date().getTime();

// Define mw ( if not already set )
if( !window['mw'] ){
	window['mw'] = {};
}

// Define the dom ready flag
var kAlreadyRunDomReadyFlag = false;

// Try and override the swfObject at runtime
// In case it was included before mwEmbedLoader and the embedSWF call is inline
kOverideSwfObject();

// Setup preMwEmbedReady queue
if( !preMwEmbedReady ){
	var preMwEmbedReady = [];
}
// Wrap mw.ready to preMwEmbedReady values
if( !mw.ready){
	mw.ready = function( fn ){
		preMwEmbedReady.push( fn );
		// Check if mw.ready was called after the dom is ready:
		if( kAlreadyRunDomReadyFlag ){
			kCheckAddScript();
		}
	}
}
// Setup a preMwEmbedConfig var
if( ! preMwEmbedConfig ) {
	var preMwEmbedConfig = [];
}
if( !mw.setConfig ){
	mw.setConfig = function( set, value ){
		var valueQueue = {};
		if( typeof value != 'undefined'  ) {
			preMwEmbedConfig[ set	] = value;
		} else if ( typeof set == 'object' ){
			for( var i in set ){
				preMwEmbedConfig[ i ] = set[i];
			}
		}
	}
}
// Test if swfObject exists, try and override its embed method to wrap html5 rewrite calls.
function kOverideSwfObject(){
	// Check if already override
	if( window['swfobject'] && window['swfobject']['originalEmbedSWF'] ){
		return ;
	}

	if( window['swfobject'] && window['swfobject']['embedSWF'] ){
		window['swfobject']['originalEmbedSWF'] = window['swfobject']['embedSWF'];
		// override embedObjec for our own ends
		window['swfobject']['embedSWF'] = function( swfUrlStr, replaceElemIdStr, widthStr,
				heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn)
		{
			var kEmbedSettings = kGetKalturaEmbedSettings( swfUrlStr, flashvarsObj);
			// Check if mobile safari:

			if( kBrowserAgentShouldUseHTML5() && kEmbedSettings.entryId ){
				// Make sure we have kaltura script:
				kAddScript();
				mw.ready(function(){
					var width = ( widthStr )? parseInt( widthStr ) : $j('#' + replaceElemIdStr ).width();
					var height = ( heightStr)? parseInt( heightStr ) : $j('#' + replaceElemIdStr ).height();

					var poster = 'http://cdnakmi.kaltura.com/p/' + kEmbedSettings.partnerId + '/sp/' +
						kEmbedSettings.partnerId + '00/thumbnail/entry_id/' + kEmbedSettings.entryId + '/width/' +
						height + '/height/' + width;
					$j('#' + replaceElemIdStr ).css({
						'width' : width,
						'height' : height
					}).embedPlayer({
						'poster': poster,
						'kentryid': kEmbedSettings.entryId,
						'kwidgetid' : kEmbedSettings.widgetId
					});
				});
			} else {
				// Else call the original EmbedSWF with all its arguments
				window['swfobject']['originalEmbedSWF']( swfUrlStr, replaceElemIdStr, widthStr,
						heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn )
			}
		}
	}
}

// Check dom for kaltura embeds ( fall forward )
// && html5 video tag ( for fallback & html5 player interface )
function kCheckAddScript(){
	// If user javascript is using mw.ready add script
	if( preMwEmbedReady.length ) {
		kAddScript();
		return ;
	}

	// If document includes audio or video tags
	if( document.getElementsByTagName('video').length != 0
		|| document.getElementsByTagName('audio').length != 0 ) {
		kAddScript();
		return ;
	}

	// If document includes kaltura embed tags && isMobile safari:
	if ( kBrowserAgentShouldUseHTML5() ) {
		// Check for kaltura objects in the page
		var usedIdSet = [];
		for(var i=0; i < document.getElementsByTagName('object').length; i++) {
			var embedTag = document.getElementsByTagName('object')[i];
			if( embedTag.getAttribute( 'name' ) == 'kaltura_player' ) {
				kAddScript();
				var kId = embedTag.getAttribute( 'id' );
				if( usedIdSet[ kId ] ) {
					// Update the id ( append index )
					embedTag.setAttribute( 'id',  kId + '_' + i);
				}
				usedIdSet[ embedTag.getAttribute( 'id' ) ] = true;
			}
		}
	}
}
function kBrowserAgentShouldUseHTML5(){
	return (  (navigator.userAgent.indexOf('iPhone') != -1) ||
	(navigator.userAgent.indexOf('iPod') != -1) ||
	(navigator.userAgent.indexOf('iPad') != -1) ||
	// to debug in chrome / desktop safari
	(document.URL.indexOf('forceMobileSafari') != -1 )
	);
}

// Add the kaltura html5 mwEmbed script
var kAddedScript = false;
function kAddScript(){
	if( kAddedScript ){
		return ;
	}
	kAddedScript = true;
	var url = SCRIPT_LOADER_URL + '?class=';

	if( typeof window.jQuery == 'undefined' ) {
		url+='window.jQuery,'
	}
	// Add mwEmbed and common style sheet
	url+= 'mwEmbed';

	// Add all the classes needed for video
	var jsPlayerRequest = [
		// core skin:
		'mw.style.mwCommon',
		'mw.style.ui_redmond',

		// embed player:
		'mw.EmbedPlayer',
		'mw.style.EmbedPlayer',
		'mw.PlayerControlBuilder',

		// default skin:
		'mw.PlayerSkinMvpcf',
		'mw.style.PlayerSkinMvpcf',

		// common playback methods:
		'mw.EmbedPlayerNative',
		'mw.EmbedPlayerKplayer',
		'mw.EmbedPlayerJava',

		// jQuery helpers
		'$j.ui',
		'$j.fn.hoverIntent',
		'$j.cookie',
		'JSON',
		'$j.ui.slider',
		'$j.fn.menu',
		'mw.style.jquerymenu',

		// Timed Text module
		'mw.TimedText',
		'mw.style.TimedText'
	];
	url+= ',' + jsPlayerRequest.join(',');

	url+='&urid=' + kURID;
	url+='&uselang=en';

	if ( SCRIPT_FORCE_DEBUG ){
		url+='&debug=true';
	}

	var script = document.createElement( 'script' );
	script.type = 'text/javascript';
	script.src = url;
	// no handlers:
	document.getElementsByTagName('body')[0].appendChild( script );
};

/**
* DOM-ready setup ( similar to jQuery.ready )
*/
function kRunMwDomReady(){
	kAlreadyRunDomReadyFlag  = true;
	kOverideSwfObject();
	kCheckAddScript();
}
// Check if already ready:
if ( document.readyState === "complete" ) {
	kRunMwDomReady();
}

// Cleanup functions for the document ready method
if ( document.addEventListener ) {
	DOMContentLoaded = function() {
		document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
		kRunMwDomReady();
	};

} else if ( document.attachEvent ) {
	DOMContentLoaded = function() {
		// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
		if ( document.readyState === "complete" ) {
			document.detachEvent( "onreadystatechange", DOMContentLoaded );
			kRunMwDomReady();
		}
	};
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
	// Use the handy event callback
	document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );

	// A fallback to window.onload, that will always work
	window.addEventListener( "load", kRunMwDomReady, false );

// If IE event model is used
} else if ( document.attachEvent ) {
	// ensure firing before onload,
	// maybe late but safe also for iframes
	document.attachEvent("onreadystatechange", DOMContentLoaded);

	// A fallback to window.onload, that will always work
	window.attachEvent( "onload", kRunMwDomReady );

	// If IE and not a frame
	// continually check to see if the document is ready
	var toplevel = false;

	try {
		toplevel = window.frameElement == null;
	} catch(e) {}

	if ( document.documentElement.doScroll && toplevel ) {
		doScrollCheck();
	}
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
	if ( kAlreadyRunDomReadyFlag ) {
		return;
	}
	try {
		// If IE is used, use the trick by Diego Perini
		// http://javascript.nwbox.com/IEContentLoaded/
		document.documentElement.doScroll("left");
	} catch( error ) {
		setTimeout( doScrollCheck, 1 );
		return;
	}
	// and execute any waiting functions
	kRunMwDomReady();
}
// Copied from kalturaSupport loader mw.getKalturaEmbedSettingsFromUrl
kGetKalturaEmbedSettings = function( swfUrl, flashvars ){
	// If the url does not include kwidget or entry_id probably not a kaltura settings url:
	if( swfUrl.indexOf('kwidget') == -1 || swfUrl.indexOf('entry_id') == -1 ){
		return {};
	}
	if( !flashvars )
		flashvars= {};

	var dataUrlParts = swfUrl.split('/');
	var embedSettings = {};

	embedSettings.entryId =  dataUrlParts.pop();
	// Search backward for 'widgetId'
	var widgetId = false;
	while( dataUrlParts.length ){
		var curUrlPart =  dataUrlParts.pop();
		if( curUrlPart == 'wid'){
			widgetId = prevUrlPart;
			break;
		}
		prevUrlPart = curUrlPart;
	}
	if( widgetId ){
		embedSettings.widgetId = widgetId;
		// Also set the partner id;
		embedSettings.partnerId = widgetId.replace(/_/,'');
	}
	// Flash vars take precedence:
	for( var i in  flashvars){
		embedSettings[i] = flashvars[i];
	}
	return embedSettings;
};
<|endoftext|>


<commit_before>let baseUrl = 'http://192.168.99.100:32770';
import {dateFormatter} from '../src/ReactDashboard';

export var settings = {
  title: 'State Medical Board Licensure Data',
  queries: {
    by_age: {
      group_by: "age",
      count: "age",
      //fields: "age"
    },
  },
  components: [
    {
      type: 'Region',
      className: 'row',
      children: [
       {
        type: 'Region',
        className: 'zeroth-row col-md-6',
        children: [
           {
             type: 'img',
             src: "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTd9zBTlpPrH5EaWGrQISVCjA1E3AAzXCI_go0ml5QHI-58Cld73VBBRv8",
             style: {borderStyle:'double',borderWidth: '10px', borderColor:'teal', padding: '10px', margin: '10px'},
           },
        ]
       },
       {
        type: 'Region',
        className: 'zeroth-row col-md-6',
        children: [
           {
             type: 'h4',
             dangerouslySetInnerHTML: {__html: 'A text description set from the settings file, using native react html element.'},
             style: {margin: '20px'}
           },
        ]
       },
		  ]
		},
    {
      type: 'Region',
      className: 'dashboard-top-filter',
      header: 'Foobar',
      children: [
        {
          type: 'Autocomplete',
          name: 'county-autocomplete',
          multi: true,
          url: baseUrl+'/dashboard_autocomplete/GBPW_Counties',
          cardStyle: 'none',
          id: 'county-autocomplete',
          placeholder: 'Select county'
        },
      ]
    },
    {
      type: 'Region',
      className: 'dashboard-top-metrics',
      children: [
        {
          type: 'Metric',
          cardStyle: 'metric',
          value: 'Value from Config',
          background: 'muave',
          iconClass: 'glyphicons glyphicons-link'
        },
        {
          type: 'Metric',
          cardStyle: 'metric',
          background: 'navy',
          iconClass: 'fa fa-clock-o',
          dataHandlers: [
            'getFTE'
          ],
        }
      ]
    },
   /* {
      type: 'Chart',
      header: 'Physician Distribution by Age...',
      settings: {
        type: 'multiBarHorizontalChart',
        x: 'age',
        y: 'count_age',
        color: ['blue'],
      },
      dataHandlers: [
        {
          name: 'getXYByQueryData',
          queryKey: 'by_age',
          xField: 'age',
          yField: 'count'
        },
        {
          name: 'groupByRange',
          ranges: [ [0,34], [35,39], [40,44], [45,49], [50,54], [55,59], [60,64], [65,125] ],
          xField: 'age',
          yField: 'count_age'
        },
        {
          name: 'NVD3.returnChartSeries',
          series: [
            {name: 'Age', color:'#FF0000'},
          ]
        }
      ]
    }, */
    {
      header:'Gold Prices',
      type: 'Chart',
      iconClass: 'glyphicon glyphicon-tree-conifer',
      settings: {
          id:'lineChart2',
          type: 'lineChart',
          x: 'date',
          height: 340,
          margin: {
              left: 38
          },
          color: ['#EA7E7E'],
          xAxis: {
            tickFormat: dateFormatter('%Y')
          }
      },
      dataHandlers: [
          {
              name: 'common.parseDateField',
              field: 'date'
          },
          {
              name: 'common.fieldsToXYSeries',
              field: 'price',
              xField: 'date'
          },
          {
              name: 'NVD3.returnChartSeries',
              series: [
                  {name: 'Price', color:'#FF0000'},
              ]
          }
      ],
      cardStyle: 'card',
      fetchData: {
          type:'backend',
          backend: 'csv',
          url: 'http://demo.getdkan.com/sites/default/files/data_0.csv'
      },
      filters: [
        {
          type: 'ReactSelect',
          options: [
            {
              label: 'ALL',
              value: 'all'
            },
            {
              label: '1949 - 1976',
              value: '1949_1976'
            },
            {
              label: '1976 - 2012',
              value: '1976_2012'
            }
          ],
          dataHandlers: [
            'customDataHandler',
            {
              name: 'common.parseDateField',
              field: 'date'
            },
            {
              name: 'common.fieldsToXYSeries',
              field: 'price',
              xField: 'date'
            },
            {
              name: 'NVD3.returnChartSeries',
              series: [
                {name: 'Price', color:'#FF0000'},
              ]
            }
          ]
        },
      ],
    },
		/* {
     type: 'Region',
     header: 'Choropleth -- GEOJSON',
     children: [
        {
          type: 'Choropleth',
          cardStyle: 'none',
          format: 'geojson',
          fetchData: {
            url: '/data/apollo-parsed-1737-325_0.csv',
            type: 'backend',
            backend: 'csv',
          },
          id: 'Choropleth',
          dataKeyField: 'Zone',
          dataValueField: 'Total Observers',
          geometryKeyField: 'name',
          geometry: 'https://dl.dropboxusercontent.com/u/73703010/zones.geojson', // topojson or geojson
          projection: 'mercator', // https://github.com/d3/d3/wiki/Geo-Projections
          //projection: 'equirectangular', // https://github.com/d3/d3/wiki/Geo-Projections
          scaleDenominator: .7,
          borderColor: '#000000',
          noDataColor: '#F3F3F3',
          startColor: 'red',
          endColor: 'yellow',
          dataClassification: 'equidistant',
          legend: {
            classesCount: 5,
            legendHeader: 'abcdef',
            palleteKey: 'GnBu',
            pallete: ['#f0f9e8', '#bae4bc', '#7bccc4', '#43a2ca', '#0868ac'],
            domainStartValue: '',
            domainEndValue: '',
          }
        },
      ]
    }, */
		{
     type: 'Region',
     header: 'Choropleth -- TOPOJSON',
     children: [
        {
          type: 'Choropleth',
          format: 'topojson',
          fetchData: {
            url: '/data/unemployment.tsv',
            type: 'backend',
            backend: 'csv',
            delimiter: '\t',
          },
          id: 'Choropleth-topo',
          dataKeyField: 'id',
          dataValueField: 'rate',
          geometryKeyField: 'id',
          geometry: '/data/us.json', // topojson or geojson
          projection: 'mercator', // https://github.com/d3/d3/wiki/Geo-Projections
          //projection: 'equirectangular', // https://github.com/d3/d3/wiki/Geo-Projections
          scaleDenominator: .7,
          borderColor: 'black',
          noDataColor: 'red',
          topologyObject: 'counties',
          startColor: 'red',
          endColor: 'yellow',
          dataClassification: 'equidistant',
          legend: {
            classesCount: 5,
            palleteKey: 'GnBu',
            pallete: ['#f0f9e8', '#bae4bc', '#7bccc4', '#43a2ca', '#0868ac'],
            domainStartValue: '',
            domainEndValue: '',
          }
        },
      ]
    }
  ]
};
<commit_msg>Fix projection for topojson choropleth<commit_after>let baseUrl = 'http://192.168.99.100:32770';
import {dateFormatter} from '../src/ReactDashboard';

export var settings = {
  title: 'State Medical Board Licensure Data',
  queries: {
    by_age: {
      group_by: "age",
      count: "age",
      //fields: "age"
    },
  },
  components: [
    {
      type: 'Region',
      className: 'row',
      children: [
       {
        type: 'Region',
        className: 'zeroth-row col-md-6',
        children: [
           {
             type: 'img',
             src: "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTd9zBTlpPrH5EaWGrQISVCjA1E3AAzXCI_go0ml5QHI-58Cld73VBBRv8",
             style: {borderStyle:'double',borderWidth: '10px', borderColor:'teal', padding: '10px', margin: '10px'},
           },
        ]
       },
       {
        type: 'Region',
        className: 'zeroth-row col-md-6',
        children: [
           {
             type: 'h4',
             dangerouslySetInnerHTML: {__html: 'A text description set from the settings file, using native react html element.'},
             style: {margin: '20px'}
           },
        ]
       },
		  ]
		},
    {
      type: 'Region',
      className: 'dashboard-top-filter',
      header: 'Foobar',
      children: [
        {
          type: 'Autocomplete',
          name: 'county-autocomplete',
          multi: true,
          url: baseUrl+'/dashboard_autocomplete/GBPW_Counties',
          cardStyle: 'none',
          id: 'county-autocomplete',
          placeholder: 'Select county'
        },
      ]
    },
    {
      type: 'Region',
      className: 'dashboard-top-metrics',
      children: [
        {
          type: 'Metric',
          cardStyle: 'metric',
          value: 'Value from Config',
          background: 'muave',
          iconClass: 'glyphicons glyphicons-link'
        },
        {
          type: 'Metric',
          cardStyle: 'metric',
          background: 'navy',
          iconClass: 'fa fa-clock-o',
          dataHandlers: [
            'getFTE'
          ],
        }
      ]
    },
   /* {
      type: 'Chart',
      header: 'Physician Distribution by Age...',
      settings: {
        type: 'multiBarHorizontalChart',
        x: 'age',
        y: 'count_age',
        color: ['blue'],
      },
      dataHandlers: [
        {
          name: 'getXYByQueryData',
          queryKey: 'by_age',
          xField: 'age',
          yField: 'count'
        },
        {
          name: 'groupByRange',
          ranges: [ [0,34], [35,39], [40,44], [45,49], [50,54], [55,59], [60,64], [65,125] ],
          xField: 'age',
          yField: 'count_age'
        },
        {
          name: 'NVD3.returnChartSeries',
          series: [
            {name: 'Age', color:'#FF0000'},
          ]
        }
      ]
    }, */
    {
      header:'Gold Prices',
      type: 'Chart',
      iconClass: 'glyphicon glyphicon-tree-conifer',
      settings: {
          id:'lineChart2',
          type: 'lineChart',
          x: 'date',
          height: 340,
          margin: {
              left: 38
          },
          color: ['#EA7E7E'],
          xAxis: {
            tickFormat: dateFormatter('%Y')
          }
      },
      dataHandlers: [
          {
              name: 'common.parseDateField',
              field: 'date'
          },
          {
              name: 'common.fieldsToXYSeries',
              field: 'price',
              xField: 'date'
          },
          {
              name: 'NVD3.returnChartSeries',
              series: [
                  {name: 'Price', color:'#FF0000'},
              ]
          }
      ],
      cardStyle: 'card',
      fetchData: {
          type:'backend',
          backend: 'csv',
          url: 'http://demo.getdkan.com/sites/default/files/data_0.csv'
      },
      filters: [
        {
          type: 'ReactSelect',
          options: [
            {
              label: 'ALL',
              value: 'all'
            },
            {
              label: '1949 - 1976',
              value: '1949_1976'
            },
            {
              label: '1976 - 2012',
              value: '1976_2012'
            }
          ],
          dataHandlers: [
            'customDataHandler',
            {
              name: 'common.parseDateField',
              field: 'date'
            },
            {
              name: 'common.fieldsToXYSeries',
              field: 'price',
              xField: 'date'
            },
            {
              name: 'NVD3.returnChartSeries',
              series: [
                {name: 'Price', color:'#FF0000'},
              ]
            }
          ]
        },
      ],
    },
		/* {
     type: 'Region',
     header: 'Choropleth -- GEOJSON',
     children: [
        {
          type: 'Choropleth',
          cardStyle: 'none',
          format: 'geojson',
          fetchData: {
            url: '/data/apollo-parsed-1737-325_0.csv',
            type: 'backend',
            backend: 'csv',
          },
          id: 'Choropleth',
          dataKeyField: 'Zone',
          dataValueField: 'Total Observers',
          geometryKeyField: 'name',
          geometry: 'https://dl.dropboxusercontent.com/u/73703010/zones.geojson', // topojson or geojson
          projection: 'mercator', // https://github.com/d3/d3/wiki/Geo-Projections
          //projection: 'equirectangular', // https://github.com/d3/d3/wiki/Geo-Projections
          scaleDenominator: .7,
          borderColor: '#000000',
          noDataColor: '#F3F3F3',
          startColor: 'red',
          endColor: 'yellow',
          dataClassification: 'equidistant',
          legend: {
            classesCount: 5,
            legendHeader: 'abcdef',
            palleteKey: 'GnBu',
            pallete: ['#f0f9e8', '#bae4bc', '#7bccc4', '#43a2ca', '#0868ac'],
            domainStartValue: '',
            domainEndValue: '',
          }
        },
      ]
    }, */
		{
     type: 'Region',
     header: 'Unemployment by U.S. County',
     children: [
        {
          type: 'h4',
          dangerouslySetInnerHTML: {__html: 'Choropleth Heat Map -- topojson'}
        },
        {
          type: 'Choropleth',
          format: 'topojson',
          fetchData: {
            url: '/data/unemployment.tsv',
            type: 'backend',
            backend: 'csv',
            delimiter: '\t',
          },
          id: 'Choropleth-topo',
          dataKeyField: 'id',
          dataValueField: 'rate',
          geometryKeyField: 'id',
          geometry: '/data/us.json', // topojson or geojson
          //projection: 'mercator', // https://github.com/d3/d3/wiki/Geo-Projections
          projection: 'albersUsa', // https://github.com/d3/d3/wiki/Geo-Projections
          scaleDenominator: .8,
          borderColor: '#fff',
          noDataColor: 'red',
          topologyObject: 'counties',
          startColor: 'red',
          endColor: 'yellow',
          dataClassification: 'equidistant',
          legend: {
            classesCount: 5,
            palleteKey: 'GnBu',
            pallete: ['#f0f9e8', '#bae4bc', '#7bccc4', '#43a2ca', '#0868ac'],
            domainStartValue: '',
            domainEndValue: '',
          }
        },
      ]
    }
  ]
};
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var IncomingRequest = require('./incoming_request');
var IncomingResponse = require('./incoming_response');
var OutgoingRequest = require('./outgoing_request');
var OutgoingResponse = require('./outgoing_response');

var inherits = require('util').inherits;

var v2 = require('./v2');

var TChannelConnectionBase = require('./connection_base');

function TChannelSelfConnection(channel) {
    if (!(this instanceof TChannelSelfConnection)) {
        return new TChannelSelfConnection(channel);
    }
    var self = this;
    TChannelConnectionBase.call(self, channel, 'in', channel.hostPort);
    self.idCount = 0;
}
inherits(TChannelSelfConnection, TChannelConnectionBase);

TChannelSelfConnection.prototype.buildOutgoingRequest = function buildOutgoingRequest(options) {
    var self = this;
    var id = self.idCount++;
    if (!options) options = {};
    options.logger = self.logger;
    options.random = self.random;
    options.timers = self.timers;
    options.sendFrame = {
        callRequest: passParts,
        callRequestCont: passParts
    };
    options.tracer = self.tracer;
    var outreq = new OutgoingRequest(id, options);

    if (outreq.span) {
        options.tracing = outreq.span.getTracing();
    }
    options.hostPort = self.channel.hostPort;

    var inreq = new IncomingRequest(id, options);
    var called = false;
    inreq.on('error', onError);
    inreq.on('response', onResponse);
    self.handleCallRequest(inreq);
    return outreq;

    function onError(err) {
        if (called) return;
        called = true;
        self.popOutOp(id);
        inreq.removeListener('response', onResponse);
        outreq.emit('error', err);
    }

    function onResponse(res) {
        if (called) return;
        called = true;
        self.popOutOp(id);
        inreq.removeListener('error', onError);
        outreq.emit('response', res);
    }

    function passParts(args, isLast ) {
        inreq.handleFrame(args);
        if (isLast) inreq.handleFrame(null);
        if (!self.closing) self.lastTimeoutTime = 0;
    }
};

TChannelSelfConnection.prototype.buildOutgoingResponse = function buildOutgoingResponse(req, options) {
    var self = this;
    if (!options) options = {};
    options.logger = self.logger;
    options.random = self.random;
    options.timers = self.timers;
    options.tracing = req.tracing;

    // options.checksum = new v2.Checksum(None);

    options.sendFrame = {
        callResponse: passParts,
        callResponseCont: passParts,
        error: passError
    };
    var outres = new OutgoingResponse(req.id, options);
    var inres = new IncomingResponse(req.id, options);
    var first = true;
    return outres;

    function passParts(args, isLast) {
        inres.handleFrame(args);
        if (isLast) inres.handleFrame(null);
        if (first) {
            inres.code = outres.code;
            inres.ok = outres.ok;
            first = false;
            req.emit('response', inres);
        }
        if (!self.closing) self.lastTimeoutTime = 0;
    }

    function passError(codeString, message) {
        var code = v2.ErrorResponse.Codes[codeString];
        var err = v2.ErrorResponse.CodeErrors[code]({
            originalId: req.id,
            message: message
        });
        req.emit('error', err);
        // TODO: should terminate corresponding inc res
        if (!self.closing) self.lastTimeoutTime = 0;
    }
};

module.exports = TChannelSelfConnection;
<commit_msg>SelfConnection: correct req error emit<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var IncomingRequest = require('./incoming_request');
var IncomingResponse = require('./incoming_response');
var OutgoingRequest = require('./outgoing_request');
var OutgoingResponse = require('./outgoing_response');

var inherits = require('util').inherits;

var v2 = require('./v2');

var TChannelConnectionBase = require('./connection_base');

function TChannelSelfConnection(channel) {
    if (!(this instanceof TChannelSelfConnection)) {
        return new TChannelSelfConnection(channel);
    }
    var self = this;
    TChannelConnectionBase.call(self, channel, 'in', channel.hostPort);
    self.idCount = 0;
}
inherits(TChannelSelfConnection, TChannelConnectionBase);

TChannelSelfConnection.prototype.buildOutgoingRequest = function buildOutgoingRequest(options) {
    var self = this;
    var id = self.idCount++;
    if (!options) options = {};
    options.logger = self.logger;
    options.random = self.random;
    options.timers = self.timers;
    options.sendFrame = {
        callRequest: passParts,
        callRequestCont: passParts
    };
    options.tracer = self.tracer;
    var outreq = new OutgoingRequest(id, options);

    if (outreq.span) {
        options.tracing = outreq.span.getTracing();
    }
    options.hostPort = self.channel.hostPort;

    var inreq = new IncomingRequest(id, options);
    var called = false;
    inreq.on('error', onError);
    inreq.on('response', onResponse);
    inreq.outreq = outreq; // TODO: make less hacky when have proper subclasses
    self.handleCallRequest(inreq);
    return outreq;

    function onError(err) {
        if (called) return;
        called = true;
        self.popOutOp(id);
        inreq.removeListener('response', onResponse);
        outreq.emit('error', err);
    }

    function onResponse(res) {
        if (called) return;
        called = true;
        self.popOutOp(id);
        inreq.removeListener('error', onError);
        outreq.emit('response', res);
    }

    function passParts(args, isLast ) {
        inreq.handleFrame(args);
        if (isLast) inreq.handleFrame(null);
        if (!self.closing) self.lastTimeoutTime = 0;
    }
};

TChannelSelfConnection.prototype.buildOutgoingResponse = function buildOutgoingResponse(inreq, options) {
    var self = this;
    var outreq = inreq.outreq;

    if (!options) options = {};
    options.logger = self.logger;
    options.random = self.random;
    options.timers = self.timers;
    options.tracing = inreq.tracing;

    // options.checksum = new v2.Checksum(None);

    options.sendFrame = {
        callResponse: passParts,
        callResponseCont: passParts,
        error: passError
    };
    var outres = new OutgoingResponse(inreq.id, options);
    var inres = new IncomingResponse(inreq.id, options);
    var first = true;
    return outres;

    function passParts(args, isLast) {
        inres.handleFrame(args);
        if (isLast) inres.handleFrame(null);
        if (first) {
            inres.code = outres.code;
            inres.ok = outres.ok;
            first = false;
            inreq.emit('response', inres);
        }
        if (!self.closing) self.lastTimeoutTime = 0;
    }

    function passError(codeString, message) {
        var code = v2.ErrorResponse.Codes[codeString];
        var err = v2.ErrorResponse.CodeErrors[code]({
            originalId: inreq.id,
            message: message
        });
        outreq.emit('error', err);
        if (!self.closing) self.lastTimeoutTime = 0;
    }
};

module.exports = TChannelSelfConnection;
<|endoftext|>


<commit_before><commit_msg>array iteration<commit_after><|endoftext|>


<commit_before>import nacl from '../external/nacl-fast';
import convert from '../utils/convert';
import Helpers from '../utils/helpers';
import KeyPair from '../crypto/keyPair';
import CryptoHelpers from '../crypto/cryptoHelpers';
import Address from '../model/address';

/**
 * Create a wallet object
 *
 * @param {string} walletName - The wallet name
 * @param {string} addr - The main account address
 * @param {boolean} brain - Is brain or not
 * @param {string} algo - The wallet algorithm
 * @param {object} encrypted - The encrypted private key object
 * @param {number} network - The network id
 *
 * @return {object} - A wallet object
 */
let _buildWallet = function(walletName, addr, brain, algo, encrypted, network) {
    return {
        "name": walletName,
        "accounts": {
            "0": {
                "brain": brain,
                "algo": algo,
                "encrypted": encrypted.ciphertext || "",
                "iv": encrypted.iv || "",
                "address": addr.toUpperCase().replace(/-/g, ''),
                "label": 'Primary',
                "network": network,
            }
        }
    };
}

/**
 * Create a wallet containing a private key generated using a Pseudo Random Number Generator
 *
 * @param {string} walletName - The wallet name
 * @param {string} password - The wallet password
 * @param {number} network - The network id
 *
 * @return {object} - A PRNG wallet object
 */
let createPRNG = function (walletName, password, network) {
    if (!walletName.length || !password.length || !network) throw new Error('A parameter is missing !');
    // Generate keypair from random private key
    var pk = convert.ua2hex(nacl.randomBytes(32));
    var kp = KeyPair.create(pk);
    // Create address from public key
    let addr = Address.toAddress(kp.publicKey.toString(), network);
    // Encrypt private key using password
    let encrypted = CryptoHelpers.encodePrivKey(pk, password);
    return _buildWallet(walletName, addr, true, "pass:bip32", encrypted, network);
}

/**
 * Create a wallet containing a private key generated using a derived passphrase
 *
 * @param {string} walletName - The wallet name
 * @param {string} passphrase - The wallet passphrase
 * @param {number} network - The network id
 *
 * @return {object} - A Brain wallet object
 */
let createBrain = function (walletName, passphrase, network) {
    if (!walletName.length || !passphrase.length || !network) throw new Error('A parameter is missing !');
    var r = CryptoHelpers.derivePassSha(passphrase, 6000);
    var kp = KeyPair.create(r.priv);
    // Create address from public key
    let addr = Address.toAddress(kp.publicKey.toString(), network);
    return _buildWallet(walletName, addr, true, "pass:6k", "", network);
}

/**
 * Create a wallet containing any private key
 *
 * @param {string} walletName - The wallet name
 * @param {string} password - The wallet passphrase
 * @param {string} privateKey - The private key to import
 * @param {number} network - The network id
 *
 * @return {object} - A private key wallet object
 */
let importPrivatekey = function (walletName, password, privateKey, network) {
    if (!walletName.length || !password.length || !network || !privateKey) throw new Error('A parameter is missing !');
    if (privateKey.length !== 64 || privateKey.length !== 66) throw new Error('Private key length must be 64 or 66 characters !');
    if (!Helpers.isHexadecimal(privateKey)) throw new Error('Private key must be hexadecimal only !');
    // Create address from private key
    let kp = KeyPair.create(privateKey);
    let addr = Address.toAddress(kp.publicKey.toString(), network);
    // Encrypt private key using password
    let encrypted = CryptoHelpers.encodePrivKey(pk, password);
    return _buildWallet(walletName, addr, false, "pass:enc", encrypted, network);
}

module.exports = {
    createPRNG,
    createBrain,
    importPrivatekey
}<commit_msg>Fix camel case and issue in importPrivateKey, rename private key variable<commit_after>import nacl from '../external/nacl-fast';
import convert from '../utils/convert';
import Helpers from '../utils/helpers';
import KeyPair from '../crypto/keyPair';
import CryptoHelpers from '../crypto/cryptoHelpers';
import Address from '../model/address';

/**
 * Create a wallet object
 *
 * @param {string} walletName - The wallet name
 * @param {string} addr - The main account address
 * @param {boolean} brain - Is brain or not
 * @param {string} algo - The wallet algorithm
 * @param {object} encrypted - The encrypted private key object
 * @param {number} network - The network id
 *
 * @return {object} - A wallet object
 */
let _buildWallet = function(walletName, addr, brain, algo, encrypted, network) {
    return {
        "name": walletName,
        "accounts": {
            "0": {
                "brain": brain,
                "algo": algo,
                "encrypted": encrypted.ciphertext || "",
                "iv": encrypted.iv || "",
                "address": addr.toUpperCase().replace(/-/g, ''),
                "label": 'Primary',
                "network": network,
            }
        }
    };
}

/**
 * Create a wallet containing a private key generated using a Pseudo Random Number Generator
 *
 * @param {string} walletName - The wallet name
 * @param {string} password - The wallet password
 * @param {number} network - The network id
 *
 * @return {object} - A PRNG wallet object
 */
let createPRNG = function (walletName, password, network) {
    if (!walletName.length || !password.length || !network) throw new Error('A parameter is missing !');
    // Generate keypair from random private key
    var privateKey = convert.ua2hex(nacl.randomBytes(32));
    var kp = KeyPair.create(privateKey);
    // Create address from public key
    let addr = Address.toAddress(kp.publicKey.toString(), network);
    // Encrypt private key using password
    let encrypted = CryptoHelpers.encodePrivKey(privateKey, password);
    return _buildWallet(walletName, addr, true, "pass:bip32", encrypted, network);
}

/**
 * Create a wallet containing a private key generated using a derived passphrase
 *
 * @param {string} walletName - The wallet name
 * @param {string} passphrase - The wallet passphrase
 * @param {number} network - The network id
 *
 * @return {object} - A Brain wallet object
 */
let createBrain = function (walletName, passphrase, network) {
    if (!walletName.length || !passphrase.length || !network) throw new Error('A parameter is missing !');
    var privateKey = CryptoHelpers.derivePassSha(passphrase, 6000).priv;
    var kp = KeyPair.create(privateKey);
    // Create address from public key
    let addr = Address.toAddress(kp.publicKey.toString(), network);
    return _buildWallet(walletName, addr, true, "pass:6k", "", network);
}

/**
 * Create a wallet containing any private key
 *
 * @param {string} walletName - The wallet name
 * @param {string} password - The wallet passphrase
 * @param {string} privateKey - The private key to import
 * @param {number} network - The network id
 *
 * @return {object} - A private key wallet object
 */
let importPrivateKey = function (walletName, password, privateKey, network) {
    if (!walletName.length || !password.length || !network || !privateKey) throw new Error('A parameter is missing !');
    if (!Helpers.isPrivateKeyValid(privateKey)) throw new Error('Private key is not valid !');
    // Create address from private key
    let kp = KeyPair.create(privateKey);
    let addr = Address.toAddress(kp.publicKey.toString(), network);
    // Encrypt private key using password
    let encrypted = CryptoHelpers.encodePrivKey(privateKey, password);
    return _buildWallet(walletName, addr, false, "pass:enc", encrypted, network);
}

module.exports = {
    createPRNG,
    createBrain,
    importPrivateKey
}<|endoftext|>


<commit_before>'use strict';
var request = require('request');
var fs = require('fs');

module.exports = {
  config: {},
  routes: function (app, context) {
    app.get('/report', function (req, res) {
      var org = req.params.org;
      var repo = req.params.repo;
      var branch = req.body.branch;
      var protocol = req.protocol;
      var hostName = req.get('Host');
      request(protocol + '://' + hostName + '/' + org + '/' + repo + '/jobs', function (err, response, body) {
        console.log('BODY', body);
        var latestJobId = JSON.parse(body)[0];
        console.log('LATEST',latestJobId);
        var coveragLocation = '~/.strider/data/'+ org + '-' + repo + '-' + branch + '/job-' + latestJobId + '/coverage/index.html';
        res.render(coveragLocation);
      });
    });
  },
  globalRoutes: function (app, context) {
    app.get('/report', function (req, res) {
      res.json({context: context});
    });
  }
};
<commit_msg>reports endpoint<commit_after>'use strict';
var request = require('request');
var fs = require('fs');

module.exports = {
  config: {},
  routes: function (app, context) {
    app.get('/report', function (req, res) {
      var org = req.params.org;
      var repo = req.params.repo;
      var branch = req.body.branch;
      var protocol = req.protocol;
      var hostName = req.get('Host');
      var jobsEndpoint = protocol + '://' + hostName + '/' + org + '/' + repo + '/jobs';
      console.log('JOBS',jobsEndpoint)
      request(jobsEndpoint, function (err, response, body) {
        console.log('BODY', body);
        var latestJobId = JSON.parse(body)[0];
        var coveragLocation = '~/.strider/data/'+ org + '-' + repo + '-' + branch + '/job-' + latestJobId + '/coverage/index.html';
        res.render(coveragLocation);
      });
    });
  },
  globalRoutes: function (app, context) {
    app.get('/report', function (req, res) {
      res.json({context: context});
    });
  }
};
<|endoftext|>


<commit_before>const rgbControls = require('./RGB_control');
var fs = require('fs');
var defaultAnimations = "anims.json";
var userAnimations = "anims-user.json";

var animations = {};

function writeAnimFile() {
    var json = JSON.stringify(animations);
    fs.writeFile(userAnimations, json, 'utf8', function () {
        console.log("Saving animation file done.")
    });
}

function readAnimFile() {
    var content = fs.readFileSync(defaultAnimations);
    animations = JSON.parse(content);
    if (fs.existsSync(userAnimations)) {
        content = fs.readFileSync(userAnimations);
        Object.assign(animations, JSON.parse(content));
    }
}

function getAnimNames() {
    var keys = Object.keys(animations);
    var ret = {};
    ret.animations = keys;
    return ret;
}

function getAnim(name) {
    var ret = {};
    ret[name] = animations[name];
    return ret;
}

function saveAnim(name, data) {
    animations[name] = {};
    animations[name] = data;
    writeAnimFile();
    if (curAnim == name)
        startAnim(name);
}

function deleteAnim(name) {
    delete animations[name];
    writeAnimFile();
}

var animIdx = 0;
var animLength;
var curAnim = "";
var animTimeout;

function startAnim(name) {
    stopAnim();
    curAnim = name;
    animLength = animations[name].length;
    //animTimeout = setTimeout(function(){
    doFrame(animations[name][0]);
    //}, 0);
}

function changeRoom(obj, roomNumber) {
    var mac = rgbControls.roomToMAC(roomNumber);

    if (obj.fade == 0) {
        rgbControls.sendRGB(mac, obj.color);
    }
    else {
        rgbControls.sendFade(mac, obj.color, obj.fade);
    }

   rgbControls.sendDevices();
}

function doFrame(frame) {
    var frameData = frame.frameData;
    frameData.forEach(function (obj) { //TODO all rooms
        if (Array.isArray(obj.room)) {
            obj.room.forEach(function (room) {
                changeRoom(obj, room);
            });
        } else {
            changeRoom(obj, obj.room);
        }
    });

    ++animIdx;
    if (animIdx >= animLength)
        animIdx = 0;
    animTimeout = setTimeout(function () {
        doFrame(animations[curAnim][animIdx])
    }, frame.pause);
}

function stopAnim() {
    animIdx = 0;
    clearTimeout(animTimeout);
    rgbControls.turnOffNow();
}

readAnimFile();

module.exports = {getAnimNames, getAnim, saveAnim, deleteAnim, startAnim, stopAnim};
<commit_msg>added logging<commit_after>const rgbControls = require('./RGB_control');
var fs = require('fs');
var defaultAnimations = "anims.json";
var userAnimations = "anims-user.json";

var animations = {};

function writeAnimFile() {
    var json = JSON.stringify(animations);
    fs.writeFile(userAnimations, json, 'utf8', function () {
        console.log("Saving animation file done.")
    });
}

function readAnimFile() {
    var content = fs.readFileSync(defaultAnimations);
    animations = JSON.parse(content);
    if (fs.existsSync(userAnimations)) {
        content = fs.readFileSync(userAnimations);
        Object.assign(animations, JSON.parse(content));
    }
}

function getAnimNames() {
    var keys = Object.keys(animations);
    var ret = {};
    ret.animations = keys;
    return ret;
}

function getAnim(name) {
    var ret = {};
    ret[name] = animations[name];
    return ret;
}

function saveAnim(name, data) {
    console.log("save anim: ", name, " data: ",data);
    animations[name] = {};
    animations[name] = data;
    writeAnimFile();
    if (curAnim == name)
        startAnim(name);
}

function deleteAnim(name) {
    delete animations[name];
    writeAnimFile();
}

var animIdx = 0;
var animLength;
var curAnim = "";
var animTimeout;

function startAnim(name) {
    stopAnim();
    curAnim = name;
    animLength = animations[name].length;
    //animTimeout = setTimeout(function(){
    doFrame(animations[name][0]);
    //}, 0);
}

function changeRoom(obj, roomNumber) {
    var mac = rgbControls.roomToMAC(roomNumber);

    if (obj.fade == 0) {
        rgbControls.sendRGB(mac, obj.color);
    }
    else {
        rgbControls.sendFade(mac, obj.color, obj.fade);
    }

   rgbControls.sendDevices();
}

function doFrame(frame) {
    var frameData = frame.frameData;
    frameData.forEach(function (obj) { //TODO all rooms
        if (Array.isArray(obj.room)) {
            obj.room.forEach(function (room) {
                changeRoom(obj, room);
            });
        } else {
            changeRoom(obj, obj.room);
        }
    });

    ++animIdx;
    if (animIdx >= animLength)
        animIdx = 0;
    animTimeout = setTimeout(function () {
        doFrame(animations[curAnim][animIdx])
    }, frame.pause);
}

function stopAnim() {
    animIdx = 0;
    clearTimeout(animTimeout);
    rgbControls.turnOffNow();
}

readAnimFile();

module.exports = {getAnimNames, getAnim, saveAnim, deleteAnim, startAnim, stopAnim};
<|endoftext|>


<commit_before><commit_msg>correct isAllowed test<commit_after><|endoftext|>


<commit_before>var Bittrex = require('node.bittrex.api');
var util = require('../core/util.js');
var _ = require('lodash');
var moment = require('moment');
var log = require('../core/log');
var apiKeyManager = require('../web/apiKeyManager.js');

// Helper methods
function joinCurrencies(currencyA, currencyB){
    return currencyA + '-' + currencyB;
}

var Trader = function(config) {
  _.bindAll(this);

  // not nice but works to use a web module here to grab the keys
  var keys = apiKeyManager._getApiKeyPair('bittrex');

  if(_.isObject(keys)) {
    config.key = keys.key;
    config.secret = keys.secret;
  } else {
    // no api key defined -> we need to set a dummy key, otherwise the Bittrex module will not work even for public requests
    config.key = 'dummyApiKey';
    config.secret = 'dummyApiKey';
  }

  // override if cmd line mode (not --ui)
  if(_.isObject(config)) {
    this.key = config.key;
    this.secret = config.secret;
    this.currency = config.currency;
    this.asset = config.asset;
  }

  this.name = 'Bittrex';
  this.balance;
  this.price;

  this.pair = [this.currency, this.asset].join('-');

  Bittrex.options({
    'apikey':  this.key,
    'apisecret': this.secret,
    'stream': false,
    'verbose': false,
    'cleartext': false
  });

  log.debug('Init', 'New Bittrex Trader', {currency: this.currency, asset: this.asset});

  this.bittrexApi = Bittrex;
}

// if the exchange errors we try the same call again after
// waiting 10 seconds
Trader.prototype.retry = function(method, args) {
  var wait = +moment.duration(10, 'seconds');
  log.debug(this.name, 'returned an error, retrying.', args);

  var self = this;

  // make sure the callback (and any other fn)
  // is bound to Trader
  _.each(args, function(arg, i) {
    if(_.isFunction(arg))
      args[i] = _.bind(arg, self);
  });

  // run the failed method again with the same
  // arguments after wait
  setTimeout(
    function() { method.apply(self, args) },
    wait
  );
}

Trader.prototype.getPortfolio = function(callback) {
  var args = _.toArray(arguments);
  log.debug('getPortfolio', 'called');

  var set = function(data, err) {
    if(err) {
      log.error('getPortfolio', 'Error', err);
      return this.retry(this.getPortfolio, args);
    }

    data = data.result;

    var assetEntry = _.find(data, function(i) { return i.Currency == this.asset}.bind(this));
    var currencyEntry = _.find(data, function(i) { return i.Currency == this.currency}.bind(this));

    if(_.isUndefined(assetEntry)) {
      assetEntry = {
        Available: 0.0,
        Currency: this.asset
      }
    }

    if(_.isUndefined(currencyEntry)) {
      currencyEntry = {
        Available: 0.0,
        Currency: this.currency
      }
    }

    var assetAmount = parseFloat( assetEntry.Available );
    var currencyAmount = parseFloat( currencyEntry.Available );

    if(
      !_.isNumber(assetAmount) || _.isNaN(assetAmount) ||
      !_.isNumber(currencyAmount) || _.isNaN(currencyAmount)
    ) {
      log.info('asset:', this.asset);
      log.info('currency:', this.currency);
      log.info('exchange data:', data);
      util.die('Gekko was unable to set the portfolio');
    }

    var portfolio = [
      { name: this.asset, amount: assetAmount },
      { name: this.currency, amount: currencyAmount }
    ];

    log.debug('getPortfolio', 'result:', portfolio);

    callback(err, portfolio);
  }.bind(this);

  this.bittrexApi.getbalances(set);
}

Trader.prototype.getTicker = function(callback) {
  var args = _.toArray(arguments);

  log.debug('getTicker', 'called');

  this.bittrexApi.getticker({market: this.pair}, function(data, err) {
    if(err)
      return this.retry(this.getTicker, args);

    var tick = data.result;

    log.debug('getTicker', 'result', tick);

    callback(null, {
      bid: parseFloat(tick.Bid),
      ask: parseFloat(tick.Ask),
    })

  }.bind(this));
}

Trader.prototype.getFee = function(callback) {

  log.debug('getFee', 'called');
  /*var set = function(data, err) {
    if(err || data.error)
      return callback(err || data.error);

    data = data.result;

    var assetEntry = _.find(data, function(c) { return c.Currency == this.asset}.bind(this));
    //var currencyEntry = _.find(data, function(c) { return c.Currency == this.currency}.bind(this));

    var fee = parseFloat(assetEntry.TxFee);

    callback(false, parseFloat(assetEntry.TxFee));
  }.bind(this);

  this.bittrexApi.getcurrencies(set); */

   callback(false, parseFloat(0.00025));
}

Trader.prototype.buy = function(amount, price, callback) {
  var args = _.toArray(arguments);

  log.debug('buy', 'called', {amount: amount, price: price});
  // correct the amount to avoid an INSUFFICIENT_FUNDS exception
  amount = amount - (0.00255*amount);
  log.debug('buy', 'corrected amount', {amount: amount, price: price});

  var set = function(result, err) {
    if(err || result.error) {
      if(err && err.message === 'INSUFFICIENT_FUNDS') {
        // retry with the already reduced amount, will be reduced again in the recursive call
         return this.retry(this.buy, [amount, price, callback]);
      }
      log.error('unable to buy:', {err: err, result: result});
      return this.retry(this.buy, args);
    }

    log.debug('buy', 'result', result);

    callback(null, result.result.uuid);
  }.bind(this);

  this.bittrexApi.buylimit({market: this.pair, quantity: amount, rate: price}, set);
}

Trader.prototype.sell = function(amount, price, callback) {
  var args = _.toArray(arguments);

  log.debug('sell', 'called', {amount: amount, price: price});

  var set = function(result, err) {
    if(err || result.error) {
       log.error('unable to sell:',  {err: err, result: result});
      return this.retry(this.sell, args);
    }

    log.debug('sell', 'result', result);

    callback(null, result.result.uuid);
  }.bind(this);

  this.bittrexApi.selllimit({market: this.pair, quantity: amount, rate: price}, set);
}

Trader.prototype.checkOrder = function(order, callback) {
  var check = function(result, err) {
    log.debug('checkOrder', 'called');

    var stillThere = _.find(result.result, function(o) { return o.OrderUuid === order });

    log.debug('checkOrder', 'result', stillThere);
    callback(err, !stillThere);
  }.bind(this);

  this.bittrexApi.getopenorders({market: this.pair}, check);
}

Trader.prototype.getOrder = function(order, callback) {

  var get = function(result, err) {

    log.debug('getOrder', 'called');

    if(err)
      return callback(err);

    var price = 0;
    var amount = 0;
    var date = moment(0);

    if(!result.success)
      return callback(null, {price, amount, date});

    var resultOrder = result.result;

    price = resultOrder.Price;
    amount = resultOrder.Quantity;

    if(resultOrder.IsOpen) {
         date = moment(resultOrder.Opened);
    } else {
       date = moment(resultOrder.Closed);
    }

    log.debug('getOrder', 'result', {price, amount, date});
    callback(err, {price, amount, date});
  }.bind(this);

  this.bittrexApi.getorder({uuid: order}, get);
}

Trader.prototype.cancelOrder = function(order, callback) {
  var args = _.toArray(arguments);
  var cancel = function(result, err) {
    log.debug('cancelOrder', 'called', order);

    if(err || !result.success) {
      log.error('unable to cancel order', order, '(', err, result, '), retrying');
      return this.retry(this.cancelOrder, args);
    }

    log.debug('getOrder', 'result', result);

    callback();
  }.bind(this);

  this.bittrexApi.cancel({uuid: order}, cancel);
}

Trader.prototype.getTrades = function(since, callback, descending) {

  log.debug('getTrades called!', { descending: descending} );

  var firstFetch = !!since;

  var args = _.toArray(arguments);
  var process = function(data, err) {
    if(err) {
      log.error('Error getTrades()', err)
      return this.retry(this.getTrades, args);
    }

    var result = data.result;

    // Edge case, see here:
    // @link https://github.com/askmike/gekko/issues/479
    if(firstFetch && _.size(result) === 50000)
      util.die(
        [
          'Bittrex did not provide enough data. Read this:',
          'https://github.com/askmike/gekko/issues/479'
        ].join('\n\n')
      );

      result = _.map(result, function(trade) {
        var mr = {
            tid: trade.Id,
            amount: +trade.Quantity,
            date: moment.utc(trade.TimeStamp).unix(),
            timeStamp: trade.TimeStamp,
            price: +trade.Price
        };
    	return mr;
    });

    callback(null, result.reverse());
  }.bind(this);

  var params = {
    currencyPair: joinCurrencies(this.currency, this.asset)
  }

  if(since)
    params.start = since.unix();

  this.bittrexApi.getmarkethistory({ market: params.currencyPair }, process);
}

Trader.getCapabilities = function () {
  return {
    name: 'bittrex',
    slug: 'bittrex',
    currencies: ['BTC', 'ETH', 'USDT'],
    assets: [
      'BTC', 'BCC','ETH','NEO','BCC','PAY'
    ],
    markets: [
      // *** BTC <-> XXX
      { pair: ['BTC', 'BCC'], minimalOrder: { amount: 0.0001, unit: 'asset' } },
      { pair: ['BTC', 'ETH'], minimalOrder: { amount: 0.0001, unit: 'asset' } },
      { pair: ['BTC', 'NEO'], minimalOrder: { amount: 0.0001, unit: 'asset' } },
      { pair: ['BTC', 'PAY'], minimalOrder: { amount: 0.0001, unit: 'asset' } },

      // *** USDT <-> XXX
      { pair: ['USDT', 'BTC'], minimalOrder: { amount: 0.0001, unit: 'asset' } },
      { pair: ['USDT', 'BCC'], minimalOrder: { amount: 0.0001, unit: 'asset' } },
      { pair: ['USDT', 'ETH'], minimalOrder: { amount: 0.0001, unit: 'asset' } },
      { pair: ['USDT', 'NEO'], minimalOrder: { amount: 0.0001, unit: 'asset' } },

      // *** ETH <-> XXX
      { pair: ['ETH', 'BCC'], minimalOrder: { amount: 0.0001, unit: 'asset' } },
      { pair: ['ETH', 'NEO'], minimalOrder: { amount: 0.0001, unit: 'asset' } },
      { pair: ['ETH', 'BTC'], minimalOrder: { amount: 0.0001, unit: 'asset' } },
      { pair: ['ETH', 'PAY'], minimalOrder: { amount: 0.0001, unit: 'asset' } }

    ],
    requires: ['key', 'secret'],
    tid: 'tid',
    providesHistory: 'date',
    providesFullHistory: true,
    tradable: true
  };
}

module.exports = Trader;
<commit_msg>bugfix: endless loop in cancel order<commit_after>var Bittrex = require('node.bittrex.api');
var util = require('../core/util.js');
var _ = require('lodash');
var moment = require('moment');
var log = require('../core/log');
var apiKeyManager = require('../web/apiKeyManager.js');

// Helper methods
function joinCurrencies(currencyA, currencyB){
    return currencyA + '-' + currencyB;
}

var Trader = function(config) {
  _.bindAll(this);

  // not nice but works to use a web module here to grab the keys
  var keys = apiKeyManager._getApiKeyPair('bittrex');

  if(_.isObject(keys)) {
    config.key = keys.key;
    config.secret = keys.secret;
  } else {
    // no api key defined -> we need to set a dummy key, otherwise the Bittrex module will not work even for public requests
    config.key = 'dummyApiKey';
    config.secret = 'dummyApiKey';
  }

  // override if cmd line mode (not --ui)
  if(_.isObject(config)) {
    this.key = config.key;
    this.secret = config.secret;
    this.currency = config.currency;
    this.asset = config.asset;
  }

  this.name = 'Bittrex';
  this.balance;
  this.price;

  this.pair = [this.currency, this.asset].join('-');

  Bittrex.options({
    'apikey':  this.key,
    'apisecret': this.secret,
    'stream': false,
    'verbose': false,
    'cleartext': false
  });

  log.debug('Init', 'New Bittrex Trader', {currency: this.currency, asset: this.asset});

  this.bittrexApi = Bittrex;
}

// if the exchange errors we try the same call again after
// waiting 10 seconds
Trader.prototype.retry = function(method, args) {
  var wait = +moment.duration(10, 'seconds');
  log.debug(this.name, 'returned an error, retrying.', args);

  var self = this;

  // make sure the callback (and any other fn)
  // is bound to Trader
  _.each(args, function(arg, i) {
    if(_.isFunction(arg))
      args[i] = _.bind(arg, self);
  });

  // run the failed method again with the same
  // arguments after wait
  setTimeout(
    function() { method.apply(self, args) },
    wait
  );
}

Trader.prototype.getPortfolio = function(callback) {
  var args = _.toArray(arguments);
  log.debug('getPortfolio', 'called');

  var set = function(data, err) {
    if(err) {
      log.error('getPortfolio', 'Error', err);
      return this.retry(this.getPortfolio, args);
    }

    data = data.result;

    var assetEntry = _.find(data, function(i) { return i.Currency == this.asset}.bind(this));
    var currencyEntry = _.find(data, function(i) { return i.Currency == this.currency}.bind(this));

    if(_.isUndefined(assetEntry)) {
      assetEntry = {
        Available: 0.0,
        Currency: this.asset
      }
    }

    if(_.isUndefined(currencyEntry)) {
      currencyEntry = {
        Available: 0.0,
        Currency: this.currency
      }
    }

    var assetAmount = parseFloat( assetEntry.Available );
    var currencyAmount = parseFloat( currencyEntry.Available );

    if(
      !_.isNumber(assetAmount) || _.isNaN(assetAmount) ||
      !_.isNumber(currencyAmount) || _.isNaN(currencyAmount)
    ) {
      log.info('asset:', this.asset);
      log.info('currency:', this.currency);
      log.info('exchange data:', data);
      util.die('Gekko was unable to set the portfolio');
    }

    var portfolio = [
      { name: this.asset, amount: assetAmount },
      { name: this.currency, amount: currencyAmount }
    ];

    log.debug('getPortfolio', 'result:', portfolio);

    callback(err, portfolio);
  }.bind(this);

  this.bittrexApi.getbalances(set);
}

Trader.prototype.getTicker = function(callback) {
  var args = _.toArray(arguments);

  log.debug('getTicker', 'called');

  this.bittrexApi.getticker({market: this.pair}, function(data, err) {
    if(err)
      return this.retry(this.getTicker, args);

    var tick = data.result;

    log.debug('getTicker', 'result', tick);

    callback(null, {
      bid: parseFloat(tick.Bid),
      ask: parseFloat(tick.Ask),
    })

  }.bind(this));
}

Trader.prototype.getFee = function(callback) {

  log.debug('getFee', 'called');
  /*var set = function(data, err) {
    if(err || data.error)
      return callback(err || data.error);

    data = data.result;

    var assetEntry = _.find(data, function(c) { return c.Currency == this.asset}.bind(this));
    //var currencyEntry = _.find(data, function(c) { return c.Currency == this.currency}.bind(this));

    var fee = parseFloat(assetEntry.TxFee);

    callback(false, parseFloat(assetEntry.TxFee));
  }.bind(this);

  this.bittrexApi.getcurrencies(set); */

   callback(false, parseFloat(0.00025));
}

Trader.prototype.buy = function(amount, price, callback) {
  var args = _.toArray(arguments);

  log.debug('buy', 'called', {amount: amount, price: price});
  // correct the amount to avoid an INSUFFICIENT_FUNDS exception
  amount = amount - (0.00255*amount);
  log.debug('buy', 'corrected amount', {amount: amount, price: price});

  var set = function(result, err) {
    if(err || result.error) {
      if(err && err.message === 'INSUFFICIENT_FUNDS') {
        // retry with the already reduced amount, will be reduced again in the recursive call
         return this.retry(this.buy, [amount, price, callback]);
      }
      log.error('unable to buy:', {err: err, result: result});
      return this.retry(this.buy, args);
    }

    log.debug('buy', 'result', result);

    callback(null, result.result.uuid);
  }.bind(this);

  this.bittrexApi.buylimit({market: this.pair, quantity: amount, rate: price}, set);
}

Trader.prototype.sell = function(amount, price, callback) {
  var args = _.toArray(arguments);

  log.debug('sell', 'called', {amount: amount, price: price});

  var set = function(result, err) {
    if(err || result.error) {
       log.error('unable to sell:',  {err: err, result: result});
      return this.retry(this.sell, args);
    }

    log.debug('sell', 'result', result);

    callback(null, result.result.uuid);
  }.bind(this);

  this.bittrexApi.selllimit({market: this.pair, quantity: amount, rate: price}, set);
}

Trader.prototype.checkOrder = function(order, callback) {
  var check = function(result, err) {
    log.debug('checkOrder', 'called');

    var stillThere = _.find(result.result, function(o) { return o.OrderUuid === order });

    log.debug('checkOrder', 'result', stillThere);
    callback(err, !stillThere);
  }.bind(this);

  this.bittrexApi.getopenorders({market: this.pair}, check);
}

Trader.prototype.getOrder = function(order, callback) {

  var get = function(result, err) {

    log.debug('getOrder', 'called');

    if(err)
      return callback(err);

    var price = 0;
    var amount = 0;
    var date = moment(0);

    if(!result.success)
      return callback(null, {price, amount, date});

    var resultOrder = result.result;

    price = resultOrder.Price;
    amount = resultOrder.Quantity;

    if(resultOrder.IsOpen) {
         date = moment(resultOrder.Opened);
    } else {
       date = moment(resultOrder.Closed);
    }

    log.debug('getOrder', 'result', {price, amount, date});
    callback(err, {price, amount, date});
  }.bind(this);

  this.bittrexApi.getorder({uuid: order}, get);
}

Trader.prototype.cancelOrder = function(order, callback) {
  var args = _.toArray(arguments);
  var cancel = function(result, err) {
    log.debug('cancelOrder', 'called', order);

    if(err) {
      log.error('unable to cancel order', order, '(', err, result, '), retrying');
      return this.retry(this.cancelOrder, args);
    }

    if(!result.success && result.message === 'ORDER_NOT_OPEN') {
      log.debug('getOrder', 'ORDER_NOT_OPEN: assuming already closed or executed');
    }

    log.debug('getOrder', 'result', result);

    callback();
  }.bind(this);

  this.bittrexApi.cancel({uuid: order}, cancel);
}

Trader.prototype.getTrades = function(since, callback, descending) {

  log.debug('getTrades called!', { descending: descending} );

  var firstFetch = !!since;

  var args = _.toArray(arguments);
  var process = function(data, err) {
    if(err) {
      log.error('Error getTrades()', err)
      return this.retry(this.getTrades, args);
    }

    var result = data.result;

    // Edge case, see here:
    // @link https://github.com/askmike/gekko/issues/479
    if(firstFetch && _.size(result) === 50000)
      util.die(
        [
          'Bittrex did not provide enough data. Read this:',
          'https://github.com/askmike/gekko/issues/479'
        ].join('\n\n')
      );

      result = _.map(result, function(trade) {
        var mr = {
            tid: trade.Id,
            amount: +trade.Quantity,
            date: moment.utc(trade.TimeStamp).unix(),
            timeStamp: trade.TimeStamp,
            price: +trade.Price
        };
    	return mr;
    });

    callback(null, result.reverse());
  }.bind(this);

  var params = {
    currencyPair: joinCurrencies(this.currency, this.asset)
  }

  if(since)
    params.start = since.unix();

  this.bittrexApi.getmarkethistory({ market: params.currencyPair }, process);
}

Trader.getCapabilities = function () {
  return {
    name: 'bittrex',
    slug: 'bittrex',
    currencies: ['BTC', 'ETH', 'USDT'],
    assets: [
      'BTC', 'BCC','ETH','NEO','BCC','PAY'
    ],
    markets: [
      // *** BTC <-> XXX
      { pair: ['BTC', 'BCC'], minimalOrder: { amount: 0.0001, unit: 'asset' } },
      { pair: ['BTC', 'ETH'], minimalOrder: { amount: 0.0001, unit: 'asset' } },
      { pair: ['BTC', 'NEO'], minimalOrder: { amount: 0.0001, unit: 'asset' } },
      { pair: ['BTC', 'PAY'], minimalOrder: { amount: 0.0001, unit: 'asset' } },

      // *** USDT <-> XXX
      { pair: ['USDT', 'BTC'], minimalOrder: { amount: 0.0001, unit: 'asset' } },
      { pair: ['USDT', 'BCC'], minimalOrder: { amount: 0.0001, unit: 'asset' } },
      { pair: ['USDT', 'ETH'], minimalOrder: { amount: 0.0001, unit: 'asset' } },
      { pair: ['USDT', 'NEO'], minimalOrder: { amount: 0.0001, unit: 'asset' } },

      // *** ETH <-> XXX
      { pair: ['ETH', 'BCC'], minimalOrder: { amount: 0.0001, unit: 'asset' } },
      { pair: ['ETH', 'NEO'], minimalOrder: { amount: 0.0001, unit: 'asset' } },
      { pair: ['ETH', 'BTC'], minimalOrder: { amount: 0.0001, unit: 'asset' } },
      { pair: ['ETH', 'PAY'], minimalOrder: { amount: 0.0001, unit: 'asset' } }

    ],
    requires: ['key', 'secret'],
    tid: 'tid',
    providesHistory: 'date',
    providesFullHistory: true,
    tradable: true
  };
}

module.exports = Trader;
<|endoftext|>


<commit_before>/* jshint node: true */
"use strict";

var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var consolidate = require('consolidate');
var csurf = require('csurf');
var express = require('express');
var session = require('express-session');
var fsSession = require('fs-session')({ session: session });
var _ = require('underscore');

var DBConn = require('./dbconn');
var gravatar = require('./gravatar');
var webforms = require('./webforms');

function WebApp(config, callback) {
	if (!("dbConnection" in config)) {
		callback(new Error("Missing dbConnection in WebApp configuration."));
		return;
	}
	if (!("dbOptions" in config)) {
		callback(new Error("Missing dbOptions in WebApp configuration."));
		return;
	}
	if (!("webPort" in config)) {
		callback(new Error("Missing webPort in WebApp configuration."));
		return;
	}
	if (!("webSecret" in config)) {
		callback(new Error("Missing webSecret in WebApp configuration."));
		return;
	}

	// Set ReCAPTCHA settings if present
	if ("recaptcha" in config) {
		if (!("privateKey" in config.recaptcha)) {
			callback(new Error("Missing privateKey in WebApp ReCAPTCHA configuration."));
			return;
		}

		if (!("publicKey" in config.recaptcha)) {
			callback(new Error("Missing publicKey in WebApp ReCAPTCHA configuration."));
			return;
		}

		this.recaptcha = {
			publicKey: config.recaptcha.publicKey,
			privateKey: config.recaptcha.privateKey
		};
	}

	// Create database connection
	var self = this;
	this.dbconn = new DBConn({
		dbConnection: config.dbConnection,
		dbOptions: config.dbOptions
	}, function(err, dbconn) {
		if (err) {
			callback(err);
			return;
		}

		self.app = express();

		// Middleware
		self.app.use(express.static(__dirname + '/public'));
		self.app.use(bodyParser.urlencoded());
		self.app.use(cookieParser());
		self.app.use(session({
			secret: config.webSecret,
			store: new fsSession()
		}));
		self.app.use(csurf());

		// Template engine
		self.app.engine('hjs', consolidate.hogan);

		// Configuration
		self.app.set('view engine', 'hjs');

		// Top-level routes
		self.app.get('/', self.home.bind(self));
		self.app.all('/login', self.login.bind(self));
		self.app.get('/logout', self.logout.bind(self));
		self.app.all('/register', self.register.bind(self));

		// Users
		self.app.get('/users', self.getUsers.bind(self));
		self.app.all('/users/new', self.newUser.bind(self));
		self.app.get('/users/:id', self.getUser.bind(self));
		self.app.all('/users/:id/edit', self.editUser.bind(self));
		self.app.all('/users/:id/destroy', self.destroyUser.bind(self));

		// Start listening for connections
		self.app.listen(config.webPort, function() {
			callback(null, self);
		});
	});
}

WebApp.prototype.render = function(req, res, layout, options) {
	res.render('layout', _.extend(options || {}, {
		session: req.session,
		partials: {
			body: layout,
			header: 'header'
		}
	}));
}

// Top level controllers
WebApp.prototype.home = function(req, res) {
	this.render(req, res, 'home');
};
WebApp.prototype.login = function(req, res) {
	var self = this;

	function render(data, errors) {
		var data = data || {};
		var errors = errors || {};

		data._csrf = req.csrfToken();
		self.render(req, res, 'login', {
			data: data, errors: errors,
		});
		return;
	}

	var data = req.body;
	if (!_.isEmpty(data)) {
		webforms.loginForm(data, this.dbconn.User, function(errors, user) {
			if (errors) {
				render(data, errors);
			} else {
				req.session.user = user;
				res.redirect('/');
			}
		});
	} else {
		render();
	}
};
WebApp.prototype.logout = function(req, res) {
	delete req.session.user;

	res.render('layout', {
		partials: { body: 'logout' }
	});
};
WebApp.prototype.register = function(req, res) {
	var self = this;

	function render(data, errors) {
		var data = data || {};
		var errors = errors || {};

		data._csrf = req.csrfToken();
		self.render(req, res, 'register', {
			data: data, errors: errors,
			recaptcha_public_key: self.recaptcha ? self.recaptcha.publicKey : null
		});
		return;
	}

	var data = req.body;
	if (!_.isEmpty(data)) {
		webforms.registerForm(
			data, req.ip,
			this.recaptcha ? this.recaptcha.privateKey : null,
			this.dbconn.User,
			function(errors, user) {
				if (errors) {
					render(data, errors);
				} else {
					self.render(req, res, 'registerNotify', {
						data: data
					});
				}
			}
		);
	} else {
		render();
	}
};

// Users controllers

WebApp.prototype.getUsers = function(req, res) {
	this.dbconn.User.findAll()
	.success(function(users) {
		res.render('layout', { users: users, partials: { body: 'getUsers' }});
	});
};
WebApp.prototype.newUser = function(req, res) {
	res.render('layout', {
		partials: { body: 'newUser' }
	});
};
WebApp.prototype.getUser = function(req, res) {
	this.dbconn.User.find({
		include: [ this.dbconn.Profile ],
		where: { username: req.params.id }
	}).success(function(user) {
		res.render('layout', {
			user: user,
			gravatar: gravatar.image(user.email),
			partials: { body: 'getUser' }
		});
	});
};
WebApp.prototype.editUser = function(req, res) {
	res.render('layout', {
		partials: { body: 'editUser' }
	});
};
WebApp.prototype.destroyUser = function(req, res) {
	res.render('layout', {
		partials: { body: 'destroyUser' }
	});
};

module.exports = WebApp;
<commit_msg>Lint.<commit_after>/* jshint node: true */
"use strict";

var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var consolidate = require('consolidate');
var csurf = require('csurf');
var express = require('express');
var session = require('express-session');
var fsSession = require('fs-session')({ session: session });
var _ = require('underscore');

var DBConn = require('./dbconn');
var gravatar = require('./gravatar');
var webforms = require('./webforms');

function WebApp(config, callback) {
	if (!("dbConnection" in config)) {
		callback(new Error("Missing dbConnection in WebApp configuration."));
		return;
	}
	if (!("dbOptions" in config)) {
		callback(new Error("Missing dbOptions in WebApp configuration."));
		return;
	}
	if (!("webPort" in config)) {
		callback(new Error("Missing webPort in WebApp configuration."));
		return;
	}
	if (!("webSecret" in config)) {
		callback(new Error("Missing webSecret in WebApp configuration."));
		return;
	}

	// Set ReCAPTCHA settings if present
	if ("recaptcha" in config) {
		if (!("privateKey" in config.recaptcha)) {
			callback(new Error("Missing privateKey in WebApp ReCAPTCHA configuration."));
			return;
		}

		if (!("publicKey" in config.recaptcha)) {
			callback(new Error("Missing publicKey in WebApp ReCAPTCHA configuration."));
			return;
		}

		this.recaptcha = {
			publicKey: config.recaptcha.publicKey,
			privateKey: config.recaptcha.privateKey
		};
	}

	// Create database connection
	var self = this;
	this.dbconn = new DBConn({
		dbConnection: config.dbConnection,
		dbOptions: config.dbOptions
	}, function(err, dbconn) {
		if (err) {
			callback(err);
			return;
		}

		self.app = express();

		// Middleware
		self.app.use(express.static(__dirname + '/public'));
		self.app.use(bodyParser.urlencoded());
		self.app.use(cookieParser());
		self.app.use(session({
			secret: config.webSecret,
			store: new fsSession()
		}));
		self.app.use(csurf());

		// Template engine
		self.app.engine('hjs', consolidate.hogan);

		// Configuration
		self.app.set('view engine', 'hjs');

		// Top-level routes
		self.app.get('/', self.home.bind(self));
		self.app.all('/login', self.login.bind(self));
		self.app.get('/logout', self.logout.bind(self));
		self.app.all('/register', self.register.bind(self));

		// Users
		self.app.get('/users', self.getUsers.bind(self));
		self.app.all('/users/new', self.newUser.bind(self));
		self.app.get('/users/:id', self.getUser.bind(self));
		self.app.all('/users/:id/edit', self.editUser.bind(self));
		self.app.all('/users/:id/destroy', self.destroyUser.bind(self));

		// Start listening for connections
		self.app.listen(config.webPort, function() {
			callback(null, self);
		});
	});
}

WebApp.prototype.render = function(req, res, layout, options) {
	res.render('layout', _.extend(options || {}, {
		session: req.session,
		partials: {
			body: layout,
			header: 'header'
		}
	}));
};

// Top level controllers
WebApp.prototype.home = function(req, res) {
	this.render(req, res, 'home');
};
WebApp.prototype.login = function(req, res) {
	var self = this;

	function render(data, errors) {
		data = data || {};
		errors = errors || {};

		data._csrf = req.csrfToken();
		self.render(req, res, 'login', {
			data: data, errors: errors,
		});
		return;
	}

	var data = req.body;
	if (!_.isEmpty(data)) {
		webforms.loginForm(data, this.dbconn.User, function(errors, user) {
			if (errors) {
				render(data, errors);
			} else {
				req.session.user = user;
				res.redirect('/');
			}
		});
	} else {
		render();
	}
};
WebApp.prototype.logout = function(req, res) {
	delete req.session.user;

	res.render('layout', {
		partials: { body: 'logout' }
	});
};
WebApp.prototype.register = function(req, res) {
	var self = this;

	function render(data, errors) {
		data = data || {};
		errors = errors || {};

		data._csrf = req.csrfToken();
		self.render(req, res, 'register', {
			data: data, errors: errors,
			recaptcha_public_key: self.recaptcha ? self.recaptcha.publicKey : null
		});
		return;
	}

	var data = req.body;
	if (!_.isEmpty(data)) {
		webforms.registerForm(
			data, req.ip,
			this.recaptcha ? this.recaptcha.privateKey : null,
			this.dbconn.User,
			function(errors, user) {
				if (errors) {
					render(data, errors);
				} else {
					self.render(req, res, 'registerNotify', {
						data: data
					});
				}
			}
		);
	} else {
		render();
	}
};

// Users controllers

WebApp.prototype.getUsers = function(req, res) {
	this.dbconn.User.findAll()
	.success(function(users) {
		res.render('layout', { users: users, partials: { body: 'getUsers' }});
	});
};
WebApp.prototype.newUser = function(req, res) {
	res.render('layout', {
		partials: { body: 'newUser' }
	});
};
WebApp.prototype.getUser = function(req, res) {
	this.dbconn.User.find({
		include: [ this.dbconn.Profile ],
		where: { username: req.params.id }
	}).success(function(user) {
		res.render('layout', {
			user: user,
			gravatar: gravatar.image(user.email),
			partials: { body: 'getUser' }
		});
	});
};
WebApp.prototype.editUser = function(req, res) {
	res.render('layout', {
		partials: { body: 'editUser' }
	});
};
WebApp.prototype.destroyUser = function(req, res) {
	res.render('layout', {
		partials: { body: 'destroyUser' }
	});
};

module.exports = WebApp;
<|endoftext|>