<commit_before>!function(){function a(a){return a.replace(/\w\S*/g,function(a){return a.charAt(0).toUpperCase()+a.substr(1).toLowerCase()})}function e(a){if(a)for(var e=0;e<a.length;++e)a[e]=a[e].toLowerCase()}function t(t){for(var n=0;n<t.length;++n){var r=t[n];r.text=a(r.text),e(r.keywords)}}function n(){return location.protocol+"//"+location.hostname+(location.port&&":"+location.port)+"/"}function r(a){for(var e=a.length-1;e>0;e--){var t=Math.floor(Math.random()*(e+1)),n=a[e];a[e]=a[t],a[t]=n}return a}function i(a){var e=document.createElement("div");return e.innerHTML=a,e}function T(a,e,t){a.image=t?n()+"img/seo/"+a.image:p+a.image;var r=e.render(a);return i(r)}function o(a,e){var t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];currentMonth=t[e.getMonth()];for(var n=[],r=0;r-1)&&n.push(i)}return n}function A(a,e){return a.keywords?a.keywords.indexOf(e)>-1:!1}function O(a,t){function n(a,e,t){for(var n=a.link,r=0;r<t.length;++r){var i=t[r];if(i.data.link==n)return void(i.priority+=e)}t.push({data:a,priority:e})}function i(a){for(var e=[],t=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY,i=0;io&&(t=o),o>n&&(n=o),e[o]||(e[o]=[]),e[o].push(T.data)}for(var A=[],i=n;i>=t;--i){var a=e[i];a&&(A=A.concat(r(a)))}return A}function T(a,e){for(var t=[],n=0;n<a.length;++n){for(var r=!1,i=a[n],T=i.link,o=0;o<e.length;++o)if(e[o].data.link==T){r=!0;break}r||t.push(i)}return t}e(t);for(var o=[],O=t.length,s=0;O>s;++s)for(var h=t[s],g=0;g<a.length;++g){var p=a[g];A(p,h)&&n(p,O-s,o)}var d=i(o),E=d.slice(0,R);if(E.length<R){var u=T(a,o);E=E.concat(r(u).slice(0,R-E.length))}return E}function s(){t(d),t(h);var a=window.seoKeywords||[],e=new Date,n=$("#seoHolder");if(n.length){var A=$("#seoTemplate").html(),s=Hogan.compile(A),p=r(d).slice(0,R),E=O(o(h,e),a),u=document.createDocumentFragment();if(p.length>0){$(u).append(i("
SPONSORED

"));for(var H=0;H<p.length;++H){var l=p[H];u.appendChild(T(l,s,!0))}$(u).append(i("
"))}else $(u).append(i("
RECOMMENDED TRIPS

"));for(var H=0;H<E.length;++H){var l=E[H];l.link=g+l.link,u.appendChild(T(l,s,!1))}n.append(u)}}var R=12,h=[],g="http://www.wilderhood.com/trip/",p="https://az741737.vo.msecnd.net/wilderhood-public/medium/";h.push({link:"EMERALD ISLES - WILDLIFE PHOTOGRAPHY TOUR OF ANDAMAN",image:"Darter/Trip/Andaman/Andaman.jpg",text:"EMERALD ISLES - WILDLIFE PHOTOGRAPHY TOUR OF ANDAMAN",keywords:["Andaman","Birding Destinations","Port Blair","Travel","Exotic"],months:["Jul","Aug","Sep","Oct"]}),h.push({link:"MOUNTAINS AND MONASTERIES - A PHOTOGRAPHY TOUR OF LADAKH",image:"Darter/Trip/Ladakh/Ladakh.jpg",text:"MOUNTAINS AND MONASTERIES - A PHOTOGRAPHY TOUR OF LADAKH",keywords:["Ladakh","Travel Destinations","Landscape Destinations","Leh","Ladakh","Travel","Exotic"],months:["Jul","Aug"]}),h.push({link:"CAMBODIA PHOTOGRAPHY TOUR - TEMPLES OF ANGKOR WAT & BEYOND",image:"Darter/Trip/Cambodia/Cambodia.jpg",text:"CAMBODIA PHOTOGRAPHY TOUR - TEMPLES OF ANGKOR WAT & BEYOND",keywords:["Cambodia","Travel","Landscape Destinations","Exotic"],months:["Jul","Aug","Sep","Oct"]}),h.push({link:"WALK ON THE HILLY SIDE IN BHUTAN",image:"BeyondRoads/Trip/Bhutan/Bhutan.jpg",text:"WALK ON THE HILLY SIDE IN BHUTAN",keywords:["Bhutan","Travel","Landscape Destinations","Exotic"],months:["Jul","Aug","Sep"]}),h.push({link:"BHUTAN TRAVEL ROUTERS TOURS AND TREKS",image:"BeyondRoads/Trip/Bhutan/Bhutan.jpg",text:"BHUTAN TRAVEL ROUTERS TOURS AND TREKS",keywords:["Bhutan","Travel","Landscape Destinations","Exotic"],months:["Jul","Aug","Sep"]}),h.push({link:"CLASSIC MYANMAR - A PHOTOGRAPHY TOUR",image:"Darter/Trip/Myanmar/Myanmar.jpg",text:"CLASSIC MYANMAR - A PHOTOGRAPHY TOUR",keywords:["Myanmar","Travel","Landscape Destinations","Exotic"],months:["Jul","Aug","Sep","Oct"]}),h.push({link:"PHOTOGRAPHY IN NORTH-EAST INDIA AND HORNBILL FESTIVAL",image:"Darter/Trip/Hornbill/Hornbill.jpg",text:"PHOTOGRAPHY IN NORTH-EAST INDIA AND HORNBILL FESTIVAL",keywords:["HORNBILL FESTIVAL","Travel","Landscape Destinations"],months:["Jul","Aug","Sep","Oct","Nov"]}),h.push({link:"FORTS AND DUNES OF RAJASTHAN - A TRAVEL PHOTOGRAPHY TOUR",image:"Darter/Trip/Rajasthan/Rajasthan.jpg",text:"FORTS AND DUNES OF RAJASTHAN - A TRAVEL PHOTOGRAPHY TOUR",keywords:["Travel","Landscape Destinations"],months:["Jul","Aug","Sep","Oct","Nov","Dec"]}),h.push({link:"A SNOW FILLED WINTER IN LADAKH - PHOTOGRAPHY TOUR",image:"Darter/Trip/Ladakh/Ladakh-snow.jpg",text:"A SNOW FILLED WINTER IN LADAKH - PHOTOGRAPHY TOUR",keywords:["Travel","Landscape Destinations"],months:["Jul","Aug","Sep","Oct","Nov","Dec"]}),h.push({link:"A SNOW FILLED WINTER IN LADAKH - PHOTOGRAPHY TOUR",image:"Darter/Trip/Ladakh/Ladakh-snow.jpg",text:"A SNOW FILLED WINTER IN LADAKH - PHOTOGRAPHY TOUR",keywords:["Travel","Landscape Destinations"],months:["Jul","Aug","Sep","Oct","Nov","Dec"]}),h.push({link:"MASAI MARA MIGRATION - SEPT 2015",image:"Sudhir/Trip/Maara/Maara.jpg",text:"MASAI MARA MIGRATION - SEPT 2015",keywords:["Africa","Maara","Great Migration","BigCats"],months:["Jul","Aug","Sep"]}),h.push({link:"MOTHER OF ALL PARKS-SERENGETI",image:"BeyondRoads/Trip/Serengeti/Serengeti.jpg",text:"MOTHER OF ALL PARKS-SERENGETI",keywords:["Africa","Serengeti","Tanzania","Great Migration","BigCats"],months:["Jul","Aug","Sep","Oct","Nov","Dec"]}),h.push({link:"THE PHANTOM AND THE WETLANDS - WILDLIFE PHOTOGRAPHY TOUR",image:"Toehold/Trip/Pantanal/Pantanal.jpg",text:"THE PHANTOM AND THE WETLANDS - WILDLIFE PHOTOGRAPHY TOUR",keywords:["Exotic","Birding Destinations","BigCats"],months:["Jul","Aug","Sep"]}),h.push({link:"GIR - THE LIONS LAST LAIR",image:"BirdWing/Trip/Gir/Gir.jpg",text:"GIR - THE LIONS LAST LAIR",keywords:["Gir","Birding Destinations","BigCats"],months:["Jul","Aug","Sep","Oct","Nov"]}),h.push({link:"WILD WEST - WILDLIFE PHOTOGRAPHY TOUR OF KUTCH",image:"Darter/Trip/Kutch/Kutch.jpg",text:"WILD WEST - WILDLIFE PHOTOGRAPHY TOUR OF KUTCH",keywords:["Gir","Birding Destinations","BigCats"],months:["Jul","Aug","Sep","Oct","Nov","Dec"]}),h.push({link:"OOTY",image:"BeyondRoads/Trip/Ooty/Ooty.jpg",text:"OOTY - Birding trip",keywords:["OOTY","Birding Destinations","Nilgiri"],months:["Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb"]}),h.push({link:"RANGANTHITTU-BANDIPUR",image:"BeyondRoads/Trip/Ranganathittu/Ranganathittu.jpg",text:"RANGANTHITTU-BANDIPUR",keywords:["Tiger","Bandipur","Kabini","Ranganathittu","Birding Destinations","BigCats"],months:["Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar","Apr"]}),h.push({link:"FELINE FORTUNE - TIGER PHOTOGRAPHY TOUR",image:"Toehold/Trip/Tadoba/Tadoba.jpg",text:"FELINE FORTUNE - TIGER PHOTOGRAPHY TOUR",keywords:["Tiger","Tadoba","Pench","Kanha","Bandhavgarh","Tadoba","BigCats"],months:["Jul","Aug","Sep","Oct"]}),h.push({link:"KAZIRANGA ROAM WITH THE RHINOS",image:"BeyondRoads/Trip/Kaziranga/Kaziranga.jpg",text:"KAZIRANGA ROAM WITH THE RHINOS",keywords:["Tiger","Ranthambore","Khaziranga","BigCats","RHINOS"],months:["Jul","Aug","Sep","Oct"]}),h.push({link:"TIGER CENTRAL - WILDLIFE PHOTOGRAPHY TOUR",image:"Toehold/Trip/Bandhavgarh/Bandhavgarh.jpg",text:"TIGER CENTRAL - WILDLIFE PHOTOGRAPHY TOUR",keywords:["Tiger","Bandhavgarh","Pench","Kanha","Tadoba","Bandhavgarh","BigCats"],months:["Jul","Aug","Sep","Oct"]}),h.push({link:"BHANDHAVGARH PHOTO TOUR",image:"MysticWild/Trip/Bandhavgarh/1.jpg",text:"BHANDHAVGARH PHOTO TOUR",keywords:["Tiger","Bandhavgarh","Pench","Kanha","Tadoba","BigCats"],months:["Jul","Aug","Sep","Oct"]}),h.push({link:"TIGER SOLSTICE - FULL-DAY TIGER PHOTOGRAPHY TOUR",image:"Toehold/Trip/Bandhavgarh/Bandhavgarh.jpg",text:"TIGER SOLSTICE - FULL-DAY TIGER PHOTOGRAPHY TOUR",keywords:["Tiger","Bandhavgarh","Pench","Kanha","Tadoba","BigCats"],months:["Jul","Aug","Sep","Oct"]}),h.push({link:"TIGER CENTRAL - WILDLIFE PHOTOGRAPHY TOUR",image:"Toehold/Trip/Bandhavgarh/Bandhavgarh.jpg",text:"TIGER CENTRAL - WILDLIFE PHOTOGRAPHY TOUR",keywords:["Tiger","Bandhavgarh","Pench","Kanha","Tadoba","BigCats"],months:["Jul","Aug","Sep","Oct"]}),h.push({link:"BANDHAVGARH TIGER RESERVE - SUNRISE TO SUNSET DEC 2015",image:"Sudhir/Trip/Bandhavgarh/Bandhavgarh.jpg",text:"BANDHAVGARH TIGER RESERVE - SUNRISE TO SUNSET DEC 2015",keywords:["Tiger","Bandhavgarh","Pench","Kanha","Tadoba","BigCats"],months:["Jul","Aug","Sep","Oct","Nov"]}),h.push({link:"BEAR FEAST IN THE FAR EAST - WILDLIFE PHOTOGRAPHY TOUR",image:"Toehold/Trip/Kamchatka/Kamchatka.jpg",text:"BEAR FEAST IN THE FAR EAST - WILDLIFE PHOTOGRAPHY TOUR",keywords:["Kamchatka","Exotic"],months:["Jul","Aug"]}),h.push({link:"HERPING AND PHOTOGRAPHY TOUR AT THAR DESERT",image:"BikeNHike/Trip/Thar/4.jpg",text:"THAR DESERT - HERPING",keywords:["Thar Desert","HERPING"],months:["Jul","Aug","Sep"]});var d=[];s()}();<commit_msg>Checking in minified js<commit_after>!function(){function a(a){return a.replace(/\w\S*/g,function(a){return a.charAt(0).toUpperCase()+a.substr(1).toLowerCase()})}function e(a){if(a)for(var e=0;e<a.length;++e)a[e]=a[e].toLowerCase()}function t(t){for(var n=0;n<t.length;++n){var i=t[n];i.text=a(i.text),e(i.keywords)}}function n(){return location.protocol+"//"+location.hostname+(location.port&&":"+location.port)+"/"}function i(a){for(var e=a.length-1;e>0;e--){var t=Math.floor(Math.random()*(e+1)),n=a[e];a[e]=a[t],a[t]=n}return a}function r(a){var e=document.createElement("div");return e.innerHTML=a,e}function T(a,e,t){a.image=t?n()+"img/seo/"+a.image:p+a.image;var i=e.render(a);return r(i)}function o(a,e){var t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];currentMonth=t[e.getMonth()];for(var n=[],i=0;i-1)&&n.push(r)}return n}function A(a,e){return a.keywords?a.keywords.indexOf(e)>-1:!1}function s(a,t){function n(a,e,t){for(var n=a.link,i=0;i<t.length;++i){var r=t[i];if(r.data.link==n)return void(r.priority+=e)}t.push({data:a,priority:e})}function r(a){for(var e=[],t=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY,r=0;ro&&(t=o),o>n&&(n=o),e[o]||(e[o]=[]),e[o].push(T.data)}for(var A=[],r=n;r>=t;--r){var a=e[r];a&&(A=A.concat(i(a)))}return A}function T(a,e){for(var t=[],n=0;n<a.length;++n){for(var i=!1,r=a[n],T=r.link,o=0;o<e.length;++o)if(e[o].data.link==T){i=!0;break}i||t.push(r)}return t}e(t);for(var o=[],s=t.length,O=0;s>O;++O)for(var R=t[O],g=0;g<a.length;++g){var p=a[g];A(p,R)&&n(p,s-O,o)}var d=r(o),E=d.slice(0,h);if(E.length<h){var u=T(a,o);E=E.concat(i(u).slice(0,h-E.length))}return E}function O(){t(d),t(R);var a=window.seoKeywords||[],e=new Date,n=$("#seoHolder");if(n.length){var A=$("#seoTemplate").html(),O=Hogan.compile(A),p=i(d).slice(0,h),E=s(o(R,e),a),u=document.createDocumentFragment();if(p.length>0){$(u).append(r("
SPONSORED

"));for(var I=0;I<p.length;++I){var l=p[I];u.appendChild(T(l,O,!0))}$(u).append(r("
"))}else $(u).append(r("
RECOMMENDED TRIPS

"));for(var I=0;I<E.length;++I){var l=E[I];l.link=g+l.link,u.appendChild(T(l,O,!1))}n.append(u)}}var h=9,R=[],g="http://www.wilderhood.com/trip/",p="https://az741737.vo.msecnd.net/wilderhood-public/medium/";R.push({link:"EMERALD ISLES - WILDLIFE PHOTOGRAPHY TOUR OF ANDAMAN",image:"Darter/Trip/Andaman/Andaman.jpg",text:"EMERALD ISLES - WILDLIFE PHOTOGRAPHY TOUR OF ANDAMAN",keywords:["Andaman","Birding Destinations","Port Blair","Travel","Exotic"],months:["Jul","Aug","Sep","Oct"]}),R.push({link:"MOUNTAINS AND MONASTERIES - A PHOTOGRAPHY TOUR OF LADAKH",image:"Darter/Trip/Ladakh/Ladakh.jpg",text:"MOUNTAINS AND MONASTERIES - A PHOTOGRAPHY TOUR OF LADAKH",keywords:["Ladakh","Travel Destinations","Landscape Destinations","Leh","Ladakh","Travel","Exotic"],months:["Jul","Aug"]}),R.push({link:"CAMBODIA PHOTOGRAPHY TOUR - TEMPLES OF ANGKOR WAT & BEYOND",image:"Darter/Trip/Cambodia/Cambodia.jpg",text:"CAMBODIA PHOTOGRAPHY TOUR - TEMPLES OF ANGKOR WAT & BEYOND",keywords:["Cambodia","Travel","Landscape Destinations","Exotic"],months:["Jul","Aug","Sep","Oct"]}),R.push({link:"WALK ON THE HILLY SIDE IN BHUTAN",image:"BeyondRoads/Trip/Bhutan/Bhutan.jpg",text:"WALK ON THE HILLY SIDE IN BHUTAN",keywords:["Bhutan","Travel","Landscape Destinations","Exotic"],months:["Jul","Aug","Sep"]}),R.push({link:"BHUTAN TRAVEL ROUTERS TOURS AND TREKS",image:"BeyondRoads/Trip/Bhutan/Bhutan.jpg",text:"BHUTAN TRAVEL ROUTERS TOURS AND TREKS",keywords:["Bhutan","Travel","Landscape Destinations","Exotic"],months:["Jul","Aug","Sep"]}),R.push({link:"CLASSIC MYANMAR - A PHOTOGRAPHY TOUR",image:"Darter/Trip/Myanmar/Myanmar.jpg",text:"CLASSIC MYANMAR - A PHOTOGRAPHY TOUR",keywords:["Myanmar","Travel","Landscape Destinations","Exotic"],months:["Jul","Aug","Sep","Oct"]}),R.push({link:"PHOTOGRAPHY IN NORTH-EAST INDIA AND HORNBILL FESTIVAL",image:"Darter/Trip/Hornbill/Hornbill.jpg",text:"PHOTOGRAPHY IN NORTH-EAST INDIA AND HORNBILL FESTIVAL",keywords:["HORNBILL FESTIVAL","Travel","Landscape Destinations"],months:["Jul","Aug","Sep","Oct","Nov"]}),R.push({link:"FORTS AND DUNES OF RAJASTHAN - A TRAVEL PHOTOGRAPHY TOUR",image:"Darter/Trip/Rajasthan/Rajasthan.jpg",text:"FORTS AND DUNES OF RAJASTHAN - A TRAVEL PHOTOGRAPHY TOUR",keywords:["Travel","Landscape Destinations"],months:["Jul","Aug","Sep","Oct","Nov","Dec"]}),R.push({link:"A SNOW FILLED WINTER IN LADAKH - PHOTOGRAPHY TOUR",image:"Darter/Trip/Ladakh/Ladakh-snow.jpg",text:"A SNOW FILLED WINTER IN LADAKH - PHOTOGRAPHY TOUR",keywords:["Travel","Landscape Destinations"],months:["Jul","Aug","Sep","Oct","Nov","Dec"]}),R.push({link:"A SNOW FILLED WINTER IN LADAKH - PHOTOGRAPHY TOUR",image:"Darter/Trip/Ladakh/Ladakh-snow.jpg",text:"A SNOW FILLED WINTER IN LADAKH - PHOTOGRAPHY TOUR",keywords:["Travel","Landscape Destinations"],months:["Jul","Aug","Sep","Oct","Nov","Dec"]}),R.push({link:"MASAI MARA MIGRATION - SEPT 2015",image:"Sudhir/Trip/Maara/Maara.jpg",text:"MASAI MARA MIGRATION - SEPT 2015",keywords:["Africa","Maara","Great Migration","BigCats"],months:["Jul","Aug","Sep"]}),R.push({link:"MOTHER OF ALL PARKS-SERENGETI",image:"BeyondRoads/Trip/Serengeti/Serengeti.jpg",text:"MOTHER OF ALL PARKS-SERENGETI",keywords:["Africa","Serengeti","Tanzania","Great Migration","BigCats"],months:["Jul","Aug","Sep","Oct","Nov","Dec"]}),R.push({link:"THE PHANTOM AND THE WETLANDS - WILDLIFE PHOTOGRAPHY TOUR",image:"Toehold/Trip/Pantanal/Pantanal.jpg",text:"THE PHANTOM AND THE WETLANDS - WILDLIFE PHOTOGRAPHY TOUR",keywords:["Exotic","Birding Destinations","BigCats"],months:["Jul","Aug","Sep"]}),R.push({link:"GIR - THE LIONS LAST LAIR",image:"BirdWing/Trip/Gir/Gir.jpg",text:"GIR - THE LIONS LAST LAIR",keywords:["Gir","Birding Destinations","BigCats"],months:["Jul","Aug","Sep","Oct","Nov"]}),R.push({link:"WILD WEST - WILDLIFE PHOTOGRAPHY TOUR OF KUTCH",image:"Darter/Trip/Kutch/Kutch.jpg",text:"WILD WEST - WILDLIFE PHOTOGRAPHY TOUR OF KUTCH",keywords:["Gir","Birding Destinations","BigCats"],months:["Jul","Aug","Sep","Oct","Nov","Dec"]}),R.push({link:"OOTY",image:"BeyondRoads/Trip/Ooty/Ooty.jpg",text:"OOTY - Birding trip",keywords:["OOTY","Birding Destinations","Nilgiri"],months:["Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb"]}),R.push({link:"RANGANTHITTU-BANDIPUR",image:"BeyondRoads/Trip/Ranganathittu/Ranganathittu.jpg",text:"RANGANTHITTU-BANDIPUR",keywords:["Tiger","Bandipur","Kabini","Ranganathittu","Birding Destinations","BigCats"],months:["Jul","Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar","Apr"]}),R.push({link:"FELINE FORTUNE - TIGER PHOTOGRAPHY TOUR",image:"Toehold/Trip/Tadoba/Tadoba.jpg",text:"FELINE FORTUNE - TIGER PHOTOGRAPHY TOUR",keywords:["Tiger","Tadoba","Pench","Kanha","Bandhavgarh","Tadoba","BigCats"],months:["Jul","Aug","Sep","Oct"]}),R.push({link:"KAZIRANGA ROAM WITH THE RHINOS",image:"BeyondRoads/Trip/Kaziranga/Kaziranga.jpg",text:"KAZIRANGA ROAM WITH THE RHINOS",keywords:["Tiger","Ranthambore","Khaziranga","BigCats","RHINOS"],months:["Jul","Aug","Sep","Oct"]}),R.push({link:"TIGER CENTRAL - WILDLIFE PHOTOGRAPHY TOUR",image:"Toehold/Trip/Bandhavgarh/Bandhavgarh.jpg",text:"TIGER CENTRAL - WILDLIFE PHOTOGRAPHY TOUR",keywords:["Tiger","Bandhavgarh","Pench","Kanha","Tadoba","Bandhavgarh","BigCats"],months:["Jul","Aug","Sep","Oct"]}),R.push({link:"BHANDHAVGARH PHOTO TOUR",image:"MysticWild/Trip/Bandhavgarh/1.jpg",text:"BHANDHAVGARH PHOTO TOUR",keywords:["Tiger","Bandhavgarh","Pench","Kanha","Tadoba","BigCats"],months:["Jul","Aug","Sep","Oct"]}),R.push({link:"TIGER SOLSTICE - FULL-DAY TIGER PHOTOGRAPHY TOUR",image:"Toehold/Trip/Bandhavgarh/Bandhavgarh.jpg",text:"TIGER SOLSTICE - FULL-DAY TIGER PHOTOGRAPHY TOUR",keywords:["Tiger","Bandhavgarh","Pench","Kanha","Tadoba","BigCats"],months:["Jul","Aug","Sep","Oct"]}),R.push({link:"TIGER CENTRAL - WILDLIFE PHOTOGRAPHY TOUR",image:"Toehold/Trip/Bandhavgarh/Bandhavgarh.jpg",text:"TIGER CENTRAL - WILDLIFE PHOTOGRAPHY TOUR",keywords:["Tiger","Bandhavgarh","Pench","Kanha","Tadoba","BigCats"],months:["Jul","Aug","Sep","Oct"]}),R.push({link:"BANDHAVGARH TIGER RESERVE - SUNRISE TO SUNSET DEC 2015",image:"Sudhir/Trip/Bandhavgarh/Bandhavgarh.jpg",text:"BANDHAVGARH TIGER RESERVE - SUNRISE TO SUNSET DEC 2015",keywords:["Tiger","Bandhavgarh","Pench","Kanha","Tadoba","BigCats"],months:["Jul","Aug","Sep","Oct","Nov"]}),R.push({link:"BEAR FEAST IN THE FAR EAST - WILDLIFE PHOTOGRAPHY TOUR",image:"Toehold/Trip/Kamchatka/Kamchatka.jpg",text:"BEAR FEAST IN THE FAR EAST - WILDLIFE PHOTOGRAPHY TOUR",keywords:["Kamchatka","Exotic"],months:["Jul","Aug"]}),R.push({link:"HERPING AND PHOTOGRAPHY TOUR AT THAR DESERT",image:"BikeNHike/Trip/Thar/4.jpg",text:"THAR DESERT - HERPING",keywords:["Thar Desert","HERPING"],months:["Jul","Aug","Sep"]}),R.push({link:"BUTTERFLY WATCHING, BIRD WATCHING AND HERPING TOUR",image:"MysticWild/Trip/Someshwar/collage.jpg",text:"BUTTERFLY WATCHING, BIRD WATCHING AND HERPING TOUR",keywords:["Agumbe","Monsoon"],months:["Aug","Sep"]}),R.push({link:"TADOBA WILDLIFE SAFARI TOUR",image:"MysticWild/Trip/Tadoba/banner.jpg",text:"TADOBA WILDLIFE SAFARI TOUR",keywords:["Tiger","Bandhavgarh","Pench","Kanha","Tadoba","BigCats"],months:["Jul","Aug","Sep","Oct","Nov"]});var d=[];d.push({link:"http://thewolfpackstore.com",image:"wolfpack.jpeg",text:"Feel Leopard on you",keywords:["Kabini","BigCats"]}),d.push({link:"http://thewolfpackstore.com",image:"gaur.jpeg",text:"Kabini is home for Indian Gaurs",keywords:["Kabini","BigCats"]}),O()}();<|endoftext|>


<commit_before>/* See also:
    http://www.html5rocks.com/en/tutorials/webrtc/basics/
    https://code.google.com/p/webrtc-samples/source/browse/trunk/apprtc/index.html

    https://webrtc-demos.appspot.com/html/pc1.html
*/

var cfg = {"iceServers":[{"url":"stun:23.21.150.121"}]},
    con = { 'optional': [{'DtlsSrtpKeyAgreement': true}, {'RtpDataChannels': true }] };

// createDataChannel needs `open /Applications/Google\ Chrome\ Canary.app --args --enable-data-channels` :-(

function writeToChatLog(message, message_type) {
    document.getElementById('chatlog').innerHTML += '
' + message + '
';
}

/* THIS IS ALICE, THE CALLER/SENDER */

var pc1 = new RTCPeerConnection(cfg, con),
    dc1 = null, tn1 = null;

var pc1icedone = false;

$('#showLocalOffer').modal('hide');
$('#getRemoteAnswer').modal('hide');
$('#waitForConnection').modal('hide');
$('#createOrJoin').modal('show');

$('#createBtn').click(function() {
    $('#showLocalOffer').modal('show');
});

$('#joinBtn').click(function() {
    $('#getRemoteOffer').modal('show');
});

$('#offerSentBtn').click(function() {
    $('#getRemoteAnswer').modal('show');
});

$('#offerRecdBtn').click(function() {
    var offer = $('#remoteOffer').val();
    var offerDesc = new RTCSessionDescription(JSON.parse(offer));
    console.log("Received remote offer", offer);
    writeToChatLog("Received remote offer", "text-success");
    handleOfferFromPC1(offerDesc);
    $('#showLocalAnswer').modal('show');
});

$('#answerSentBtn').click(function() {
    $('#waitForConnection').modal('show');
});

$('#answerRecdBtn').click(function() {
    var answer = $('#remoteAnswer').val();
    var answerDesc = new RTCSessionDescription(JSON.parse(answer));
    handleAnswerFromPC2(answerDesc);
    $('#waitForConnection').modal('show');
});

$('#sendMessageBtn').click(function() {
});

function setupDC1() {
    try {
        dc1 = pc1.createDataChannel('test', {reliable:false});
        console.log("Created datachannel (pc1)");
        dc1.onmessage = function (e) {
            console.log("Got message (pc1)", e.data);
            writeToChatLog(e.data, "text-failure");
        };
    } catch (e) { console.warn("No data channel (pc1)", e); }
}

getUserMedia({'audio':true, fake:true}, function (stream) {
    console.log("Got local audio", stream);
    pc1.addStream(stream);
    setupDC1();
    //tn1 = pc1.createDTMFSender(pc1.getLocalStreams()[0].getAudioTracks()[0])
    pc1.createOffer(function (offerDesc) {
        console.log("Created local offer", offerDesc);
        pc1.setLocalDescription(offerDesc);
        $('#localOffer').html(JSON.stringify(offerDesc));
    }, function () { console.warn("Couldn't create offer"); });
}, function () { console.warn("No audio"); });

pc1.onicecandidate = function (e) {
    console.log("ICE candidate (pc1)", e);
    if (e.candidate) {
        //handleCandidateFromPC1(e.candidate)
        if (!pc1icedone) {
            document.localICECandidateForm.localICECandidate.value = JSON.stringify(e.candidate);
            pc1icedone = true;
        }
    }
};

function handleOnconnection() {
    console.log("pc1: datachannel connected");
    writeToChatLog("Datachannel connected", "text-success");
    $('#waitForConnection').modal('hide');
    // If we didn't call remove() here, there would be a race on pc2:
    //   - first onconnection() hides the dialog, then someone clicks
    //     on answerSentBtn which shows it, and it stays shown forever.
    $('#waitForConnection').remove();
}

pc1.onconnection = handleOnconnection;

function handleAnswerFromPC2(answerDesc) {
    console.log("Received remote answer: ", answerDesc);
    writeToChatLog("Received remote answer", "text-success");
    pc1.setRemoteDescription(answerDesc);
}

function handleCandidateFromPC2(iceCandidate) {
    pc1.addIceCandidate(iceCandidate);
}

/* THIS IS BOB, THE ANSWERER/RECEIVER */

var pc2 = new RTCPeerConnection(cfg, con),
    dc2 = null;

var pc2icedone = false;

pc2.ondatachannel = function (e) {
    var datachannel = e.channel || e; // Chrome sends event, FF sends raw channel
    console.log("Received datachannel (pc2)", arguments);
    dc2 = datachannel;
    dc2.onmessage = function (e) {
        console.log("Got message (pc2)", e.data);
        writeToChatLog(e.data, "text-success");
    };
};

function handleOfferFromPC1(offerDesc) {
    pc2.setRemoteDescription(offerDesc);
    pc2.createAnswer(function (answerDesc) {
        writeToChatLog("Created local answer", "text-success");
        console.log("Created local answer: ", answerDesc);
        pc2.setLocalDescription(answerDesc);
        $('#localAnswer').html(JSON.stringify(answerDesc));
    }, function () { console.warn("No create answer"); });
}

pc2.onicecandidate = function (e) {
    console.log("ICE candidate (pc2)", e);
    if (e.candidate)
      handleCandidateFromPC2(e.candidate);
};

function handleCandidateFromPC1(iceCandidate) {
    pc2.addIceCandidate(iceCandidate);
}

pc2.onaddstream = function (e) {
    console.log("Got remote stream", e);
    var el = new Audio();
    el.autoplay = true;
    attachMediaStream(el, e.stream);
};

pc2.onconnection = handleOnconnection;
<commit_msg>Show new messages in the textarea<commit_after>/* See also:
    http://www.html5rocks.com/en/tutorials/webrtc/basics/
    https://code.google.com/p/webrtc-samples/source/browse/trunk/apprtc/index.html

    https://webrtc-demos.appspot.com/html/pc1.html
*/

var cfg = {"iceServers":[{"url":"stun:23.21.150.121"}]},
    con = { 'optional': [{'DtlsSrtpKeyAgreement': true}, {'RtpDataChannels': true }] };

// createDataChannel needs `open /Applications/Google\ Chrome\ Canary.app --args --enable-data-channels` :-(

function writeToChatLog(message, message_type) {
    document.getElementById('chatlog').innerHTML += '
' + message + '
';
}

/* THIS IS ALICE, THE CALLER/SENDER */

var pc1 = new RTCPeerConnection(cfg, con),
    dc1 = null, tn1 = null;

// Since the same JS file contains code for both sides of the connection,
// activedb tracks which of the two possible datachannel variables we're using.
var activedc;

var pc1icedone = false;

$('#showLocalOffer').modal('hide');
$('#getRemoteAnswer').modal('hide');
$('#waitForConnection').modal('hide');
$('#createOrJoin').modal('show');

$('#createBtn').click(function() {
    $('#showLocalOffer').modal('show');
});

$('#joinBtn').click(function() {
    $('#getRemoteOffer').modal('show');
});

$('#offerSentBtn').click(function() {
    $('#getRemoteAnswer').modal('show');
});

$('#offerRecdBtn').click(function() {
    var offer = $('#remoteOffer').val();
    var offerDesc = new RTCSessionDescription(JSON.parse(offer));
    console.log("Received remote offer", offerDesc);
    writeToChatLog("Received remote offer", "text-success");
    handleOfferFromPC1(offerDesc);
    $('#showLocalAnswer').modal('show');
});

$('#answerSentBtn').click(function() {
    $('#waitForConnection').modal('show');
});

$('#answerRecdBtn').click(function() {
    var answer = $('#remoteAnswer').val();
    var answerDesc = new RTCSessionDescription(JSON.parse(answer));
    handleAnswerFromPC2(answerDesc);
    $('#waitForConnection').modal('show');
});

$('#sendMessageBtn').click(function() {
    writeToChatLog($('#messageTextBox').val(), "text-success");
    activedc.send($('#messageTextBox').val());
});

function setupDC1() {
    try {
        dc1 = pc1.createDataChannel('test', {reliable:false});
        activedc = dc1;
        console.log("Created datachannel (pc1)");
        dc1.onmessage = function (e) {
            console.log("Got message (pc1)", e.data);
            writeToChatLog(e.data, "text-info");
        };
    } catch (e) { console.warn("No data channel (pc1)", e); }
}

getUserMedia({'audio':true, fake:true}, function (stream) {
    console.log("Got local audio", stream);
    pc1.addStream(stream);
    setupDC1();
    //tn1 = pc1.createDTMFSender(pc1.getLocalStreams()[0].getAudioTracks()[0])
    pc1.createOffer(function (offerDesc) {
        console.log("Created local offer", offerDesc);
        pc1.setLocalDescription(offerDesc);
        $('#localOffer').html(JSON.stringify(offerDesc));
    }, function () { console.warn("Couldn't create offer"); });
}, function () { console.warn("No audio"); });

pc1.onicecandidate = function (e) {
    console.log("ICE candidate (pc1)", e);
    if (e.candidate) {
        //handleCandidateFromPC1(e.candidate)
        if (!pc1icedone) {
            document.localICECandidateForm.localICECandidate.value = JSON.stringify(e.candidate);
            pc1icedone = true;
        }
    }
};

function handleOnconnection() {
    console.log("Datachannel connected");
    writeToChatLog("Datachannel connected", "text-success");
    $('#waitForConnection').modal('hide');
    // If we didn't call remove() here, there would be a race on pc2:
    //   - first onconnection() hides the dialog, then someone clicks
    //     on answerSentBtn which shows it, and it stays shown forever.
    $('#waitForConnection').remove();
}

pc1.onconnection = handleOnconnection;

function handleAnswerFromPC2(answerDesc) {
    console.log("Received remote answer: ", answerDesc);
    writeToChatLog("Received remote answer", "text-success");
    pc1.setRemoteDescription(answerDesc);
}

function handleCandidateFromPC2(iceCandidate) {
    pc1.addIceCandidate(iceCandidate);
}

/* THIS IS BOB, THE ANSWERER/RECEIVER */

var pc2 = new RTCPeerConnection(cfg, con),
    dc2 = null;

var pc2icedone = false;

pc2.ondatachannel = function (e) {
    var datachannel = e.channel || e; // Chrome sends event, FF sends raw channel
    console.log("Received datachannel (pc2)", arguments);
    dc2 = datachannel;
    activedc = dc2;
    dc2.onmessage = function (e) {
        console.log("Got message (pc2)", e.data);
        writeToChatLog(e.data, "text-info");
    };
};

function handleOfferFromPC1(offerDesc) {
    pc2.setRemoteDescription(offerDesc);
    pc2.createAnswer(function (answerDesc) {
        writeToChatLog("Created local answer", "text-success");
        console.log("Created local answer: ", answerDesc);
        pc2.setLocalDescription(answerDesc);
        $('#localAnswer').html(JSON.stringify(answerDesc));
    }, function () { console.warn("No create answer"); });
}

pc2.onicecandidate = function (e) {
    console.log("ICE candidate (pc2)", e);
    if (e.candidate)
      handleCandidateFromPC2(e.candidate);
};

function handleCandidateFromPC1(iceCandidate) {
    pc2.addIceCandidate(iceCandidate);
}

pc2.onaddstream = function (e) {
    console.log("Got remote stream", e);
    var el = new Audio();
    el.autoplay = true;
    attachMediaStream(el, e.stream);
};

pc2.onconnection = handleOnconnection;
<|endoftext|>


<commit_before>myApp.factory('Settings', ['$rootScope', '$cookies', 'localStorageService', function($rootScope, $cookies, localStorageService) {
    var selectedService = '';
    var viewMode = '';
    var firstIssueHighlight = "true";
    var coverQuality = "large";

    if (localStorageService.isSupported) {
        // Selected Service
        if (localStorageService.get('selectedService') === "Marvel" ||
            localStorageService.get('selectedService') === "Comic Vine") {
            selectedService = localStorageService.get('selectedService');
        } else {
            selectedService = 'Marvel';
            localStorageService.set('selectedService', selectedService);
        }

        // View Mode
        if (localStorageService.get('viewMode') === "standard" ||
            localStorageService.get('viewMode') === "compact") {
            viewMode = localStorageService.get('viewMode');
        } else {
            viewMode = 'standard';
            localStorageService.set('viewMode', viewMode);
        }

        // First Issue Highlight
        if (localStorageService.get('firstIssueHighlight')) {
            firstIssueHighlight = localStorageService.get('firstIssueHighlight');
        } else {
            firstIssueHighlight = "true";
            localStorageService.set('firstIssueHighlight', firstIssueHighlight);
        }

        // Cover Quality
        if (localStorageService.get('coverQuality')) {
            coverQuality = localStorageService.get('coverQuality');
        } else {
            coverQuality = "large";
            localStorageService.set('coverQuality', coverQuality);
        }
    } else {
        // Selected Service
        if ($cookies.get('selectedService') === "Marvel" ||
            $cookies.get('selectedService') === "Comic Vine") {
            selectedService = $cookies.get('selectedService');
        } else {
            selectedService = 'Marvel';
            $cookies.put('selectedService', selectedService);
        }

        // View Mode
        if ($cookies.get('viewMode') === "standard" ||
            $cookies.get('viewMode') === "compact") {
            viewMode = $cookies.get('viewMode');
        } else {
            viewMode = 'standard';
            $cookies.put('viewMode', viewMode);
        }

        // First Issue Highlight
        if ($cookies.get('firstIssueHighlight')) {
            firstIssueHighlight = $cookies.get('firstIssueHighlight');
        } else {
            firstIssueHighlight = "true";
            $cookies.put('firstIssueHighlight', firstIssueHighlight);
        }

        // Cover Quality
        if ($cookies.get('coverQuality')) {
            coverQuality = $cookies.get('coverQuality');
        } else {
            coverQuality = "large";
            $cookies.put('coverQuality', coverQuality);
        }
    }

    var myObject = {
        // Selected Service
        getSelectedServicePrefix: function() {
            var selectedServicePrefix = '';
            if (selectedService == 'Marvel') {
                selectedServicePrefix = 'marvel';
            } else if (selectedService == 'Comic Vine') {
                selectedServicePrefix = 'comic-vine';
            }
            return selectedServicePrefix;
        },
        getSelectedService: function() {
            return selectedService;
        },
        setSelectedService: function(service) {
            selectedService = service;
            if (localStorageService.isSupported) {
                localStorageService.set('selectedService', selectedService);
            } else {
                $cookies.put('selectedService', selectedService);
            }
        },
        // View Mode
        getViewMode: function() {
            return viewMode;
        },
        setViewMode: function(mode) {
            viewMode = mode;
            if (localStorageService.isSupported) {
                localStorageService.set('viewMode', viewMode);
            } else {
                $cookies.put('viewMode', viewMode);
            }
        },

        // First Issue Highlight
        getFirstIssueHighlight: function() {
            return firstIssueHighlight;
        },
        setFirstIssueHighlight: function(highlightSetting) {
            firstIssueHighlight = highlightSetting;
            if (localStorageService.isSupported) {
                localStorageService.set('firstIssueHighlight', firstIssueHighlight);
            } else {
                $cookies.put('firstIssueHighlight', firstIssueHighlight);
            }
        },

        // Cover Quality
        getCoverQuality: function() {
            return coverQuality;
        },
        setCoverQuality: function(quality) {
            coverQuality = quality;
            if (localStorageService.isSupported) {
                localStorageService.set('coverQuality', coverQuality);
            } else {
                $cookies.put('coverQuality', coverQuality);
            }
        }
    };
    return myObject;
}]);
<commit_msg>Changing the default data source to Comic Vine<commit_after>myApp.factory('Settings', ['$rootScope', '$cookies', 'localStorageService', function($rootScope, $cookies, localStorageService) {
    var selectedService = '';
    var viewMode = '';
    var firstIssueHighlight = "true";
    var coverQuality = "large";

    if (localStorageService.isSupported) {
        // Selected Service
        if (localStorageService.get('selectedService') === "Marvel" ||
            localStorageService.get('selectedService') === "Comic Vine") {
            selectedService = localStorageService.get('selectedService');
        } else {
            selectedService = 'Comic Vine';
            localStorageService.set('selectedService', selectedService);
        }

        // View Mode
        if (localStorageService.get('viewMode') === "standard" ||
            localStorageService.get('viewMode') === "compact") {
            viewMode = localStorageService.get('viewMode');
        } else {
            viewMode = 'standard';
            localStorageService.set('viewMode', viewMode);
        }

        // First Issue Highlight
        if (localStorageService.get('firstIssueHighlight')) {
            firstIssueHighlight = localStorageService.get('firstIssueHighlight');
        } else {
            firstIssueHighlight = "true";
            localStorageService.set('firstIssueHighlight', firstIssueHighlight);
        }

        // Cover Quality
        if (localStorageService.get('coverQuality')) {
            coverQuality = localStorageService.get('coverQuality');
        } else {
            coverQuality = "large";
            localStorageService.set('coverQuality', coverQuality);
        }
    } else {
        // Selected Service
        if ($cookies.get('selectedService') === "Marvel" ||
            $cookies.get('selectedService') === "Comic Vine") {
            selectedService = $cookies.get('selectedService');
        } else {
            selectedService = 'Comic Vine';
            $cookies.put('selectedService', selectedService);
        }

        // View Mode
        if ($cookies.get('viewMode') === "standard" ||
            $cookies.get('viewMode') === "compact") {
            viewMode = $cookies.get('viewMode');
        } else {
            viewMode = 'standard';
            $cookies.put('viewMode', viewMode);
        }

        // First Issue Highlight
        if ($cookies.get('firstIssueHighlight')) {
            firstIssueHighlight = $cookies.get('firstIssueHighlight');
        } else {
            firstIssueHighlight = "true";
            $cookies.put('firstIssueHighlight', firstIssueHighlight);
        }

        // Cover Quality
        if ($cookies.get('coverQuality')) {
            coverQuality = $cookies.get('coverQuality');
        } else {
            coverQuality = "large";
            $cookies.put('coverQuality', coverQuality);
        }
    }

    var myObject = {
        // Selected Service
        getSelectedServicePrefix: function() {
            var selectedServicePrefix = '';
            if (selectedService == 'Marvel') {
                selectedServicePrefix = 'marvel';
            } else if (selectedService == 'Comic Vine') {
                selectedServicePrefix = 'comic-vine';
            }
            return selectedServicePrefix;
        },
        getSelectedService: function() {
            return selectedService;
        },
        setSelectedService: function(service) {
            selectedService = service;
            if (localStorageService.isSupported) {
                localStorageService.set('selectedService', selectedService);
            } else {
                $cookies.put('selectedService', selectedService);
            }
        },
        // View Mode
        getViewMode: function() {
            return viewMode;
        },
        setViewMode: function(mode) {
            viewMode = mode;
            if (localStorageService.isSupported) {
                localStorageService.set('viewMode', viewMode);
            } else {
                $cookies.put('viewMode', viewMode);
            }
        },

        // First Issue Highlight
        getFirstIssueHighlight: function() {
            return firstIssueHighlight;
        },
        setFirstIssueHighlight: function(highlightSetting) {
            firstIssueHighlight = highlightSetting;
            if (localStorageService.isSupported) {
                localStorageService.set('firstIssueHighlight', firstIssueHighlight);
            } else {
                $cookies.put('firstIssueHighlight', firstIssueHighlight);
            }
        },

        // Cover Quality
        getCoverQuality: function() {
            return coverQuality;
        },
        setCoverQuality: function(quality) {
            coverQuality = quality;
            if (localStorageService.isSupported) {
                localStorageService.set('coverQuality', coverQuality);
            } else {
                $cookies.put('coverQuality', coverQuality);
            }
        }
    };
    return myObject;
}]);
<|endoftext|>


<commit_before>/**
* correlation coefficients plotting using d3
* Isaak Y Tecle <iyt2@cornell.edu>
*
*/

jQuery(document).ready( function () {
    var page = document.URL;

    if (page.match(/solgs\/traits\/all\//) != null) {
        //genetic correlation
        listAllCorrePopulations();

    } else {
        phenotypicCorrelation();
    }
});

function listAllCorrePopulations ()  {
    var modelData = getTrainingPopulationData();

    var trainingPopIdName = JSON.stringify(modelData);

    var  popsList =  '
'
        + '
 Choose a population
'
        + '
'
        + '
'
        + '
'
        + '' + modelData.name + '' + trainingPopIdName + ''
        + '
';

    popsList += '

';

    jQuery("#corre_select_a_population_div").empty().append(popsList).show();

    var dbSelPopsList;
    if( modelData.id.match(/uploaded/) == null) {
        dbSelPopsList = addSelectionPopulations();
    }

    if (dbSelPopsList) {
            jQuery("#corre_select_a_population_div ul").append(dbSelPopsList);
    }

    var userUploadedSelExists = jQuery("#uploaded_selection_pops_table").doesExist();
    if( userUploadedSelExists == true) {

        var userSelPops = listUploadedSelPopulations();
        if (userSelPops) {

            jQuery("#corre_select_a_population_div ul").append(userSelPops);
        }
    }

    //getSelectionPopTraits(modelData.id, modelData.id);

   jQuery(".corre_dropdown dt a").click(function() {
            jQuery(".corre_dropdown dd ul").toggle();
        });

    jQuery(".corre_dropdown dd ul li a").click(function() {

        var text = jQuery(this).html();

        jQuery(".corre_dropdown dt a span").html(text);
        jQuery(".corre_dropdown dd ul").hide();

        var idPopName = jQuery("#corre_selected_population").find("dt a span.value").html();
        idPopName     = JSON.parse(idPopName);
        modelId = jQuery("#model_id").val();

        selectedPopId   = idPopName.id;
        selectedPopName = idPopName.name;
        selectedPopType = idPopName.pop_type;
        //alert('pop_type: ' + selectedPopType);

        jQuery("#corre_selected_population_name").val(selectedPopName);
        jQuery("#corre_selected_population_id").val(selectedPopId);
        jQuery("#corre_selected_population_type").val(selectedPopType);

         //   getSelectionPopTraits(modelId, selectedPopId);

    });

    jQuery(".corre_dropdown").bind('click', function(e) {
        var clicked = jQuery(e.target);

        if (! clicked.parents().hasClass("corre_dropdown"))
            jQuery(".corre_dropdown dd ul").hide();

        e.preventDefault();

    });
}

function formatGenCorInputData (popId) {

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        data: {'type': type, 'population_id': popId },
        url: '/correlation/genetic/data/',
        success: function(response) {
                if(response.status == 'success') {
                    runCorrelationAnalysis();
                } else {
                    jQuery("#correlation_message")
                        .css({"padding-left": '0px'})
                        .html("This population has no additive genetic data.");
                }
            },
            error: function(response) {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("Error occured preparing the additive genetic data for correlation analysis.");
            }
    });
}

function getPopulationDetails () {

    var populationId = jQuery("#population_id").val();
    var populationName = jQuery("#population_name").val();

    if(populationId == 'undefined' ) {
        populationId = jQuery("#model_id").val();
        populationName = jQuery("#model_name").val();
    }

    return {'population_id' : populationId,
            'population_name' : populationName
            };

}

function phenotypicCorrelation () {

    var population = getPopulationDetails();

    jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            data: {'population_id': population.population_id },
            url: '/correlation/phenotype/data/',
            success: function(response) {
                if(response.status == 'success') {
                    runCorrelationAnalysis();
                } else {
                    jQuery("#correlation_message")
                        .css({"padding-left": '0px'})
                        .html("This population has no phenotype data.");
                }
            },
            error: function(response) {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("Error occured preparing the phenotype data for correlation analysis.");
            }
    });

}

function runCorrelationAnalysis () {
    var population = getPopulationDetails();

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        data: {'population_id': population.population_id },
        url: '/correlation/analysis/output',
        success: function(response) {
            if (response.status == 'success') {
                plotCorrelation(response.data);
                jQuery("#correlation_message").empty();
            } else {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("There is no correlation output for this dataset.");
            }
        },
        error: function(response) {
            jQuery("#correlation_message")
                .css({"padding-left": '0px'})
                .html("Error occured running the correlation analysis.");
        }
    });

}

function plotCorrelation (data) {

    data = data.replace(/\s/g, '');
    data = data.replace(/\\/g, '');
    data = data.replace(/^\"/, '');
    data = data.replace(/\"$/, '');
    data = data.replace(/\"NA\"/g, 100);

    data = JSON.parse(data);

    var height = 400;
    var width  = 400;
    var pad    = {left:70, top:20, right:100, bottom: 70};
    var totalH = height + pad.top + pad.bottom;
    var totalW = width + pad.left + pad.right;

    var nTraits = data.traits.length;
    var corXscale = d3.scale.ordinal().domain(d3.range(nTraits)).rangeBands([0, width]);
    var corYscale = d3.scale.ordinal().domain(d3.range(nTraits)).rangeBands([height, 0]);
    var corZscale = d3.scale.linear().domain([-1, 0, 1]).range(["#A52A2A","white", "#0000A0"]);

    var xAxisScale = d3.scale.ordinal()
        .domain(data.traits)
        .rangeBands([0, width]);

    var yAxisScale = d3.scale.ordinal()
        .domain(data.traits)
        .rangeRoundBands([height, 0]);

    var svg = d3.select("#correlation_canvas")
        .append("svg")
        .attr("height", totalH)
        .attr("width", totalW);

    var xAxis = d3.svg.axis()
        .scale(xAxisScale)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(yAxisScale)
        .orient("left");

    var corrplot = svg.append("g")
        .attr("id", "correlation_plot")
        .attr("transform", "translate(" + pad.left + "," + pad.top + ")");

    corrplot.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height +")")
        .call(xAxis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", 10)
        .attr("dy", ".1em")
        .attr("transform", "rotate(90)")
        .attr("fill", "purple")
        .style({"text-anchor":"start", "fill": "purple"});

    corrplot.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate(0,0)")
        .call(yAxis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", -10)
        .attr("dy", ".1em")
        .attr("fill", "purple")
        .style("fill", "purple");

    var corr = [];
    var coefs = [];
    for (var i=0; i<data.coefficients.length; i++) {
        for  (var j=0;  j<data.coefficients[i].length; j++) {
            corr.push({"row":i, "col":j, "value": data.coefficients[i][j]});

            if(data.coefficients[i][j] != 100) {
                coefs.push(data.coefficients[i][j]);
            }
        }
    }

    var cell = corrplot.selectAll("rect")
        .data(corr)
        .enter().append("rect")
        .attr("class", "cell")
        .attr("x", function (d) { return corXscale(d.col)})
        .attr("y", function (d) { return corYscale(d.row)})
        .attr("width", corXscale.rangeBand())
        .attr("height", corYscale.rangeBand())
        .attr("fill", function (d) {
                if (d.value === 100) {return "white";}
                else {return corZscale(d.value)}
            })
        .attr("stroke", "none")
        .attr("stroke-width", 2)
        .on("mouseover", function (d) {
                if(d.value != 100) {
                    d3.select(this)
                        .attr("stroke", "green")
                    corrplot.append("text")
                        .attr("id", "corrtext")
                        .text("[" + data.traits[d.row]
                              + " vs. " + data.traits[d.col]
                              + ": " + d3.format(".2f")(d.value)
                              + "]")
                        .style("fill", "purple")
                        .attr("x", totalW * 0.5)
                        .attr("y", totalH * 0.5)
                        .attr("font-weight", "bold")
                        .attr("dominant-baseline", "middle")
                        .attr("text-anchor", "middle")
                }
        })
        .on("mouseout", function() {
                d3.selectAll("text.corrlabel").remove()
                d3.selectAll("text#corrtext").remove()
                d3.select(this).attr("stroke","none")
            });

    corrplot.append("rect")
        .attr("height", height)
        .attr("width", width)
        .attr("fill", "none")
        .attr("stroke", "purple")
        .attr("stroke-width", 1)
        .attr("pointer-events", "none");

    var legendValues = [[1,d3.min(coefs)], [2,0], [3,d3.max(coefs)]];

    var legend = corrplot.append("g")
        .attr("class", "cell")
        .attr("transform", "translate(" + (width + 10) + "," +  (height * 0.4) + ")")
        .attr("height", 100)
        .attr("width", 100);

    legend = legend.selectAll("rect")
        .data(legendValues)
        .enter()
        .append("rect")
        .attr("x", function (d) { return 1;})
        .attr("y",  function (d) { return corXscale(d[0])})
        .attr("width", 20)
        .attr("height", 20)
        .attr("fill", function (d) {
            if (d === 100) {return "white"}
            else {return corZscale(d[1])}
        });

    var legendTxt = corrplot.append("g")
        .attr("transform", "translate(" + (width + 40) + "," + ((height * 0.4) + 10) + ")")
        .attr("id", "legendtext");

    legendTxt.selectAll("text")
        .data(legendValues)
        .enter()
        .append("text")
        .attr("fill", "green")
        .style("fill", "green")
        .attr("x", 1)
        .attr("y", function (d) { return corXscale(d[0])})
        .text(function(d) {
              if (d[1] > 0) { return "Positive";}
              else if (d[1] < 0) { return "Negative";}
              else { return "Neutral";}
        })
        .attr("dominant-baseline", "middle")
        .attr("text-anchor", "start");

}

<commit_msg>prepare input data for genetic correlation analysis..<commit_after>/**
* correlation coefficients plotting using d3
* Isaak Y Tecle <iyt2@cornell.edu>
*
*/

jQuery(document).ready( function () {
    var page = document.URL;

    if (page.match(/solgs\/traits\/all\//) != null) {
        //genetic correlation
        listAllCorrePopulations();

    } else {
        phenotypicCorrelation();
    }
});

jQuery("#run_genetic_correlation").live("click", function() {
    var popId   = jQuery("#corre_selected_population_id").val();
    var popType = jQuery("#corre_selected_population_type").val();

    jQuery("#correlation_message")
        .css({"padding-left": '0px'})
        .html("Running genetic correlation analysis...");

    formatGenCorInputData(popId, popType);

});

function listAllCorrePopulations ()  {
    var modelData = getTrainingPopulationData();

    var trainingPopIdName = JSON.stringify(modelData);

    var  popsList =  '
'
        + '
 Choose a population
'
        + '
'
        + '
'
        + '
'
        + '' + modelData.name + '' + trainingPopIdName + ''
        + '
';

    popsList += '

';

    jQuery("#corre_select_a_population_div").empty().append(popsList).show();

    var dbSelPopsList;
    if( modelData.id.match(/uploaded/) == null) {
        dbSelPopsList = addSelectionPopulations();
    }

    if (dbSelPopsList) {
            jQuery("#corre_select_a_population_div ul").append(dbSelPopsList);
    }

    var userUploadedSelExists = jQuery("#uploaded_selection_pops_table").doesExist();
    if( userUploadedSelExists == true) {

        var userSelPops = listUploadedSelPopulations();
        if (userSelPops) {

            jQuery("#corre_select_a_population_div ul").append(userSelPops);
        }
    }

    //getSelectionPopTraits(modelData.id, modelData.id);

   jQuery(".corre_dropdown dt a").click(function() {
            jQuery(".corre_dropdown dd ul").toggle();
        });

    jQuery(".corre_dropdown dd ul li a").click(function() {

        var text = jQuery(this).html();

        jQuery(".corre_dropdown dt a span").html(text);
        jQuery(".corre_dropdown dd ul").hide();

        var idPopName = jQuery("#corre_selected_population").find("dt a span.value").html();
        idPopName     = JSON.parse(idPopName);
        modelId = jQuery("#model_id").val();

        selectedPopId   = idPopName.id;
        selectedPopName = idPopName.name;
        selectedPopType = idPopName.pop_type;
        //alert('pop_type: ' + selectedPopType);

        jQuery("#corre_selected_population_name").val(selectedPopName);
        jQuery("#corre_selected_population_id").val(selectedPopId);
        jQuery("#corre_selected_population_type").val(selectedPopType);

         //   getSelectionPopTraits(modelId, selectedPopId);

    });

    jQuery(".corre_dropdown").bind('click', function(e) {
        var clicked = jQuery(e.target);

        if (! clicked.parents().hasClass("corre_dropdown"))
            jQuery(".corre_dropdown dd ul").hide();

        e.preventDefault();

    });
}

function formatGenCorInputData (popId, type) {

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        data: {'type': type, 'population_id': popId },
        url: '/correlation/genetic/data/',
        success: function(response) {
                if(response.status == 'success') {
                    runCorrelationAnalysis();
                } else {
                    jQuery("#correlation_message")
                        .css({"padding-left": '0px'})
                        .html("This population has no additive genetic data.");
                }
            },
            error: function(response) {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("Error occured preparing the additive genetic data for correlation analysis.");
            }
    });
}

function getPopulationDetails () {

    var populationId = jQuery("#population_id").val();
    var populationName = jQuery("#population_name").val();

    if(populationId == 'undefined' ) {
        populationId = jQuery("#model_id").val();
        populationName = jQuery("#model_name").val();
    }

    return {'population_id' : populationId,
            'population_name' : populationName
            };

}

function phenotypicCorrelation () {

    var population = getPopulationDetails();

    jQuery.ajax({
            type: 'POST',
            dataType: 'json',
            data: {'population_id': population.population_id },
            url: '/correlation/phenotype/data/',
            success: function(response) {
                if(response.status == 'success') {
                    runCorrelationAnalysis();
                } else {
                    jQuery("#correlation_message")
                        .css({"padding-left": '0px'})
                        .html("This population has no phenotype data.");
                }
            },
            error: function(response) {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("Error occured preparing the phenotype data for correlation analysis.");
            }
    });

}

function runCorrelationAnalysis () {
    var population = getPopulationDetails();

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        data: {'population_id': population.population_id },
        url: '/correlation/analysis/output',
        success: function(response) {
            if (response.status == 'success') {
                plotCorrelation(response.data);
                jQuery("#correlation_message").empty();
            } else {
                jQuery("#correlation_message")
                    .css({"padding-left": '0px'})
                    .html("There is no correlation output for this dataset.");
            }
        },
        error: function(response) {
            jQuery("#correlation_message")
                .css({"padding-left": '0px'})
                .html("Error occured running the correlation analysis.");
        }
    });

}

function plotCorrelation (data) {

    data = data.replace(/\s/g, '');
    data = data.replace(/\\/g, '');
    data = data.replace(/^\"/, '');
    data = data.replace(/\"$/, '');
    data = data.replace(/\"NA\"/g, 100);

    data = JSON.parse(data);

    var height = 400;
    var width  = 400;
    var pad    = {left:70, top:20, right:100, bottom: 70};
    var totalH = height + pad.top + pad.bottom;
    var totalW = width + pad.left + pad.right;

    var nTraits = data.traits.length;
    var corXscale = d3.scale.ordinal().domain(d3.range(nTraits)).rangeBands([0, width]);
    var corYscale = d3.scale.ordinal().domain(d3.range(nTraits)).rangeBands([height, 0]);
    var corZscale = d3.scale.linear().domain([-1, 0, 1]).range(["#A52A2A","white", "#0000A0"]);

    var xAxisScale = d3.scale.ordinal()
        .domain(data.traits)
        .rangeBands([0, width]);

    var yAxisScale = d3.scale.ordinal()
        .domain(data.traits)
        .rangeRoundBands([height, 0]);

    var svg = d3.select("#correlation_canvas")
        .append("svg")
        .attr("height", totalH)
        .attr("width", totalW);

    var xAxis = d3.svg.axis()
        .scale(xAxisScale)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(yAxisScale)
        .orient("left");

    var corrplot = svg.append("g")
        .attr("id", "correlation_plot")
        .attr("transform", "translate(" + pad.left + "," + pad.top + ")");

    corrplot.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height +")")
        .call(xAxis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", 10)
        .attr("dy", ".1em")
        .attr("transform", "rotate(90)")
        .attr("fill", "purple")
        .style({"text-anchor":"start", "fill": "purple"});

    corrplot.append("g")
        .attr("class", "y axis")
        .attr("transform", "translate(0,0)")
        .call(yAxis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", -10)
        .attr("dy", ".1em")
        .attr("fill", "purple")
        .style("fill", "purple");

    var corr = [];
    var coefs = [];
    for (var i=0; i<data.coefficients.length; i++) {
        for  (var j=0;  j<data.coefficients[i].length; j++) {
            corr.push({"row":i, "col":j, "value": data.coefficients[i][j]});

            if(data.coefficients[i][j] != 100) {
                coefs.push(data.coefficients[i][j]);
            }
        }
    }

    var cell = corrplot.selectAll("rect")
        .data(corr)
        .enter().append("rect")
        .attr("class", "cell")
        .attr("x", function (d) { return corXscale(d.col)})
        .attr("y", function (d) { return corYscale(d.row)})
        .attr("width", corXscale.rangeBand())
        .attr("height", corYscale.rangeBand())
        .attr("fill", function (d) {
                if (d.value === 100) {return "white";}
                else {return corZscale(d.value)}
            })
        .attr("stroke", "none")
        .attr("stroke-width", 2)
        .on("mouseover", function (d) {
                if(d.value != 100) {
                    d3.select(this)
                        .attr("stroke", "green")
                    corrplot.append("text")
                        .attr("id", "corrtext")
                        .text("[" + data.traits[d.row]
                              + " vs. " + data.traits[d.col]
                              + ": " + d3.format(".2f")(d.value)
                              + "]")
                        .style("fill", "purple")
                        .attr("x", totalW * 0.5)
                        .attr("y", totalH * 0.5)
                        .attr("font-weight", "bold")
                        .attr("dominant-baseline", "middle")
                        .attr("text-anchor", "middle")
                }
        })
        .on("mouseout", function() {
                d3.selectAll("text.corrlabel").remove()
                d3.selectAll("text#corrtext").remove()
                d3.select(this).attr("stroke","none")
            });

    corrplot.append("rect")
        .attr("height", height)
        .attr("width", width)
        .attr("fill", "none")
        .attr("stroke", "purple")
        .attr("stroke-width", 1)
        .attr("pointer-events", "none");

    var legendValues = [[1,d3.min(coefs)], [2,0], [3,d3.max(coefs)]];

    var legend = corrplot.append("g")
        .attr("class", "cell")
        .attr("transform", "translate(" + (width + 10) + "," +  (height * 0.4) + ")")
        .attr("height", 100)
        .attr("width", 100);

    legend = legend.selectAll("rect")
        .data(legendValues)
        .enter()
        .append("rect")
        .attr("x", function (d) { return 1;})
        .attr("y",  function (d) { return corXscale(d[0])})
        .attr("width", 20)
        .attr("height", 20)
        .attr("fill", function (d) {
            if (d === 100) {return "white"}
            else {return corZscale(d[1])}
        });

    var legendTxt = corrplot.append("g")
        .attr("transform", "translate(" + (width + 40) + "," + ((height * 0.4) + 10) + ")")
        .attr("id", "legendtext");

    legendTxt.selectAll("text")
        .data(legendValues)
        .enter()
        .append("text")
        .attr("fill", "green")
        .style("fill", "green")
        .attr("x", 1)
        .attr("y", function (d) { return corXscale(d[0])})
        .text(function(d) {
              if (d[1] > 0) { return "Positive";}
              else if (d[1] < 0) { return "Negative";}
              else { return "Neutral";}
        })
        .attr("dominant-baseline", "middle")
        .attr("text-anchor", "start");

}

<|endoftext|>


<commit_before>(function () {
    'use strict';

    // globals
    var bloodsVelociy = -200;
    var obstaclesVelociy = -200;
    var gameVelocity = 1;

    var GameState = function() {
        // load sprites here
        this.player              = gameManager.getSprite('player');
        this.backgroundOne       = gameManager.getSprite('backgroundOne');
        this.backgroundTwo       = gameManager.getSprite('backgroundTwo');
        this.backgroundThree     = gameManager.getSprite('backgroundThree');
        this.backgroundFour      = gameManager.getSprite('backgroundFour');
        this.ground              = gameManager.getSprite('ground');
        this.transparentGround   = gameManager.getSprite('transparentGround');
        this.wallLeft            = gameManager.getSprite('wallLeft');
    }

    GameState.prototype.preload = function() {
        // player
        this.player.preload();

        // parallax
        this.backgroundOne.preload();
        this.backgroundTwo.preload();
        this.backgroundThree.preload();
        this.backgroundFour.preload();
        this.ground.preload();

        // wall horizontal
        this.game.load.image('wall', 'assets/img/wallHorizontal.png');

        // blood
        this.game.load.audio('jumpSound', 'assets/audio/jump.ogg');
        this.game.load.image('blood', 'assets/img/blood.png');
        this.game.load.audio('bloodSound', 'assets/audio/blood.ogg');

        // obstacles
        this.game.load.image('obstacle', 'assets/img/obstaculo.png');

    }

    GameState.prototype.create = function() {

        // sound
        this.game.sound.stopAll();
        this.jumpSound = this.game.add.audio('jumpSound');
        this.bloodSound = this.game.add.audio('bloodSound');

        // activate physics system
        this.game.physics.startSystem(Phaser.Physics.ARCADE);
        this.game.stage.backgroundColor = '#53078e';

        // parallax
        this.backgroundFour.setup();
        this.backgroundThree.setup();
        this.backgroundTwo.setup();
        this.backgroundOne.setup();

        // ground sprite
        this.ground.setup();

        // transparent ground platform
        // this one is where the player collides
        this.transparentGround.setup('wall');

        // wall left
        // use this to kill objects outside the screen
        this.wallLeft.setup('wall');

        // setup initial player properties
        this.player.setup();

        // blood group
        this.bloods = this.game.add.group();
        this.bloods.enableBody = true;
        this.game.time.events.loop(Phaser.Timer.SECOND, createBloods, this);

        // obstacles
        this.obstacles = this.game.add.group();
        this.obstacles.enableBody = true;
        this.game.time.events.loop(this.game.rnd.integerInRange(1500, 2000), createObstacles, this);

        // handle all inputs
        handleInputs.apply(this);
    }

    GameState.prototype.update = function() {
        updateParallaxes.apply(this);
        handleColliders.apply(this);
    }

    GameState.prototype.render = function() {
        this.game.debug.inputInfo(32, 32);
    }

    // collision checkers
    function handleColliders() {
        this.game.physics.arcade.collide(this.player.sprite, this.transparentGround.sprite, this.player.groundCollision, null, this.player);
        this.game.physics.arcade.overlap(this.player.sprite, this.bloods, this.player.bloodCollision, null, this);

        // obstacles collision
        this.game.physics.arcade.overlap(this.player.sprite, this.obstacles, platformCollision, null, this);
    }

    function platformCollision(player, platform){
        this.game.state.start("lose");
    }

    function handleInputs() {
        // mouse click or touch
        this.game.input.onDown.add(this.player.jump, this.player);
    }

    function updateParallaxes() {
        this.backgroundOne.sprite.tilePosition.x -= 0.85;
        this.backgroundTwo.sprite.tilePosition.x -= 0.60;
        this.backgroundThree.sprite.tilePosition.x -= 0.10;
        this.backgroundFour.sprite.tilePosition.x -= 0.05;
        this.ground.sprite.tilePosition.x -= 3;
    }

    function createBloods() {
        var blood = this.bloods.create(this.game.world.width, this.game.rnd.integerInRange(135, 410), 'blood');
        blood.body.velocity.x = bloodsVelociy;
        blood.body.immovable = true;
        blood.checkWorldBounds = true;
        blood.outOfBoundsKill = true;
    }

    function createObstacles() {
        var obstacle = this.obstacles.create(this.game.world.width, 530, 'obstacle');
        obstacle.scale.setTo(0.2, 0.2);
        obstacle.body.velocity.x = obstaclesVelociy;
        obstacle.body.immovable = true;
        obstacle.checkWorldBounds = true;
        obstacle.outOfBoundsKill = true;
    }

    gameManager.addState('game', GameState);

})();<commit_msg>Remove logs de debug do mouse<commit_after>(function () {
    'use strict';

    // globals
    var bloodsVelociy = -200;
    var obstaclesVelociy = -200;
    var gameVelocity = 1;

    var GameState = function() {
        // load sprites here
        this.player              = gameManager.getSprite('player');
        this.backgroundOne       = gameManager.getSprite('backgroundOne');
        this.backgroundTwo       = gameManager.getSprite('backgroundTwo');
        this.backgroundThree     = gameManager.getSprite('backgroundThree');
        this.backgroundFour      = gameManager.getSprite('backgroundFour');
        this.ground              = gameManager.getSprite('ground');
        this.transparentGround   = gameManager.getSprite('transparentGround');
        this.wallLeft            = gameManager.getSprite('wallLeft');
    }

    GameState.prototype.preload = function() {
        // player
        this.player.preload();

        // parallax
        this.backgroundOne.preload();
        this.backgroundTwo.preload();
        this.backgroundThree.preload();
        this.backgroundFour.preload();
        this.ground.preload();

        // wall horizontal
        this.game.load.image('wall', 'assets/img/wallHorizontal.png');

        // blood
        this.game.load.audio('jumpSound', 'assets/audio/jump.ogg');
        this.game.load.image('blood', 'assets/img/blood.png');
        this.game.load.audio('bloodSound', 'assets/audio/blood.ogg');

        // obstacles
        this.game.load.image('obstacle', 'assets/img/obstaculo.png');

    }

    GameState.prototype.create = function() {

        // sound
        this.game.sound.stopAll();
        this.jumpSound = this.game.add.audio('jumpSound');
        this.bloodSound = this.game.add.audio('bloodSound');

        // activate physics system
        this.game.physics.startSystem(Phaser.Physics.ARCADE);
        this.game.stage.backgroundColor = '#53078e';

        // parallax
        this.backgroundFour.setup();
        this.backgroundThree.setup();
        this.backgroundTwo.setup();
        this.backgroundOne.setup();

        // ground sprite
        this.ground.setup();

        // transparent ground platform
        // this one is where the player collides
        this.transparentGround.setup('wall');

        // wall left
        // use this to kill objects outside the screen
        this.wallLeft.setup('wall');

        // setup initial player properties
        this.player.setup();

        // blood group
        this.bloods = this.game.add.group();
        this.bloods.enableBody = true;
        this.game.time.events.loop(Phaser.Timer.SECOND, createBloods, this);

        // obstacles
        this.obstacles = this.game.add.group();
        this.obstacles.enableBody = true;
        this.game.time.events.loop(this.game.rnd.integerInRange(1500, 2000), createObstacles, this);

        // handle all inputs
        handleInputs.apply(this);
    }

    GameState.prototype.update = function() {
        updateParallaxes.apply(this);
        handleColliders.apply(this);
    }

    GameState.prototype.render = function() {
        // this.game.debug.inputInfo(32, 32);
    }

    // collision checkers
    function handleColliders() {
        this.game.physics.arcade.collide(this.player.sprite, this.transparentGround.sprite, this.player.groundCollision, null, this.player);
        this.game.physics.arcade.overlap(this.player.sprite, this.bloods, this.player.bloodCollision, null, this);

        // obstacles collision
        this.game.physics.arcade.overlap(this.player.sprite, this.obstacles, platformCollision, null, this);
    }

    function platformCollision(player, platform){
        this.game.state.start("lose");
    }

    function handleInputs() {
        // mouse click or touch
        this.game.input.onDown.add(this.player.jump, this.player);
    }

    function updateParallaxes() {
        this.backgroundOne.sprite.tilePosition.x -= 0.85;
        this.backgroundTwo.sprite.tilePosition.x -= 0.60;
        this.backgroundThree.sprite.tilePosition.x -= 0.10;
        this.backgroundFour.sprite.tilePosition.x -= 0.05;
        this.ground.sprite.tilePosition.x -= 3;
    }

    function createBloods() {
        var blood = this.bloods.create(this.game.world.width, this.game.rnd.integerInRange(135, 410), 'blood');
        blood.body.velocity.x = bloodsVelociy;
        blood.body.immovable = true;
        blood.checkWorldBounds = true;
        blood.outOfBoundsKill = true;
    }

    function createObstacles() {
        var obstacle = this.obstacles.create(this.game.world.width, 530, 'obstacle');
        obstacle.scale.setTo(0.2, 0.2);
        obstacle.body.velocity.x = obstaclesVelociy;
        obstacle.body.immovable = true;
        obstacle.checkWorldBounds = true;
        obstacle.outOfBoundsKill = true;
    }

    gameManager.addState('game', GameState);

})();<|endoftext|>


<commit_before>(function () {
  var providers = {};

  L.TileLayer.Provider = L.TileLayer.extend({
    initialize: function (arg, options) {
      var parts = arg.split('.');

      var providerName = parts[0];
      var variantName = parts[1];

      if (!providers[providerName]) {
        throw "No such provider (" + providerName + ")";
      }

      var provider = {
        url: providers[providerName].url,
        options: providers[providerName].options
      };

      // overwrite values in provider from variant.
      if (variantName && 'variants' in providers[providerName]) {
        if (!(variantName in providers[providerName].variants)) {
          throw "No such name in provider (" + variantName + ")";
        }
        var variant = providers[providerName].variants[variantName];
        provider = {
          url: variant.url || provider.url,
          options: L.Util.extend({}, provider.options, variant.options)
        };
      } else if (typeof provider.url === 'function') {
        provider.url = provider.url(parts.splice(1).join('.'));
      }

      // replace attribution placeholders with their values from toplevel provider attribution.
      var attribution = provider.options.attribution;
      if (attribution.indexOf('{attribution.') != -1) {
        provider.options.attribution = attribution.replace(/\{attribution.(\w*)\}/,
          function(match, attributionName){
            return providers[attributionName].options.attribution;
          });
      }
      // Compute final options combining provider options with any user overrides
      var layer_opts = L.Util.extend({}, provider.options, options);
      L.TileLayer.prototype.initialize.call(this, provider.url, layer_opts);
    }
  });

  /**
   * Definition of providers.
   * see http://leafletjs.com/reference.html#tilelayer for options in the options map.
   */
  providers = {
    OpenStreetMap: {
      url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
      options: {
        attribution: '© OpenStreetMap contributors, CC-BY-SA'
      },
      variants: {
        Mapnik: {},
        BlackAndWhite: {
          url: 'http://{s}.www.toolserver.org/tiles/bw-mapnik/{z}/{x}/{y}.png'
        },
        DE: {
          url: 'http://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png'
        }
      }
    },
    OpenCycleMap: {
      url: 'http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png',
      options: {
        attribution: '© OpenCycleMap, OpenStreetMap contributors, CC-BY-SA'
      }
    },
    Thunderforest: {
      url: 'http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png',
      options: {
        attribution: '{attribution.OpenCycleMap}'
      },
      variants: {
        OpenCycleMap: {},
        Transport: {
          url: 'http://{s}.tile2.opencyclemap.org/transport/{z}/{x}/{y}.png'
        },
        Landscape: {
          url: 'http://{s}.tile3.opencyclemap.org/landscape/{z}/{x}/{y}.png'
        }
      }
    },
    MapQuestOpen: {
      url: 'http://otile{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png',
      options: {
        attribution: 'Tiles Courtesy of MapQuest — Map data {attribution.OpenStreetMap}',
        subdomains: '1234'
      },
      variants: {
        OSM: {},
        Aerial:{
          url: 'http://oatile{s}.mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg',
          options: {
            attribution:
              'Tiles Courtesy of MapQuest — ' +
              'Portions Courtesy NASA/JPL-Caltech and U.S. Depart. of Agriculture, Farm Service Agency'
          }
        }
      }
    },
    MapBox: {
      url: function(id) {
        return 'http://{s}.tiles.mapbox.com/v3/' + id + '/{z}/{x}/{y}.png';
      },
      options: {
        attribution: 'Imagery from MapBox — Map data {attribution.OpenStreetMap}',
        subdomains: 'abcd'
      }
    },
    Stamen: {
      url: 'http://{s}.tile.stamen.com/toner/{z}/{x}/{y}.png',
      options: {
        attribution:
          'Map tiles by Stamen Design, CC BY 3.0 — ' +
          'Map data {attribution.OpenStreetMap}',
        subdomains: 'abcd',
        minZoom: 0,
        maxZoom: 20
      },
      variants: {
        Toner: {},
        TonerBackground: {
          url: 'http://{s}.tile.stamen.com/toner-background/{z}/{x}/{y}.png'
        },
        TonerHybrid: {
          url: 'http://{s}.tile.stamen.com/toner-hybrid/{z}/{x}/{y}.png'
        },
        TonerLines: {
          url: 'http://{s}.tile.stamen.com/toner-lines/{z}/{x}/{y}.png'
        },
        TonerLabels: {
          url: 'http://{s}.tile.stamen.com/toner-labels/{z}/{x}/{y}.png'
        },
        TonerLite: {
          url: 'http://{s}.tile.stamen.com/toner-lite/{z}/{x}/{y}.png'
        },
        Terrain: {
          url: 'http://{s}.tile.stamen.com/terrain/{z}/{x}/{y}.png',
          options: {
            minZoom: 4,
            maxZoom: 18
          }
        },
        Watercolor: {
          url: 'http://{s}.tile.stamen.com/watercolor/{z}/{x}/{y}.png',
          options: {
            minZoom: 3,
            maxZoom: 16
          }
        }
      }
    },
    Esri: {
      url: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}',
      options: {
        attribution: 'Tiles © Esri'
      },
      variants: {
        WorldStreetMap: {
          options: {
            attribution: '{attribution.Esri} — Source: Esri, DeLorme, NAVTEQ, USGS, Intermap, iPC, NRCAN, Esri Japan, METI, Esri China (Hong Kong), Esri (Thailand), TomTom, 2012'
          }
        },
        DeLorme: {
          url: 'http://server.arcgisonline.com/ArcGIS/rest/services/Specialty/DeLorme_World_Base_Map/MapServer/tile/{z}/{y}/{x}',
          options: {
            maxZoom: 11,
            attribution: '{attribution.Esri} — Copyright: ©2012 DeLorme'
          }
        },
        WorldTopoMap: {
          url: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}',
          options: {
            attribution: '{attribution.Esri} — Esri, DeLorme, NAVTEQ, TomTom, Intermap, iPC, USGS, FAO, NPS, NRCAN, GeoBase, Kadaster NL, Ordnance Survey, Esri Japan, METI, Esri China (Hong Kong), and the GIS User Community'
          }
        },
        WorldImagery: {
          url: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
          options: {
            attribution: '{attribution.Esri} — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
          }
        },
        WorldTerrain: {
          url: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Terrain_Base/MapServer/tile/{z}/{y}/{x}',
          options: {
            attribution: '{attribution.Esri} — Source: USGS, Esri, TANA, DeLorme, and NPS'
          }
        },
        WorldShadedRelief: {
          url: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile/{z}/{y}/{x}',
          options: {
            attribution: '{attribution.Esri} — Source: Esri'
          }
        },
        WorldPhysical: {
          url: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Physical_Map/MapServer/tile/{z}/{y}/{x}',
          options: {
            attribution: '{attribution.Esri} — Source: US National Park Service'
          }
        },
        OceanBasemap: {
          url: 'http://services.arcgisonline.com/ArcGIS/rest/services/Ocean_Basemap/MapServer/tile/{z}/{y}/{x}',
          options: {
            maxZoom: 11,
            attribution: '{attribution.Esri} — Sources: GEBCO, NOAA, CHS, OSU, UNH, CSUMB, National Geographic, DeLorme, NAVTEQ, and Esri'
          }
        },
        NatGeoWorldMap: {
          url: 'http://services.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer/tile/{z}/{y}/{x}',
          options: {
            attribution: '{attribution.Esri} — National Geographic, Esri, DeLorme, NAVTEQ, UNEP-WCMC, USGS, NASA, ESA, METI, NRCAN, GEBCO, NOAA, iPC'
          }
        },
        WorldGrayCanvas: {
          url: 'http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}',
          options: {
            attribution: '{attribution.Esri} — Esri, DeLorme, NAVTEQ'
          }
        }
      }
    },
    OpenWeatherMap: {
      options: {
        attribution: 'Map data © OpenWeatherMap'
      },
      variants: {
        Clouds: {
          url: 'http://{s}.tile.openweathermap.org/map/clouds/{z}/{x}/{y}.png'
        },
        CloudsClassic: {
          url: 'http://{s}.tile.openweathermap.org/map/clouds_cls/{z}/{x}/{y}.png'
        },
        Precipitation: {
          url: 'http://{s}.tile.openweathermap.org/map/precipitation/{z}/{x}/{y}.png'
        },
        PrecipitationClassic: {
          url: 'http://{s}.tile.openweathermap.org/map/precipitation_cls/{z}/{x}/{y}.png'
        },
        Rain: {
          url: 'http://{s}.tile.openweathermap.org/map/rain/{z}/{x}/{y}.png'
        },
        RainClassic: {
          url: 'http://{s}.tile.openweathermap.org/map/rain_cls/{z}/{x}/{y}.png'
        },
        Pressure: {
          url: 'http://{s}.tile.openweathermap.org/map/pressure/{z}/{x}/{y}.png'
        },
        PressureContour: {
          url: 'http://{s}.tile.openweathermap.org/map/pressure_cntr/{z}/{x}/{y}.png'
        },
        Wind: {
          url: 'http://{s}.tile.openweathermap.org/map/wind/{z}/{x}/{y}.png'
        },
        Temperature: {
          url: 'http://{s}.tile.openweathermap.org/map/temp/{z}/{x}/{y}.png'
        },
        Snow: {
          url: 'http://{s}.tile.openweathermap.org/map/snow/{z}/{x}/{y}.png'
        }
      }
    }

  };
}());

L.TileLayer.provider = function(provider){
  return new L.TileLayer.Provider(provider);
};

<commit_msg>Add options to provider function<commit_after>(function () {
  var providers = {};

  L.TileLayer.Provider = L.TileLayer.extend({
    initialize: function (arg, options) {
      var parts = arg.split('.');

      var providerName = parts[0];
      var variantName = parts[1];

      if (!providers[providerName]) {
        throw "No such provider (" + providerName + ")";
      }

      var provider = {
        url: providers[providerName].url,
        options: providers[providerName].options
      };

      // overwrite values in provider from variant.
      if (variantName && 'variants' in providers[providerName]) {
        if (!(variantName in providers[providerName].variants)) {
          throw "No such name in provider (" + variantName + ")";
        }
        var variant = providers[providerName].variants[variantName];
        provider = {
          url: variant.url || provider.url,
          options: L.Util.extend({}, provider.options, variant.options)
        };
      } else if (typeof provider.url === 'function') {
        provider.url = provider.url(parts.splice(1).join('.'));
      }

      // replace attribution placeholders with their values from toplevel provider attribution.
      var attribution = provider.options.attribution;
      if (attribution.indexOf('{attribution.') != -1) {
        provider.options.attribution = attribution.replace(/\{attribution.(\w*)\}/,
          function(match, attributionName){
            return providers[attributionName].options.attribution;
          });
      }
      // Compute final options combining provider options with any user overrides
      var layer_opts = L.Util.extend({}, provider.options, options);
      L.TileLayer.prototype.initialize.call(this, provider.url, layer_opts);
    }
  });

  /**
   * Definition of providers.
   * see http://leafletjs.com/reference.html#tilelayer for options in the options map.
   */
  providers = {
    OpenStreetMap: {
      url: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
      options: {
        attribution: '© OpenStreetMap contributors, CC-BY-SA'
      },
      variants: {
        Mapnik: {},
        BlackAndWhite: {
          url: 'http://{s}.www.toolserver.org/tiles/bw-mapnik/{z}/{x}/{y}.png'
        },
        DE: {
          url: 'http://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png'
        }
      }
    },
    OpenCycleMap: {
      url: 'http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png',
      options: {
        attribution: '© OpenCycleMap, OpenStreetMap contributors, CC-BY-SA'
      }
    },
    Thunderforest: {
      url: 'http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png',
      options: {
        attribution: '{attribution.OpenCycleMap}'
      },
      variants: {
        OpenCycleMap: {},
        Transport: {
          url: 'http://{s}.tile2.opencyclemap.org/transport/{z}/{x}/{y}.png'
        },
        Landscape: {
          url: 'http://{s}.tile3.opencyclemap.org/landscape/{z}/{x}/{y}.png'
        }
      }
    },
    MapQuestOpen: {
      url: 'http://otile{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png',
      options: {
        attribution: 'Tiles Courtesy of MapQuest — Map data {attribution.OpenStreetMap}',
        subdomains: '1234'
      },
      variants: {
        OSM: {},
        Aerial:{
          url: 'http://oatile{s}.mqcdn.com/tiles/1.0.0/sat/{z}/{x}/{y}.jpg',
          options: {
            attribution:
              'Tiles Courtesy of MapQuest — ' +
              'Portions Courtesy NASA/JPL-Caltech and U.S. Depart. of Agriculture, Farm Service Agency'
          }
        }
      }
    },
    MapBox: {
      url: function(id) {
        return 'http://{s}.tiles.mapbox.com/v3/' + id + '/{z}/{x}/{y}.png';
      },
      options: {
        attribution: 'Imagery from MapBox — Map data {attribution.OpenStreetMap}',
        subdomains: 'abcd'
      }
    },
    Stamen: {
      url: 'http://{s}.tile.stamen.com/toner/{z}/{x}/{y}.png',
      options: {
        attribution:
          'Map tiles by Stamen Design, CC BY 3.0 — ' +
          'Map data {attribution.OpenStreetMap}',
        subdomains: 'abcd',
        minZoom: 0,
        maxZoom: 20
      },
      variants: {
        Toner: {},
        TonerBackground: {
          url: 'http://{s}.tile.stamen.com/toner-background/{z}/{x}/{y}.png'
        },
        TonerHybrid: {
          url: 'http://{s}.tile.stamen.com/toner-hybrid/{z}/{x}/{y}.png'
        },
        TonerLines: {
          url: 'http://{s}.tile.stamen.com/toner-lines/{z}/{x}/{y}.png'
        },
        TonerLabels: {
          url: 'http://{s}.tile.stamen.com/toner-labels/{z}/{x}/{y}.png'
        },
        TonerLite: {
          url: 'http://{s}.tile.stamen.com/toner-lite/{z}/{x}/{y}.png'
        },
        Terrain: {
          url: 'http://{s}.tile.stamen.com/terrain/{z}/{x}/{y}.png',
          options: {
            minZoom: 4,
            maxZoom: 18
          }
        },
        Watercolor: {
          url: 'http://{s}.tile.stamen.com/watercolor/{z}/{x}/{y}.png',
          options: {
            minZoom: 3,
            maxZoom: 16
          }
        }
      }
    },
    Esri: {
      url: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}',
      options: {
        attribution: 'Tiles © Esri'
      },
      variants: {
        WorldStreetMap: {
          options: {
            attribution: '{attribution.Esri} — Source: Esri, DeLorme, NAVTEQ, USGS, Intermap, iPC, NRCAN, Esri Japan, METI, Esri China (Hong Kong), Esri (Thailand), TomTom, 2012'
          }
        },
        DeLorme: {
          url: 'http://server.arcgisonline.com/ArcGIS/rest/services/Specialty/DeLorme_World_Base_Map/MapServer/tile/{z}/{y}/{x}',
          options: {
            maxZoom: 11,
            attribution: '{attribution.Esri} — Copyright: ©2012 DeLorme'
          }
        },
        WorldTopoMap: {
          url: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}',
          options: {
            attribution: '{attribution.Esri} — Esri, DeLorme, NAVTEQ, TomTom, Intermap, iPC, USGS, FAO, NPS, NRCAN, GeoBase, Kadaster NL, Ordnance Survey, Esri Japan, METI, Esri China (Hong Kong), and the GIS User Community'
          }
        },
        WorldImagery: {
          url: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
          options: {
            attribution: '{attribution.Esri} — Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community'
          }
        },
        WorldTerrain: {
          url: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Terrain_Base/MapServer/tile/{z}/{y}/{x}',
          options: {
            attribution: '{attribution.Esri} — Source: USGS, Esri, TANA, DeLorme, and NPS'
          }
        },
        WorldShadedRelief: {
          url: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Shaded_Relief/MapServer/tile/{z}/{y}/{x}',
          options: {
            attribution: '{attribution.Esri} — Source: Esri'
          }
        },
        WorldPhysical: {
          url: 'http://server.arcgisonline.com/ArcGIS/rest/services/World_Physical_Map/MapServer/tile/{z}/{y}/{x}',
          options: {
            attribution: '{attribution.Esri} — Source: US National Park Service'
          }
        },
        OceanBasemap: {
          url: 'http://services.arcgisonline.com/ArcGIS/rest/services/Ocean_Basemap/MapServer/tile/{z}/{y}/{x}',
          options: {
            maxZoom: 11,
            attribution: '{attribution.Esri} — Sources: GEBCO, NOAA, CHS, OSU, UNH, CSUMB, National Geographic, DeLorme, NAVTEQ, and Esri'
          }
        },
        NatGeoWorldMap: {
          url: 'http://services.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer/tile/{z}/{y}/{x}',
          options: {
            attribution: '{attribution.Esri} — National Geographic, Esri, DeLorme, NAVTEQ, UNEP-WCMC, USGS, NASA, ESA, METI, NRCAN, GEBCO, NOAA, iPC'
          }
        },
        WorldGrayCanvas: {
          url: 'http://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}',
          options: {
            attribution: '{attribution.Esri} — Esri, DeLorme, NAVTEQ'
          }
        }
      }
    },
    OpenWeatherMap: {
      options: {
        attribution: 'Map data © OpenWeatherMap'
      },
      variants: {
        Clouds: {
          url: 'http://{s}.tile.openweathermap.org/map/clouds/{z}/{x}/{y}.png'
        },
        CloudsClassic: {
          url: 'http://{s}.tile.openweathermap.org/map/clouds_cls/{z}/{x}/{y}.png'
        },
        Precipitation: {
          url: 'http://{s}.tile.openweathermap.org/map/precipitation/{z}/{x}/{y}.png'
        },
        PrecipitationClassic: {
          url: 'http://{s}.tile.openweathermap.org/map/precipitation_cls/{z}/{x}/{y}.png'
        },
        Rain: {
          url: 'http://{s}.tile.openweathermap.org/map/rain/{z}/{x}/{y}.png'
        },
        RainClassic: {
          url: 'http://{s}.tile.openweathermap.org/map/rain_cls/{z}/{x}/{y}.png'
        },
        Pressure: {
          url: 'http://{s}.tile.openweathermap.org/map/pressure/{z}/{x}/{y}.png'
        },
        PressureContour: {
          url: 'http://{s}.tile.openweathermap.org/map/pressure_cntr/{z}/{x}/{y}.png'
        },
        Wind: {
          url: 'http://{s}.tile.openweathermap.org/map/wind/{z}/{x}/{y}.png'
        },
        Temperature: {
          url: 'http://{s}.tile.openweathermap.org/map/temp/{z}/{x}/{y}.png'
        },
        Snow: {
          url: 'http://{s}.tile.openweathermap.org/map/snow/{z}/{x}/{y}.png'
        }
      }
    }

  };
}());

L.TileLayer.provider = function(provider, options){
  return new L.TileLayer.Provider(provider, options);
};

<|endoftext|>


<commit_before>import React, { Component } from 'react';

import BandSelector from './BandSelector';
import OhmageIndicator from './OhmageIndicator';
import ResetButton from './ResetButton';
import SVGResistor from './SVGResistor';
import ToleranceIndicator from './ToleranceIndicator';

class ResistanceCalculator extends Component {
    constructor(props) {
        super(props);
        this.state = {
            bands: props.config.bands.map(v => v.value || 0),
            resistance: 0,
            tolerance: 0
        };
    }
    getMultiplier() {
        if(this.state.bands[3] == 10)
            return 0.1;
        if(this.state.bands[3] == 11)
            return 0.01;
        return Math.pow(10, this.state.bands[3]);

    }
    calculateResistance() {
        return this.getMultiplier() *
            ((100 * this.state.bands[0]) +
            (10  * this.state.bands[1]) +
            (1   * this.state.bands[2]));
    }
    updateBandState(band, value) {
        debugger;
        const { bandOptions } = this.props.config;
        const { bands } = this.state;
        bands[band] = value;
        this.setState({
            bands,
            resistance: this.calculateResistance(),
            tolerance: bandOptions[this.state.bands[4]].tolerance
        });
    }
    reset() {
        this.setState({
            bands: [0,0,0,0,0],
            resistance: 0,
            tolerance: 0
        });
    }
    render() {
        const { bandOptions, bands: bandsConfig } = this.props.config;
        const { bands, resistance, tolerance } = this.state;
        return (

                <SVGResistor bands={bands} bandOptions={bandOptions} />
                <OhmageIndicator resistance={resistance} />
                <ToleranceIndicator tolerance={tolerance} />
                {bands.map((b, i) => {
                    const options = bandOptions.filter((b, j) => (
                        bandsConfig[i].omitOptions.indexOf(j) === -1
                    ));
                    return (
                        <BandSelector
                            options={options}
                            key={i}
                            band={i}
                            value={b}
                            onChange={::this.updateBandState}
                        />
                    );
                })}
                <ResetButton onClick={::this.reset}/>

        );
    }
};

ResistanceCalculator.propTypes = {
    config: React.PropTypes.object.isRequired
};

export default ResistanceCalculator;
<commit_msg>Removed debugger statement<commit_after>import React, { Component } from 'react';

import BandSelector from './BandSelector';
import OhmageIndicator from './OhmageIndicator';
import ResetButton from './ResetButton';
import SVGResistor from './SVGResistor';
import ToleranceIndicator from './ToleranceIndicator';

class ResistanceCalculator extends Component {
    constructor(props) {
        super(props);
        this.state = {
            bands: props.config.bands.map(v => v.value || 0),
            resistance: 0,
            tolerance: 0
        };
    }
    getMultiplier() {
        if(this.state.bands[3] == 10)
            return 0.1;
        if(this.state.bands[3] == 11)
            return 0.01;
        return Math.pow(10, this.state.bands[3]);

    }
    calculateResistance() {
        return this.getMultiplier() *
            ((100 * this.state.bands[0]) +
            (10  * this.state.bands[1]) +
            (1   * this.state.bands[2]));
    }
    updateBandState(band, value) {
        const { bandOptions } = this.props.config;
        const { bands } = this.state;
        bands[band] = value;
        this.setState({
            bands,
            resistance: this.calculateResistance(),
            tolerance: bandOptions[this.state.bands[4]].tolerance
        });
    }
    reset() {
        this.setState({
            bands: [0,0,0,0,0],
            resistance: 0,
            tolerance: 0
        });
    }
    render() {
        const { bandOptions, bands: bandsConfig } = this.props.config;
        const { bands, resistance, tolerance } = this.state;
        return (

                <SVGResistor bands={bands} bandOptions={bandOptions} />
                <OhmageIndicator resistance={resistance} />
                <ToleranceIndicator tolerance={tolerance} />
                {bands.map((b, i) => {
                    const options = bandOptions.filter((b, j) => (
                        bandsConfig[i].omitOptions.indexOf(j) === -1
                    ));
                    return (
                        <BandSelector
                            options={options}
                            key={i}
                            band={i}
                            value={b}
                            onChange={::this.updateBandState}
                        />
                    );
                })}
                <ResetButton onClick={::this.reset}/>

        );
    }
};

ResistanceCalculator.propTypes = {
    config: React.PropTypes.object.isRequired
};

export default ResistanceCalculator;
<|endoftext|>


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

// For demo purposes. The hostname is used to determine the usage of
// development localhost URL vs production URL
const advertiserUrl = window.location.host;

const AD_URLS = [
  { url: `https://localhost:4437/ads/default-ad.html` },
  { url: `https://localhost:4437/ads/example-ad.html` },
];

async function injectAd() {
  // Load the worklet module
  await window.sharedStorage.worklet.addModule('frequency-cap-worklet.js');

  // Set the initial frequency cap to 5
  window.sharedStorage.set('frequency-cap-count', 5, {
    ignoreIfPresent: true,
  });

  // Run the URL selection operation to choose an ad based on the frequency cap in shared storage
  const opaqueURL = await window.sharedStorage.selectURL('frequency-cap', AD_URLS);

  // Render the opaque URL into a fenced frame
  document.getElementById('ad-slot').src = opaqueURL;
}

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

// For demo purposes. The hostname is used to determine the usage of
// development localhost URL vs production URL
const advertiserUrl = window.location.host;

const AD_URLS = [
  { url: `https://${advertiserUrl}/ads/default-ad.html` },
  { url: `https://${advertiserUrl}/ads/example-ad.html` },
];

async function injectAd() {
  // Load the worklet module
  await window.sharedStorage.worklet.addModule('frequency-cap-worklet.js');

  // Set the initial frequency cap to 5
  window.sharedStorage.set('frequency-cap-count', 5, {
    ignoreIfPresent: true,
  });

  // Run the URL selection operation to choose an ad based on the frequency cap in shared storage
  const opaqueURL = await window.sharedStorage.selectURL('frequency-cap', AD_URLS);

  // Render the opaque URL into a fenced frame
  document.getElementById('ad-slot').src = opaqueURL;
}

injectAd();
<|endoftext|>