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

    angular.module('ariaNg').factory('aria2TaskService', ['$q', '$translate', 'aria2RpcService', 'ariaNgCommonService', function ($q, $translate, aria2RpcService, ariaNgCommonService) {
        var getFileName = function (file) {
            if (!file) {
                return '';
            }

            var path = file.path;

            if (!path && file.uris && file.uris.length > 0) {
                path = file.uris[0].uri;
            }

            var index = path.lastIndexOf('/');

            if (index <= 0 || index == path.length) {
                return path;
            }

            return path.substring(index + 1);
        };

        var calculateDownloadRemainTime = function (remainBytes, downloadSpeed) {
            if (downloadSpeed == 0) {
                return 0;
            }

            return remainBytes / downloadSpeed;
        };

        var getTaskName = function (task) {
            var taskName = "";
            var success = true;

            if (task.bittorrent && task.bittorrent.info) {
                taskName = task.bittorrent.info.name;
            }

            if (!taskName && task.files && task.files.length > 0) {
                taskName = getFileName(task.files[0]);
            }

            if (!taskName) {
                taskName = $translate.instant('Unknown');
                success = false;
            }

            return {
                name: taskName,
                success: success
            };
        };

        var processDownloadTask = function (task) {
            if (!task) {
                return task;
            }

            task.totalLength = parseInt(task.totalLength);
            task.completedLength = parseInt(task.completedLength);
            task.completePercent = (task.totalLength > 0 ? task.completedLength / task.totalLength * 100 : 0);
            task.remainLength = task.totalLength - task.completedLength;
            task.remainPercent = 100 - task.completePercent;
            task.uploadLength = (task.uploadLength ? parseInt(task.uploadLength) : 0);
            task.shareRatio = (task.completedLength > 0 ? task.uploadLength / task.completedLength : 0);

            task.uploadSpeed = parseInt(task.uploadSpeed);
            task.downloadSpeed = parseInt(task.downloadSpeed);

            task.idle = task.downloadSpeed == 0;
            task.remainTime = calculateDownloadRemainTime(task.remainLength, task.downloadSpeed);

            var taskNameResult = getTaskName(task);
            task.taskName = taskNameResult.name;
            task.hasTaskName = taskNameResult.success;

            if (task.files) {
                var selectedFileCount = 0;

                for (var i = 0; i < task.files.length; i++) {
                    var file = task.files[i];
                    file.fileName = getFileName(file);
                    file.length = parseInt(file.length);
                    file.selected = (file.selected === true || file.selected === 'true');
                    file.completedLength = parseInt(file.completedLength);
                    file.completePercent = (file.length > 0 ? file.completedLength / file.length * 100 : 0);

                    selectedFileCount += file.selected ? 1 : 0;
                }

                task.selectedFileCount = selectedFileCount;
            }

            return task;
        };

        var getPieceStatus = function (bitField, pieceCount) {
            var pieces = [];

            if (!bitField) {
                return pieces;
            }

            var pieceIndex = 0;

            for (var i = 0; i < bitField.length; i++) {
                var bitSet = parseInt(bitField[i], 16);

                for (var j = 1; j <= 4; j++) {
                    var bit = (1 << (4 - j));
                    var isCompleted = (bitSet & bit) == bit;

                    pieces.push(isCompleted);
                    pieceIndex++;

                    if (pieceIndex >= pieceCount) {
                        return pieces;
                    }
                }
            }

            return pieces;
        };

        var getCombinedPieces = function (bitField, pieceCount) {
            var pieces = getPieceStatus(bitField, pieceCount);
            var combinedPieces = [];

            for (var i = 0; i < pieces.length; i++) {
                var isCompleted = pieces[i];

                if (combinedPieces.length > 0 && combinedPieces[combinedPieces.length - 1].isCompleted == isCompleted) {
                    combinedPieces[combinedPieces.length - 1].count++;
                } else {
                    combinedPieces.push({
                        isCompleted: isCompleted,
                        count: 1
                    });
                }
            }

            return combinedPieces;
        };

        var createLocalPeerFromTask = function (task) {
            return {
                local: true,
                bitfield: task.bitfield,
                completePercent: task.completePercent,
                downloadSpeed: task.downloadSpeed,
                name: '(local)',
                seeder: task.seeder,
                uploadSpeed: task.uploadSpeed
            };
        };

        return {
            getTaskList: function (type, full, callback, silent) {
                var invokeMethod = null;

                if (type == 'downloading') {
                    invokeMethod = aria2RpcService.tellActive;
                } else if (type == 'waiting') {
                    invokeMethod = aria2RpcService.tellWaiting;
                } else if (type == 'stopped') {
                    invokeMethod = aria2RpcService.tellStopped;
                } else {
                    return;
                }

                return invokeMethod({
                    requestWholeInfo: full,
                    requestParams: full ? aria2RpcService.getFullTaskParams() : aria2RpcService.getBasicTaskParams(),
                    silent: !!silent,
                    callback: function (response) {
                        if (!callback) {
                            return;
                        }

                        callback(response);
                    }
                });
            },
            getTaskStatus: function (gid, callback, silent) {
                return aria2RpcService.tellStatus({
                    gid: gid,
                    silent: !!silent,
                    callback: function (response) {
                        if (!callback) {
                            return;
                        }

                        if (response.success) {
                            processDownloadTask(response.data);
                        }

                        callback(response);
                    }
                });
            },
            getTaskOptions: function (gid, callback, silent) {
                return aria2RpcService.getOption({
                    gid: gid,
                    silent: !!silent,
                    callback: callback
                });
            },
            setTaskOption: function (gid, key, value, callback, silent) {
                var data = {};
                data[key] = value;

                return aria2RpcService.changeOption({
                    gid: gid,
                    options: data,
                    silent: !!silent,
                    callback: callback
                });
            },
            selectTaskFile: function (gid, selectedFileIndexArr, callback, silent) {
                var selectedFileIndex = '';

                for (var i = 0; i < selectedFileIndexArr.length; i++) {
                    if (selectedFileIndex.length > 0) {
                        selectedFileIndex += ',';
                    }

                    selectedFileIndex += selectedFileIndexArr[i];
                }

                return this.setTaskOption(gid, 'select-file', selectedFileIndex, callback, silent);
            },
            getBtTaskPeers: function (task, callback, silent, includeLocal) {
                return aria2RpcService.getPeers({
                    gid: task.gid,
                    silent: !!silent,
                    callback: function (response) {
                        if (!callback) {
                            return;
                        }

                        if (response.success) {
                            var peers = response.data;

                            for (var i = 0; i < peers.length; i++) {
                                var peer = peers[i];
                                var upstreamToSpeed = peer.uploadSpeed;
                                var downstreamFromSpeed = peer.downloadSpeed;
                                var completedPieces = getPieceStatus(peer.bitfield, task.numPieces);

                                peer.name = peer.ip + ':' + peer.port;
                                peer.completePercent = ariaNgCommonService.countArray(completedPieces, true) / task.numPieces * 100;
                                peer.downloadSpeed = upstreamToSpeed;
                                peer.uploadSpeed = downstreamFromSpeed;
                            }

                            if (includeLocal) {
                                peers.push(createLocalPeerFromTask(task));
                            }
                        }

                        callback(response);
                    }
                });
            },
            newUriTask: function (task, pauseOnAdded, callback, silent) {
                return aria2RpcService.addUri({
                    task: task,
                    pauseOnAdded: !!pauseOnAdded,
                    silent: !!silent,
                    callback: callback
                });
            },
            newUriTasks: function (tasks, pauseOnAdded, callback, silent) {
                return aria2RpcService.addUriMulti({
                    tasks: tasks,
                    pauseOnAdded: !!pauseOnAdded,
                    silent: !!silent,
                    callback: callback
                });
            },
            newTorrentTask: function (task, pauseOnAdded, callback, silent) {
                return aria2RpcService.addTorrent({
                    task: task,
                    pauseOnAdded: !!pauseOnAdded,
                    silent: !!silent,
                    callback: callback
                });
            },
            newMetalinkTask: function (task, pauseOnAdded, callback, silent) {
                return aria2RpcService.addMetalink({
                    task: task,
                    pauseOnAdded: !!pauseOnAdded,
                    silent: !!silent,
                    callback: callback
                });
            },
            startTasks: function (gids, callback, silent) {
                return aria2RpcService.unpauseMulti({
                    gids: gids,
                    silent: !!silent,
                    callback: callback
                });
            },
            pauseTasks: function (gids, callback, silent) {
                return aria2RpcService.forcePauseMulti({
                    gids: gids,
                    silent: !!silent,
                    callback: callback
                });
            },
            removeTasks: function (tasks, callback, silent) {
                var runningTaskGids = [];
                var stoppedTaskGids = [];

                for (var i = 0; i < tasks.length; i++) {
                    if (tasks[i].status == 'complete' || tasks[i].status == 'error' || tasks[i].status == 'removed') {
                        stoppedTaskGids.push(tasks[i].gid);
                    } else {
                        runningTaskGids.push(tasks[i].gid);
                    }
                }

                var promises = [];

                var hasSuccess = false;
                var hasError = false;
                var results = [];

                if (runningTaskGids.length > 0) {
                    promises.push(aria2RpcService.forceRemoveMulti({
                        gids: runningTaskGids,
                        silent: !!silent,
                        callback: function (response) {
                            ariaNgCommonService.pushArrayTo(results, response.results);
                            hasSuccess = hasSuccess | response.hasSuccess;
                            hasError = hasError | response.hasError;
                        }
                    }));
                }

                if (stoppedTaskGids.length > 0) {
                    promises.push(aria2RpcService.removeDownloadResultMulti({
                        gids: stoppedTaskGids,
                        silent: !!silent,
                        callback: function (response) {
                            ariaNgCommonService.pushArrayTo(results, response.results);
                            hasSuccess = hasSuccess | response.hasSuccess;
                            hasError = hasError | response.hasError;
                        }
                    }));
                }

                return $q.all(promises).then(function () {
                    if (callback) {
                        callback({
                            hasSuccess: !!hasSuccess,
                            hasError: !!hasError,
                            results: results
                        });
                    }
                });
            },
            changeTaskPosition: function (gid, position, callback, silent) {
                return aria2RpcService.changePosition({
                    gid: gid,
                    pos: position,
                    how: 'POS_SET',
                    silent: !!silent,
                    callback: callback
                })
            },
            clearStoppedTasks: function (callback, silent) {
                return aria2RpcService.purgeDownloadResult({
                    silent: !!silent,
                    callback: callback
                });
            },
            processDownloadTasks: function (tasks) {
                if (!angular.isArray(tasks)) {
                    return;
                }

                for (var i = 0; i < tasks.length; i++) {
                    processDownloadTask(tasks[i]);
                }
            },
            getPieceStatus: function (bitField, pieceCount) {
                return getPieceStatus(bitField, pieceCount);
            },
            getCombinedPieces: function (bitField, pieceCount) {
                return getCombinedPieces(bitField, pieceCount);
            },
            estimateHealthPercentFromPeers: function (task, peers) {
                if (peers.length < 1) {
                    return task.completePercent;
                }

                var totalPieces = [];
                var currentPieces = getPieceStatus(task.bitfield, task.numPieces);
                var maxCompletedPieceCount = 0;
                var maxCompletedPercent = task.completePercent;

                for (var i = 0; i < currentPieces.length; i++) {
                    var count = currentPieces[i] ? 1 : 0;
                    totalPieces.push(count);
                    maxCompletedPieceCount += count;
                }

                for (var i = 0; i < peers.length; i++) {
                    var peer = peers[i];
                    var peerPieces = getPieceStatus(peer.bitfield, task.numPieces);
                    var completedPieceCount = 0;

                    for (var j = 0; j < peerPieces.length; j++) {
                        var count = (peerPieces[j] ? 1 : 0);
                        totalPieces[j] += count;
                        completedPieceCount += count;
                    }

                    if (completedPieceCount > maxCompletedPieceCount) {
                        maxCompletedPieceCount = completedPieceCount;
                        maxCompletedPercent = peer.completePercent;
                    } else if (completedPieceCount == maxCompletedPieceCount && peer.completePercent > maxCompletedPercent) {
                        maxCompletedPercent = peer.completePercent;
                    }
                }

                var totalCompletedPieceCount = 0;

                while (true) {
                    var completed = true;

                    for (var i = 0; i < totalPieces.length; i++) {
                        if (totalPieces[i] > 0) {
                            totalCompletedPieceCount++;
                            totalPieces[i]--;
                        } else {
                            completed = false;
                        }
                    }

                    if (!completed) {
                        break;
                    }
                }

                if (totalCompletedPieceCount <= maxCompletedPieceCount) {
                    return maxCompletedPercent;
                }

                var healthPercent = totalCompletedPieceCount / task.numPieces * 100;

                if (healthPercent <= maxCompletedPercent) {
                    return maxCompletedPercent;
                }

                return healthPercent;
            }
        };
    }]);
})();
<commit_msg>fix bug<commit_after>(function () {
    'use strict';

    angular.module('ariaNg').factory('aria2TaskService', ['$q', '$translate', 'aria2RpcService', 'ariaNgCommonService', function ($q, $translate, aria2RpcService, ariaNgCommonService) {
        var getFileName = function (file) {
            if (!file) {
                return '';
            }

            var path = file.path;

            if (!path && file.uris && file.uris.length > 0) {
                path = file.uris[0].uri;
            }

            var index = path.lastIndexOf('/');

            if (index <= 0 || index == path.length) {
                return path;
            }

            return path.substring(index + 1);
        };

        var calculateDownloadRemainTime = function (remainBytes, downloadSpeed) {
            if (downloadSpeed == 0) {
                return 0;
            }

            return remainBytes / downloadSpeed;
        };

        var getTaskName = function (task) {
            var taskName = "";
            var success = true;

            if (task.bittorrent && task.bittorrent.info) {
                taskName = task.bittorrent.info.name;
            }

            if (!taskName && task.files && task.files.length > 0) {
                taskName = getFileName(task.files[0]);
            }

            if (!taskName) {
                taskName = $translate.instant('Unknown');
                success = false;
            }

            return {
                name: taskName,
                success: success
            };
        };

        var processDownloadTask = function (task) {
            if (!task) {
                return task;
            }

            task.totalLength = parseInt(task.totalLength);
            task.completedLength = parseInt(task.completedLength);
            task.completePercent = (task.totalLength > 0 ? task.completedLength / task.totalLength * 100 : 0);
            task.remainLength = task.totalLength - task.completedLength;
            task.remainPercent = 100 - task.completePercent;
            task.uploadLength = (task.uploadLength ? parseInt(task.uploadLength) : 0);
            task.shareRatio = (task.completedLength > 0 ? task.uploadLength / task.completedLength : 0);

            task.uploadSpeed = parseInt(task.uploadSpeed);
            task.downloadSpeed = parseInt(task.downloadSpeed);

            task.idle = task.downloadSpeed == 0;
            task.remainTime = calculateDownloadRemainTime(task.remainLength, task.downloadSpeed);

            var taskNameResult = getTaskName(task);
            task.taskName = taskNameResult.name;
            task.hasTaskName = taskNameResult.success;

            if (task.files) {
                var selectedFileCount = 0;

                for (var i = 0; i < task.files.length; i++) {
                    var file = task.files[i];
                    file.fileName = getFileName(file);
                    file.length = parseInt(file.length);
                    file.selected = (file.selected === true || file.selected === 'true');
                    file.completedLength = parseInt(file.completedLength);
                    file.completePercent = (file.length > 0 ? file.completedLength / file.length * 100 : 0);

                    selectedFileCount += file.selected ? 1 : 0;
                }

                task.selectedFileCount = selectedFileCount;
            }

            return task;
        };

        var getPieceStatus = function (bitField, pieceCount) {
            var pieces = [];

            if (!bitField) {
                return pieces;
            }

            var pieceIndex = 0;

            for (var i = 0; i < bitField.length; i++) {
                var bitSet = parseInt(bitField[i], 16);

                for (var j = 1; j <= 4; j++) {
                    var bit = (1 << (4 - j));
                    var isCompleted = (bitSet & bit) == bit;

                    pieces.push(isCompleted);
                    pieceIndex++;

                    if (pieceIndex >= pieceCount) {
                        return pieces;
                    }
                }
            }

            return pieces;
        };

        var getCombinedPieces = function (bitField, pieceCount) {
            var pieces = getPieceStatus(bitField, pieceCount);
            var combinedPieces = [];

            for (var i = 0; i < pieces.length; i++) {
                var isCompleted = pieces[i];

                if (combinedPieces.length > 0 && combinedPieces[combinedPieces.length - 1].isCompleted == isCompleted) {
                    combinedPieces[combinedPieces.length - 1].count++;
                } else {
                    combinedPieces.push({
                        isCompleted: isCompleted,
                        count: 1
                    });
                }
            }

            return combinedPieces;
        };

        var createLocalPeerFromTask = function (task) {
            return {
                local: true,
                bitfield: task.bitfield,
                completePercent: task.completePercent,
                downloadSpeed: task.downloadSpeed,
                name: '(local)',
                seeder: task.seeder,
                uploadSpeed: task.uploadSpeed
            };
        };

        return {
            getTaskList: function (type, full, callback, silent) {
                var invokeMethod = null;

                if (type == 'downloading') {
                    invokeMethod = aria2RpcService.tellActive;
                } else if (type == 'waiting') {
                    invokeMethod = aria2RpcService.tellWaiting;
                } else if (type == 'stopped') {
                    invokeMethod = aria2RpcService.tellStopped;
                } else {
                    return;
                }

                return invokeMethod({
                    requestWholeInfo: full,
                    requestParams: full ? aria2RpcService.getFullTaskParams() : aria2RpcService.getBasicTaskParams(),
                    silent: !!silent,
                    callback: function (response) {
                        if (!callback) {
                            return;
                        }

                        callback(response);
                    }
                });
            },
            getTaskStatus: function (gid, callback, silent) {
                return aria2RpcService.tellStatus({
                    gid: gid,
                    silent: !!silent,
                    callback: function (response) {
                        if (!callback) {
                            return;
                        }

                        if (response.success) {
                            processDownloadTask(response.data);
                        }

                        callback(response);
                    }
                });
            },
            getTaskOptions: function (gid, callback, silent) {
                return aria2RpcService.getOption({
                    gid: gid,
                    silent: !!silent,
                    callback: callback
                });
            },
            setTaskOption: function (gid, key, value, callback, silent) {
                var data = {};
                data[key] = value;

                return aria2RpcService.changeOption({
                    gid: gid,
                    options: data,
                    silent: !!silent,
                    callback: callback
                });
            },
            selectTaskFile: function (gid, selectedFileIndexArr, callback, silent) {
                var selectedFileIndex = '';

                for (var i = 0; i < selectedFileIndexArr.length; i++) {
                    if (selectedFileIndex.length > 0) {
                        selectedFileIndex += ',';
                    }

                    selectedFileIndex += selectedFileIndexArr[i];
                }

                return this.setTaskOption(gid, 'select-file', selectedFileIndex, callback, silent);
            },
            getBtTaskPeers: function (task, callback, silent, includeLocal) {
                return aria2RpcService.getPeers({
                    gid: task.gid,
                    silent: !!silent,
                    callback: function (response) {
                        if (!callback) {
                            return;
                        }

                        if (response.success) {
                            var peers = response.data;
                            var localTaskCompletedPieces = getPieceStatus(task.bitfield, task.numPieces);
                            var localTaskCompletedPieceCount = ariaNgCommonService.countArray(localTaskCompletedPieces, true);
                            var localTaskCompletedPercent = task.completePercent;

                            for (var i = 0; i < peers.length; i++) {
                                var peer = peers[i];
                                var upstreamToSpeed = peer.uploadSpeed;
                                var downstreamFromSpeed = peer.downloadSpeed;
                                var completedPieces = getPieceStatus(peer.bitfield, task.numPieces);
                                var completedPieceCount = ariaNgCommonService.countArray(completedPieces, true);

                                peer.name = peer.ip + ':' + peer.port;
                                peer.completePercent = completedPieceCount / task.numPieces * 100;
                                peer.downloadSpeed = upstreamToSpeed;
                                peer.uploadSpeed = downstreamFromSpeed;

                                if (completedPieceCount == localTaskCompletedPieceCount && peer.completePercent != localTaskCompletedPercent) {
                                    peer.completePercent = localTaskCompletedPercent;
                                }
                            }

                            if (includeLocal) {
                                peers.push(createLocalPeerFromTask(task));
                            }
                        }

                        callback(response);
                    }
                });
            },
            newUriTask: function (task, pauseOnAdded, callback, silent) {
                return aria2RpcService.addUri({
                    task: task,
                    pauseOnAdded: !!pauseOnAdded,
                    silent: !!silent,
                    callback: callback
                });
            },
            newUriTasks: function (tasks, pauseOnAdded, callback, silent) {
                return aria2RpcService.addUriMulti({
                    tasks: tasks,
                    pauseOnAdded: !!pauseOnAdded,
                    silent: !!silent,
                    callback: callback
                });
            },
            newTorrentTask: function (task, pauseOnAdded, callback, silent) {
                return aria2RpcService.addTorrent({
                    task: task,
                    pauseOnAdded: !!pauseOnAdded,
                    silent: !!silent,
                    callback: callback
                });
            },
            newMetalinkTask: function (task, pauseOnAdded, callback, silent) {
                return aria2RpcService.addMetalink({
                    task: task,
                    pauseOnAdded: !!pauseOnAdded,
                    silent: !!silent,
                    callback: callback
                });
            },
            startTasks: function (gids, callback, silent) {
                return aria2RpcService.unpauseMulti({
                    gids: gids,
                    silent: !!silent,
                    callback: callback
                });
            },
            pauseTasks: function (gids, callback, silent) {
                return aria2RpcService.forcePauseMulti({
                    gids: gids,
                    silent: !!silent,
                    callback: callback
                });
            },
            removeTasks: function (tasks, callback, silent) {
                var runningTaskGids = [];
                var stoppedTaskGids = [];

                for (var i = 0; i < tasks.length; i++) {
                    if (tasks[i].status == 'complete' || tasks[i].status == 'error' || tasks[i].status == 'removed') {
                        stoppedTaskGids.push(tasks[i].gid);
                    } else {
                        runningTaskGids.push(tasks[i].gid);
                    }
                }

                var promises = [];

                var hasSuccess = false;
                var hasError = false;
                var results = [];

                if (runningTaskGids.length > 0) {
                    promises.push(aria2RpcService.forceRemoveMulti({
                        gids: runningTaskGids,
                        silent: !!silent,
                        callback: function (response) {
                            ariaNgCommonService.pushArrayTo(results, response.results);
                            hasSuccess = hasSuccess | response.hasSuccess;
                            hasError = hasError | response.hasError;
                        }
                    }));
                }

                if (stoppedTaskGids.length > 0) {
                    promises.push(aria2RpcService.removeDownloadResultMulti({
                        gids: stoppedTaskGids,
                        silent: !!silent,
                        callback: function (response) {
                            ariaNgCommonService.pushArrayTo(results, response.results);
                            hasSuccess = hasSuccess | response.hasSuccess;
                            hasError = hasError | response.hasError;
                        }
                    }));
                }

                return $q.all(promises).then(function () {
                    if (callback) {
                        callback({
                            hasSuccess: !!hasSuccess,
                            hasError: !!hasError,
                            results: results
                        });
                    }
                });
            },
            changeTaskPosition: function (gid, position, callback, silent) {
                return aria2RpcService.changePosition({
                    gid: gid,
                    pos: position,
                    how: 'POS_SET',
                    silent: !!silent,
                    callback: callback
                })
            },
            clearStoppedTasks: function (callback, silent) {
                return aria2RpcService.purgeDownloadResult({
                    silent: !!silent,
                    callback: callback
                });
            },
            processDownloadTasks: function (tasks) {
                if (!angular.isArray(tasks)) {
                    return;
                }

                for (var i = 0; i < tasks.length; i++) {
                    processDownloadTask(tasks[i]);
                }
            },
            getPieceStatus: function (bitField, pieceCount) {
                return getPieceStatus(bitField, pieceCount);
            },
            getCombinedPieces: function (bitField, pieceCount) {
                return getCombinedPieces(bitField, pieceCount);
            },
            estimateHealthPercentFromPeers: function (task, peers) {
                if (peers.length < 1) {
                    return task.completePercent;
                }

                var totalPieces = [];
                var currentPieces = getPieceStatus(task.bitfield, task.numPieces);
                var maxCompletedPieceCount = 0;
                var maxCompletedPercent = task.completePercent;

                for (var i = 0; i < currentPieces.length; i++) {
                    var count = currentPieces[i] ? 1 : 0;
                    totalPieces.push(count);
                    maxCompletedPieceCount += count;
                }

                for (var i = 0; i < peers.length; i++) {
                    var peer = peers[i];
                    var peerPieces = getPieceStatus(peer.bitfield, task.numPieces);
                    var completedPieceCount = 0;

                    for (var j = 0; j < peerPieces.length; j++) {
                        var count = (peerPieces[j] ? 1 : 0);
                        totalPieces[j] += count;
                        completedPieceCount += count;
                    }

                    if (completedPieceCount > maxCompletedPieceCount) {
                        maxCompletedPieceCount = completedPieceCount;
                        maxCompletedPercent = peer.completePercent;
                    } else if (completedPieceCount == maxCompletedPieceCount && peer.completePercent > maxCompletedPercent) {
                        maxCompletedPercent = peer.completePercent;
                    }
                }

                var totalCompletedPieceCount = 0;

                while (true) {
                    var completed = true;

                    for (var i = 0; i < totalPieces.length; i++) {
                        if (totalPieces[i] > 0) {
                            totalCompletedPieceCount++;
                            totalPieces[i]--;
                        } else {
                            completed = false;
                        }
                    }

                    if (!completed) {
                        break;
                    }
                }

                if (totalCompletedPieceCount <= maxCompletedPieceCount) {
                    return maxCompletedPercent;
                }

                var healthPercent = totalCompletedPieceCount / task.numPieces * 100;

                if (healthPercent <= maxCompletedPercent) {
                    return maxCompletedPercent;
                }

                return healthPercent;
            }
        };
    }]);
})();
<|endoftext|>


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

import SearchableSelect from '../SearchableSelect';

import styles from './styles.css';

import { apiModel } from '../../../utils/api';

export default class RelationField extends React.Component { // eslint-disable-line react/prefer-stateless-function
  static contextTypes = {
    notify: PropTypes.func
  };
  static propTypes = {
    value: PropTypes.string,
    onChange: PropTypes.func,
    relation: PropTypes.object,
    className: PropTypes.string,
    props: PropTypes.object,
  }
  componentDidMount() {
    this.fetchRelation();
  }
  onInputEvents = (event) => {
    const { value } = event.target;
    const ENTER_KEY = 13;
    if (event.type === 'blur' && !value) {
      this.setState({ relationState: 'none' });
    } else if (event.type === 'keypress' && event.charCode !== ENTER_KEY) {
      event.stopPropagation();
    } else {
      event.preventDefault();
      if (!value) return;
      this.newRelation(value);
    }
  }
  newRelation = name => apiModel.new(this.props.relation.model, { name }).then(result => {
    this.setState({ relationState: 'none' });
    this.fetchRelation(result.instance.uuid);
  }).catch(() => {
    this.context.notify('Couldn\'t create activity type, validation failed', 'error');
    this.setState({ relationState: 'none' });
  })
  handleValueChange = (value) => {
    if (this.props.onChange) this.props.onChange(value === 'none' ? null : value);
  }
  fetchRelation = value => {
    const { relation, onChange } = this.props;
    return apiModel.search(relation.model, relation.query).then(result => {
      if (value) onChange(value);
      this.setState({ options: result.instances });
    });
  }
  render() {
    const state = this.state || {};
    const { className, props } = this.props;
    let { value } = this.props;
    if (typeof value === 'object') value = value.uuid;
    const options = 'options' in state ? state.options : [];
    const searchableAttrs = { options, value, className };
    return (

      <SearchableSelect {...searchableAttrs} {...props} dispatchRefresh={this.fetchRelation} onChange={this.handleValueChange} addItem={this.newRelation} />

);
  }
}
<commit_msg>Fix broken thing<commit_after>import React, { PropTypes } from 'react';

import SearchableSelect from '../SearchableSelect';

import styles from './styles.css';

import { apiModel } from '../../../utils/api';

export default class RelationField extends React.Component { // eslint-disable-line react/prefer-stateless-function
  static contextTypes = {
    notify: PropTypes.func
  };
  static propTypes = {
    value: PropTypes.string,
    onChange: PropTypes.func,
    relation: PropTypes.object,
    className: PropTypes.string,
    props: PropTypes.object,
  }
  componentDidMount() {
    this.fetchRelation();
  }
  onInputEvents = (event) => {
    const { value } = event.target;
    const ENTER_KEY = 13;
    if (event.type === 'blur' && !value) {
      this.setState({ relationState: 'none' });
    } else if (event.type === 'keypress' && event.charCode !== ENTER_KEY) {
      event.stopPropagation();
    } else {
      event.preventDefault();
      if (!value) return;
      this.newRelation(value);
    }
  }
  newRelation = name => apiModel.new(this.props.relation.model, { name }).then(result => {
    this.setState({ relationState: 'none' });
    this.fetchRelation(result.instance.uuid);
  }).catch(() => {
    this.context.notify('Couldn\'t create activity type, validation failed', 'error');
    this.setState({ relationState: 'none' });
  })
  handleValueChange = (value) => {
    if (this.props.onChange) this.props.onChange(value === 'none' ? null : value);
  }
  fetchRelation = value => {
    const { relation, onChange } = this.props;
    return apiModel.search(relation.model, relation.query).then(result => {
      if (value) onChange(value);
      this.setState({ options: result.instances });
    });
  }
  render() {
    const state = this.state || {};
    const { className, props } = this.props;
    let { value } = this.props;
    if (value && typeof value === 'object') value = value.uuid;
    const options = 'options' in state ? state.options : [];
    const searchableAttrs = { options, value, className };
    return (

      <SearchableSelect {...searchableAttrs} {...props} dispatchRefresh={this.fetchRelation} onChange={this.handleValueChange} addItem={this.newRelation} />

);
  }
}
<|endoftext|>


<commit_before>/**
*
* ToolsComponents
*
*/

import React from 'react';
import styled from 'styled-components';
import { ThemeProvider } from 'styled-components';
import { Link } from 'react-router';

import ContentBlock from 'components/ContentBlock';
import Isvg from 'react-inlinesvg';

import messages from './messages';

import { TYPE_STORIES, TYPE_TACTICS, TYPE_PRINCIPLES,
          TYPE_THEORIES, TYPE_METHODOLOGIES } from './constants';

import RealWorldIconImage from 'assets/images/icons/real-world.svg';

export const getToolTypeColor = (type) => {
  switch(type) {
    case TYPE_STORIES:
      return "#08eb8c";
    case TYPE_TACTICS:
      return "#ff9200";
    case TYPE_PRINCIPLES:
      return "#0088ff";
    case TYPE_THEORIES:
      return "#f93732";
    case TYPE_METHODOLOGIES:
      return "#b700c2";
  }
}

/*** START OF TOOLS ICONS ***/
export const RealWorldIcon = styled(Isvg)`
  svg {
    fill: ${props=>props.type ? getToolTypeColor(props.type) : 'red'};

    .circle {
      fill: black;
    }
  }
`;

export const PotentialRiskIcon = styled(Isvg)`
  svg {
    fill: ${props=>props.type ? getToolTypeColor(props.type) : 'red'};
  }
`;
/*** END OF TOOLS ICONS ***/

export const ToolsButton = styled.button`
  outline: none;
  cursor: pointer;
  ${p => p.color ? `color: ${p.color};` : ''}
  font-weight: bold;
  padding: 0;
  img { margin-right: 10px;}
  display: inline-block;
  ${
    props=> {
      if (props.lang&&props.lang==='ar') {
        return `transform: ${props.toShow&&props.rotate ? 'rotate(0)' : 'rotate(180deg)'};`
      } else {
        return `transform: ${props.toShow&&props.rotate ? 'rotate(180deg)' : 'rotate(0)'};`
      }
    }
  }

  transition:  transform 0.4s ease;

  text-transform: uppercase;

  svg, svg * {
    fill: ${props=>props.color ? props.color : (props.toShow ? 'black' : '#828486')};
    width: ${props=>props.width || 'auto'};
    transition:  fill 0.4s ease;
  }
`;
export const ToolsListMenu = styled.ul`
    padding: 0;
    padding: 10px 0 10px;
    border-bottom: 2px solid black;
    margin: 0;
    display: ${props=>props.show?'block':'none'};

    & > li:first-child {
      ${props=>props.lang==='ar' ? 'border-left' : 'border-right'}: 2px solid;
    }
`;
export const ToolsListMenuItem = styled.li`
  list-style: none;
  display: inline-block;
  width: 49%;
  text-align: center;
`;

export const ToolType = styled.h3`
  margin: 0;
  font-size: ${p=>p.ar?'32px':'20px'};
  letter-spacing: ${p=>p.ar?'3px':'0'};
  text-align: ${p=>p.theme.isArabic?'right':'left'};
  padding-top: 20px;
  font-family: 'Paint Hand', 'Massira Spray', serif;
  color: ${props => getToolTypeColor(props.type) };
`;

export const ToolTitle = styled.h1`
  font-size: 32px;
  letter-spacing: 1px;
  font-weight: normal;
  margin: 0;
  margin-bottom: 26px;
  text-align: ${p=>p.theme.isArabic?'right':'left'};
  font-size: ${p=>p.theme.isArabic?'30px':'30px'};
  line-height: 1;

  > a {
    color: ${props=>props.color || 'black'};
  }
  color: ${props=>props.color || 'black'};
`;
export const ToolsList = styled.ul`
padding: 0 0 0 5px;
margin: 0;
`;
export const ToolsListItem = styled.li`
  list-style: none;
  margin: 10px 10px 30px;
  border-top: 2px solid;

  &:first-child {
    border: none;
  }
`;

export const ToolsMenu = styled.ul`
  width: 73px;
  float: ${props=>props.theme.lang === 'ar' ? 'right' : 'left'};
  height: 100%;
  margin: 0;
  padding: 20px 0;
  // border: solid black;
  // border-width: ${props=>props.theme.lang === 'ar' ? '0 0 0 2px' : '0 2px 0 0'};
  @media(max-width: 700px) {
    display: flex;
    padding: 0;
    width: 100%;
    border: none;
  }
`;
export const ToolsMenuItem = styled.li`
  list-style: none;
  margin: 10px 0;

  margin-bottom: ${p=> p.marginBottom || '20px'};

  .isvg {
    &::after {
      content: ' ';
      display: block;
      clear: both;
    }
  }

  @media(max-width: 700px) {
    flex-grow: 1;
  }
`;

export const ToolsListContainer = styled.div``;
export const ToolsViewport = styled.div`
    ${(props) => props.showTools ? '350px' : '75px' };
height: 100%;`;

export const ToolsContainer = styled.div`
  position: fixed;

  width: ${(props) => props.showTools ? '350px' : '75px' };
  height: calc(100vh - 220px)
  border: 2px solid black;
  // top: 217px;

  bottom: 0;
  border-width: ${props=>props.lang == 'ar' ? '2px 2px 0 0' : '2px 0 0 2px'};

  ${props=>props.lang == 'ar' ? 'left: 0;' : 'right: 0;'}
  transition: transform 0.3s ease, width 0.3s ease;
  overflow-x: hidden;
  overflow-y: hidden;

  //mobile
  @media(max-width: 700px) {
    position: fixed;
    bottom: 0;
    top: auto;
    left: 0;
    width: 100vw;
    height: 70px;
    background-color: white;
    z-index: 600;

    border-width: 2px;
  }
`;

export const ToolContainer = styled.div`
  ${props=>props.lang==='ar' ? 'float: right' : 'float: left'};
  text-align: left;
`;

export const BlockAddRem = styled.div`
  text-align: ${p=>p.theme.isArabic?'right':'left'};
`;

//List View
export const ListContainer = styled(ToolContainer)`
  width: 370px;
  text-align: left;
  margin-${p=>p.lang==='ar'?'left':'right'}: ${p=>p.index%2==0?'0':'130px'};
  padding-bottom: 40px;

  @media(max-width: 700px) {
    margin: 0;
    width: 100%;
    padding: 20px;
  }
`;

export const ListSpiel = styled(ContentBlock)`
  margin: 0;
`;
export const ListDivider = styled.h3`
  color: black;
  border-color: black;
  border-width: 2px;
  margin-top: 0px;
  width: 60px;
`;
<commit_msg>https://3.basecamp.com/3161453/buckets/3412210/todos/633294972 There should be no horizontal lines under fb, twitter, pdf, and email<commit_after>/**
*
* ToolsComponents
*
*/

import React from 'react';
import styled from 'styled-components';
import { ThemeProvider } from 'styled-components';
import { Link } from 'react-router';

import ContentBlock from 'components/ContentBlock';
import Isvg from 'react-inlinesvg';

import messages from './messages';

import { TYPE_STORIES, TYPE_TACTICS, TYPE_PRINCIPLES,
          TYPE_THEORIES, TYPE_METHODOLOGIES } from './constants';

import RealWorldIconImage from 'assets/images/icons/real-world.svg';

export const getToolTypeColor = (type) => {
  switch(type) {
    case TYPE_STORIES:
      return "#08eb8c";
    case TYPE_TACTICS:
      return "#ff9200";
    case TYPE_PRINCIPLES:
      return "#0088ff";
    case TYPE_THEORIES:
      return "#f93732";
    case TYPE_METHODOLOGIES:
      return "#b700c2";
  }
}

/*** START OF TOOLS ICONS ***/
export const RealWorldIcon = styled(Isvg)`
  svg {
    fill: ${props=>props.type ? getToolTypeColor(props.type) : 'red'};

    .circle {
      fill: black;
    }
  }
`;

export const PotentialRiskIcon = styled(Isvg)`
  svg {
    fill: ${props=>props.type ? getToolTypeColor(props.type) : 'red'};
  }
`;
/*** END OF TOOLS ICONS ***/

export const ToolsButton = styled.button`
  outline: none;
  cursor: pointer;
  ${p => p.color ? `color: ${p.color};` : ''}
  font-weight: bold;
  padding: 0;
  img { margin-right: 10px;}
  display: inline-block;
  ${
    props=> {
      if (props.lang&&props.lang==='ar') {
        return `transform: ${props.toShow&&props.rotate ? 'rotate(0)' : 'rotate(180deg)'};`
      } else {
        return `transform: ${props.toShow&&props.rotate ? 'rotate(180deg)' : 'rotate(0)'};`
      }
    }
  }

  transition:  transform 0.4s ease;

  text-transform: uppercase;

  svg, svg * {
    fill: ${props=>props.color ? props.color : (props.toShow ? 'black' : '#828486')};
    width: ${props=>props.width || 'auto'};
    transition:  fill 0.4s ease;
  }
`;
export const ToolsListMenu = styled.ul`
    padding: 0;
    padding: 10px 0 10px;
    margin: 0;
    display: ${props=>props.show?'block':'none'};

    & > li:first-child {
      ${props=>props.lang==='ar' ? 'border-left' : 'border-right'}: 2px solid;
    }
`;
export const ToolsListMenuItem = styled.li`
  list-style: none;
  display: inline-block;
  width: 49%;
  text-align: center;
`;

export const ToolType = styled.h3`
  margin: 0;
  font-size: ${p=>p.ar?'32px':'20px'};
  letter-spacing: ${p=>p.ar?'3px':'0'};
  text-align: ${p=>p.theme.isArabic?'right':'left'};
  padding-top: 20px;
  font-family: 'Paint Hand', 'Massira Spray', serif;
  color: ${props => getToolTypeColor(props.type) };
`;

export const ToolTitle = styled.h1`
  font-size: 32px;
  letter-spacing: 1px;
  font-weight: normal;
  margin: 0;
  margin-bottom: 26px;
  text-align: ${p=>p.theme.isArabic?'right':'left'};
  font-size: ${p=>p.theme.isArabic?'30px':'30px'};
  line-height: 1;

  > a {
    color: ${props=>props.color || 'black'};
  }
  color: ${props=>props.color || 'black'};
`;
export const ToolsList = styled.ul`
padding: 0 0 0 5px;
margin: 0;
`;
export const ToolsListItem = styled.li`
  list-style: none;
  margin: 10px 10px 30px;
  border-top: 2px solid;

  &:first-child {
    border: none;
  }
`;

export const ToolsMenu = styled.ul`
  width: 73px;
  float: ${props=>props.theme.lang === 'ar' ? 'right' : 'left'};
  height: 100%;
  margin: 0;
  padding: 20px 0;
  // border: solid black;
  // border-width: ${props=>props.theme.lang === 'ar' ? '0 0 0 2px' : '0 2px 0 0'};
  @media(max-width: 700px) {
    display: flex;
    padding: 0;
    width: 100%;
    border: none;
  }
`;
export const ToolsMenuItem = styled.li`
  list-style: none;
  margin: 10px 0;

  margin-bottom: ${p=> p.marginBottom || '20px'};

  .isvg {
    &::after {
      content: ' ';
      display: block;
      clear: both;
    }
  }

  @media(max-width: 700px) {
    flex-grow: 1;
  }
`;

export const ToolsListContainer = styled.div``;
export const ToolsViewport = styled.div`
    ${(props) => props.showTools ? '350px' : '75px' };
height: 100%;`;

export const ToolsContainer = styled.div`
  position: fixed;

  width: ${(props) => props.showTools ? '350px' : '75px' };
  height: calc(100vh - 220px)
  border: 2px solid black;
  // top: 217px;

  bottom: 0;
  border-width: ${props=>props.lang == 'ar' ? '2px 2px 0 0' : '2px 0 0 2px'};

  ${props=>props.lang == 'ar' ? 'left: 0;' : 'right: 0;'}
  transition: transform 0.3s ease, width 0.3s ease;
  overflow-x: hidden;
  overflow-y: hidden;

  //mobile
  @media(max-width: 700px) {
    position: fixed;
    bottom: 0;
    top: auto;
    left: 0;
    width: 100vw;
    height: 70px;
    background-color: white;
    z-index: 600;

    border-width: 2px;
  }
`;

export const ToolContainer = styled.div`
  ${props=>props.lang==='ar' ? 'float: right' : 'float: left'};
  text-align: left;
`;

export const BlockAddRem = styled.div`
  text-align: ${p=>p.theme.isArabic?'right':'left'};
`;

//List View
export const ListContainer = styled(ToolContainer)`
  width: 370px;
  text-align: left;
  margin-${p=>p.lang==='ar'?'left':'right'}: ${p=>p.index%2==0?'0':'130px'};
  padding-bottom: 40px;

  @media(max-width: 700px) {
    margin: 0;
    width: 100%;
    padding: 20px;
  }
`;

export const ListSpiel = styled(ContentBlock)`
  margin: 0;
`;
export const ListDivider = styled.h3`
  color: black;
  border-color: black;
  border-width: 2px;
  margin-top: 0px;
  width: 60px;
`;
<|endoftext|>


<commit_before>'use strict';
var isInit = true,
    helpers = require('../../utils/widgets/helper'),
    navigationProperty = require('../../utils/widgets/navigation-property'),
    // additional requires
    viewModel = require('./browseView-view-model'),
    modBrowse = require('../../lib/modBrowse/modBrowse.js'),
    modBrowser = require('../../lib/modBrowser/modBrowser.js')
	scanner = require('../../utils/nativeBarcodeScanner'),
	;

// additional functions
function pageLoaded(args) {
    var page = args.object;

    helpers.platformInit(page);
    page.bindingContext = viewModel;
    // additional pageLoaded

    if (isInit) {
        isInit = false;

        // additional pageInit
    }
}

// START_CUSTOM_CODE_homeView
// Add custom code here. For more information about custom code, see http://docs.telerik.com/platform/screenbuilder/troubleshooting/how-to-keep-custom-code-changes
var view = require("ui/core/view");
function goTap(args) {
    var sender = args.object;
    var parent = sender.parent;
    if (parent) {
        var tf = view.getViewById(parent, "urlTF");
        if (tf) {
            var url = tf.text;
            modBrowse.pushHistory(url, function(status) {
                var browser = modBrowser.createBrowser();
                browser.open(url);
            });

        }
    }
}
function goScan(args) {
    var sender = args.object;
    var parent = sender.parent;
    if (parent) {
        scanner.scan(function(result) {
			alert(JSON.stringify(result));
		});
    }
}
exports.goTap = goTap;
exports.goScan = goScan;
// END_CUSTOM_CODE_homeView
exports.pageLoaded = pageLoaded;<commit_msg>fix import issue<commit_after>'use strict';
var isInit = true,
    helpers = require('../../utils/widgets/helper'),
    navigationProperty = require('../../utils/widgets/navigation-property'),
    // additional requires
    viewModel = require('./browseView-view-model'),
    modBrowse = require('../../lib/modBrowse/modBrowse.js'),
    modBrowser = require('../../lib/modBrowser/modBrowser.js'),
	scanner = require('../../utils/nativeBarcodeScanner')
	;

// additional functions
function pageLoaded(args) {
    var page = args.object;

    helpers.platformInit(page);
    page.bindingContext = viewModel;
    // additional pageLoaded

    if (isInit) {
        isInit = false;

        // additional pageInit
    }
}

// START_CUSTOM_CODE_homeView
// Add custom code here. For more information about custom code, see http://docs.telerik.com/platform/screenbuilder/troubleshooting/how-to-keep-custom-code-changes
var view = require("ui/core/view");
function goTap(args) {
    var sender = args.object;
    var parent = sender.parent;
    if (parent) {
        var tf = view.getViewById(parent, "urlTF");
        if (tf) {
            var url = tf.text;
            modBrowse.pushHistory(url, function(status) {
                var browser = modBrowser.createBrowser();
                browser.open(url);
            });

        }
    }
}
function goScan(args) {
    var sender = args.object;
    var parent = sender.parent;
    if (parent) {
        scanner.scan(function(result) {
			alert(JSON.stringify(result));
		});
    }
}
exports.goTap = goTap;
exports.goScan = goScan;
// END_CUSTOM_CODE_homeView
exports.pageLoaded = pageLoaded;<|endoftext|>


<commit_before>/*
  @module wholetale
  @submodule nice-dropzone
*/
import Ember from 'ember';
import layout from './template';

var dragTimer;

// A google drive like dropzone.
// Intended to mimic how google drive handles file uploads.
// How I'd like for this to behave:
//   0) Dropzone is initially hidden
//   1) Show dropzone when dragging files (not folders or page elements)
//      over the page.
//   2) Re-hide when dropped
//   3) Show file upload progress pane in lower right.
//   4) On complete, check for errors and display green check or red X
//      in the upload progress pane.
export default Ember.Component.extend({
    layout,
    initialized_listeners: false,

    didRender() {
        Ember.$('.dropzone').addClass('hidden');
        this.resizeDropzone();

        if(!this.initialized_listeners) {
            let self = this;
            Ember.$('#dz-drag').on('dragover', this.showDropzone.bind(this));
            Ember.$('.dropzone').on('dragover', this.showDropzone.bind(this));
            Ember.$('#dz-drag').on('dragleave', function(evt) {
                window.clearTimeout(dragTimer);
                dragTimer = window.setTimeout(function() {
                    Ember.$('.dropzone').addClass('hidden');
                }, 85);
            });
            this.set('initialized_listeners', true);
        }
    },

    //////////////////////////////////////////////////
    resizeDropzone() {
        let viewport = Ember.$(document);
        Ember.$('#dz-drag').height(viewport.height()-180);
        Ember.$('.dropzone .dz-message').height(viewport.height()-180);
    },

    //////////////////////////////////////////////////
    showDropzone(evt) {
        let self = this;
        let dt = evt.originalEvent.dataTransfer;
        if (dt.types && (dt.types.indexOf ? dt.types.indexOf('Files') != -1 : dt.types.includes('Files'))) {
            window.clearTimeout(dragTimer);
            Ember.$('.dropzone').removeClass('hidden');
        }
    }
});
<commit_msg>Remove duplicate dropzone component<commit_after><|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { TableHeaderColumn, TableRowColumn } from 'material-ui/Table';
import FlatButton from 'material-ui/FlatButton';
import ContentSort from 'material-ui/svg-icons/content/sort';
import title from '../../util/title';

const styles = {
    table: {
        backgroundColor: '#fff',
        padding: '0px 24px',
        width: '100%',
        borderCollapse: 'collapse',
        borderSpacing: 0,
    },
    tbody: {
        height: 'inherit',
    },
    tr: {
        borderBottom: '1px solid rgb(224, 224, 224)',
        color: 'rgba(0, 0, 0, 0.870588)',
        height: 48,
    },
};

class Datagrid extends Component {
    updateSort = (event) => {
        event.stopPropagation();
        this.props.setSort(event.currentTarget.dataset.sort);
    }

    render() {
        const { resource, children, ids, data, currentSort, basePath, updateSort } = this.props;
        return (

                        {React.Children.toArray(children).map(field => (
                            <TableHeaderColumn key={field.props.label || field.props.source || 'no-key'}>
                                {(field.props.label || field.props.source) &&
                                    <FlatButton
                                        labelPosition="before"
                                        onClick={this.updateSort}
                                        data-sort={field.props.source}
                                        label={title(field.props.label, field.props.source)}
                                        icon={field.props.source === currentSort.sort ? <ContentSort style={currentSort.order === 'ASC' ? { transform: 'rotate(180deg)' } : {}} /> : false}
                                    />
                                }
                            </TableHeaderColumn>
                        ))}

                    {ids.map(id => (

                            {React.Children.toArray(children).map(field => (
                                <TableRowColumn key={`${id}-${field.props.source}`}>
                                    <field.type {...field.props} record={data[id]} basePath={basePath} resource={resource} />
                                </TableRowColumn>
                            ))}

                    ))}

        );
    }
}

Datagrid.propTypes = {
    ids: PropTypes.arrayOf(PropTypes.any).isRequired,
    resource: PropTypes.string,
    data: PropTypes.object.isRequired,
    currentSort: PropTypes.shape({
        sort: PropTypes.string,
        order: PropTypes.string,
    }),
    basePath: PropTypes.string,
    setSort: PropTypes.func,
};

Datagrid.defaultProps = {
    data: {},
    ids: [],
};

export default Datagrid;
<commit_msg>Fallback key to index<commit_after>import React, { Component, PropTypes } from 'react';
import { TableHeaderColumn, TableRowColumn } from 'material-ui/Table';
import FlatButton from 'material-ui/FlatButton';
import ContentSort from 'material-ui/svg-icons/content/sort';
import title from '../../util/title';

const styles = {
    table: {
        backgroundColor: '#fff',
        padding: '0px 24px',
        width: '100%',
        borderCollapse: 'collapse',
        borderSpacing: 0,
    },
    tbody: {
        height: 'inherit',
    },
    tr: {
        borderBottom: '1px solid rgb(224, 224, 224)',
        color: 'rgba(0, 0, 0, 0.870588)',
        height: 48,
    },
};

class Datagrid extends Component {
    updateSort = (event) => {
        event.stopPropagation();
        this.props.setSort(event.currentTarget.dataset.sort);
    }

    render() {
        const { resource, children, ids, data, currentSort, basePath, updateSort } = this.props;
        return (

                        {React.Children.map(children, (field, index) => (
                            <TableHeaderColumn key={field.props.label || field.props.source || index}>
                                {(field.props.label || field.props.source) &&
                                    <FlatButton
                                        labelPosition="before"
                                        onClick={this.updateSort}
                                        data-sort={field.props.source}
                                        label={title(field.props.label, field.props.source)}
                                        icon={field.props.source === currentSort.sort ? <ContentSort style={currentSort.order === 'ASC' ? { transform: 'rotate(180deg)' } : {}} /> : false}
                                    />
                                }
                            </TableHeaderColumn>
                        ))}

                    {ids.map(id => (

                            {React.Children.toArray(children).map(field => (
                                <TableRowColumn key={`${id}-${field.props.source}`}>
                                    <field.type {...field.props} record={data[id]} basePath={basePath} resource={resource} />
                                </TableRowColumn>
                            ))}

                    ))}

        );
    }
}

Datagrid.propTypes = {
    ids: PropTypes.arrayOf(PropTypes.any).isRequired,
    resource: PropTypes.string,
    data: PropTypes.object.isRequired,
    currentSort: PropTypes.shape({
        sort: PropTypes.string,
        order: PropTypes.string,
    }),
    basePath: PropTypes.string,
    setSort: PropTypes.func,
};

Datagrid.defaultProps = {
    data: {},
    ids: [],
};

export default Datagrid;
<|endoftext|>


<commit_before>'use strict'

;(function (thisDoc) {
  document.addEventListener('DOMContentLoaded', () => {
    // scope styles
    window.ShadyCSS.prepareTemplate(thisDoc.querySelector('template'), 'm-transaction')

    window.customElements.define('m-transaction', class extends HTMLElement {
      constructor () {
        super()

        this.debug = false
        if (this.debug) console.log('constructing')

        this.tx = {}
      }

      connectedCallback () {
        if (this.debug) console.log(`connected ${this.index}`)

        this.attachShadow({mode: 'open'})
        this.root = this.shadowRoot

        const template = thisDoc.querySelector('template')
        this.root.appendChild(document.importNode(template.content, true))

        window.ShadyCSS.applyStyle(this)

        this.render()

        this.addEventListener('click', this.clickCallback.bind(this))
      }

      render () {
        if (this.debug) console.log(`rendering ${this.index}`)

        this.root.querySelector('.description').textContent = this.description

        if (this.notes.trim() !== '') {
          this.root.querySelector('.notes').classList.add('noted')
          this.root.querySelector('.notes').textContent = this.notes
        }

        this.root.querySelector('.amount').textContent = this.amount
        if (this.tx.amount >= 0) this.root.querySelector('.amount').classList.add('income')

        this.root.querySelector('.icon').src = this.icon

        if ('decline_reason' in this.tx) this.classList.add('declined')
        if (!('settled' in this.tx) || ('settled' in this.tx && this.tx.settled.trim() === '')) this.classList.add('pending')

        this.dataset.category = this.tx.category
      }

      get index () {
        return this.dataset.index
      }

      get description () {
        if ('merchant' in this.tx && this.tx.merchant && this.tx.merchant.name) {
          return this.tx.merchant.name
        } else return this.tx.description
      }

      get notes () {
        return this.tx.notes.split('\n')[0]
      }

      get amount () {
        let amount = this.tx.amount / 100

        if (amount < 0) amount = `${Math.abs(amount).toFixed(2)}`
        else amount = `+${amount.toFixed(2)}`

        return amount
      }

      formatCurrency (amount) {
        const currencies = {
          'GBP': '£',
          'USD': '$',
          'EUR': '€'
        }

        return `${currencies[this.tx.currency] || ''}${amount}`
      }

      get icon () {
        if ('is_topup' in this.tx.metadata && this.tx.metadata.is_topup) {
          return './icons/topup.png'
        }

        if (this.tx.counterparty && 'user_id' in this.tx.counterparty) {
          return './icons/peer.png'
        }

        if ('merchant' in this.tx && this.tx.merchant && 'logo' in this.tx.merchant && this.tx.merchant.logo) {
          return this.tx.merchant.logo
        }

        return `./icons/${this.tx.category}.png`
      }

      clickCallback () {
        if (this.debug) console.log(`clicked ${this.index}`)
        Array.from(document.querySelectorAll('m-transaction-detail')).forEach(item => {
          item.classList.remove('show')
        })

        document.querySelector(`m-transaction-detail[data-index="${this.index}"]`).classList.add('show')
      }

      disconnectedCallback () {
        if (this.debug) console.log(`disconnection ${this.index}`)
      }

      adoptedCallback () {
        if (this.debug) console.log(`adopted ${this.index}`)
      }

      static get observedAttributes () {
        return []
      }

      attributeChangedCallback (attrName, oldVal, newVal) {
        if (this.debug) console.log(`attribute changed on ${this.index}: ${attrName}, ${oldVal} => ${newVal}`)
        const changes = {}

        if (attrName in changes) changes[attrName]()

        this.render()
      }
    })
  })
})(document.currentScript.ownerDocument)
<commit_msg>improve detail view toggle<commit_after>'use strict'

;(function (thisDoc) {
  document.addEventListener('DOMContentLoaded', () => {
    // scope styles
    window.ShadyCSS.prepareTemplate(thisDoc.querySelector('template'), 'm-transaction')

    window.customElements.define('m-transaction', class extends HTMLElement {
      constructor () {
        super()

        this.debug = false
        if (this.debug) console.log('constructing')

        this.tx = {}
      }

      connectedCallback () {
        if (this.debug) console.log(`connected ${this.index}`)

        this.attachShadow({mode: 'open'})
        this.root = this.shadowRoot

        const template = thisDoc.querySelector('template')
        this.root.appendChild(document.importNode(template.content, true))

        window.ShadyCSS.applyStyle(this)

        this.render()

        this.addEventListener('click', this.clickHandler.bind(this))
      }

      render () {
        if (this.debug) console.log(`rendering ${this.index}`)

        this.root.querySelector('.description').textContent = this.description

        if (this.notes.trim() !== '') {
          this.root.querySelector('.notes').classList.add('noted')
          this.root.querySelector('.notes').textContent = this.notes
        }

        this.root.querySelector('.amount').textContent = this.amount
        if (this.tx.amount >= 0) this.root.querySelector('.amount').classList.add('income')

        this.root.querySelector('.icon').src = this.icon

        if ('decline_reason' in this.tx) this.classList.add('declined')
        if (!('settled' in this.tx) || (
          'settled' in this.tx &&
          this.tx.settled.trim() === ''
        )) this.classList.add('pending')

        this.dataset.category = this.tx.category
      }

      get index () {
        return this.dataset.index
      }

      get description () {
        if ('merchant' in this.tx && this.tx.merchant && this.tx.merchant.name) {
          return this.tx.merchant.name
        } else return this.tx.description
      }

      get notes () {
        return this.tx.notes.split('\n')[0]
      }

      get amount () {
        let amount = this.tx.amount / 100

        if (amount < 0) amount = `${Math.abs(amount).toFixed(2)}`
        else amount = `+${amount.toFixed(2)}`

        return amount
      }

      formatCurrency (amount) {
        const currencies = {
          'GBP': '£',
          'USD': '$',
          'EUR': '€'
        }

        return `${currencies[this.tx.currency] || ''}${amount}`
      }

      get icon () {
        if ('is_topup' in this.tx.metadata && this.tx.metadata.is_topup) {
          return './icons/topup.png'
        }

        if (this.tx.counterparty && 'user_id' in this.tx.counterparty) {
          return './icons/peer.png'
        }

        if (
          'merchant' in this.tx &&
          this.tx.merchant &&
          'logo' in this.tx.merchant &&
          this.tx.merchant.logo
        ) {
          return this.tx.merchant.logo
        }

        return `./icons/${this.tx.category}.png`
      }

      clickHandler () {
        if (this.debug) console.log(`clicked ${this.index}`)
        const thisDetail = document.querySelector(`m-transaction-detail[data-index="${this.index}"]`)

        if (thisDetail.classList.contains('show')) {
          thisDetail.classList.remove('show')
          this.classList.remove('show')
        } else {
          Array.from(document.querySelectorAll('m-transaction-detail'))
          .concat(Array.from(document.querySelectorAll('m-transaction'))).forEach(item => {
            item.classList.remove('show')
          })

          thisDetail.classList.add('show')
          this.classList.add('show')

          const pos = this.getBoundingClientRect().top + window.scrollY
          const offset = document.querySelector('.balances').getBoundingClientRect().height
          window.scrollTo(0, pos - offset - 40)
        }
      }

      disconnectedCallback () {
        if (this.debug) console.log(`disconnection ${this.index}`)
      }

      adoptedCallback () {
        if (this.debug) console.log(`adopted ${this.index}`)
      }

      static get observedAttributes () {
        return []
      }

      attributeChangedCallback (attrName, oldVal, newVal) {
        if (this.debug) console.log(`attribute changed on ${this.index}: ${attrName}, ${oldVal} => ${newVal}`)
        const changes = {}

        if (attrName in changes) changes[attrName]()

        this.render()
      }
    })
  })
})(document.currentScript.ownerDocument)
<|endoftext|>


<commit_before>#!/usr/bin/env node

/*
 *
 * Copyright 2014 Canonical Ltd.
 *
 * 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.
 *
*/
var assert = require('assert');
var colors = require('colors');
var fs = require('fs');
var path = require('path');
var shell = require('shelljs');

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

var Devices = require('./device');
var Constants = require('./constants');
var Utils = require('./utils');

var PLATFORMS = Constants.PLATFORM_TYPES;
var MSG = Constants.MSG;

module.exports.run = function(rootDir, desktop, debug, target, nobuild, emulator, framework) {
    if (desktop && !emulator) {
        return build(rootDir, PLATFORMS.DESKTOP, nobuild, null, null, debug).then(function () {
            return runNative(rootDir, debug);
        });
    }

    if (!framework)
        framework = Constants.DEFAULT_FRAMEWORK;

    if (!target) {
        var devices = Devices.list();

        if (!devices.length) {
            console.error(MSG.UBUNTU_TOUCH_DEVICE_NOT_AVALIABLE.red)
            process.exit(1);
        }

        if (emulator) {
            devices = devices.filter(function (name) {
                return name.match(/^emulator-/);
            });
            if (!devices.length) {
                console.error(MSG.EMULATOR_IS_NOT_RUNNING.red)
                process.exit(1);
            }
        }

        target = devices[0];

        if (devices.length > 1) {
            console.warn('you can specify target with --target <device id>'.yellow);
            console.warn(('running on ' + target).yellow);
        }
    }
    var arch = Devices.arch(target);

    return build(rootDir, PLATFORMS.PHONE, nobuild, arch, framework, debug).then(function () {
        return runOnDevice(rootDir, debug, target, arch, framework);
    });
};

function runNative(rootDir, debug) {
    console.log('Running Cordova'.green);
    var ubuntuDir = path.join(rootDir, 'platforms', 'ubuntu');
    var nativeDir = path.join(ubuntuDir, 'native');

    Utils.pushd(path.join(nativeDir, 'prefix'));

    var cmd = 'QTWEBKIT_INSPECTOR_SERVER=9222 ./cordova-ubuntu www/';
    if (debug) {
        cmd = "DEBUG=1 " + cmd;
        console.error('Debug enabled. Try pointing a WebKit browser to http://127.0.0.1:9222'.yellow);
    }

    return Utils.execAsync(cmd).then(function () {
        Utils.popd();
    });
}

function runOnDevice(rootDir, debug, target, architecture, framework) {
    var ubuntuDir = path.join(rootDir, 'platforms', 'ubuntu');

    if (!isDeviceAttached(target)) {
        console.error(MSG.UBUNTU_TOUCH_DEVICE_NOT_AVALIABLE.red)
        process.exit(1);
    }

    var archDir = path.join(ubuntuDir, framework, architecture);
    var prefixDir = path.join(archDir, 'prefix');

    Utils.pushd(prefixDir);

    var manifest = JSON.parse(fs.readFileSync(path.join(ubuntuDir, 'manifest.json'), {encoding: "utf8"}));
    var appId = manifest.name;

    var names = shell.ls().filter(function (name) {
        return name.indexOf(appId) == 0 && name.indexOf('.click');
    });

    assert.ok(names.length == 1);

    adbExec(target, 'shell "ps -A -eo pid,cmd | grep cordova-ubuntu | awk \'{ print \\$1 }\' | xargs kill -9"')

    if (debug)
        adbExec(target, 'forward --remove-all');

    adbExec(target, 'push ' + names[0] + ' /home/phablet');
    adbExec(target, 'shell "cd /home/phablet/; pkcon install-local ' + names[0] + ' -p --allow-untrusted -y"');

    if (debug) {
        console.error('Debug enabled. Try pointing a WebKit browser to http://127.0.0.1:9222');

        adbExec(target, 'forward tcp:9222 tcp:9222');
    }

    console.log('have fun!'.rainbow);

    return adbExecAsync(target, 'shell bash -c "ubuntu-app-launch  \\`ubuntu-app-triplet ' + appId + '\\`"').then(function () {
        Utils.popd();
    });
}
<commit_msg>Run On Device was not working because of invalid calls.<commit_after>#!/usr/bin/env node

/*
 *
 * Copyright 2014 Canonical Ltd.
 *
 * 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.
 *
*/
var assert = require('assert');
var colors = require('colors');
var fs = require('fs');
var path = require('path');
var shell = require('shelljs');

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

var Devices = require('./device');
var Constants = require('./constants');
var Utils = require('./utils');

var PLATFORMS = Constants.PLATFORM_TYPES;
var MSG = Constants.MSG;

module.exports.run = function(rootDir, desktop, debug, target, nobuild, emulator, framework) {
    if (desktop && !emulator) {
        return build(rootDir, PLATFORMS.DESKTOP, nobuild, null, null, debug).then(function () {
            return runNative(rootDir, debug);
        });
    }

    if (!framework)
        framework = Constants.DEFAULT_FRAMEWORK;

    if (!target) {
        var devices = Devices.list();

        if (!devices.length) {
            console.error(MSG.UBUNTU_TOUCH_DEVICE_NOT_AVALIABLE.red)
            process.exit(1);
        }

        if (emulator) {
            devices = devices.filter(function (name) {
                return name.match(/^emulator-/);
            });
            if (!devices.length) {
                console.error(MSG.EMULATOR_IS_NOT_RUNNING.red)
                process.exit(1);
            }
        }

        target = devices[0];

        if (devices.length > 1) {
            console.warn('you can specify target with --target <device id>'.yellow);
            console.warn(('running on ' + target).yellow);
        }
    }
    var arch = Devices.arch(target);

    return build(rootDir, PLATFORMS.PHONE, nobuild, arch, framework, debug).then(function () {
        return runOnDevice(rootDir, debug, target, arch, framework);
    });
};

function runNative(rootDir, debug) {
    console.log('Running Cordova'.green);
    var ubuntuDir = path.join(rootDir, 'platforms', 'ubuntu');
    var nativeDir = path.join(ubuntuDir, 'native');

    Utils.pushd(path.join(nativeDir, 'prefix'));

    var cmd = 'QTWEBKIT_INSPECTOR_SERVER=9222 ./cordova-ubuntu www/';
    if (debug) {
        cmd = "DEBUG=1 " + cmd;
        console.error('Debug enabled. Try pointing a WebKit browser to http://127.0.0.1:9222'.yellow);
    }

    return Utils.execAsync(cmd).then(function () {
        Utils.popd();
    });
}

function runOnDevice(rootDir, debug, target, architecture, framework) {
    var ubuntuDir = path.join(rootDir, 'platforms', 'ubuntu');

    if (!Devices.isAttached(target)) {
        console.error(MSG.UBUNTU_TOUCH_DEVICE_NOT_AVALIABLE.red);
        process.exit(1);
    }

    var archDir = path.join(ubuntuDir, framework, architecture);
    var prefixDir = path.join(archDir, 'prefix');

    Utils.pushd(prefixDir);

    var manifest = JSON.parse(fs.readFileSync(path.join(ubuntuDir, 'manifest.json'), {encoding: "utf8"}));
    var appId = manifest.name;

    var names = shell.ls().filter(function (name) {
        return name.indexOf(appId) == 0 && name.indexOf('.click');
    });

    assert.ok(names.length == 1);

    Devices.adbExec(target, 'shell "ps -A -eo pid,cmd | grep cordova-ubuntu | awk \'{ print \\$1 }\' | xargs kill -9"');

    if (debug)
        Devices.adbExec(target, 'forward --remove-all');

    Devices.adbExec(target, 'push ' + names[0] + ' /home/phablet');
    Devices.adbExec(target, 'shell "cd /home/phablet/; pkcon install-local ' + names[0] + ' -p --allow-untrusted -y"');

    if (debug) {
        console.error('Debug enabled. Try pointing a WebKit browser to http://127.0.0.1:9222');
        Devices.adbExec(target, 'forward tcp:9222 tcp:9222');
    }

    console.log('have fun!'.rainbow);

    return Devices.adbExecAsync(target, 'shell bash -c "ubuntu-app-launch  \\`ubuntu-app-triplet ' + appId + '\\`"').then(function () {
        Utils.popd();
    });
}
<|endoftext|>


<commit_before>/*jslint forin:true sub:true undef: true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/
/*jslint undef: true*/
/*
* Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/

// Provided by the fw
// ARROW = {};
// ARROW.autoTest = false; // for self contained app and test, such as html
// ARROW.testParams = {};
// ARROW.appSeed = ""; // YUI min or equivalent
// ARROW.testLibs = [];
// ARROW.scriptType = "test";
// ARROW.testScript = "test-file.js";
// ARROW.actionScript = "action-file.js";
// ARROW.onSeeded = function() { /* add test, hand over to runner */}

ARROW.testBag = ["test"];
ARROW.testReport = null;
ARROW.actionReport = null;
ARROW.actionReported = false;

// try to catch unhandled errors
if ((typeof window !== "undefined") && !window.onerror) {
    window.onerror = function (errorMsg, sourceUrl, lineNumber) {
        console.log("javascript error: " + errorMsg + " at " + lineNumber + ", url: " + sourceUrl);
        return true;
    };
}

(function () {

    function loadScript(url, callback) {
        var script = document.createElement("script");
        script.type = "text/javascript";

        if (script.readyState) { // IE
            script.onreadystatechange = function () {
                if (("loaded" === script.readyState) || ("complete" === script.readyState)) {
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else { // Others
            script.onload = function() {
                callback();
            };
        }

        script.src = url;
        document.body.appendChild(script);
    }

    function captureConsoleMessages() {

        try {
            if (console) {
                //capturing console log
                console.oldLog = console.log;
                console.log = function(line) {
                    ARROW.consoleLog += "[LOG] " + line + "\n";
                    console.oldLog(line);
                };

                //capturing console info
                console.oldInfo = console.info;
                console.info = function(line) {
                    ARROW.consoleLog += "[INFO] " + line + "\n";
                    console.oldInfo(line);
                };

                //capturing console warn
                console.oldWarn = console.warn;
                console.warn = function(line) {
                    ARROW.consoleLog += "[WARN] " + line + "\n";
                    console.oldWarn(line);
                };

                //capturing console debug
                console.oldDebug = console.debug;
                console.debug = function(line) {
                    ARROW.consoleLog += "[DEBUG] " + line + "\n";
                    console.oldDebug(line);
                };

                //capturing console debug
                console.oldError = console.error;
                console.error = function(line) {
                    ARROW.consoleLog += "[ERROR] " + line + "\n";
                    console.oldError(line);
                };
            }
        } catch (e) {

        }

    }

    function onYUIAvailable() {
        var module = ARROW.testParams["module"],
            yuiAddFunc = YUI.add;

        //initializing Arrow console log
        ARROW.consoleLog = "";

        //capturing console messages
        captureConsoleMessages();

        // capture module style tests
        YUI.add = function (name, fn, version, meta) {
            yuiAddFunc(name, fn, version, meta);

            if (module && (name !== module)) {
                return;
            }

            if (("test" === ARROW.scriptType) && (-1 !== name.indexOf("-tests"))) {
                console.log("Found test module: " + name);
                ARROW.testBag.push(name);
            } else if (("action" === ARROW.scriptType) && (-1 !== name.indexOf("-action"))) {
                console.log("Found test action: " + name);
                ARROW.testBag.push(name);
            }
        };

        ARROW.onSeeded();
    }

    if (typeof YUI === "undefined") {
        if ((typeof process !== "undefined") && (typeof require !== "undefined")) {
            if (console) {
                console.log("requiring YUI");
            }
            YUI = require("yui").YUI;
            onYUIAvailable();
        } else {
            if (console) {
                console.log("Injecting YUI");
            }
            loadScript(ARROW.appSeed, onYUIAvailable);
        }
    } else if (parseFloat(YUI.version) < parseFloat("3.4.0")) {
        if (console) {
            console.log("Found old YUI");
        }
        loadScript(ARROW.appSeed, onYUIAvailable);
    } else {
        if (console) {
            console.log("YUI Version :" + YUI.version);
        }
        onYUIAvailable();
    }
})();

<commit_msg>commenting comsole.log, as it breaks ff3.6. Need to make it work for all browsers.<commit_after>/*jslint forin:true sub:true undef: true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/
/*jslint undef: true*/
/*
* Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/

// Provided by the fw
// ARROW = {};
// ARROW.autoTest = false; // for self contained app and test, such as html
// ARROW.testParams = {};
// ARROW.appSeed = ""; // YUI min or equivalent
// ARROW.testLibs = [];
// ARROW.scriptType = "test";
// ARROW.testScript = "test-file.js";
// ARROW.actionScript = "action-file.js";
// ARROW.onSeeded = function() { /* add test, hand over to runner */}

ARROW.testBag = ["test"];
ARROW.testReport = null;
ARROW.actionReport = null;
ARROW.actionReported = false;

// try to catch unhandled errors
if ((typeof window !== "undefined") && !window.onerror) {
    window.onerror = function (errorMsg, sourceUrl, lineNumber) {

        try{
            console.log("javascript error: " + errorMsg + " at " + lineNumber + ", url: " + sourceUrl);
        } catch(e) {

        }
        return true;
    };
}

(function () {

    function loadScript(url, callback) {
        var script = document.createElement("script");
        script.type = "text/javascript";

        if (script.readyState) { // IE
            script.onreadystatechange = function () {
                if (("loaded" === script.readyState) || ("complete" === script.readyState)) {
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else { // Others
            script.onload = function() {
                callback();
            };
        }

        script.src = url;
        document.body.appendChild(script);
    }

    function captureConsoleMessages() {

        try {
            if (console) {
                //capturing console log
                console.oldLog = console.log;
                console.log = function(line) {
                    ARROW.consoleLog += "[LOG] " + line + "\n";
                    console.oldLog(line);
                };

                //capturing console info
                console.oldInfo = console.info;
                console.info = function(line) {
                    ARROW.consoleLog += "[INFO] " + line + "\n";
                    console.oldInfo(line);
                };

                //capturing console warn
                console.oldWarn = console.warn;
                console.warn = function(line) {
                    ARROW.consoleLog += "[WARN] " + line + "\n";
                    console.oldWarn(line);
                };

                //capturing console debug
                console.oldDebug = console.debug;
                console.debug = function(line) {
                    ARROW.consoleLog += "[DEBUG] " + line + "\n";
                    console.oldDebug(line);
                };

                //capturing console debug
                console.oldError = console.error;
                console.error = function(line) {
                    ARROW.consoleLog += "[ERROR] " + line + "\n";
                    console.oldError(line);
                };
            }
        } catch (e) {

        }

    }

    function onYUIAvailable() {
        var module = ARROW.testParams["module"],
            yuiAddFunc = YUI.add;

        //initializing Arrow console log
        ARROW.consoleLog = "";

        //capturing console messages
        captureConsoleMessages();

        // capture module style tests
        YUI.add = function (name, fn, version, meta) {
            yuiAddFunc(name, fn, version, meta);

            if (module && (name !== module)) {
                return;
            }

            if (("test" === ARROW.scriptType) && (-1 !== name.indexOf("-tests"))) {
                //console.log("Found test module: " + name);
                ARROW.testBag.push(name);
            } else if (("action" === ARROW.scriptType) && (-1 !== name.indexOf("-action"))) {
                //console.log("Found test action: " + name);
                ARROW.testBag.push(name);
            }
        };

        ARROW.onSeeded();
    }

    if (typeof YUI === "undefined") {
        if ((typeof process !== "undefined") && (typeof require !== "undefined")) {
            //console.log("requiring YUI");
            YUI = require("yui").YUI;
            onYUIAvailable();
        } else {
            //console.log("Injecting YUI");
            loadScript(ARROW.appSeed, onYUIAvailable);
        }
    } else if (parseFloat(YUI.version) < parseFloat("3.4.0")) {
        //console.log("Found old YUI");
        loadScript(ARROW.appSeed, onYUIAvailable);
    } else {
        //console.log("YUI Version :" + YUI.version);
        onYUIAvailable();
    }
})();

<|endoftext|>


<commit_before>/*jslint forin:true sub:true undef: true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/
/*jslint undef: true*/
/*
* Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/

// Provided by the fw
// ARROW = {};
// ARROW.autoTest = false; // for self contained app and test, such as html
// ARROW.testParams = {};
// ARROW.appSeed = ""; // YUI min or equivalent
// ARROW.testLibs = [];
// ARROW.scriptType = "test";
// ARROW.testScript = "test-file.js";
// ARROW.actionScript = "action-file.js";
// ARROW.onSeeded = function() { /* add test, hand over to runner */}

ARROW.testBag = ["test"];
ARROW.testReport = null;
ARROW.actionReport = null;
ARROW.actionReported = false;

// try to catch unhandled errors
if ((typeof window !== "undefined") && !window.onerror) {
    window.onerror = function (errorMsg, sourceUrl, lineNumber) {

        try {
            console.log("javascript error: " + errorMsg + " at " + lineNumber + ", url: " + sourceUrl);
        } catch (e) {

        }
        return true;
    };
}

(function () {

    function loadScript(url, callback) {
        var script = document.createElement("script");
        script.type = "text/javascript";

        if (script.readyState) { // IE
            script.onreadystatechange = function () {
                if (("loaded" === script.readyState) || ("complete" === script.readyState)) {
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else { // Others
            script.onload = function() {
                callback();
            };
        }

        script.src = url;
        document.body.appendChild(script);
    }

    function captureConsoleMessages() {

        try {
            if (console) {
                //Making sure we dont redefine console methods
                if (!console.oldLog) {

                    //capturing console log
                    console.oldLog = console.log;
                    console.log = function(line) {
                        ARROW.consoleLog += "[LOG] " + line + "\n";
                        console.oldLog(line);
                    };

                    //capturing console info
                    console.oldInfo = console.info;
                    console.info = function(line) {
                        ARROW.consoleLog += "[INFO] " + line + "\n";
                        console.oldInfo(line);
                    };

                    //capturing console warn
                    console.oldWarn = console.warn;
                    console.warn = function(line) {
                        ARROW.consoleLog += "[WARN] " + line + "\n";
                        console.oldWarn(line);
                    };

                    //capturing console debug
                    console.oldDebug = console.debug;
                    console.debug = function(line) {
                        ARROW.consoleLog += "[DEBUG] " + line + "\n";
                        console.oldDebug(line);
                    };

                    //capturing console debug
                    console.oldError = console.error;
                    console.error = function(line) {
                        ARROW.consoleLog += "[ERROR] " + line + "\n";
                        console.oldError(line);
                    };
                }
            }
        } catch (e) {

        }

    }

    function onYUIAvailable() {
        var module = ARROW.testParams["module"],
            yuiAddFunc = YUI.add;

        //initializing Arrow console log
        ARROW.consoleLog = "";

        //capturing console messages
        captureConsoleMessages();

        // capture module style tests
        YUI.add = function (name, fn, version, meta) {
            yuiAddFunc(name, fn, version, meta);

            if (module && (name !== module)) {
                return;
            }

            if (("test" === ARROW.scriptType) && (-1 !== name.indexOf("-tests"))) {
                //console.log("Found test module: " + name);
                ARROW.testBag.push(name);
            } else if (("action" === ARROW.scriptType) && (-1 !== name.indexOf("-action"))) {
                //console.log("Found test action: " + name);
                ARROW.testBag.push(name);
            }
        };

        ARROW.onSeeded();
    }

    if (typeof YUI === "undefined") {
        if ((typeof process !== "undefined") && (typeof require !== "undefined")) {
            //console.log("requiring YUI");
            YUI = require("yui").YUI;

            //console.log("Injecting martini seed (YUI global config)");
            var fs = require('fs');
            if (ARROW.martiniServerSeed !== undefined && fs.existsSync(ARROW.martiniServerSeed)) {
                var globalConf = fs.readFileSync(ARROW.martiniServerSeed, "utf-8");
                eval(globalConf);
            }

            onYUIAvailable();
        } else {
            //console.log("Injecting YUI");
            loadScript(ARROW.appSeed, onYUIAvailable);
        }
    } else if (parseFloat(YUI.version) < parseFloat("3.4.0")) {
        //console.log("Found old YUI");
        loadScript(ARROW.appSeed, onYUIAvailable);
    } else {
        //console.log("YUI Version :" + YUI.version);
        onYUIAvailable();
    }
})();

<commit_msg>remote node 0.8 dependency<commit_after>/*jslint forin:true sub:true undef: true anon:true, sloppy:true, stupid:true nomen:true, node:true continue:true*/
/*jslint undef: true*/
/*
* Copyright (c) 2012, Yahoo! Inc.  All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/

// Provided by the fw
// ARROW = {};
// ARROW.autoTest = false; // for self contained app and test, such as html
// ARROW.testParams = {};
// ARROW.appSeed = ""; // YUI min or equivalent
// ARROW.testLibs = [];
// ARROW.scriptType = "test";
// ARROW.testScript = "test-file.js";
// ARROW.actionScript = "action-file.js";
// ARROW.onSeeded = function() { /* add test, hand over to runner */}

ARROW.testBag = ["test"];
ARROW.testReport = null;
ARROW.actionReport = null;
ARROW.actionReported = false;

// try to catch unhandled errors
if ((typeof window !== "undefined") && !window.onerror) {
    window.onerror = function (errorMsg, sourceUrl, lineNumber) {

        try {
            console.log("javascript error: " + errorMsg + " at " + lineNumber + ", url: " + sourceUrl);
        } catch (e) {

        }
        return true;
    };
}

(function () {

    function loadScript(url, callback) {
        var script = document.createElement("script");
        script.type = "text/javascript";

        if (script.readyState) { // IE
            script.onreadystatechange = function () {
                if (("loaded" === script.readyState) || ("complete" === script.readyState)) {
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else { // Others
            script.onload = function() {
                callback();
            };
        }

        script.src = url;
        document.body.appendChild(script);
    }

    function captureConsoleMessages() {

        try {
            if (console) {
                //Making sure we dont redefine console methods
                if (!console.oldLog) {

                    //capturing console log
                    console.oldLog = console.log;
                    console.log = function(line) {
                        ARROW.consoleLog += "[LOG] " + line + "\n";
                        console.oldLog(line);
                    };

                    //capturing console info
                    console.oldInfo = console.info;
                    console.info = function(line) {
                        ARROW.consoleLog += "[INFO] " + line + "\n";
                        console.oldInfo(line);
                    };

                    //capturing console warn
                    console.oldWarn = console.warn;
                    console.warn = function(line) {
                        ARROW.consoleLog += "[WARN] " + line + "\n";
                        console.oldWarn(line);
                    };

                    //capturing console debug
                    console.oldDebug = console.debug;
                    console.debug = function(line) {
                        ARROW.consoleLog += "[DEBUG] " + line + "\n";
                        console.oldDebug(line);
                    };

                    //capturing console debug
                    console.oldError = console.error;
                    console.error = function(line) {
                        ARROW.consoleLog += "[ERROR] " + line + "\n";
                        console.oldError(line);
                    };
                }
            }
        } catch (e) {

        }

    }

    function onYUIAvailable() {
        var module = ARROW.testParams["module"],
            yuiAddFunc = YUI.add;

        //initializing Arrow console log
        ARROW.consoleLog = "";

        //capturing console messages
        captureConsoleMessages();

        // capture module style tests
        YUI.add = function (name, fn, version, meta) {
            yuiAddFunc(name, fn, version, meta);

            if (module && (name !== module)) {
                return;
            }

            if (("test" === ARROW.scriptType) && (-1 !== name.indexOf("-tests"))) {
                //console.log("Found test module: " + name);
                ARROW.testBag.push(name);
            } else if (("action" === ARROW.scriptType) && (-1 !== name.indexOf("-action"))) {
                //console.log("Found test action: " + name);
                ARROW.testBag.push(name);
            }
        };

        ARROW.onSeeded();
    }

    if (typeof YUI === "undefined") {
        if ((typeof process !== "undefined") && (typeof require !== "undefined")) {
            //console.log("requiring YUI");
            YUI = require("yui").YUI;

            //console.log("Injecting martini seed (YUI global config)");
            var fs = require('fs');
            if (ARROW.martiniServerSeed !== undefined) {
                try {
                    if (fs.stateSync(ARROW.martiniServerSeed).isFile()) {
                        var globalConf = fs.readFileSync(ARROW.martiniServerSeed, "utf-8");
                        eval(globalConf);
                    }
                } catch (e) {
                    console.log("Martini seed cannot be injected");
                }
            }

            onYUIAvailable();
        } else {
            //console.log("Injecting YUI");
            loadScript(ARROW.appSeed, onYUIAvailable);
        }
    } else if (parseFloat(YUI.version) < parseFloat("3.4.0")) {
        //console.log("Found old YUI");
        loadScript(ARROW.appSeed, onYUIAvailable);
    } else {
        //console.log("YUI Version :" + YUI.version);
        onYUIAvailable();
    }
})();

<|endoftext|>