<commit_before>
var keysAPI = require('./keys.js');
var keys = new keysAPI('MichaelDHyson');

var twitterAPI = require('node-twitter-api');
var twitter = new twitterAPI({
    consumerKey: keys.twitterKey,
    consumerSecret: keys.twitterSecret,
    callback: 'http://local.twitter.com/'
});

// Doesn't work
function doGetToken() {
	twitter.getRequestToken(function(error, requestToken, requestTokenSecret, results){
	    if (error) {
		console.log("Error getting OAuth request token : ");
		console.log(error);
	    } else {
		//store token and tokenSecret somewhere, you'll need them later; redirect user
		console.log(error);
		console.log(requestToken);
		console.log(requestTokenSecret);
		console.log(results);
		doSearch("fitness since:2014-08-08", handleSearchResults);
		twitter.getAccessToken(requestToken, requestTokenSecret, oauth_verifier, function(error, accessToken, accessTokenSecret, results) {
		    if (error) {
			console.log(error);
		    } else {
			keys.accessToken = requestToken;
			keys.accessTokenSecret = requestTokenSecret;
			//store accessToken and accessTokenSecret somewhere (associated to the user)
			//Step 4: Verify Credentials belongs here
			console.log(results);
			doSearch("fitness since:2014-08-08", handleSearchResults);
		    }
		});
	    }
	});
}

function doPost(msg) {
	twitter.statuses("update", {
		status: msg
	    },
	    keys.accessToken,
	    keys.accessTokenSecret,
	    function(error, data, response) {
		if (error) {
			console.log(error);
		    // something went wrong
		} else {
		    // data contains the data sent by twitter
		    console.log("Success!");
		    console.log(data);
		}
	    }
	);
}

// https://twitter.com/TechCrunch/status/499919536263401473
function doRetweet(id, callback) {
	console.log("^^^^^^^^^ Retweeting: "+id);
	twitter.statuses("retweet", {
		id: id
	    },
	    keys.accessToken,
	    keys.accessTokenSecret,
	    function(error, data, response) {
		if (error) {
			console.log("Retweet Error!!!");
			console.log(error);
		    // something went wrong
		} else {
		    // data contains the data sent by twitter
		    console.log("Retweet Success!");
		    console.log(data);
		}
	    }
	);
}

//nytimes
function doSearch(term, callback) {
	var out = {success:0, msg:''};
	twitter.search({
		q: term,
		count: 100,
	    },
	    keys.accessToken,
	    keys.accessTokenSecret,
	    function(error, data, response) {
		if (error) {
			console.log(error);
			out['msg'] = error;
		    // something went wrong
		} else {
		    // data contains the data sent by twitter
		    //console.log("Success!");
		    //console.log(data);
		    out['success'] = 1;
		    out['data'] = data;
		}
		callback(out);
	    }
	);
}

var a_table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";
var b_table = a_table.split(' ').map(function(s){ return parseInt(s,16) });
function b_crc32 (str) {
    var crc = crc ^ (-1);
    for(var i=0, iTop=str.length; i<iTop; i++) {
        crc = ( crc >>> 8 ) ^ b_table[( crc ^ str.charCodeAt( i ) ) & 0xFF];
    }
    return (crc ^ (-1)) >>> 0;
};

function handleSearchResults(result) {
	if(result['success']) {
		var dups = {}
		var alreadyRetweeted = false;
		if(false) {
			console.log(result['data']);
		}
		var statuses = result['data']['statuses'];
		for(var i in statuses) {
			var originalID = 0;
			var status = statuses[i];
			var crc = b_crc32(status['text']);
			if(crc in dups) {
				console.log("Dup");
			} else {
				dups[crc] = 1;
			}
			console.log(status['id'] + ":" + status['text']);
			if(status['text'].substr(0, 2) == 'RT') {
				//console.log(status['retweeted_status']);
				if('retweeted_status' in status) {
					originalID = status['retweeted_status']['id'];
					console.log("RETWEET of: "+ originalID);
				}
			}
			if(status['retweet_count'] > 0) {
				console.log('Retweeted '+status['retweet_count']+' times!!!');
				if(!alreadyRetweeted && status['retweet_count'] > 2) {
					alreadyRetweeted = true;
					var id = 499927703404154900; //status['id'];
					if(originalID) {
						//id = originalID;
					}
					console.log("_________________Retweeting: "+id);
					//doRetweet(id);

				}
			}
			if(status['favorite_count'] > 0) {
				console.log('Favorited!!!');
			}
		}
	}
};

//doSearch("fitness since:2014-08-08");
//doSearch("fitness", handleSearchResults);
doPost("Don't look too far behind you.");
<commit_msg>DJR:Corrected id truncation problem<commit_after>// Check if running as Node
var nodejs = false;
if (typeof window === 'undefined') {
	nodejs = true;
	var Firebase = require('firebase');
	var document = {};
}

var myDataRef = new Firebase('https://blinding-fire-4882.firebaseio.com/');
var user = 'dan_';
var retweetsRef = myDataRef.child(user + "retweets");

var keysAPI = require('./keys.js');
var boidieName = 'DanRahmel';
var keys = new keysAPI(boidieName);

var twitterAPI = require('node-twitter-api');
var twitter = new twitterAPI({
    consumerKey: keys.twitterKey,
    consumerSecret: keys.twitterSecret,
    callback: 'http://local.twitter.com/'
});

// Doesn't work
function doGetToken() {
	twitter.getRequestToken(function(error, requestToken, requestTokenSecret, results){
	    if (error) {
		console.log("Error getting OAuth request token : ");
		console.log(error);
	    } else {
		//store token and tokenSecret somewhere, you'll need them later; redirect user
		console.log(error);
		console.log(requestToken);
		console.log(requestTokenSecret);
		console.log(results);
		doSearch("fitness since:2014-08-08", handleSearchResults);
		twitter.getAccessToken(requestToken, requestTokenSecret, oauth_verifier, function(error, accessToken, accessTokenSecret, results) {
		    if (error) {
			console.log(error);
		    } else {
			keys.accessToken = requestToken;
			keys.accessTokenSecret = requestTokenSecret;
			//store accessToken and accessTokenSecret somewhere (associated to the user)
			//Step 4: Verify Credentials belongs here
			console.log(results);
			doSearch("fitness since:2014-08-08", handleSearchResults);
		    }
		});
	    }
	});
}

function doPost(msg) {
	twitter.statuses("update", {
		status: msg
	    },
	    keys.accessToken,
	    keys.accessTokenSecret,
	    function(error, data, response) {
		if (error) {
			console.log(error);
		    // something went wrong
		} else {
		    // data contains the data sent by twitter
		    console.log("Success!");
		    console.log(data);
		}
	    }
	);
}

// https://twitter.com/TechCrunch/status/499919536263401473
function doRetweet(id, callback) {
	twitter.statuses("retweet", {
		id: id
	    },
	    keys.accessToken,
	    keys.accessTokenSecret,
	    function(error, data, response) {
		if (error) {
			console.log("Retweet Error!!!"+id);
			console.log(error);
		    // something went wrong
		} else {
		    // data contains the data sent by twitter
		    console.log("Retweet Success!"+id);
		    console.log(data);
		}
	    }
	);
}

//nytimes
function doSearch(term, callback) {
	var out = {success:0, msg:''};
	twitter.search({
		q: term,
		count: 100,
	    },
	    keys.accessToken,
	    keys.accessTokenSecret,
	    function(error, data, response) {
		if (error) {
			console.log(error);
			out['msg'] = error;
		    // something went wrong
		} else {
		    // data contains the data sent by twitter
		    //console.log("Success!");
		    //console.log(data);
		    out['success'] = 1;
		    out['data'] = data;
		}
		callback(out);
	    }
	);
}

var a_table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";
var b_table = a_table.split(' ').map(function(s){ return parseInt(s,16) });
function b_crc32 (str) {
    var crc = crc ^ (-1);
    for(var i=0, iTop=str.length; i<iTop; i++) {
        crc = ( crc >>> 8 ) ^ b_table[( crc ^ str.charCodeAt( i ) ) & 0xFF];
    }
    return (crc ^ (-1)) >>> 0;
};

function handleSearchResults(result) {
	if(result['success']) {
		var dups = {}
		var alreadyRetweeted = false;
		if(false) {
			console.log(result['data']);
		}
		var statuses = result['data']['statuses'];
		for(var i in statuses) {
			var originalID = 0;
			var status = statuses[i];
			var crc = b_crc32(status['text']);
			if(crc in dups) {
				console.log("Dup");
			} else {
				dups[crc] = 1;
			}
			console.log(status['id'] + ":" + status['text']);
			if(status['text'].substr(0, 2) == 'RT') {
				//console.log(status['retweeted_status']);
				if('retweeted_status' in status) {
					originalID = status['retweeted_status']['id_str'];
					console.log("...RETWEET of: "+ originalID);
				}
			}
			if(status['favorite_count'] > 0) {
				console.log('...Favorited!!!');
			}
			if(status['retweet_count'] > 0) {
				console.log('Retweeted '+status['retweet_count']+' times!!!');
				if(!alreadyRetweeted && status['retweet_count'] > 20) {
					alreadyRetweeted = true;
					var id = status['id_str'];
					if(originalID) {
						id = originalID;
					}
					console.log("_________________Retweeting: "+id);
					retweetsRef.child(id).set({ name: boidieName });

					doRetweet(id);

				}
			}
		}
		console.log("Done. _________________");
	}
};

//doSearch("fitness since:2014-08-08");
doSearch("iPad", handleSearchResults);
//doPost("The scale doesn't lie.");
//doRetweet('499919536263401473');
//process.exit();

<|endoftext|>


<commit_before>(function (ng, app) {
    ng.module(app, [
            'ui.router',
            'titleService',
            'plusOne',
            'sokratik.atelier.services.istari',
            'sokratik.atelier.services.dialogue',
            'sokratik.atelier.services.acoustics',
            'ngSanitize',
            'ngAnimate'])

        .config(["$stateProvider", function config($stateProvider) {
            $stateProvider.state('record', {
                url: '/record/:presentationId',
                resolve: {
                    answer: ["$stateParams", "anduril", function ($stateParams, anduril) {
                        return anduril.fetchAnswer($stateParams.presentationId);
                    }], audioNode: ["acoustics", function (acoustics) {
                        return acoustics.getAudioNode();
                    }],
                    stream: [ "acoustics", "$stateParams", function (acoustics, $stateParams) {
                        return acoustics.stream($stateParams.presentationId);
                    }],
                    recordAction: ["anduril", "$stateParams", function (anduril, $stateParams) {
                        "use strict";
                        return function (resp) {
                            anduril.recordAction($stateParams.presentationId, resp);
                        };
                    }]
                },
                data: {
                    mode: "record"
                },
                views: {
                    "main": {
                        controller: 'RecordCtrl',
                        templateUrl: 'record/record.tpl.html'
                    }
                }
            });
            //this state represents the master view of all the slides
            $stateProvider.state('record.master', {
                url: "/master",
                views: {
                    "workspace": {
                        controller: 'RecordMaster',
                        templateUrl: 'record/master.tpl.html'
                    }
                }
            });
            $stateProvider.state('record.activate', {
                url: "/activate/:page",
                views: {
                    "workspace": {
                        controller: 'RecordDialogue',
                        templateUrl: 'record/active.tpl.html'
                    }
                }
            });
            $stateProvider.state('complete', {
                url: "/complete/:answerId",
                views: {
                    "main": {
                        controller: 'RecordComplete',
                        templateUrl: 'record/complete.tpl.html'
                    }
                }
            });

        }])
        .controller('RecordCtrl', ["$scope", "acoustics", "audioNode", "$state", "anduril", "$q", "stream", "answer", "recordAction",
            function ($scope, acoustics, audioNode, $state, anduril, $q, stream, answer, recordAction) {
                answer.script = [];//reseting the script
                $scope.presentationId = answer._id;

                $scope.record = function () {
                    var recordingStart = new Date().getTime();
                    answer.recordingStarted = answer.recordingStarted || recordingStart;
                    $scope.recording = true;
                    recordAction({"fnName": "resume", "args": {},
                        actionInitiated: new Date().getTime() });
                    acoustics.resume(audioNode, stream);
                };
                var answerId = answer._id;//this is a HACK replace with restangular why this is hack log the answer in
                //then clause
                $scope.complete = function () {
                    acoustics.stopRecording(audioNode, stream, answer._id);
                    $q.when(anduril.completeRecord(answer._id))
                        .then(function (resp) {
                            "use strict";
                            $state.go("complete", {answerId: answerId});
                        });

                };
                var pause = $scope.pause = function () {
                    acoustics.pause(audioNode, stream);
                    recordAction({"fnName": "pause", "args": {},
                        actionInitiated: new Date().getTime() });
                    $scope.recording = false;
                };

                $scope.$on('$stateChangeSuccess',
                    function () {
                        "use strict";
                        pause(audioNode, stream);
                        $scope.recording = false;
                    });
                pause(audioNode, stream);
            }])
        .controller('RecordMaster', ["$scope", "answer", "acoustics", "audioNode", "stream", "dialogue", "anduril", "recordAction",
            function ($scope, answer, acoustics, audioNode, stream, dialogue, anduril, recordAction) {
                $scope.presentations = _.map(answer.presentationData, function (obj) { //todo move to clojure script
                    obj.templateName = obj.templateName || "master";
                    return obj;
                });
                $scope.activate = function (index) {
                    var resp = dialogue.changeState({subState: ".activate", params: {page: index}});
                    anduril.recordAction(answer._id, resp);
                };
                $scope.presentationId = answer._id;

            }])
        .controller('RecordDialogue', ["$scope", "answer", "anduril", "dialogue", "$stateParams", "recordAction", "$q",
            function ($scope, answer, anduril, dialogue, $stateParams, recordAction, $q) {
                var page = parseInt($stateParams.page, 10);
                $scope.presentation = answer.presentationData[page];
                var fragmentFn = null;
                $scope.addFragment = function (fragment) {//TODO remove duplication
                    fragmentFn = fragment;
                    function resetFragments() {
                        dialogue.resetFragments({fragments: fragmentFn()}, $q.defer()).then(ng.noop);
                    }

                    if (_.size(fragment()) > 0) {  //TODO tie this properly with fragments in presentation also try prelinking and postlinking
                        resetFragments();
                    } else {
                        _.delay(resetFragments, 1000);//dom is not yet ready retry after 1000 ms
                    }
                };
                $scope.masterView = function () {
                    recordAction(dialogue.changeState({subState: ".master", params: null}));
                };
                var index = 0;
                $scope.next = function () {
                    dialogue.makeVisible({fragments: fragmentFn(), index: index++}, $q.defer()).then(recordAction);
                };
                $scope.previous = function () {
                    dialogue.hide({fragments: fragmentFn(), index: --index}, $q.defer()).then(recordAction);
                };
                $scope.nextSlide = function () {
                    recordAction(dialogue.changeState({subState: ".activate", params: {page: ++page}}));
                };
                var stepsRecordedTillThisSlide = _.size(answer.script) - 1;//we exclude the pause

                $scope.redoSlide = function () {
                    "use strict";
                    var scriptToPreserve = _.first(answer.script, stepsRecordedTillThisSlide);
                    console.log("[Redo] Before scripts size" + _.size(answer.script) + " After scripts " + stepsRecordedTillThisSlide);
                    scriptToPreserve[stepsRecordedTillThisSlide - 1].actionInitiated = new Date().getTime();
                    anduril.insertScript(answer._id, scriptToPreserve);
                    answer.script = scriptToPreserve;
                    dialogue.resetFragments({fragments: fragmentFn()}, $q.defer()).then(function () {
                        $scope.pause();
                    });
                    index = 0;
                };
            }
        ])
        .controller('RecordComplete', ["$scope", "$stateParams", function ($scope, $stateParams) {
            "use strict";
            $scope.answerId = $stateParams.answerId;
        }]);
})(angular, "sokratik.atelier.record");
<commit_msg>[v1.1] syncing fixes<commit_after>(function (ng, app) {
    ng.module(app, [
            'ui.router',
            'titleService',
            'plusOne',
            'sokratik.atelier.services.istari',
            'sokratik.atelier.services.dialogue',
            'sokratik.atelier.services.acoustics',
            'ngSanitize',
            'ngAnimate'])

        .config(["$stateProvider", function config($stateProvider) {
            $stateProvider.state('record', {
                url: '/record/:presentationId',
                resolve: {
                    answer: ["$stateParams", "anduril", function ($stateParams, anduril) {
                        return anduril.fetchAnswer($stateParams.presentationId);
                    }], audioNode: ["acoustics", function (acoustics) {
                        return acoustics.getAudioNode();
                    }],
                    stream: [ "acoustics", "$stateParams", function (acoustics, $stateParams) {
                        return acoustics.stream($stateParams.presentationId);
                    }],
                    recordAction: ["anduril", "$stateParams", function (anduril, $stateParams) {
                        "use strict";
                        return function (resp) {
                            anduril.recordAction($stateParams.presentationId, resp);
                        };
                    }]
                },
                data: {
                    mode: "record"
                },
                views: {
                    "main": {
                        controller: 'RecordCtrl',
                        templateUrl: 'record/record.tpl.html'
                    }
                }
            });
            //this state represents the master view of all the slides
            $stateProvider.state('record.master', {
                url: "/master",
                views: {
                    "workspace": {
                        controller: 'RecordMaster',
                        templateUrl: 'record/master.tpl.html'
                    }
                }
            });
            $stateProvider.state('record.activate', {
                url: "/activate/:page",
                views: {
                    "workspace": {
                        controller: 'RecordDialogue',
                        templateUrl: 'record/active.tpl.html'
                    }
                }
            });
            $stateProvider.state('complete', {
                url: "/complete/:answerId",
                views: {
                    "main": {
                        controller: 'RecordComplete',
                        templateUrl: 'record/complete.tpl.html'
                    }
                }
            });

        }])
        .controller('RecordCtrl', ["$scope", "acoustics", "audioNode", "$state", "anduril", "$q", "stream", "answer", "recordAction",
            function ($scope, acoustics, audioNode, $state, anduril, $q, stream, answer, recordAction) {
                answer.script = [];//reseting the script
                $scope.presentationId = answer._id;
                answer.recordingStarted = new Date().getTime();
                $scope.record = function () {
                    $scope.recording = true;
                    recordAction({"fnName": "resume", "args": {},
                        actionInitiated: new Date().getTime() });
                    acoustics.resume(audioNode, stream);
                };
                var answerId = answer._id;//this is a HACK replace with restangular why this is hack log the answer in
                //then clause
                $scope.complete = function () {
                    acoustics.stopRecording(audioNode, stream, answer._id);
                    $q.when(anduril.completeRecord(answer._id))
                        .then(function (resp) {
                            "use strict";
                            $state.go("complete", {answerId: answerId});
                        });

                };
                var pause = $scope.pause = function () {
                    acoustics.pause(audioNode, stream);
                    recordAction({"fnName": "pause", "args": {},
                        actionInitiated: new Date().getTime() });
                    $scope.recording = false;
                };

                $scope.$on('$stateChangeSuccess',
                    function () {
                        "use strict";
                        pause(audioNode, stream);
                        $scope.recording = false;
                    });
                pause(audioNode, stream);
            }])
        .controller('RecordMaster', ["$scope", "answer", "acoustics", "audioNode", "stream", "dialogue", "anduril", "recordAction",
            function ($scope, answer, acoustics, audioNode, stream, dialogue, anduril, recordAction) {
                $scope.presentations = _.map(answer.presentationData, function (obj) { //todo move to clojure script
                    obj.templateName = obj.templateName || "master";
                    return obj;
                });
                $scope.activate = function (index) {
                    var resp = dialogue.changeState({subState: ".activate", params: {page: index}});
                    anduril.recordAction(answer._id, resp);
                };
                $scope.presentationId = answer._id;

            }])
        .controller('RecordDialogue', ["$scope", "answer", "anduril", "dialogue", "$stateParams", "recordAction", "$q",
            function ($scope, answer, anduril, dialogue, $stateParams, recordAction, $q) {
                var page = parseInt($stateParams.page, 10);
                $scope.presentation = answer.presentationData[page];
                var fragmentFn = null;
                $scope.addFragment = function (fragment) {//TODO remove duplication
                    fragmentFn = fragment;
                    function resetFragments() {
                        dialogue.resetFragments({fragments: fragmentFn()}, $q.defer()).then(ng.noop);
                    }

                    if (_.size(fragment()) > 0) {  //TODO tie this properly with fragments in presentation also try prelinking and postlinking
                        resetFragments();
                    } else {
                        _.delay(resetFragments, 1000);//dom is not yet ready retry after 1000 ms
                    }
                };
                $scope.masterView = function () {
                    recordAction(dialogue.changeState({subState: ".master", params: null}));
                };
                var index = 0;
                $scope.next = function () {
                    dialogue.makeVisible({fragments: fragmentFn(), index: index++}, $q.defer()).then(recordAction);
                };
                $scope.previous = function () {
                    dialogue.hide({fragments: fragmentFn(), index: --index}, $q.defer()).then(recordAction);
                };
                $scope.nextSlide = function () {
                    recordAction(dialogue.changeState({subState: ".activate", params: {page: ++page}}));
                };
                var stepsRecordedTillThisSlide = _.size(answer.script) - 1;//we exclude the pause

                $scope.redoSlide = function () {
                    "use strict";
                    var scriptToPreserve = _.first(answer.script, stepsRecordedTillThisSlide);
                    console.log("[Redo] Before scripts size" + _.size(answer.script) + " After scripts " + stepsRecordedTillThisSlide);
                    scriptToPreserve[stepsRecordedTillThisSlide - 1].actionInitiated = new Date().getTime();
                    anduril.insertScript(answer._id, scriptToPreserve);
                    answer.script = scriptToPreserve;
                    dialogue.resetFragments({fragments: fragmentFn()}, $q.defer()).then(function () {
                        $scope.pause();
                    });
                    index = 0;
                };
            }
        ])
        .controller('RecordComplete', ["$scope", "$stateParams", function ($scope, $stateParams) {
            "use strict";
            $scope.answerId = $stateParams.answerId;
        }]);
})(angular, "sokratik.atelier.record");
<|endoftext|>


<commit_before>import buffList from '../../support/buffObj';
import formatLocalDateTime from '../../common/formatLocalDateTime';
import {fshBuffLog} from '../../support/constants';
import getForage from '../../ajax/getForage';
import getValue from '../../system/getValue';
import partial from '../../common/partial';
import querySelectorArray from '../../common/querySelectorArray';
import setForage from '../../ajax/setForage';

function buff(thisBuff, el) {return el.name === thisBuff;}

function getStamUsed(buffCast) {
  var thisBuff = buffList.find(partial(buff, buffCast[1]));
  if (thisBuff) {return thisBuff.stam.toString();}
  return '-';
}

function successfull(timeStamp, buffCast) {
  return timeStamp + ' ' + buffCast[0] + ' (' + getStamUsed(buffCast) +
    ' stamina)
';
}

function rejected(timeStamp, buffsNotCast) {
  return timeStamp + ' ' + buffsNotCast[0] + '
';
}

var transform = [
  [new RegExp('Skill ([\\w ]*) level (\\d*) was activated on \'(\\w*)\''),
    successfull],
  [new RegExp('The skill ([\\w ]*) of current or higher level is currently ' +
    'active on \'(\\w*)\''), rejected],
  [new RegExp('Player \'(\\w*)\' has set their preferences to block the ' +
    'skill \'([\\w ]*)\' from being cast on them.'), rejected]
];

function doRegExp(el, pair) {
  return [
    pair[0].exec(el.innerText),
    pair[1]
  ];
}

function match(pair) {return pair[0] !== null;}

function logFormat(timeStamp, el) {
  var transformed = transform.map(partial(doRegExp, el)).find(match);
  return transformed[1](timeStamp, transformed[0]);
}

function buffResult(buffLog) {
  var timeStamp = formatLocalDateTime(new Date());
  var buffsAttempted = querySelectorArray('#quickbuff-report p:not(.back)')
    .map(partial(logFormat, timeStamp));
  setForage(fshBuffLog, buffsAttempted.reverse().join('') + buffLog);
}

export default function updateBuffLog() {
  if (!getValue('keepBuffLog')) {return;}
  getForage(fshBuffLog).done(buffResult);
}
<commit_msg>refactor transform - stop running code at evaluate/compile<commit_after>import buffList from '../../support/buffObj';
import formatLocalDateTime from '../../common/formatLocalDateTime';
import {fshBuffLog} from '../../support/constants';
import getForage from '../../ajax/getForage';
import getValue from '../../system/getValue';
import partial from '../../common/partial';
import querySelectorArray from '../../common/querySelectorArray';
import setForage from '../../ajax/setForage';

function buff(thisBuff, el) {return el.name === thisBuff;}

function getStamUsed(buffCast) {
  var thisBuff = buffList.find(partial(buff, buffCast[1]));
  if (thisBuff) {return thisBuff.stam.toString();}
  return '-';
}

function successfull(timeStamp, buffCast) {
  return timeStamp + ' ' + buffCast[0] + ' (' + getStamUsed(buffCast) +
    ' stamina)
';
}

function rejected(timeStamp, buffsNotCast) {
  return timeStamp + ' ' + buffsNotCast[0] + '
';
}

var transform;

function buildTransform() {
  return [
    [new RegExp('Skill ([\\w ]*) level (\\d*) was activated on \'(\\w*)\''),
      successfull],
    [new RegExp('The skill ([\\w ]*) of current or higher level is currently ' +
      'active on \'(\\w*)\''), rejected],
    [new RegExp('Player \'(\\w*)\' has set their preferences to block the ' +
      'skill \'([\\w ]*)\' from being cast on them.'), rejected]
  ];
}

function doRegExp(el, pair) {
  return [
    pair[0].exec(el.innerText),
    pair[1]
  ];
}

function match(pair) {return pair[0] !== null;}

function logFormat(timeStamp, el) {
  var transformed = transform.map(partial(doRegExp, el)).find(match);
  return transformed[1](timeStamp, transformed[0]);
}

function buffResult(buffLog) {
  var timeStamp = formatLocalDateTime(new Date());
  var buffsAttempted = querySelectorArray('#quickbuff-report p:not(.back)')
    .map(partial(logFormat, timeStamp));
  setForage(fshBuffLog, buffsAttempted.reverse().join('') + buffLog);
}

export default function updateBuffLog() {
  if (!getValue('keepBuffLog')) {return;}
  getForage(fshBuffLog).done(buffResult);
  transform = buildTransform();
}
<|endoftext|>


<commit_before>import { mount } from '@vue/test-utils';
import store from 'kolibri.coreVue.vuex.store';
import SearchSideBar from '../src/views/SearchSideBar';
import SampleSearchResults from './SampleSearchResults';

function createWrapper() {
  return mount(SearchSideBar, {
    propsData: {
      book: {},
    },
    store,
  });
}

describe('Search side bar', () => {
  it('should mount', () => {
    const wrapper = createWrapper();
    expect(wrapper.exists()).toBe(true);
  });

  it('should allow parent to focus on input box', () => {
    const wrapper = createWrapper();
    wrapper.vm.focusOnInput();
    const elementThatIsFocused = document.activeElement;
    expect(elementThatIsFocused.classList.contains('search-input')).toBe(true);
  });

  it('should highlight search terms', () => {
    const wrapper = createWrapper();
    wrapper.vm.searchQuery = 'biology';
    wrapper.vm.searchResults = SampleSearchResults;
    wrapper.vm.createMarks(wrapper.vm.searchQuery);
    expect.assertions(1);
    wrapper.vm.$nextTick(() => {
      const allMarks = wrapper.findAll('mark');
      expect(allMarks.length).toBeGreaterThanOrEqual(wrapper.vm.searchResults.length);
    });
  });
});
<commit_msg>Fix SearchSideBar.spec.js<commit_after>import { mount } from '@vue/test-utils';
import store from 'kolibri.coreVue.vuex.store';
import SearchSideBar from '../src/views/SearchSideBar';
import SampleSearchResults from './SampleSearchResults';

function createWrapper() {
  return mount(SearchSideBar, {
    propsData: {
      book: {},
    },
    store,
  });
}

describe('Search side bar', () => {
  it('should mount', () => {
    const wrapper = createWrapper();
    expect(wrapper.exists()).toBe(true);
  });

  it('should allow parent to focus on input box', () => {
    const wrapper = createWrapper();
    wrapper.vm.focusOnInput();
    const elementThatIsFocused = document.activeElement;
    expect(elementThatIsFocused.classList.contains('search-input')).toBe(true);
  });

  it('should highlight search terms', () => {
    const wrapper = createWrapper();
    wrapper.vm.searchQuery = 'biology';
    wrapper.vm.searchResults = SampleSearchResults;
    wrapper.vm.createMarks(wrapper.vm.searchQuery);
    // const allMarks = wrapper.findAll('mark');
    // expect(allMarks.length).toBeGreaterThanOrEqual(wrapper.vm.searchResults.length);
    // Listen for event as a proxy for Mark to have done the highlighting
    expect(wrapper.emitted().newSearchQuery[0]).toEqual(['biology'])
  });
});
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import stackedArea from './stackedAreaChart';

export default class StackedArea extends React.Component {

    static defaultProps = {
        chart: stackedArea,
    }

    static PropTypes = {
        axisTimeCombinations: PropTypes.number,
        areaOpacity: PropTypes.object,
        aspectRatio: PropTypes.number,
        chart: PropTypes.func,
        colorSchema: PropTypes.arrayOf(PropTypes.string),
        data: PropTypes.array.isRequired,
        dateLabel: PropTypes.number,
        grid: PropTypes.string,
        height: PropTypes.number,
        isAnimated: PropTypes.bool,
        keyLabel: PropTypes.number,
        locale: PropTypes.string,
        margin: PropTypes.object,
        tooltipThreshold: PropTypes.object,
        valueLabel: PropTypes.number,
        width: PropTypes.number,
        xAxisCustomFormat: PropTypes.string,
        xAxisFormat: PropTypes.string,
        xTicks: PropTypes.number,
        yTicks: PropTypes.number,
    }

    constructor(props) {
        super(props);

        // We want to make this throw an error if no data is provided
        if (!props.data) {
            throw new Error('Data is required!');
        }
    }

    componentDidMount() {
        this.props.chart.create(this._rootNode, this.props.data, this._getChartConfiguration());
    }

    componentDidUpdate() {
        this.props.chart.update(this._rootNode, this.props.data, this._getChartConfiguration());
    }

    componentWillUnmount() {
        this.props.chart.destroy(this._rootNode);
    }

    /**
     * We want to remove the chart and data from the props in order to have a configuration object
     * @return {Object} Configuration object for the chart
     */
    _getChartConfiguration() {
        let configuration = {...this.props};

        delete configuration.data;
        delete configuration.chart;

        return configuration;
    }

    _setRef(componentNode) {
        if (componentNode) {
            this._rootNode = componentNode;
        }
    }

    render() {
        return (

        );
    }
}
<commit_msg>Required props first<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import stackedArea from './stackedAreaChart';

export default class StackedArea extends React.Component {

    static defaultProps = {
        chart: stackedArea,
    }

    static PropTypes = {
        data: PropTypes.array.isRequired,

        axisTimeCombinations: PropTypes.number,
        areaOpacity: PropTypes.object,
        aspectRatio: PropTypes.number,
        chart: PropTypes.func,
        colorSchema: PropTypes.arrayOf(PropTypes.string),
        dateLabel: PropTypes.number,
        grid: PropTypes.string,
        height: PropTypes.number,
        isAnimated: PropTypes.bool,
        keyLabel: PropTypes.number,
        locale: PropTypes.string,
        margin: PropTypes.object,
        tooltipThreshold: PropTypes.object,
        valueLabel: PropTypes.number,
        width: PropTypes.number,
        xAxisCustomFormat: PropTypes.string,
        xAxisFormat: PropTypes.string,
        xTicks: PropTypes.number,
        yTicks: PropTypes.number,
    }

    constructor(props) {
        super(props);

        // We want to make this throw an error if no data is provided
        if (!props.data) {
            throw new Error('Data is required!');
        }
    }

    componentDidMount() {
        this.props.chart.create(this._rootNode, this.props.data, this._getChartConfiguration());
    }

    componentDidUpdate() {
        this.props.chart.update(this._rootNode, this.props.data, this._getChartConfiguration());
    }

    componentWillUnmount() {
        this.props.chart.destroy(this._rootNode);
    }

    /**
     * We want to remove the chart and data from the props in order to have a configuration object
     * @return {Object} Configuration object for the chart
     */
    _getChartConfiguration() {
        let configuration = {...this.props};

        delete configuration.data;
        delete configuration.chart;

        return configuration;
    }

    _setRef(componentNode) {
        if (componentNode) {
            this._rootNode = componentNode;
        }
    }

    render() {
        return (

        );
    }
}
<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { c } from 'ttag';
import { SubTitle, Href, Icon, Paragraph } from 'react-components';

const MobileRedirectionStep = ({ model }) => {
    return (

            <SubTitle>{c('Title').t`Account created`}</SubTitle>
            <Icon name="on" className="mb2" fill="success" size={100} />
            <Paragraph className="mb2">{c('Info')
                .t`Your account has been successfully created. Please press the "Close" button to be taken back to the app.`}</Paragraph>
            <Href
                className="pm-button pm-button--primary pm-button--large bold"
                url={`protonvpn://registered?username=${model.username}`}
                target="_top"
            >{c('Link').t`Close`}</Href>

    );
};

MobileRedirectionStep.propTypes = {
    model: PropTypes.object.isRequired
};

export default MobileRedirectionStep;
<commit_msg>Refactor <Icon/> fill<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { c } from 'ttag';
import { SubTitle, Href, Icon, Paragraph } from 'react-components';

const MobileRedirectionStep = ({ model }) => {
    return (

            <SubTitle>{c('Title').t`Account created`}</SubTitle>
            <Icon name="on" className="mb2 color-global-success" size={100} />
            <Paragraph className="mb2">{c('Info')
                .t`Your account has been successfully created. Please press the "Close" button to be taken back to the app.`}</Paragraph>
            <Href
                className="pm-button pm-button--primary pm-button--large bold"
                url={`protonvpn://registered?username=${model.username}`}
                target="_top"
            >{c('Link').t`Close`}</Href>

    );
};

MobileRedirectionStep.propTypes = {
    model: PropTypes.object.isRequired
};

export default MobileRedirectionStep;
<|endoftext|>


<commit_before>'use strict';
var fs = require('fs');
var path = require('path');
var assert = require('assert');
var assign = require('object-assign');
var pathExists = require('path-exists');
var rimraf = require('rimraf');
var vinylFile = require('vinyl-file');

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

var defaultOptions = {
	quiet: true,
	unixNewlines: true // normalize compilation results on Windows systems
};

// load the expected result file from the compiled results directory
var expectedFile = function (relativePath, base) {
	base = base || 'result';
	var file = path.join(base, relativePath);
	return vinylFile.readSync(file, { base: base });
};

var sortByRelative = function (a, b) {
  return a.relative.localeCompare(b.relative);
};

describe('single file', function () {
	this.timeout(20000);
	var files = [];
	var expected = expectedFile('file.css');

	before(function(done) {
		sass('source/file.scss', defaultOptions)
		.on('data', function (data) {
			files.push(data);
		})
		.on('end', done);
	});

	it('creates correct number of files', function () {
		assert.equal(files.length, 1);
	});

	it('creates file at correct path', function () {
		assert(files.length);
		assert.equal(files[0].relative, expected.relative);
	});

	it('creates correct file contents', function () {
		assert(files.length);
		assert.equal(
			files[0].contents.toString(),
			expected.contents.toString()
		);
	});
});

describe('multiple files', function () {
	this.timeout(20000);
	var files = [];
	var expected = [
		expectedFile('directory with spaces/file with spaces.css'),
		expectedFile('directory/file.css'),
		expectedFile('error.css'),
		expectedFile('file.css'),
		expectedFile('warnings.css')
	];

	before(function(done) {
		sass('source/**/*.scss', defaultOptions)
		.on('data', function (data) {
			files.push(data);
		})
		.on('end', function() {
			files.sort(sortByRelative);
			done();
		});
	});

	it('creates correct number of files', function () {
		assert.equal(files.length, 5);
	});

	it('creates file at correct path', function () {
		assert(files.length);
		files.forEach(function (file, i) {
			assert.equal(file.relative, expected[i].relative);
		});
	});

	it('creates correct file contents', function () {
		assert(files.length);
		files.forEach(function (file, i) {
			// the stack trace in the error file is specific to the system it's
			// compiled on, so we just check for the error message
			if (file.basename === 'error.css') {
				var expectedError = 'Error: File to import not found or unreadable: i-dont-exist.';

				assert(
					file.contents.toString().indexOf(expectedError) !== -1,
					'The error file does not contain the expected message "' + expectedError + '".'
				);
			}
			else {
				assert.deepEqual(
					file.contents.toString(),
					expected[i].contents.toString()
				);
			}
		});
	});
});

describe('array sources', function () {
	this.timeout(20000);
	var files = [];
	var expected = [
		expectedFile('file with spaces.css', 'result/directory with spaces'),
		expectedFile('file.css')
	];

	before(function(done) {
		sass([
			'source/file.scss',
			'source/directory with spaces/file with spaces.scss'
		], defaultOptions)
		.on('data', function (data) {
			files.push(data);
		})
		.on('end', function() {
			files.sort(sortByRelative);
			done();
		});
	});

	it('creates correct number of files', function () {
		assert.equal(files.length, 2);
	});

	it('creates file at correct path', function () {
		assert(files.length);
		files.forEach(function (file, i) {
			assert.equal(file.relative, expected[i].relative);
		});
	});

	it('creates correct file contents', function () {
		assert(files.length);
		files.forEach(function (file, i) {
			assert.deepEqual(
				file.contents.toString(),
				expected[i].contents.toString()
			);
		});
	});
});

describe('concurrently run tasks', function () {
	this.timeout(20000);
	var aFiles = [];
	var bFiles = [];
	var cFiles = [];
	var counter = 0;
	var isDone = function(done) {
		counter++;
		if (counter === 3) { done(); }
	};

	before(function(done) {
		sass('source/file.scss', defaultOptions)
		.on('data', function (data) {
			aFiles.push(data);
		})
		.on('end', function () {
			isDone(done);
		});

		sass('source/directory/file.scss', defaultOptions)
		.on('data', function (data) {
			bFiles.push(data);
		})
		.on('end', function () {
			isDone(done);
		});

		sass('source/directory with spaces/file with spaces.scss', defaultOptions)
		.on('data', function (data) {
			cFiles.push(data);
		})
		.on('end', function () {
			isDone(done);
		});
	});

	it('don\'t intermix result files', function () {
		assert.equal(aFiles.length, 1);
		assert.equal(bFiles.length, 1);
		assert.equal(cFiles.length, 1);
	});
});

describe('sourcemap', function () {
	this.timeout(20000);
	var files = [];
	var options = assign({}, defaultOptions, { sourcemap: true });

	before(function(done) {
		sass('source/file.scss', options)
		.on('data', function (data) {
			files.push(data);
		})
		.on('end', done);
	});

	it('doesn\'t stream Sass sourcemap files', function () {
		assert.equal(files.length, 1);
	});

	it('removes Sass sourcemap comment', function () {
		assert(
			files[0].contents.toString().indexOf('sourceMap') === -1,
			'File contains sourcemap comment'
		);
	});

	it('adds a vinyl sourcemap', function () {
		assert.equal(typeof files[0].sourceMap, 'object');
		assert.equal(files[0].sourceMap.version, 3);
	});

	it('includes the correct sources', function () {
		assert.deepEqual(
			files[0].sourceMap.sources,
			['_partial.scss', 'file.scss', 'directory/_nested-partial.scss']
		);
	});

	describe('compiling files from glob source', function () {
		var expected = [
			[ '_partial.scss' ],
			[ '_partial.scss', 'file.scss', 'directory/_nested-partial.scss' ]
		];

		before(function(done) {
			files = [];

			sass('source/**/file.scss', options)
			.on('data', function (data) {
				files.push(data);
			})
			.on('end', function() {
				files.sort(sortByRelative);
				done();
			});
		});

		it('includes the correct sources', function () {
			files.forEach(function (file, i) {
				assert.deepEqual(file.sourceMap.sources, expected[i]);
			});
		});
	});

	describe('compiling files and directories with spaces', function () {
		var expected = ['file with spaces.scss'];

		before(function(done) {
			files = [];

			sass('source/directory with spaces/file with spaces.scss', options)
			.on('data', function (data) {
				files.push(data);
			})
			.on('end', done);
		});

		it('includes the correct sources', function () {
			assert.deepEqual(files[0].sourceMap.sources, expected);
		});
	});
});

describe('options', function () {
	this.timeout(20000);

	describe('emitCompileError', function () {
		var error;

		before(function(done) {
			var options = assign({}, defaultOptions, { emitCompileError: true });

			sass('source/error.scss', options)
			.on('data', function () {})
			.on('error', function (err) {
				error = err;
			})
			.on('end', done);
		});

		it('emits a gulp error when Sass compilation fails', function () {
			assert(error instanceof Error);
			assert.equal(
				error.message,
				'Sass compilation failed. See console output for more information.'
			);
		});
	});

	describe('base (for colliding sources)', function () {
		this.timeout(20000);
		var files = [];
		var expected = [
			expectedFile('directory/file.css'),
			expectedFile('file.css')
		];
		var options = assign({}, defaultOptions, { base: 'source' });

		before(function(done) {
			sass(['source/file.scss', 'source/directory/file.scss'], options)
			.on('data', function (data) {
				files.push(data);
			})
			.on('end', function() {
				files.sort(sortByRelative);
				done();
			});
		});

		it('creates correct number of files', function () {
			assert.equal(files.length, 2);
		});

		it('creates file at correct path', function () {
			assert(files.length);
			files.forEach(function (file, i) {
				assert.equal(file.relative, expected[i].relative);
			});
		});

		it('creates correct file contents', function () {
			assert(files.length);
			files.forEach(function (file, i) {
				assert.deepEqual(
					file.contents.toString(),
					expected[i].contents.toString()
				);
			});
		});
	});

	describe('tempDir', function () {
		it('compiles files to the specified directory', function (done) {
			var source = 'source/file.scss';
			var tempDir = './custom-temp-dir';
			var options = assign({}, defaultOptions, { tempDir: tempDir });

			assert.equal(
				pathExists.sync(tempDir),
				false,
				'The temporary directory already exists, and would create false positives.'
			);

			sass(source, options)

			.on('data', function (data) {
				console.log('heloo');

				assert( pathExists.sync(tempDir) );
			})

			// clean up if tests are run locally
			.on('end', function () {
				rimraf(tempDir, done);
			});
		});
	});
});
<commit_msg>Format anonymous function definitions<commit_after>'use strict';
var fs = require('fs');
var path = require('path');
var assert = require('assert');
var assign = require('object-assign');
var pathExists = require('path-exists');
var rimraf = require('rimraf');
var vinylFile = require('vinyl-file');

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

var defaultOptions = {
	quiet: true,
	unixNewlines: true // normalize compilation results on Windows systems
};

// load the expected result file from the compiled results directory
var expectedFile = function (relativePath, base) {
	base = base || 'result';
	var file = path.join(base, relativePath);
	return vinylFile.readSync(file, { base: base });
};

var sortByRelative = function (a, b) {
  return a.relative.localeCompare(b.relative);
};

describe('single file', function () {
	this.timeout(20000);
	var files = [];
	var expected = expectedFile('file.css');

	before(function (done) {
		sass('source/file.scss', defaultOptions)
		.on('data', function (data) {
			files.push(data);
		})
		.on('end', done);
	});

	it('creates correct number of files', function () {
		assert.equal(files.length, 1);
	});

	it('creates file at correct path', function () {
		assert(files.length);
		assert.equal(files[0].relative, expected.relative);
	});

	it('creates correct file contents', function () {
		assert(files.length);
		assert.equal(
			files[0].contents.toString(),
			expected.contents.toString()
		);
	});
});

describe('multiple files', function () {
	this.timeout(20000);
	var files = [];
	var expected = [
		expectedFile('directory with spaces/file with spaces.css'),
		expectedFile('directory/file.css'),
		expectedFile('error.css'),
		expectedFile('file.css'),
		expectedFile('warnings.css')
	];

	before(function (done) {
		sass('source/**/*.scss', defaultOptions)
		.on('data', function (data) {
			files.push(data);
		})
		.on('end', function () {
			files.sort(sortByRelative);
			done();
		});
	});

	it('creates correct number of files', function () {
		assert.equal(files.length, 5);
	});

	it('creates file at correct path', function () {
		assert(files.length);
		files.forEach(function (file, i) {
			assert.equal(file.relative, expected[i].relative);
		});
	});

	it('creates correct file contents', function () {
		assert(files.length);
		files.forEach(function (file, i) {
			// the stack trace in the error file is specific to the system it's
			// compiled on, so we just check for the error message
			if (file.basename === 'error.css') {
				var expectedError = 'Error: File to import not found or unreadable: i-dont-exist.';

				assert(
					file.contents.toString().indexOf(expectedError) !== -1,
					'The error file does not contain the expected message "' + expectedError + '".'
				);
			}
			else {
				assert.deepEqual(
					file.contents.toString(),
					expected[i].contents.toString()
				);
			}
		});
	});
});

describe('array sources', function () {
	this.timeout(20000);
	var files = [];
	var expected = [
		expectedFile('file with spaces.css', 'result/directory with spaces'),
		expectedFile('file.css')
	];

	before(function (done) {
		sass([
			'source/file.scss',
			'source/directory with spaces/file with spaces.scss'
		], defaultOptions)
		.on('data', function (data) {
			files.push(data);
		})
		.on('end', function () {
			files.sort(sortByRelative);
			done();
		});
	});

	it('creates correct number of files', function () {
		assert.equal(files.length, 2);
	});

	it('creates file at correct path', function () {
		assert(files.length);
		files.forEach(function (file, i) {
			assert.equal(file.relative, expected[i].relative);
		});
	});

	it('creates correct file contents', function () {
		assert(files.length);
		files.forEach(function (file, i) {
			assert.deepEqual(
				file.contents.toString(),
				expected[i].contents.toString()
			);
		});
	});
});

describe('concurrently run tasks', function () {
	this.timeout(20000);
	var aFiles = [];
	var bFiles = [];
	var cFiles = [];
	var counter = 0;
	var isDone = function (done) {
		counter++;
		if (counter === 3) { done(); }
	};

	before(function (done) {
		sass('source/file.scss', defaultOptions)
		.on('data', function (data) {
			aFiles.push(data);
		})
		.on('end', function () {
			isDone(done);
		});

		sass('source/directory/file.scss', defaultOptions)
		.on('data', function (data) {
			bFiles.push(data);
		})
		.on('end', function () {
			isDone(done);
		});

		sass('source/directory with spaces/file with spaces.scss', defaultOptions)
		.on('data', function (data) {
			cFiles.push(data);
		})
		.on('end', function () {
			isDone(done);
		});
	});

	it('don\'t intermix result files', function () {
		assert.equal(aFiles.length, 1);
		assert.equal(bFiles.length, 1);
		assert.equal(cFiles.length, 1);
	});
});

describe('sourcemap', function () {
	this.timeout(20000);
	var files = [];
	var options = assign({}, defaultOptions, { sourcemap: true });

	before(function (done) {
		sass('source/file.scss', options)
		.on('data', function (data) {
			files.push(data);
		})
		.on('end', done);
	});

	it('doesn\'t stream Sass sourcemap files', function () {
		assert.equal(files.length, 1);
	});

	it('removes Sass sourcemap comment', function () {
		assert(
			files[0].contents.toString().indexOf('sourceMap') === -1,
			'File contains sourcemap comment'
		);
	});

	it('adds a vinyl sourcemap', function () {
		assert.equal(typeof files[0].sourceMap, 'object');
		assert.equal(files[0].sourceMap.version, 3);
	});

	it('includes the correct sources', function () {
		assert.deepEqual(
			files[0].sourceMap.sources,
			['_partial.scss', 'file.scss', 'directory/_nested-partial.scss']
		);
	});

	describe('compiling files from glob source', function () {
		var expected = [
			[ '_partial.scss' ],
			[ '_partial.scss', 'file.scss', 'directory/_nested-partial.scss' ]
		];

		before(function (done) {
			files = [];

			sass('source/**/file.scss', options)
			.on('data', function (data) {
				files.push(data);
			})
			.on('end', function () {
				files.sort(sortByRelative);
				done();
			});
		});

		it('includes the correct sources', function () {
			files.forEach(function (file, i) {
				assert.deepEqual(file.sourceMap.sources, expected[i]);
			});
		});
	});

	describe('compiling files and directories with spaces', function () {
		var expected = ['file with spaces.scss'];

		before(function (done) {
			files = [];

			sass('source/directory with spaces/file with spaces.scss', options)
			.on('data', function (data) {
				files.push(data);
			})
			.on('end', done);
		});

		it('includes the correct sources', function () {
			assert.deepEqual(files[0].sourceMap.sources, expected);
		});
	});
});

describe('options', function () {
	this.timeout(20000);

	describe('emitCompileError', function () {
		var error;

		before(function (done) {
			var options = assign({}, defaultOptions, { emitCompileError: true });

			sass('source/error.scss', options)
			.on('data', function () {})
			.on('error', function (err) {
				error = err;
			})
			.on('end', done);
		});

		it('emits a gulp error when Sass compilation fails', function () {
			assert(error instanceof Error);
			assert.equal(
				error.message,
				'Sass compilation failed. See console output for more information.'
			);
		});
	});

	describe('base (for colliding sources)', function () {
		this.timeout(20000);
		var files = [];
		var expected = [
			expectedFile('directory/file.css'),
			expectedFile('file.css')
		];
		var options = assign({}, defaultOptions, { base: 'source' });

		before(function (done) {
			sass(['source/file.scss', 'source/directory/file.scss'], options)
			.on('data', function (data) {
				files.push(data);
			})
			.on('end', function () {
				files.sort(sortByRelative);
				done();
			});
		});

		it('creates correct number of files', function () {
			assert.equal(files.length, 2);
		});

		it('creates file at correct path', function () {
			assert(files.length);
			files.forEach(function (file, i) {
				assert.equal(file.relative, expected[i].relative);
			});
		});

		it('creates correct file contents', function () {
			assert(files.length);
			files.forEach(function (file, i) {
				assert.deepEqual(
					file.contents.toString(),
					expected[i].contents.toString()
				);
			});
		});
	});

	describe('tempDir', function () {
		it('compiles files to the specified directory', function (done) {
			var source = 'source/file.scss';
			var tempDir = './custom-temp-dir';
			var options = assign({}, defaultOptions, { tempDir: tempDir });

			assert.equal(
				pathExists.sync(tempDir),
				false,
				'The temporary directory already exists, and would create false positives.'
			);

			sass(source, options)

			.on('data', function (data) {
				console.log('heloo');

				assert( pathExists.sync(tempDir) );
			})

			// clean up if tests are run locally
			.on('end', function () {
				rimraf(tempDir, done);
			});
		});
	});
});
<|endoftext|>


<commit_before>/**
 * AnalyticsAllTrafficDashboardWidgetTopAcquisitionSources component.
 *
 * Site Kit by Google, Copyright 2019 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
 *
 *     https://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.
 */

/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';
import { Component, Fragment } from '@wordpress/element';

/**
 * Internal dependencies
 */
import { getTimeInSeconds } from '../../../../util';
import withData from '../../../../components/higherorder/withdata';
import { TYPE_MODULES } from '../../../../components/data';
import { getDataTableFromData, TableOverflowContainer } from '../../../../components/data-table';
import MiniChart from '../../../../components/mini-chart';
import PreviewTable from '../../../../components/preview-table';
import { trafficSourcesReportDataDefaults } from '../../util';

class AnalyticsAllTrafficDashboardWidgetTopAcquisitionSources extends Component {
	render() {
		const { data } = this.props;
		if ( ! data || ! data.length ) {
			return null;
		}

		const headers = [
			{
				title: __( 'Source', 'google-site-kit' ),
				primary: true,
			},
			{
				title: __( 'Percent', 'google-site-kit' ),
			},
		];

		const totalUsers = data[ 0 ].data.totals[ 0 ].values[ 1 ];

		const dataMapped = data[ 0 ].data.rows.map( ( row, i ) => {
			const percent = ( row.metrics[ 0 ].values[ 1 ] / totalUsers * 100 );

			return [
				row.dimensions[ 0 ],
				<Fragment key={ 'minichart-' + i }>
{ `${ percent.toFixed( 2 ) }%` } <MiniChart percent={ percent.toFixed( 1 ) } index={ i } />
</Fragment>,
			];
		} );

		const options = {
			hideHeader: true,
			chartsEnabled: true,
		};

		const dataTable = getDataTableFromData( dataMapped, headers, options );

		return (

				<TableOverflowContainer>
					{ dataTable }
				</TableOverflowContainer>

		);
	}
}

export default withData(
	AnalyticsAllTrafficDashboardWidgetTopAcquisitionSources,
	[
		{
			type: TYPE_MODULES,
			identifier: 'analytics',
			datapoint: 'report',
			data: trafficSourcesReportDataDefaults,
			priority: 1,
			maxAge: getTimeInSeconds( 'day' ),
			context: 'Dashboard',
		},
	],
	<PreviewTable
		rows={ 3 }
		rowHeight={ 50 }
	/>
);
<commit_msg>Add checks to ensure Array.map is not called on undefined.<commit_after>/**
 * AnalyticsAllTrafficDashboardWidgetTopAcquisitionSources component.
 *
 * Site Kit by Google, Copyright 2019 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
 *
 *     https://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.
 */

/**
 * WordPress dependencies
 */
import { __ } from '@wordpress/i18n';
import { Component, Fragment } from '@wordpress/element';

/**
 * Internal dependencies
 */
import { getTimeInSeconds } from '../../../../util';
import withData from '../../../../components/higherorder/withdata';
import { TYPE_MODULES } from '../../../../components/data';
import { getDataTableFromData, TableOverflowContainer } from '../../../../components/data-table';
import MiniChart from '../../../../components/mini-chart';
import PreviewTable from '../../../../components/preview-table';
import { trafficSourcesReportDataDefaults } from '../../util';

class AnalyticsAllTrafficDashboardWidgetTopAcquisitionSources extends Component {
	render() {
		const { data } = this.props;
		if ( ! data || ! data.length ) {
			return null;
		}
		if ( ! data[ 0 ].data.totals || ! data[ 0 ].data.totals.length ) {
			return null;
		}
		if ( ! data[ 0 ].data.rows || ! data[ 0 ].data.rows.length ) {
			return null;
		}

		const headers = [
			{
				title: __( 'Source', 'google-site-kit' ),
				primary: true,
			},
			{
				title: __( 'Percent', 'google-site-kit' ),
			},
		];

		const totalUsers = data[ 0 ].data.totals[ 0 ].values[ 1 ];

		const dataMapped = data[ 0 ].data.rows.map( ( row, i ) => {
			const percent = ( row.metrics[ 0 ].values[ 1 ] / totalUsers * 100 );

			return [
				row.dimensions[ 0 ],
				<Fragment key={ 'minichart-' + i }>
{ `${ percent.toFixed( 2 ) }%` } <MiniChart percent={ percent.toFixed( 1 ) } index={ i } />
</Fragment>,
			];
		} );

		const options = {
			hideHeader: true,
			chartsEnabled: true,
		};

		const dataTable = getDataTableFromData( dataMapped, headers, options );

		return (

				<TableOverflowContainer>
					{ dataTable }
				</TableOverflowContainer>

		);
	}
}

export default withData(
	AnalyticsAllTrafficDashboardWidgetTopAcquisitionSources,
	[
		{
			type: TYPE_MODULES,
			identifier: 'analytics',
			datapoint: 'report',
			data: trafficSourcesReportDataDefaults,
			priority: 1,
			maxAge: getTimeInSeconds( 'day' ),
			context: 'Dashboard',
		},
	],
	<PreviewTable
		rows={ 3 }
		rowHeight={ 50 }
	/>
);
<|endoftext|>


<commit_before>/*
 Copyright 2016 - 2017 by Jan Dockx

 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.
 */

module.exports = (function() {
  "use strict";

  var expect = require("chai").expect;
  var util = require("../../src/_private/util");
  var testUtil = require("../_testUtil");
  var Contract = require("../../src/I/Contract");

  var someConditions = [
    function() {return [];},
    function() {return [function() {return false;}, function() {return true;}];}
  ];
  var preCases = [
    function() {return null;}
  ].concat(someConditions);
  var postCases = [
    function() {return null;}
  ].concat(someConditions);
  var exceptionCases = [
    function() {return null;}
  ].concat(someConditions);

  //noinspection JSPrimitiveTypeWrapperUsage,MagicNumberJS
  var thingsThatAreNotAFunctionNorAContract = [
    undefined,
    null,
    "",
    "foo",
    0,
    -1,
    true,
    false,
    /lala/,
    {},
    new Date(),
    new Number(42),
    new Boolean(true),
    new String("lalala")
  ];

  var constructorPreCases = [
    function() {return undefined;}
  ].concat(preCases);
  var constructorPostCases = [
    function() {return undefined;}
  ].concat(postCases);
  var constructorExceptionCases = [
    function() {return undefined;}
  ].concat(exceptionCases);

  var location = util.eol + "    at /";

  function expectInvariants(subject) {
    expect(subject).to.be.an.instanceOf(Contract);
    testUtil.expectFrozenReadOnlyArrayPropertyWithPrivateBackingField(subject, "pre", "_pre");
    testUtil.expectToBeArrayOfFunctions(subject.pre);
    testUtil.expectFrozenReadOnlyArrayPropertyWithPrivateBackingField(subject, "post", "_post");
    testUtil.expectToBeArrayOfFunctions(subject.post);
    testUtil.expectFrozenReadOnlyArrayPropertyWithPrivateBackingField(subject, "exception", "_exception");
    testUtil.expectToBeArrayOfFunctions(subject.exception);
    testUtil.expectOwnFrozenProperty(subject, "location");
    expect(subject.location).to.satisfy(function(location) {return util.isALocationOutsideLibrary(location);});
    testUtil.expectOwnFrozenProperty(subject, "abstract");
    var abstract = subject.abstract;
    expect(abstract).to.satisfy(function(cf) {return Contract.isAContractFunction(cf);});
    expect(abstract).to.satisfy(function(cf) {return subject.isImplementedBy(cf);});
    expect(abstract).to.throw(Contract.AbstractError, Contract.AbstractError.message);
    try {
      abstract();
    }
    catch (err) {
      testUtil.log(err.stack);
    }
  }

  function expectConstructorPost(pre, post, exception, result) {
    function expectArrayPost(array, propName, privatePropName) {
      if (!array) {
        expect(result[propName]).to.eql([]);
      }
      else {
        expect(result[privatePropName]).to.eql(array);
        expect(result[privatePropName]).to.not.equal(array);  // it must be copy, don't share the array
        expect(result[privatePropName]).to.be.frozen;
        expect(result[propName]).to.eql(array);
        expect(result[propName]).to.not.equal(result[privatePropName]);  // it must be copy, don't share the array
      }
    }

    it("has a shallow copy of the given pre-conditions, and the private array is frozen", function() {
      expectArrayPost(pre, "pre", "_pre");
    });
    it("has a shallow copy of the given post-conditions, and the private array is frozen", function() {
      expectArrayPost(post, "post", "_post");
    });
    it("has a shallow copy of the given exception-conditions, and the private array is frozen", function() {
      expectArrayPost(exception, "exception", "_exception");
    });
    it("adheres to the invariants", function() {
      expectInvariants(result);
    });
  }

  function createCandidateContractFunction(dontFreezeProperty,
                                           otherPropertyName,
                                           otherPropertyValue,
                                           bind) {
    function candidate() {}

    function impl() {}

    var contract = otherPropertyName === "contract" ? otherPropertyValue : new Contract();
    var implementation = otherPropertyName === "implementation" ? otherPropertyValue : impl;
    var location = otherPropertyName === "location" ? otherPropertyValue : util.firstLocationOutsideLibrary();
    var bind = otherPropertyName === "bind" ? otherPropertyValue : Contract.bindContractFunction;

    if (dontFreezeProperty === "contract") {
      candidate.contract = contract;
    }
    else {
      util.setAndFreezeProperty(candidate, "contract", contract);
    }
    if (dontFreezeProperty === "implementation") {
      candidate.implementation = implementation;
    }
    else {
      util.setAndFreezeProperty(candidate, "implementation", implementation);
    }
    if (dontFreezeProperty === "location") {
      candidate.location = location;
    }
    else {
      util.setAndFreezeProperty(candidate, "location", location);
    }
    if (dontFreezeProperty === "bind") {
      candidate.bind = bind;
    }
    else {
      util.setAndFreezeProperty(candidate, "bind", bind);
    }
    candidate.displayName =
      (otherPropertyName === "displayName")
        ? otherPropertyValue
        : Contract.contractFunctionDisplayName(candidate);
    return candidate;
  }

  function generatePrototypeMethodsDescriptions(oneSubjectGenerator, allSubjectGenerators) {
    var self = this;

    describe("#isImplementedBy()", function() {
      it("says yes if the argument is a contract function for the contract", function() {
        var subject = oneSubjectGenerator();
        var f = createCandidateContractFunction(null, "contract", subject);
        //noinspection BadExpressionStatementJS
        expect(subject.isImplementedBy(f)).to.be.ok;
        self.expectInvariants(subject);
      });
      thingsThatAreNotAFunctionNorAContract
        .concat(["function() {}"])
        .forEach(function(thing) {
          it("says no if the argument is not a contract function but " + thing, function() {
            var subject = oneSubjectGenerator();
            //noinspection BadExpressionStatementJS
            expect(subject.isImplementedBy(thing)).not.to.be.ok;
            self.expectInvariants(subject);
          });
      });
      it("says no if the argument is a contract function for another contract", function() {
        var subject = oneSubjectGenerator();
        var otherContract = oneSubjectGenerator();
        var f = createCandidateContractFunction(null, "contract", otherContract);
        //noinspection BadExpressionStatementJS
        expect(subject.isImplementedBy(f)).not.to.be.ok;
        self.expectInvariants(subject);
      });
    });

  }

  return {
    preCases: preCases,
    postCases: postCases,
    exceptionCases: exceptionCases,
    thingsThatAreNotAFunctionNorAContract: thingsThatAreNotAFunctionNorAContract,
    constructorPreCases: constructorPreCases,
    constructorPostCases: constructorPostCases,
    constructorExceptionCases: constructorExceptionCases,
    location: location,
    expectInvariants: expectInvariants,
    expectConstructorPost: expectConstructorPost,
    createCandidateContractFunction: createCandidateContractFunction,
    generatePrototypeMethodsDescriptions: generatePrototypeMethodsDescriptions
  };

})();
<commit_msg>warning fix: noinspection<commit_after>/*
 Copyright 2016 - 2017 by Jan Dockx

 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.
 */

module.exports = (function() {
  "use strict";

  var expect = require("chai").expect;
  var util = require("../../src/_private/util");
  var testUtil = require("../_testUtil");
  var Contract = require("../../src/I/Contract");

  var someConditions = [
    function() {return [];},
    function() {return [function() {return false;}, function() {return true;}];}
  ];
  var preCases = [
    function() {return null;}
  ].concat(someConditions);
  var postCases = [
    function() {return null;}
  ].concat(someConditions);
  var exceptionCases = [
    function() {return null;}
  ].concat(someConditions);

  //noinspection JSPrimitiveTypeWrapperUsage,MagicNumberJS
  var thingsThatAreNotAFunctionNorAContract = [
    undefined,
    null,
    "",
    "foo",
    0,
    -1,
    true,
    false,
    /lala/,
    {},
    new Date(),
    new Number(42),
    new Boolean(true),
    new String("lalala")
  ];

  var constructorPreCases = [
    function() {return undefined;}
  ].concat(preCases);
  var constructorPostCases = [
    function() {return undefined;}
  ].concat(postCases);
  var constructorExceptionCases = [
    function() {return undefined;}
  ].concat(exceptionCases);

  var location = util.eol + "    at /";

  function expectInvariants(subject) {
    expect(subject).to.be.an.instanceOf(Contract);
    testUtil.expectFrozenReadOnlyArrayPropertyWithPrivateBackingField(subject, "pre", "_pre");
    testUtil.expectToBeArrayOfFunctions(subject.pre);
    testUtil.expectFrozenReadOnlyArrayPropertyWithPrivateBackingField(subject, "post", "_post");
    testUtil.expectToBeArrayOfFunctions(subject.post);
    testUtil.expectFrozenReadOnlyArrayPropertyWithPrivateBackingField(subject, "exception", "_exception");
    testUtil.expectToBeArrayOfFunctions(subject.exception);
    testUtil.expectOwnFrozenProperty(subject, "location");
    expect(subject.location).to.satisfy(function(location) {return util.isALocationOutsideLibrary(location);});
    testUtil.expectOwnFrozenProperty(subject, "abstract");
    var abstract = subject.abstract;
    expect(abstract).to.satisfy(function(cf) {return Contract.isAContractFunction(cf);});
    expect(abstract).to.satisfy(function(cf) {return subject.isImplementedBy(cf);});
    expect(abstract).to.throw(Contract.AbstractError, Contract.AbstractError.message);
    try {
      abstract();
    }
    catch (err) {
      testUtil.log(err.stack);
    }
  }

  function expectConstructorPost(pre, post, exception, result) {
    function expectArrayPost(array, propName, privatePropName) {
      if (!array) {
        expect(result[propName]).to.eql([]);
      }
      else {
        expect(result[privatePropName]).to.eql(array);
        expect(result[privatePropName]).to.not.equal(array);  // it must be copy, don't share the array
        //noinspection BadExpressionStatementJS
        expect(result[privatePropName]).to.be.frozen;
        expect(result[propName]).to.eql(array);
        expect(result[propName]).to.not.equal(result[privatePropName]);  // it must be copy, don't share the array
      }
    }

    it("has a shallow copy of the given pre-conditions, and the private array is frozen", function() {
      expectArrayPost(pre, "pre", "_pre");
    });
    it("has a shallow copy of the given post-conditions, and the private array is frozen", function() {
      expectArrayPost(post, "post", "_post");
    });
    it("has a shallow copy of the given exception-conditions, and the private array is frozen", function() {
      expectArrayPost(exception, "exception", "_exception");
    });
    it("adheres to the invariants", function() {
      expectInvariants(result);
    });
  }

  function createCandidateContractFunction(dontFreezeProperty,
                                           otherPropertyName,
                                           otherPropertyValue,
                                           bind) {
    function candidate() {}

    function impl() {}

    var contract = otherPropertyName === "contract" ? otherPropertyValue : new Contract();
    var implementation = otherPropertyName === "implementation" ? otherPropertyValue : impl;
    var location = otherPropertyName === "location" ? otherPropertyValue : util.firstLocationOutsideLibrary();
    var bind = otherPropertyName === "bind" ? otherPropertyValue : Contract.bindContractFunction;

    if (dontFreezeProperty === "contract") {
      candidate.contract = contract;
    }
    else {
      util.setAndFreezeProperty(candidate, "contract", contract);
    }
    if (dontFreezeProperty === "implementation") {
      candidate.implementation = implementation;
    }
    else {
      util.setAndFreezeProperty(candidate, "implementation", implementation);
    }
    if (dontFreezeProperty === "location") {
      candidate.location = location;
    }
    else {
      util.setAndFreezeProperty(candidate, "location", location);
    }
    if (dontFreezeProperty === "bind") {
      candidate.bind = bind;
    }
    else {
      util.setAndFreezeProperty(candidate, "bind", bind);
    }
    candidate.displayName =
      (otherPropertyName === "displayName")
        ? otherPropertyValue
        : Contract.contractFunctionDisplayName(candidate);
    return candidate;
  }

  function generatePrototypeMethodsDescriptions(oneSubjectGenerator, allSubjectGenerators) {
    var self = this;

    describe("#isImplementedBy()", function() {
      it("says yes if the argument is a contract function for the contract", function() {
        var subject = oneSubjectGenerator();
        var f = createCandidateContractFunction(null, "contract", subject);
        //noinspection BadExpressionStatementJS
        expect(subject.isImplementedBy(f)).to.be.ok;
        self.expectInvariants(subject);
      });
      thingsThatAreNotAFunctionNorAContract
        .concat(["function() {}"])
        .forEach(function(thing) {
          it("says no if the argument is not a contract function but " + thing, function() {
            var subject = oneSubjectGenerator();
            //noinspection BadExpressionStatementJS
            expect(subject.isImplementedBy(thing)).not.to.be.ok;
            self.expectInvariants(subject);
          });
      });
      it("says no if the argument is a contract function for another contract", function() {
        var subject = oneSubjectGenerator();
        var otherContract = oneSubjectGenerator();
        var f = createCandidateContractFunction(null, "contract", otherContract);
        //noinspection BadExpressionStatementJS
        expect(subject.isImplementedBy(f)).not.to.be.ok;
        self.expectInvariants(subject);
      });
    });

  }

  return {
    preCases: preCases,
    postCases: postCases,
    exceptionCases: exceptionCases,
    thingsThatAreNotAFunctionNorAContract: thingsThatAreNotAFunctionNorAContract,
    constructorPreCases: constructorPreCases,
    constructorPostCases: constructorPostCases,
    constructorExceptionCases: constructorExceptionCases,
    location: location,
    expectInvariants: expectInvariants,
    expectConstructorPost: expectConstructorPost,
    createCandidateContractFunction: createCandidateContractFunction,
    generatePrototypeMethodsDescriptions: generatePrototypeMethodsDescriptions
  };

})();
<|endoftext|>


<commit_before>$(document).ready(function() {
	var refreshTable = $("#bittrex").DataTable( {
		"ajax": {
			"url": "http://162.243.239.186:8000/?url=https://bittrex.com/api/v1.1/public/getmarketsummaries",
			"dataSrc": "result"
		},
		"columns": [
			{ "data": "MarketName", "render": function (data,type,row) { return ' ' + (data) +''; } },
			{ "data": "Last", "render": function (data,type,row) { return (data).toFixed(8); } },
                        { "data": "High", "render": function (data,type,row) { return ' ' + (data).toFixed(8) +''; }  },
                        { "data": "Low", "render": function (data,type,row) { return ' ' + (data).toFixed(8) +''; }  },
			{ "data": "BaseVolume", "render": function (data,type,row) { return ' ' + (data) +''; }  },
			{ "data": "Volume" }
		],
                "dom": 'T<"clear">lfrtip',
                "tableTools": {
                    "sSwfPath": "swf/copy_csv_xls_pdf.swf",
                    "aButtons": [
                        "copy",
                        "print",
                        {
                            "sExtends":    "collection",
                            "sButtonText": "Save",
                            "aButtons":    [ "csv", "xls", "pdf" ]
                        }
                    ]
                }
	} );
       setInterval (function test() {
         refreshTable.ajax.reload( null, false );
       }, 300000);
} );
<commit_msg>[FIX] coin image height<commit_after>$(document).ready(function() {
	var refreshTable = $("#bittrex").DataTable( {
		"ajax": {
			"url": "http://162.243.239.186:8000/?url=https://bittrex.com/api/v1.1/public/getmarketsummaries",
			"dataSrc": "result"
		},
		"columns": [
			{ "data": "MarketName", "render": function (data,type,row) { return ' ' + (data) +''; } },
			{ "data": "Last", "render": function (data,type,row) { return (data).toFixed(8); } },
                        { "data": "High", "render": function (data,type,row) { return ' ' + (data).toFixed(8) +''; }  },
                        { "data": "Low", "render": function (data,type,row) { return ' ' + (data).toFixed(8) +''; }  },
			{ "data": "BaseVolume", "render": function (data,type,row) { return ' ' + (data) +''; }  },
			{ "data": "Volume" }
		],
                "dom": 'T<"clear">lfrtip',
                "tableTools": {
                    "sSwfPath": "swf/copy_csv_xls_pdf.swf",
                    "aButtons": [
                        "copy",
                        "print",
                        {
                            "sExtends":    "collection",
                            "sButtonText": "Save",
                            "aButtons":    [ "csv", "xls", "pdf" ]
                        }
                    ]
                }
	} );
       setInterval (function test() {
         refreshTable.ajax.reload( null, false );
       }, 300000);
} );
<|endoftext|>


<commit_before>var w = 720;
var h = 200;

void setup() {
  size(w, h);
  background(100,100,255);
}

void draw() {

  /*
  function drawPath(x,y) {
    noStroke();
    x = 20*x-20;
    y = 20*y-20;
    for(var xi = x; xi < x+20; xi+=4) {
        for(var yi = y; yi < y+20; yi+=4) {
            noStroke();
            fill(random(175,200), random(175,200), 0);
            rect(xi,yi,4,4);
        }
    }
  }

  function drawDesert(x,y) {
    noStroke();
    x = 20*x-20;
    y = 20*y-20;
    for(var xi = x; xi < x+20; xi+=4) {
        for(var yi = y; yi < y+20; yi+=4) {
            noStroke();
            //224, 166, 137
            fill(random(230,255), random(200,229), random(175,199));
            rect(xi,yi,4,4);
        }
    }
}

function drawSwamp(x,y) {
    noStroke();
    x = 20*x-20;
    y = 20*y-20;
    for(var xi = x; xi < x+20; xi+=4) {
        for(var yi = y; yi < y+20; yi+=4) {
            noStroke();
            fill(0,random(50,200),random(50,150));
            rect(xi,yi,4,4);
        }
    }
  }

  function drawfLoor(x,y) {
    //stroke(255, 255, 255);
    x = 20*x-20;
    y = 20*y-20;
    for(var xi = x; xi < x+16; xi+=8) {
            //1st line
            //stroke(51, 32, 2);
            fill(random(100,125),random(75,100),0);
            rect(xi,y,4,7);
            fill(random(100,125),random(75,100),0);
            rect(xi,y+7,4,7);
            //stroke(30, 0, 0);
            fill(random(100,125),random(75,100),0);
            rect(xi,y+14,4,6);
            //2nd line
            noStroke();
            fill(random(100,125),random(75,100),0);
            rect(xi+4,y,4,4);
            fill(random(100,125),random(75,100),0);
            rect(xi+4,y+16,4,4);
            //stroke(30, 0, 0);
            fill(random(100,125),random(75,100),0);
            rect(xi+4,y+4,4,7);
            fill(random(100,125),random(75,100),0);
            rect(xi+4,y+10,4,6);
    }
    //last line
    var xi = x+16;
    //stroke(51, 32, 2);
    fill(random(100,125),random(75,100),0);
    rect(xi,y,4,7);
    fill(random(100,125),random(75,100),0);
    rect(xi,y+7,4,7);
    //stroke(30, 0, 0);
    fill(random(100,125),random(75,100),0);
    rect(xi,y+14,4,6);
}
*/

  for(var y = 1; y < 11; y++) {
     draw_Brick(1,y);
     draw_Brick(36,y);
   }

  for(var x = 2; x < 36; x++) {
    draw_Brick(x,1);
    draw_Brick(x,10);
    for(var y = 2; y < 10; y++) {
      draw_rUg(x,y);
    }
  }

draw_PlayerFacingDown();
}

void draw_PlayerFacingDown() {
  fill(player.skin[0],player.skin[1],player.skin[2]);
  //ears
  ellipse(player.x-6-player.face*2,player.y-12,4,4);
  ellipse(player.x+6+player.face*2,player.y-12,4,4);
   // head
  ellipse(player.x,player.y-10,12+player.face*4,20);

  // arms
  rect(player.x-10,player.y+8,4,4);
  rect(player.x+6,player.y+8,4,4);

  // tshirt
  fill(player.tColor[0],player.tColor[1],player.tColor[2]);
  rect(player.x-6,player.y,12,14);
  rect(player.x-10,player.y,4,8);
  rect(player.x+6,player.y,4,8);

  /*
  // hat
  rect(player.x-player.face-6, player.y-25, player.face*2+12, 5);
  fill(0,0,100);
  rect(player.x-player.face-6-3, player.y-21, 3, 2);
  */

  // tshirt logo
  fill(255,255,255);
  text(player.tshirt,player.x-3,player.y+10);

  // eye whites
  fill(255,255,255);
  ellipse(player.x-3-player.face,player.y-11,4,5);
  ellipse(player.x+3+player.face,player.y-11,4,5);

  //pupils
  fill(0,0,0);
  ellipse(player.x-3-player.face,player.y-11,1,1);
  ellipse(player.x+3+player.face,player.y-11,1,1);

  // mouth
  rect(player.x-3,player.y-5,6,1);

  // hair
  for(x = player.x-player.face*2; x <= player.x+player.face*2; x+=2) {
    noFill();
    stroke(player.hairColor[0],player.hairColor[1],player.hairColor[2]);
    ellipse(x,player.y-20,2,3);
  }
  stroke(0,0,0);

  //pants
  fill(player.pColor[0],player.pColor[1],player.pColor[2]);
  noStroke();
  rect(player.x-6,player.y+16,4,3);
  rect(player.x+2, player.y+16,4,3);
  rect(player.x-6,player.y+14,12,2);
  stroke(0,0,0);

  //shoes
  fill(0,0,0);
  rect(player.x-5,player.y+18,5,2);
  rect(player.x+2,player.y+18,5,2);
}

//rug
void draw_rUg(x,y) {
  noStroke();
  x = 20*x-20;
  y = 20*y-20;
  for(var xi = x; xi < x+20; xi+=4) {
      for(var yi = y; yi < y+20; yi+=4) {
          noStroke();
          fill(random(175,200), 0, 0);
          rect(xi,yi,4,4);
      }
  }
}

void draw_Brick(x,y) {
  //stroke(255, 255, 255);
  x = 20*x-20;
  y = 20*y-20;
  for(var yi = y; yi < y+16; yi+=8) {
    //1st line
    stroke(30, 0, 0);
    fill(random(31,255),0,0);
    rect(x,yi,6,4);
    fill(random(31,225),0,0);
    rect(x+7,yi,7,4);
    stroke(30, 0, 0);
    fill(random(31,225),0,0);
    rect(x+14,yi,6,4);
    //2nd line
    noStroke();
    fill(random(31,255),0,0);
    rect(x,yi+4,4,4);
    fill(random(31,225),0,0);
    rect(x+16,yi+4,4,4);
    stroke(30, 0, 0);
    fill(random(31,225),0,0);
    rect(x+4,yi+4,7,4);
    fill(random(31,225),0,0);
    rect(x+10,yi+4,6,4);
  }
  //last line
  var yi = y+16;
  stroke(30, 0, 0);
  fill(random(31,255),0,0);
  rect(x,yi,6,4);
  fill(random(31,225),0,0);
  rect(x+7,yi,7,4);
  stroke(30, 0, 0);
  fill(random(31,225),0,0);
  rect(x+14,yi,6,4);
  rect(x+10,yi,6,4);
  noStroke();
  }

  /*
  void draw_Grass(x,y) {
    noStroke();
    x = 20*x-20;
    y = 20*y-20;
    for(var xi = x; xi < x+20; xi+=4) {
        for(var yi = y; yi < y+20; yi+=4) {
            noStroke();
            fill(random(75,100),random(225,255),random(75,100));
            rect(xi,yi,4,4);
        }
    }
  }
  */

var brk = {
  "canPass":false,
  "draw": draw_Brick();
};

var rug = {
  "canPass":true,
  "draw": draw_rUg();
};

var map = [[brk, brk, brk, brk, brk, brk, brk, brk, brk],
           [brk, rug, rug, rug, rug, rug, rug, rug, brk],
           [brk, rug, rug, rug, rug, rug, rug, rug, brk],
           [brk, rug, rug, rug, rug, rug, rug, rug, brk],
           [brk, rug, rug, rug, rug, rug, rug, rug, brk],
           [brk, rug, rug, rug, rug, rug, rug, rug, brk],
           [brk, rug, rug, rug, rug, rug, rug, rug, brk],
           [brk, rug, rug, rug, rug, rug, rug, rug, brk],
           [brk, rug, rug, rug, rug, rug, rug, rug, brk],
           [brk, brk, brk, brk, brk, brk, brk, brk, brk]];
<commit_msg>Update drawgame.js<commit_after>var w = 720;
var h = 200;

void setup() {
  size(w, h);
  background(100,100,255);
}

void draw() {

  /*
  function drawPath(x,y) {
    noStroke();
    x = 20*x-20;
    y = 20*y-20;
    for(var xi = x; xi < x+20; xi+=4) {
        for(var yi = y; yi < y+20; yi+=4) {
            noStroke();
            fill(random(175,200), random(175,200), 0);
            rect(xi,yi,4,4);
        }
    }
  }

  function drawDesert(x,y) {
    noStroke();
    x = 20*x-20;
    y = 20*y-20;
    for(var xi = x; xi < x+20; xi+=4) {
        for(var yi = y; yi < y+20; yi+=4) {
            noStroke();
            //224, 166, 137
            fill(random(230,255), random(200,229), random(175,199));
            rect(xi,yi,4,4);
        }
    }
}

function drawSwamp(x,y) {
    noStroke();
    x = 20*x-20;
    y = 20*y-20;
    for(var xi = x; xi < x+20; xi+=4) {
        for(var yi = y; yi < y+20; yi+=4) {
            noStroke();
            fill(0,random(50,200),random(50,150));
            rect(xi,yi,4,4);
        }
    }
  }

  function drawfLoor(x,y) {
    //stroke(255, 255, 255);
    x = 20*x-20;
    y = 20*y-20;
    for(var xi = x; xi < x+16; xi+=8) {
            //1st line
            //stroke(51, 32, 2);
            fill(random(100,125),random(75,100),0);
            rect(xi,y,4,7);
            fill(random(100,125),random(75,100),0);
            rect(xi,y+7,4,7);
            //stroke(30, 0, 0);
            fill(random(100,125),random(75,100),0);
            rect(xi,y+14,4,6);
            //2nd line
            noStroke();
            fill(random(100,125),random(75,100),0);
            rect(xi+4,y,4,4);
            fill(random(100,125),random(75,100),0);
            rect(xi+4,y+16,4,4);
            //stroke(30, 0, 0);
            fill(random(100,125),random(75,100),0);
            rect(xi+4,y+4,4,7);
            fill(random(100,125),random(75,100),0);
            rect(xi+4,y+10,4,6);
    }
    //last line
    var xi = x+16;
    //stroke(51, 32, 2);
    fill(random(100,125),random(75,100),0);
    rect(xi,y,4,7);
    fill(random(100,125),random(75,100),0);
    rect(xi,y+7,4,7);
    //stroke(30, 0, 0);
    fill(random(100,125),random(75,100),0);
    rect(xi,y+14,4,6);
}
*/

  for(var y = 1; y < 11; y++) {
     draw_Grass(1,y);
     draw_Grass(36,y);
     draw_Brick(2,y);
     draw_Brick(35,y);
   }

  for(var x = 2; x < 36; x++) {
    draw_Brick(x,1);
    draw_Brick(x,10);
    for(var y = 2; y < 10; y++) {
      draw_rUg(x,y);
    }
  }

draw_PlayerFacingDown();
}

void draw_PlayerFacingDown() {
  fill(player.skin[0],player.skin[1],player.skin[2]);
  //ears
  ellipse(player.x-6-player.face*2,player.y-12,4,4);
  ellipse(player.x+6+player.face*2,player.y-12,4,4);
   // head
  ellipse(player.x,player.y-10,12+player.face*4,20);

  // arms
  rect(player.x-10,player.y+8,4,4);
  rect(player.x+6,player.y+8,4,4);

  // tshirt
  fill(player.tColor[0],player.tColor[1],player.tColor[2]);
  rect(player.x-6,player.y,12,14);
  rect(player.x-10,player.y,4,8);
  rect(player.x+6,player.y,4,8);

  /*
  // hat
  rect(player.x-player.face-6, player.y-25, player.face*2+12, 5);
  fill(0,0,100);
  rect(player.x-player.face-6-3, player.y-21, 3, 2);
  */

  // tshirt logo
  fill(255,255,255);
  text(player.tshirt,player.x-3,player.y+10);

  // eye whites
  fill(255,255,255);
  ellipse(player.x-3-player.face,player.y-11,4,5);
  ellipse(player.x+3+player.face,player.y-11,4,5);

  //pupils
  fill(0,0,0);
  ellipse(player.x-3-player.face,player.y-11,1,1);
  ellipse(player.x+3+player.face,player.y-11,1,1);

  // mouth
  rect(player.x-3,player.y-5,6,1);

  // hair
  for(x = player.x-player.face*2; x <= player.x+player.face*2; x+=2) {
    noFill();
    stroke(player.hairColor[0],player.hairColor[1],player.hairColor[2]);
    ellipse(x,player.y-20,2,3);
  }
  stroke(0,0,0);

  //pants
  fill(player.pColor[0],player.pColor[1],player.pColor[2]);
  noStroke();
  rect(player.x-6,player.y+16,4,3);
  rect(player.x+2, player.y+16,4,3);
  rect(player.x-6,player.y+14,12,2);
  stroke(0,0,0);

  //shoes
  fill(0,0,0);
  rect(player.x-5,player.y+18,5,2);
  rect(player.x+2,player.y+18,5,2);
}

//rug
void draw_rUg(x,y) {
  noStroke();
  x = 20*x-20;
  y = 20*y-20;
  for(var xi = x; xi < x+20; xi+=4) {
      for(var yi = y; yi < y+20; yi+=4) {
          noStroke();
          fill(random(175,200), 0, 0);
          rect(xi,yi,4,4);
      }
  }
}

void draw_Brick(x,y) {
  //stroke(255, 255, 255);
  x = 20*x-20;
  y = 20*y-20;
  for(var yi = y; yi < y+16; yi+=8) {
    //1st line
    stroke(30, 0, 0);
    fill(random(31,255),0,0);
    rect(x,yi,6,4);
    fill(random(31,225),0,0);
    rect(x+7,yi,7,4);
    stroke(30, 0, 0);
    fill(random(31,225),0,0);
    rect(x+14,yi,6,4);
    //2nd line
    noStroke();
    fill(random(31,255),0,0);
    rect(x,yi+4,4,4);
    fill(random(31,225),0,0);
    rect(x+16,yi+4,4,4);
    stroke(30, 0, 0);
    fill(random(31,225),0,0);
    rect(x+4,yi+4,7,4);
    fill(random(31,225),0,0);
    rect(x+10,yi+4,6,4);
  }
  //last line
  var yi = y+16;
  stroke(30, 0, 0);
  fill(random(31,255),0,0);
  rect(x,yi,6,4);
  fill(random(31,225),0,0);
  rect(x+7,yi,7,4);
  stroke(30, 0, 0);
  fill(random(31,225),0,0);
  rect(x+14,yi,6,4);
  rect(x+10,yi,6,4);
  noStroke();
  }

  void draw_Grass(x,y) {
    noStroke();
    x = 20*x-20;
    y = 20*y-20;
    for(var xi = x; xi < x+20; xi+=4) {
        for(var yi = y; yi < y+20; yi+=4) {
            noStroke();
            fill(random(75,100),random(225,255),random(75,100));
            rect(xi,yi,4,4);
        }
    }
  }

/*
var brk = {
  "canPass":false,
  "draw": draw_Brick();
};

var rug = {
  "canPass":true,
  "draw": draw_rUg();
};

var map = [[brk, brk, brk, brk, brk, brk, brk, brk, brk],
           [brk, rug, rug, rug, rug, rug, rug, rug, brk],
           [brk, rug, rug, rug, rug, rug, rug, rug, brk],
           [brk, rug, rug, rug, rug, rug, rug, rug, brk],
           [brk, rug, rug, rug, rug, rug, rug, rug, brk],
           [brk, rug, rug, rug, rug, rug, rug, rug, brk],
           [brk, rug, rug, rug, rug, rug, rug, rug, brk],
           [brk, rug, rug, rug, rug, rug, rug, rug, brk],
           [brk, rug, rug, rug, rug, rug, rug, rug, brk],
           [brk, brk, brk, brk, brk, brk, brk, brk, brk]];
           */
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Route.extend({
  _scheduleRefresh: Ember.on('init', function() {
    Ember.run.later(()=> {
      this.refresh();
      if (this.get('model.running')) {
        this._scheduleRefresh();
      }
    }, 5000);
  }),
  model() {
    return Ember.$.getJSON("/v1/status");
  },
  actions: {
    abort() {
      return Ember.$.post("/v1/abort").then(()=> {
        this.refresh();
      });
    },
  },
});
<commit_msg>[fix] Wrong property<commit_after>import Ember from 'ember';

export default Ember.Route.extend({
  _scheduleRefresh: Ember.on('init', function() {
    Ember.run.later(()=> {
      this.refresh();
      if (this.get('controller.model.running')) {
        this._scheduleRefresh();
      }
    }, 5000);
  }),
  model() {
    return Ember.$.getJSON("/v1/status");
  },
  actions: {
    abort() {
      return Ember.$.post("/v1/abort").then(()=> {
        this.refresh();
      });
    },
  },
});
<|endoftext|>