<commit_before>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you 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 deviceModule;
deviceModule = function () {
    var log = new Log("/app/modules/business-controllers/device.js");

    var utility = require('/app/modules/utility.js').utility;
    var constants = require('/app/modules/constants.js');
    var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
    var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];

//    var ArrayList = Packages.java.util.ArrayList;
//    var Properties = Packages.java.util.Properties;
//    var DeviceIdentifier = Packages.org.wso2.carbon.device.mgt.common.DeviceIdentifier;
//    var DeviceManagerUtil = Packages.org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
//    var SimpleOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.SimpleOperation;
//    var ConfigOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation;
//    var CommandOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;

    var deviceManagementService = utility.getDeviceManagementService();

    var publicMethods = {};
    var privateMethods = {};

//    var deviceCloudService = devicemgtProps["httpsURL"] + "/common/device_manager";

/**
     * Only GET method is implemented for now since there are no other type of methods used this method.
     * @param url - URL to call the backend without the host
     * @param method - HTTP Method (GET, POST)
     * @returns An object with 'status': 'success'|'error', 'content': {}
     */
    privateMethods.callBackend = function (url, method) {
        if (constants["HTTP_GET"] == method) {
            return serviceInvokers.XMLHttp.get(url,
                function (backendResponse) {
                    var response = {};
                    response.content = backendResponse.responseText;
                    if (backendResponse.status == 200) {
                        response.status = "success";
                    } else if (backendResponse.status == 400 || backendResponse.status == 401 ||
                        backendResponse.status == 404 || backendResponse.status == 500) {
                        response.status = "error";
                    }
                    return response;
                }
            );
        } else {
            log.error("Runtime error : This method only support HTTP GET requests.");
        }
    };

    privateMethods.validateAndReturn = function (value) {
        return (value == undefined || value == null) ? constants.UNSPECIFIED : value;
    };

    /*
     @Deprecated
     */
//    publicMethods.listDevices = function () {
//        var carbonUser = session.get(constants.USER_SESSION_KEY);
//        var utility = require('/app/modules/utility.js').utility;
//        if (!carbonUser) {
//            log.error("User object was not found in the session");
//            throw constants.ERRORS.USER_NOT_FOUND;
//        }
//        try {
//            utility.startTenantFlow(carbonUser);
//            var deviceManagementService = utility.getDeviceManagementService();
//            var devices = deviceManagementService.getAllDevices();
//            var deviceList = [];
//            var i, device, propertiesList, deviceObject;
//            for (i = 0; i < devices.size(); i++) {
//                device = devices.get(i);
//                propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());
//
//                deviceObject = {};
//                deviceObject[constants.DEVICE_IDENTIFIER] =
//                    privateMethods.validateAndReturn(device.getDeviceIdentifier());
//                deviceObject[constants.DEVICE_NAME] =
//                    privateMethods.validateAndReturn(device.getName());
//                deviceObject[constants.DEVICE_OWNERSHIP] =
//                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
//                deviceObject[constants.DEVICE_OWNER] =
//                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner());
//                deviceObject[constants.DEVICE_TYPE] =
//                    privateMethods.validateAndReturn(device.getType());
//                deviceObject[constants.DEVICE_PROPERTIES] = {};
//                if (device.getType() == constants.PLATFORM_IOS) {
//                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
//                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT));
//                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
//                } else {
//                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
//                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL));
//                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] =
//                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR));
//                }
//                deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] =
//                    privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION));
//
//                deviceList.push(deviceObject);
//            }
//            return deviceList;
//        } catch (e) {
//            throw e;
//        } finally {
//            utility.endTenantFlow();
//        }
//    };

    /*
     @Deprecated
     */
    /*
     Get the supported features by the device type
     */
//    publicMethods.getFeatures = function (deviceType) {
//        var carbonUser = session.get(constants.USER_SESSION_KEY);
//        var utility = require('/app/modules/utility.js').utility;
//        if (!carbonUser) {
//            log.error("User object was not found in the session");
//            throw constants.ERRORS.USER_NOT_FOUND;
//        }
//        try {
//            utility.startTenantFlow(carbonUser);
//            var deviceManagementService = utility.getDeviceManagementService();
//            var features = deviceManagementService.getFeatureManager(deviceType).getFeatures();
//            var featuresConverted = {};
//            if (features) {
//                var i, feature, featureObject;
//                for (i = 0; i < features.size(); i++) {
//                    feature = features.get(i);
//                    featureObject = {};
//                    featureObject[constants.FEATURE_NAME] = feature.getName();
//                    featureObject[constants.FEATURE_DESCRIPTION] = feature.getDescription();
//                    featuresConverted[feature.getName()] = featureObject;
//                }
//            }
//            return featuresConverted;
//        } catch (e) {
//            throw e;
//        } finally {
//            utility.endTenantFlow();
//        }
//    };

    /*
     @Deprecated
     */
//    publicMethods.performOperation = function (devices, operation) {
//        var carbonUser = session.get(constants.USER_SESSION_KEY);
//        var utility = require('/app/modules/utility.js').utility;
//        if (!carbonUser) {
//            log.error("User object was not found in the session");
//            throw constants.ERRORS.USER_NOT_FOUND;
//        }
//        try {
//            utility.startTenantFlow(carbonUser);
//            var deviceManagementService = utility.getDeviceManagementService();
//            var operationInstance;
//            if (operation.type == "COMMAND") {
//                operationInstance = new CommandOperation();
//            } else if (operation.type == "CONFIG") {
//                operationInstance = new ConfigOperation();
//            } else {
//                operationInstance = new SimpleOperation();
//            }
//            operationInstance.setCode(operation.featureName);
//            var props = new Properties();
//            var i, object;
//            for (i = 0; i < operation.properties.length; i++) {
//                object = properties[i];
//                props.setProperty(object.key, object.value);
//            }
//            operationInstance.setProperties(props);
//            var deviceList = new ArrayList();
//            var j, device, deviceIdentifier;
//            for (j = 0; j < devices.length; i++) {
//                device = devices[j];
//                deviceIdentifier = new DeviceIdentifier();
//                deviceIdentifier.setId(device.id);
//                deviceIdentifier.setType(device.type);
//                deviceList.add(deviceIdentifier);
//            }
//            deviceManagementService.addOperation(operationInstance, deviceList);
//        } catch (e) {
//            throw e;
//        } finally {
//            utility.endTenantFlow();
//        }
//    };

    /*
     @Deprecated
     */
//    privateMethods.getDevice = function (type, deviceId) {
//        var carbonUser = session.get(constants.USER_SESSION_KEY);
//        var utility = require('/app/modules/utility.js').utility;
//        if (!carbonUser) {
//            log.error("User object was not found in the session");
//            throw constants.ERRORS.USER_NOT_FOUND;
//        }
//        try {
//            utility.startTenantFlow(carbonUser);
//            var deviceManagementService = utility.getDeviceManagementService();
//            var deviceIdentifier = new DeviceIdentifier();
//            deviceIdentifier.setType(type);
//            deviceIdentifier.setId(deviceId);
//            return deviceManagementService.getDevice(deviceIdentifier);
//        } catch (e) {
//            throw e;
//        } finally {
//            utility.endTenantFlow();
//        }
//    };

    /*
     @Updated
     */
    publicMethods.viewDevice = function (deviceType, deviceId) {
        var carbonUser = session.get(constants["USER_SESSION_KEY"]);
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants["ERRORS"]["USER_NOT_FOUND"];
        }
        var utility = require('/app/modules/utility.js')["utility"];
        try {
            utility.startTenantFlow(carbonUser);
            //var url = mdmProps["httpsURL"] + "/mdm-admin/devices/view?type=" + deviceType + "&id=" + deviceId;
            var url = devicemgtProps["httpsURL"] + "/api/device-mgt/v1.0/devices/" + deviceType + "/" + deviceId;
            return serviceInvokers.XMLHttp.get(
                url,
                function (backendResponse) {
                    var response = {};
                    if (backendResponse.status == 200 && backendResponse.responseText) {
                        response["status"] = "success";
                        var device = parse(backendResponse.responseText);
                        var propertiesList = device["properties"];
                        var properties = {};
                        for (var i = 0; i < propertiesList.length; i++) {
                            properties[propertiesList[i]["name"]] =
                                propertiesList[i]["value"];
                        }
                        var deviceObject = {};
                        deviceObject[constants["DEVICE_IDENTIFIER"]] = device["deviceIdentifier"];
                        deviceObject[constants["DEVICE_NAME"]] = device["name"];
                        deviceObject[constants["DEVICE_OWNERSHIP"]] = device["enrolmentInfo"]["ownership"];
                        deviceObject[constants["DEVICE_OWNER"]] = device["enrolmentInfo"]["owner"];
                        deviceObject[constants["DEVICE_STATUS"]] = device["enrolmentInfo"]["status"];
                        deviceObject[constants["DEVICE_TYPE"]] = device["type"];
                        if (device["type"] == constants["PLATFORM_IOS"]) {
                            properties[constants["DEVICE_MODEL"]] = properties[constants["DEVICE_PRODUCT"]];
                            delete properties[constants["DEVICE_PRODUCT"]];
                            properties[constants["DEVICE_VENDOR"]] = constants["VENDOR_APPLE"];
                        }
                        deviceObject[constants["DEVICE_PROPERTIES"]] = properties;
                        response["content"] = deviceObject;
                        return response;
                    } else {
                        response["status"] = "error";
                        return response;
                    }
                }
            );
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    // Refactored methods
    publicMethods.getDevicesCount = function () {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        if (carbonUser) {
            var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
            var uiPermissions = userModule.getUIPermissions();
            var url;
            if (uiPermissions.LIST_DEVICES) {
                url = devicemgtProps["httpsURL"] +
                    devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/devices/count";
            } else if (uiPermissions.LIST_OWN_DEVICES) {
                url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
                    "/devices/user/" + carbonUser.username + "/count";
            } else {
                log.error("Access denied for user: " + carbonUser.username);
                return -1;
            }
            return serviceInvokers.XMLHttp.get(
                url, function (responsePayload) {
                    return responsePayload;
                },
                function (responsePayload) {
                    log.error(responsePayload);
                    return -1;
                }
            );
        } else {
            log.error("User object was not found in the session");
            throw constants["ERRORS"]["USER_NOT_FOUND"];
        }
    };

    publicMethods.getDeviceTypes = function () {
        var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/device-types";
        var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
        if (response.status == "success") {
            response.content = parse(response.content);
        }
        return response;
    };

    //Old methods
    //TODO: make sure these methods are updated
    /*
     @Updated
     */
    // publicMethods.getLicense = function (deviceType) {
    //     var url;
    //     var license;
    //     if (deviceType == "windows") {
    //         url = mdmProps["httpURL"] + "/mdm-windows-agent/services/device/license";
    //     } else if (deviceType == "ios") {
    //         url = mdmProps["httpsURL"] + "/ios-enrollment/license/";
    //     }

    //     if (url != null && url != undefined) {
    //         serviceInvokers.XMLHttp.get(url, function (responsePayload) {
    //             license = responsePayload.text;
    //         }, function (responsePayload) {
    //             return null;
    //         });
    //     }
    //     return license;
    // };

    publicMethods.getDevices = function (userName) {
        var url = devicemgtProps["httpsURL"] +
            devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/devices/user/" + userName;
        return serviceInvokers.XMLHttp.get(
            url, function (responsePayload) {
                for (var i = 0; i < responsePayload.length; i++) {
                    responsePayload[i].thumb = utility.getDeviceThumb(responsePayload[i].type);
                }
                return responsePayload;
            },
            function (responsePayload) {
                log.error(responsePayload);
                return -1;
            }
        );
    };
    return publicMethods;
}();
<commit_msg>Updating device module for permissions - Ui<commit_after>/*
 * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you 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 deviceModule;
deviceModule = function () {
    var log = new Log("/app/modules/business-controllers/device.js");

    var utility = require('/app/modules/utility.js').utility;
    var constants = require('/app/modules/constants.js');
    var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
    var serviceInvokers = require("/app/modules/oauth/token-protected-service-invokers.js")["invokers"];

//    var ArrayList = Packages.java.util.ArrayList;
//    var Properties = Packages.java.util.Properties;
//    var DeviceIdentifier = Packages.org.wso2.carbon.device.mgt.common.DeviceIdentifier;
//    var DeviceManagerUtil = Packages.org.wso2.carbon.device.mgt.core.util.DeviceManagerUtil;
//    var SimpleOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.SimpleOperation;
//    var ConfigOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation;
//    var CommandOperation = Packages.org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;

    var deviceManagementService = utility.getDeviceManagementService();

    var publicMethods = {};
    var privateMethods = {};

//    var deviceCloudService = devicemgtProps["httpsURL"] + "/common/device_manager";

    /**
     * Only GET method is implemented for now since there are no other type of methods used this method.
     * @param url - URL to call the backend without the host
     * @param method - HTTP Method (GET, POST)
     * @returns An object with 'status': 'success'|'error', 'content': {}
     */
    privateMethods.callBackend = function (url, method) {
        if (constants["HTTP_GET"] == method) {
            return serviceInvokers.XMLHttp.get(url,
                function (backendResponse) {
                    var response = {};
                    response.content = backendResponse.responseText;
                    if (backendResponse.status == 200) {
                        response.status = "success";
                    } else if (backendResponse.status == 400 || backendResponse.status == 401 ||
                        backendResponse.status == 404 || backendResponse.status == 500) {
                        response.status = "error";
                    }
                    return response;
                }
            );
        } else {
            log.error("Runtime error : This method only support HTTP GET requests.");
        }
    };

    privateMethods.validateAndReturn = function (value) {
        return (value == undefined || value == null) ? constants.UNSPECIFIED : value;
    };

    /*
     @Deprecated
     */
//    publicMethods.listDevices = function () {
//        var carbonUser = session.get(constants.USER_SESSION_KEY);
//        var utility = require('/app/modules/utility.js').utility;
//        if (!carbonUser) {
//            log.error("User object was not found in the session");
//            throw constants.ERRORS.USER_NOT_FOUND;
//        }
//        try {
//            utility.startTenantFlow(carbonUser);
//            var deviceManagementService = utility.getDeviceManagementService();
//            var devices = deviceManagementService.getAllDevices();
//            var deviceList = [];
//            var i, device, propertiesList, deviceObject;
//            for (i = 0; i < devices.size(); i++) {
//                device = devices.get(i);
//                propertiesList = DeviceManagerUtil.convertDevicePropertiesToMap(device.getProperties());
//
//                deviceObject = {};
//                deviceObject[constants.DEVICE_IDENTIFIER] =
//                    privateMethods.validateAndReturn(device.getDeviceIdentifier());
//                deviceObject[constants.DEVICE_NAME] =
//                    privateMethods.validateAndReturn(device.getName());
//                deviceObject[constants.DEVICE_OWNERSHIP] =
//                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwnership());
//                deviceObject[constants.DEVICE_OWNER] =
//                    privateMethods.validateAndReturn(device.getEnrolmentInfo().getOwner());
//                deviceObject[constants.DEVICE_TYPE] =
//                    privateMethods.validateAndReturn(device.getType());
//                deviceObject[constants.DEVICE_PROPERTIES] = {};
//                if (device.getType() == constants.PLATFORM_IOS) {
//                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
//                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_PRODUCT));
//                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] = constants.VENDOR_APPLE;
//                } else {
//                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_MODEL] =
//                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_MODEL));
//                    deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_VENDOR] =
//                        privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_VENDOR));
//                }
//                deviceObject[constants.DEVICE_PROPERTIES][constants.DEVICE_OS_VERSION] =
//                    privateMethods.validateAndReturn(propertiesList.get(constants.DEVICE_OS_VERSION));
//
//                deviceList.push(deviceObject);
//            }
//            return deviceList;
//        } catch (e) {
//            throw e;
//        } finally {
//            utility.endTenantFlow();
//        }
//    };

    /*
     @Deprecated
     */
    /*
     Get the supported features by the device type
     */
//    publicMethods.getFeatures = function (deviceType) {
//        var carbonUser = session.get(constants.USER_SESSION_KEY);
//        var utility = require('/app/modules/utility.js').utility;
//        if (!carbonUser) {
//            log.error("User object was not found in the session");
//            throw constants.ERRORS.USER_NOT_FOUND;
//        }
//        try {
//            utility.startTenantFlow(carbonUser);
//            var deviceManagementService = utility.getDeviceManagementService();
//            var features = deviceManagementService.getFeatureManager(deviceType).getFeatures();
//            var featuresConverted = {};
//            if (features) {
//                var i, feature, featureObject;
//                for (i = 0; i < features.size(); i++) {
//                    feature = features.get(i);
//                    featureObject = {};
//                    featureObject[constants.FEATURE_NAME] = feature.getName();
//                    featureObject[constants.FEATURE_DESCRIPTION] = feature.getDescription();
//                    featuresConverted[feature.getName()] = featureObject;
//                }
//            }
//            return featuresConverted;
//        } catch (e) {
//            throw e;
//        } finally {
//            utility.endTenantFlow();
//        }
//    };

    /*
     @Deprecated
     */
//    publicMethods.performOperation = function (devices, operation) {
//        var carbonUser = session.get(constants.USER_SESSION_KEY);
//        var utility = require('/app/modules/utility.js').utility;
//        if (!carbonUser) {
//            log.error("User object was not found in the session");
//            throw constants.ERRORS.USER_NOT_FOUND;
//        }
//        try {
//            utility.startTenantFlow(carbonUser);
//            var deviceManagementService = utility.getDeviceManagementService();
//            var operationInstance;
//            if (operation.type == "COMMAND") {
//                operationInstance = new CommandOperation();
//            } else if (operation.type == "CONFIG") {
//                operationInstance = new ConfigOperation();
//            } else {
//                operationInstance = new SimpleOperation();
//            }
//            operationInstance.setCode(operation.featureName);
//            var props = new Properties();
//            var i, object;
//            for (i = 0; i < operation.properties.length; i++) {
//                object = properties[i];
//                props.setProperty(object.key, object.value);
//            }
//            operationInstance.setProperties(props);
//            var deviceList = new ArrayList();
//            var j, device, deviceIdentifier;
//            for (j = 0; j < devices.length; i++) {
//                device = devices[j];
//                deviceIdentifier = new DeviceIdentifier();
//                deviceIdentifier.setId(device.id);
//                deviceIdentifier.setType(device.type);
//                deviceList.add(deviceIdentifier);
//            }
//            deviceManagementService.addOperation(operationInstance, deviceList);
//        } catch (e) {
//            throw e;
//        } finally {
//            utility.endTenantFlow();
//        }
//    };

    /*
     @Deprecated
     */
//    privateMethods.getDevice = function (type, deviceId) {
//        var carbonUser = session.get(constants.USER_SESSION_KEY);
//        var utility = require('/app/modules/utility.js').utility;
//        if (!carbonUser) {
//            log.error("User object was not found in the session");
//            throw constants.ERRORS.USER_NOT_FOUND;
//        }
//        try {
//            utility.startTenantFlow(carbonUser);
//            var deviceManagementService = utility.getDeviceManagementService();
//            var deviceIdentifier = new DeviceIdentifier();
//            deviceIdentifier.setType(type);
//            deviceIdentifier.setId(deviceId);
//            return deviceManagementService.getDevice(deviceIdentifier);
//        } catch (e) {
//            throw e;
//        } finally {
//            utility.endTenantFlow();
//        }
//    };

    /*
     @Updated
     */
    publicMethods.viewDevice = function (deviceType, deviceId) {
        var carbonUser = session.get(constants["USER_SESSION_KEY"]);
        if (!carbonUser) {
            log.error("User object was not found in the session");
            throw constants["ERRORS"]["USER_NOT_FOUND"];
        }
        var utility = require('/app/modules/utility.js')["utility"];
        try {
            utility.startTenantFlow(carbonUser);
            //var url = mdmProps["httpsURL"] + "/mdm-admin/devices/view?type=" + deviceType + "&id=" + deviceId;
            var url = devicemgtProps["httpsURL"] + "/api/device-mgt/v1.0/devices/" + deviceType + "/" + deviceId;
            return serviceInvokers.XMLHttp.get(
                url,
                function (backendResponse) {
                    var response = {};
                    if (backendResponse.status == 200 && backendResponse.responseText) {
                        response["status"] = "success";
                        var device = parse(backendResponse.responseText);
                        var propertiesList = device["properties"];
                        var properties = {};
                        for (var i = 0; i < propertiesList.length; i++) {
                            properties[propertiesList[i]["name"]] =
                                propertiesList[i]["value"];
                        }
                        var deviceObject = {};
                        deviceObject[constants["DEVICE_IDENTIFIER"]] = device["deviceIdentifier"];
                        deviceObject[constants["DEVICE_NAME"]] = device["name"];
                        deviceObject[constants["DEVICE_OWNERSHIP"]] = device["enrolmentInfo"]["ownership"];
                        deviceObject[constants["DEVICE_OWNER"]] = device["enrolmentInfo"]["owner"];
                        deviceObject[constants["DEVICE_STATUS"]] = device["enrolmentInfo"]["status"];
                        deviceObject[constants["DEVICE_TYPE"]] = device["type"];
                        if (device["type"] == constants["PLATFORM_IOS"]) {
                            properties[constants["DEVICE_MODEL"]] = properties[constants["DEVICE_PRODUCT"]];
                            delete properties[constants["DEVICE_PRODUCT"]];
                            properties[constants["DEVICE_VENDOR"]] = constants["VENDOR_APPLE"];
                        }
                        deviceObject[constants["DEVICE_PROPERTIES"]] = properties;
                        response["content"] = deviceObject;
                        return response;
                    } else if (backendResponse.status == 401) {
                        response["status"] = "unauthorized";
                        return response;
                    } else {
                        response["status"] = "error";
                        return response;
                    }
                }
            );
        } catch (e) {
            throw e;
        } finally {
            utility.endTenantFlow();
        }
    };

    // Refactored methods
    publicMethods.getDevicesCount = function () {
        var carbonUser = session.get(constants.USER_SESSION_KEY);
        if (carbonUser) {
            var userModule = require("/app/modules/business-controllers/user.js")["userModule"];
            var uiPermissions = userModule.getUIPermissions();
            var url;
            if (uiPermissions.LIST_DEVICES) {
                url = devicemgtProps["httpsURL"] +
                    devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/devices/count";
            } else if (uiPermissions.LIST_OWN_DEVICES) {
                url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] +
                    "/devices/user/" + carbonUser.username + "/count";
            } else {
                log.error("Access denied for user: " + carbonUser.username);
                return -1;
            }
            return serviceInvokers.XMLHttp.get(
                url, function (responsePayload) {
                    return responsePayload;
                },
                function (responsePayload) {
                    log.error(responsePayload);
                    return -1;
                }
            );
        } else {
            log.error("User object was not found in the session");
            throw constants["ERRORS"]["USER_NOT_FOUND"];
        }
    };

    publicMethods.getDeviceTypes = function () {
        var url = devicemgtProps["httpsURL"] + devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/device-types";
        var response = privateMethods.callBackend(url, constants["HTTP_GET"]);
        if (response.status == "success") {
            response.content = parse(response.content);
        }
        return response;
    };

    //Old methods
    //TODO: make sure these methods are updated
    /*
     @Updated
     */
    // publicMethods.getLicense = function (deviceType) {
    //     var url;
    //     var license;
    //     if (deviceType == "windows") {
    //         url = mdmProps["httpURL"] + "/mdm-windows-agent/services/device/license";
    //     } else if (deviceType == "ios") {
    //         url = mdmProps["httpsURL"] + "/ios-enrollment/license/";
    //     }

    //     if (url != null && url != undefined) {
    //         serviceInvokers.XMLHttp.get(url, function (responsePayload) {
    //             license = responsePayload.text;
    //         }, function (responsePayload) {
    //             return null;
    //         });
    //     }
    //     return license;
    // };

    publicMethods.getDevices = function (userName) {
        var url = devicemgtProps["httpsURL"] +
            devicemgtProps["backendRestEndpoints"]["deviceMgt"] + "/devices/user/" + userName;
        return serviceInvokers.XMLHttp.get(
            url, function (responsePayload) {
                for (var i = 0; i < responsePayload.length; i++) {
                    responsePayload[i].thumb = utility.getDeviceThumb(responsePayload[i].type);
                }
                return responsePayload;
            },
            function (responsePayload) {
                log.error(responsePayload);
                return -1;
            }
        );
    };
    return publicMethods;
}();
<|endoftext|>


<commit_before>/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "/";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(1);

/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*eslint-disable no-alert, no-undef, no-unused-vars*/

var sequenceSerializer = __webpack_require__(2),
    tickGenerator = __webpack_require__(3),
    tickConverter = __webpack_require__(4),
    tickFormatter = __webpack_require__(5),
    defaultRequestAnimFrame = function defaultRequestAnimFrame(callback) {
    return setTimeout(callback, 1000 / 60);
},
    requestAnimFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame // Chrome & Safari
|| window.mozRequestAnimationFrame // Firefox
|| window.oRequestAnimationFrame // Opera
|| window.msRequestAnimationFrame // Internet Explorer
|| defaultRequestAnimFrame,
    sequence = sequenceSerializer.read(location.search.substr(1)),
    sequenceTotal = sequence.reduce(function (total, tick) {
    return total + tick;
}, 0),
    ticker = tickGenerator.allocate(),
    ratio2Coords = function ratio2Coords(ratio) {
    var radius = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
    var precision = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10000;

    var radian = ratio * 2 * Math.PI,
        x = Math.floor(radius * precision * Math.sin(radian)) / precision,
        y = Math.floor(-radius * precision * Math.cos(radian)) / precision;
    return { x: x, y: y };
},
    getCirclePath = function getCirclePath(ratio, outerRadius, innerRadius) {
    var outer = ratio2Coords(ratio, outerRadius),
        inner = ratio2Coords(ratio, innerRadius),
        path = ["M 0 -" + outerRadius];
    if (ratio > 0.5) {
        path.push("A " + outerRadius + " " + outerRadius + " 0 0 1 0 " + outerRadius, "A " + outerRadius + " " + outerRadius + " 0 0 1 " + outer.x + " " + outer.y, "L " + inner.x + " " + inner.y, "A " + innerRadius + " " + innerRadius + " 0 0 0 0 " + innerRadius, "A " + innerRadius + " " + innerRadius + " 0 0 0 0 -" + innerRadius);
    } else {
        path.push("A " + outerRadius + " " + outerRadius + " 0 0 1 " + outer.x + " " + outer.y, "L " + inner.x + " " + inner.y, "A " + innerRadius + " " + innerRadius + " 0 0 0 0 -" + innerRadius);
    }
    path.push("L 0 -" + outerRadius);
    return path.join(" ");
},
    onTick = function onTick(tick) {

    var convertedTick = tickConverter(tick.elapsed, sequence),
        currentDuration = sequence[convertedTick.step % sequence.length],
        outer = tick.elapsed / sequenceTotal % 1,
        inner = 1 - convertedTick.remaining / currentDuration,
        formattedRemaining = tickFormatter(convertedTick.remaining);

    document.getElementById("outer").setAttribute("d", getCirclePath(outer, 0.99, 0.89));
    document.getElementById("inner").setAttribute("d", getCirclePath(inner, 0.89, 0.79));
    document.getElementById("time").innerHTML = formattedRemaining.time;
    document.getElementById("ms").innerHTML = "." + formattedRemaining.ms;

    if (convertedTick.step < sequence.length) {
        document.getElementById("step").innerHTML = convertedTick.step + 1 + " / " + sequence.length;
        requestAnimFrame(ticker.tick.bind(ticker));
    } else {
        document.getElementById("step").innerHTML = "done.";
    }
},
    genSvgTag = function genSvgTag(tagName, properties, children) {
    var element = document.createElementNS("http://www.w3.org/2000/svg", tagName);
    Object.keys(properties).forEach(function (name) {
        element.setAttribute(name, properties[name]);
    });
    [].concat(children || []).map(function (def) {
        return typeof def === "string" ? document.createTextNode(def) : def;
    }).forEach(function (node) {
        return element.appendChild(node);
    });
    return element;
},
    setup = function setup() {
    var svg = genSvgTag.bind(null, "svg"),
        circle = genSvgTag.bind(null, "circle"),
        text = genSvgTag.bind(null, "text"),
        path = genSvgTag.bind(null, "path");

    document.body.appendChild(svg({
        width: "100%",
        height: "100%",
        viewBox: "-1 -1 2 2"
    }, [circle({ cx: 0, cy: 0, r: 0.99, stroke: "white", "stroke-width": 0.01, fill: "blue" }), circle({ cx: 0, cy: 0, r: 0.89, stroke: "white", "stroke-width": 0.01, fill: "green" }), circle({ cx: 0, cy: 0, r: 0.79, stroke: "white", "stroke-width": 0.01, fill: "white" }), text({ id: "time",
        "font-family": "Arial", "font-size": 0.3, x: 0, y: 0.1, "text-anchor": "middle",
        fill: "red", stroke: "black", "stroke-width": 0.01 }, "00:00"), text({ id: "ms",
        "font-family": "Arial", "font-size": 0.1, x: 0.60, y: 0.1, "text-anchor": "end",
        fill: "red", stroke: "black", "stroke-width": 0.001 }, ".123"), text({ id: "step",
        "font-family": "Arial", "font-size": 0.1, x: 0, y: 0.3, "text-anchor": "middle",
        fill: "red", stroke: "black", "stroke-width": 0.01 }, "1 / 2"), path({ id: "outer",
        d: "M 0 -.99 A .99 .99 0 0 1 .99 0 L .89 0 A .89 .89 0 0 0 0 -.89 L 0 -.99",
        fill: "purple", stroke: "black", "stroke-width": 0.01 }), path({ id: "inner",
        d: "M 0 -.89 A .89 .89 0 0 1 .89 0 L .79 0 A .79 .79 0 0 0 0 -.79 L 0 -.89",
        fill: "red", stroke: "black", "stroke-width": 0.01 })]));
};

window.addEventListener("load", function () {
    if (0 === sequence.length) {
        alert("No sequence to play");
    } else {
        setup();
        ticker.on(onTick);
    }
});

window.addEventListener("click", function () {
    if (ticker.isPaused()) {
        ticker.resume();
    } else {
        ticker.pause();
    }
});

/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var _read = function _read(string) {
    return string ? string.split(",").map(function (time) {
        return 1000 * parseInt(time, 10);
    }) : [];
},
    _write = function _write(sequence) {
    return sequence.map(function (time) {
        return Math.floor(time / 1000);
    }).join(",");
};

module.exports = {
    read: _read,
    write: _write
};

/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var _allocate = function _allocate() {
    return {
        elapsed: 0,
        refTick: null,
        callback: function callback() {}
    };
},
    _update = function _update(ticker, active) {
    var now = new Date(),
        elapsed = ticker.elapsed;
    if (ticker.refTick) {
        elapsed += now - ticker.refTick;
        if (false === active) {
            ticker.elapsed = elapsed;
            ticker.refTick = null;
        }
    } else if (active) {
        ticker.refTick = now;
    }
    return elapsed;
},
    _notify = function _notify(ticker, active) {
    var elapsed = _update(ticker, active);
    ticker.callback({
        paused: !ticker.refTick,
        elapsed: elapsed
    });
},
    _tick = function _tick(ticker) {
    return _notify(ticker);
},
    _pause = function _pause(ticker) {
    return _notify(ticker, false);
},
    _resume = function _resume(ticker) {
    return _notify(ticker, true);
},
    _attach = function _attach(ticker, callback) {
    ticker.callback = callback;
    _notify(ticker);
};

module.exports = {

    allocate: function allocate() {
        var ticker = _allocate();
        return {
            tick: function tick() {
                return _tick(ticker);
            },
            pause: function pause() {
                return _pause(ticker);
            },
            resume: function resume() {
                return _resume(ticker);
            },
            on: function on(callback) {
                return _attach(ticker, callback);
            },
            isPaused: function isPaused() {
                return !ticker.refTick;
            }
        };
    }

};

/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function (elapsed, sequence) {
    var step = 0,
        remaining = 0;
    sequence.every(function (ms) {
        if (elapsed >= ms) {
            elapsed -= ms;
            ++step;
            return true;
        }
        remaining = ms - elapsed;
        if (remaining === 0) {
            ++step;
        }
        return false;
    });
    return { step: step, remaining: remaining };
};

/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var _zero = function _zero(x) {
    var count = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;

    var result = [],
        max = Math.pow(10, count - 1);
    while (max > 1 && x < max) {
        result.push("0");
        max /= 10;
    }
    result.push(x);
    return result.join("");
};

module.exports = function (tick) {
    var ms = _zero(tick % 1000, 3),
        seconds = (tick - ms) / 1000,
        s = _zero(seconds % 60),
        m = _zero((seconds - s) / 60),
        time = m + ":" + s;
    return { time: time, ms: ms };
};

/***/ })
/******/ ]);<commit_msg>New style<commit_after>/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "/";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

module.exports = __webpack_require__(1);

/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/*eslint-disable no-alert, no-undef, no-unused-vars*/

var TOTAL_OUTER = 0.98,
    TOTAL_INNER = 0.88,
    STEP_OUTER = 0.83,
    STEP_INNER = 0.73,
    colors = __webpack_require__(2),
    sequenceSerializer = __webpack_require__(3),
    tickGenerator = __webpack_require__(4),
    tickConverter = __webpack_require__(5),
    tickFormatter = __webpack_require__(6),
    defaultRequestAnimFrame = function defaultRequestAnimFrame(callback) {
    return setTimeout(callback, 1000 / 60);
},
    requestAnimFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame // Chrome & Safari
|| window.mozRequestAnimationFrame // Firefox
|| window.oRequestAnimationFrame // Opera
|| window.msRequestAnimationFrame // Internet Explorer
|| defaultRequestAnimFrame,
    sequence = sequenceSerializer.read(location.search.substr(1)),
    sequenceTotal = sequence.reduce(function (total, tick) {
    return total + tick;
}, 0),
    ticker = tickGenerator.allocate(),
    ratio2Coords = function ratio2Coords(ratio) {
    var radius = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1;
    var precision = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10000;

    var radian = ratio * 2 * Math.PI,
        x = Math.floor(radius * precision * Math.sin(radian)) / precision,
        y = Math.floor(-radius * precision * Math.cos(radian)) / precision;
    return { x: x, y: y };
},
    getCirclePath = function getCirclePath(ratio, outerRadius, innerRadius) {
    var outer = ratio2Coords(ratio, outerRadius),
        inner = ratio2Coords(ratio, innerRadius),
        path = ["M 0 -" + outerRadius];
    if (ratio > 0.5) {
        path.push("A " + outerRadius + " " + outerRadius + " 0 0 1 0 " + outerRadius, "A " + outerRadius + " " + outerRadius + " 0 0 1 " + outer.x + " " + outer.y, "L " + inner.x + " " + inner.y, "A " + innerRadius + " " + innerRadius + " 0 0 0 0 " + innerRadius, "A " + innerRadius + " " + innerRadius + " 0 0 0 0 -" + innerRadius);
    } else {
        path.push("A " + outerRadius + " " + outerRadius + " 0 0 1 " + outer.x + " " + outer.y, "L " + inner.x + " " + inner.y, "A " + innerRadius + " " + innerRadius + " 0 0 0 0 -" + innerRadius);
    }
    path.push("L 0 -" + outerRadius);
    return path.join(" ");
},
    onTick = function onTick(tick) {

    var convertedTick = tickConverter(tick.elapsed, sequence),
        currentDuration = sequence[convertedTick.step % sequence.length],
        total = tick.elapsed / sequenceTotal % 1,
        step = 1 - convertedTick.remaining / currentDuration,
        formattedRemaining = tickFormatter(convertedTick.remaining);

    document.getElementById("total").setAttribute("d", getCirclePath(total, TOTAL_OUTER, TOTAL_INNER));
    document.getElementById("step").setAttribute("d", getCirclePath(step, STEP_OUTER, STEP_INNER));
    document.getElementById("time").innerHTML = formattedRemaining.time;
    document.getElementById("ms").innerHTML = "." + formattedRemaining.ms;

    if (convertedTick.step < sequence.length) {
        document.getElementById("step").innerHTML = convertedTick.step + 1 + " / " + sequence.length;
        requestAnimFrame(ticker.tick.bind(ticker));
    } else {
        document.getElementById("step").innerHTML = "done.";
    }
},
    genSvgTag = function genSvgTag(tagName, properties, children) {
    var element = document.createElementNS("http://www.w3.org/2000/svg", tagName);
    Object.keys(properties).forEach(function (name) {
        element.setAttribute(name, properties[name]);
    });
    [].concat(children || []).map(function (def) {
        return typeof def === "string" ? document.createTextNode(def) : def;
    }).forEach(function (node) {
        return element.appendChild(node);
    });
    return element;
},
    svg = genSvgTag.bind(null, "svg"),
    circle = genSvgTag.bind(null, "circle"),
    text = genSvgTag.bind(null, "text"),
    path = genSvgTag.bind(null, "path"),
    progressContainer = function progressContainer(_ref) {
    var outerRadius = _ref.outerRadius,
        innerRadius = _ref.innerRadius,
        id = _ref.id,
        color = _ref.color;

    var po1 = ratio2Coords(0.085, outerRadius),
        po2 = ratio2Coords(0.165, outerRadius),
        po3 = ratio2Coords(0.585, outerRadius),
        po4 = ratio2Coords(0.665, outerRadius),
        pi1 = ratio2Coords(0.085, innerRadius),
        pi2 = ratio2Coords(0.165, innerRadius),
        pi3 = ratio2Coords(0.585, innerRadius),
        pi4 = ratio2Coords(0.665, innerRadius);
    return [circle({ cx: 0, cy: 0, r: outerRadius, stroke: colors.circle.light, "stroke-width": 0.01,
        fill: colors.circle.background }), circle({ cx: 0, cy: 0, r: innerRadius, stroke: colors.circle.light, "stroke-width": 0.01,
        fill: colors.background }), path({ d: "M " + po1.x + " " + po1.y + " A " + outerRadius + " " + outerRadius + " 0 0 1 " + po2.x + " " + po2.y,
        fill: "transparent", stroke: colors.circle.shaded, "stroke-width": 0.01 }), path({ d: "M " + po2.x + " " + po2.y + " A " + outerRadius + " " + outerRadius + " 0 0 1 " + po3.x + " " + po3.y,
        fill: "transparent", stroke: colors.circle.dark, "stroke-width": 0.01 }), path({ d: "M " + po3.x + " " + po3.y + " A " + outerRadius + " " + outerRadius + " 0 0 1 " + po4.x + " " + po4.y,
        fill: "transparent", stroke: colors.circle.shaded, "stroke-width": 0.01 }), path({ d: "M " + pi1.x + " " + pi1.y + " A " + innerRadius + " " + innerRadius + " 0 0 1 " + pi2.x + " " + pi2.y,
        fill: "transparent", stroke: colors.circle.shaded, "stroke-width": 0.01 }), path({ d: "M " + pi2.x + " " + pi2.y + " A " + innerRadius + " " + innerRadius + " 0 0 1 " + pi3.x + " " + pi3.y,
        fill: "transparent", stroke: colors.circle.dark, "stroke-width": 0.01 }), path({ d: "M " + pi3.x + " " + pi3.y + " A " + innerRadius + " " + innerRadius + " 0 0 1 " + pi4.x + " " + pi4.y,
        fill: "transparent", stroke: colors.circle.shaded, "stroke-width": 0.01 }), path({ id: id,
        d: "M 0 -" + outerRadius + " A " + outerRadius + " " + outerRadius + " 0 0 1 " + outerRadius + " 0\n                L " + innerRadius + " 0 A " + innerRadius + " " + innerRadius + " 0 0 0 0 -" + innerRadius + " L 0 -" + outerRadius,
        fill: color, stroke: color, "stroke-opacity": 0.2, "stroke-width": 0.01 })];
},
    setup = function setup() {

    document.body.appendChild(svg({
        width: "100%",
        height: "100%",
        viewBox: "-1 -1 2 2",
        style: "background-color: " + colors.background + ";"
    }, progressContainer({
        outerRadius: TOTAL_OUTER,
        innerRadius: TOTAL_INNER,
        id: "total",
        color: colors.progress.total
    }).concat(progressContainer({
        outerRadius: STEP_OUTER,
        innerRadius: STEP_INNER,
        id: "step",
        color: colors.progress.step
    })).concat([text({ id: "time",
        "font-family": "Arial", "font-size": 0.3, x: 0, y: 0.1, "text-anchor": "middle",
        fill: colors.text.time,
        stroke: colors.text.time, "stroke-opacity": 0.2, "stroke-width": 0.01 }, "00:00"), text({ id: "ms",
        "font-family": "Arial", "font-size": 0.1, x: 0.60, y: 0.1, "text-anchor": "end",
        fill: colors.text.ms,
        stroke: colors.text.ms, "stroke-opacity": 0.2, "stroke-width": 0.001 }, ".123"), text({ id: "step",
        "font-family": "Arial", "font-size": 0.1, x: 0, y: 0.3, "text-anchor": "middle",
        fill: colors.text.step,
        stroke: colors.text.step, "stroke-opacity": 0.2, "stroke-width": 0.01 }, "1 / 2")])));
};

window.addEventListener("load", function () {
    if (0 === sequence.length) {
        alert("No sequence to play");
    } else {
        setup();
        ticker.on(onTick);
    }
});

window.addEventListener("click", function () {
    if (ticker.isPaused()) {
        ticker.resume();
    } else {
        ticker.pause();
    }
});

/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = {
    background: "#ccd0d3",
    circle: {
        light: "#dce0e1",
        shaded: "#c9ced1",
        dark: "#b3b7ba",
        background: "#a8acae"
    },
    progress: {
        total: "#def1f2",
        step: "#f3dfe6"
    },
    text: {
        time: "#ffffff",
        ms: "#ffffff",
        step: "#000000"
    }
};

/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var _read = function _read(string) {
    return string ? string.split(",").map(function (time) {
        return 1000 * parseInt(time, 10);
    }) : [];
},
    _write = function _write(sequence) {
    return sequence.map(function (time) {
        return Math.floor(time / 1000);
    }).join(",");
};

module.exports = {
    read: _read,
    write: _write
};

/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var _allocate = function _allocate() {
    return {
        elapsed: 0,
        refTick: null,
        callback: function callback() {}
    };
},
    _update = function _update(ticker, active) {
    var now = new Date(),
        elapsed = ticker.elapsed;
    if (ticker.refTick) {
        elapsed += now - ticker.refTick;
        if (false === active) {
            ticker.elapsed = elapsed;
            ticker.refTick = null;
        }
    } else if (active) {
        ticker.refTick = now;
    }
    return elapsed;
},
    _notify = function _notify(ticker, active) {
    var elapsed = _update(ticker, active);
    ticker.callback({
        paused: !ticker.refTick,
        elapsed: elapsed
    });
},
    _tick = function _tick(ticker) {
    return _notify(ticker);
},
    _pause = function _pause(ticker) {
    return _notify(ticker, false);
},
    _resume = function _resume(ticker) {
    return _notify(ticker, true);
},
    _attach = function _attach(ticker, callback) {
    ticker.callback = callback;
    _notify(ticker);
};

module.exports = {

    allocate: function allocate() {
        var ticker = _allocate();
        return {
            tick: function tick() {
                return _tick(ticker);
            },
            pause: function pause() {
                return _pause(ticker);
            },
            resume: function resume() {
                return _resume(ticker);
            },
            on: function on(callback) {
                return _attach(ticker, callback);
            },
            isPaused: function isPaused() {
                return !ticker.refTick;
            }
        };
    }

};

/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

module.exports = function (elapsed, sequence) {
    var step = 0,
        remaining = 0;
    sequence.every(function (ms) {
        if (elapsed >= ms) {
            elapsed -= ms;
            ++step;
            return true;
        }
        remaining = ms - elapsed;
        if (remaining === 0) {
            ++step;
        }
        return false;
    });
    return { step: step, remaining: remaining };
};

/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

var _zero = function _zero(x) {
    var count = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;

    var result = [],
        max = Math.pow(10, count - 1);
    while (max > 1 && x < max) {
        result.push("0");
        max /= 10;
    }
    result.push(x);
    return result.join("");
};

module.exports = function (tick) {
    var ms = _zero(tick % 1000, 3),
        seconds = (tick - ms) / 1000,
        s = _zero(seconds % 60),
        m = _zero((seconds - s) / 60),
        time = m + ":" + s;
    return { time: time, ms: ms };
};

/***/ })
/******/ ]);<|endoftext|>


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

var fs = require('fs')
var minimist = require('minimist')
var mkdirp = require('mkdirp')
var path = require('path')
var transports = require('transport-stream')({command: 'hyperfs replicate -'})
var execspawn = require('execspawn')
var argv = minimist(process.argv.slice(2), {alias: {message: 'm', quiet: 'q', debug: 'D', store: 's', node: 'n'}})
var s = argv.store || 'hyperfs'

mkdirp.sync(s)

var cauf = require('./')(s)

var cmd = argv._[0]

if (cmd === 'list' || cmd === 'ls') {
  cauf.list().on('data', console.log)
  return
}

if (cmd === 'show') {
  cauf.show(argv._[1], function (err, val) {
    if (err) throw err
    cauf.readSnapshot(val.snapshot, function (err, rs) {
      if (err) throw err
      rs.on('data', function (data) {
        console.log(JSON.stringify(data))
      })
    })
  })
  return
}

if (cmd === 'version') {
  console.log(require('./package.json').version)
  return
}

if (cmd === 'nodes') {
  cauf.nodes().on('data', function (data) {
    console.log(data.key+': ' + (data.value.message || '(no message)'))
  })
  return
}

if (cmd === 'remove' || cmd === 'rm') {
  cauf.remove(argv._[1], function () {
    console.log(argv._[1] + ' removed')
  })
  return
}

if (cmd === 'info') {
  cauf.info(argv._[1], console.log)
  return
}

if (cmd === 'create') {
  if (!argv._[1]) throw new Error('volume required')
  cauf.create(argv._[1], argv, console.log)
  return
}

if (cmd === 'replicate') {
  var stream = transports(argv._[1])
  var rs = cauf.replicate(argv)

  stream.on('warn', console.error)

  if (argv._[1] !== '-' && !argv.quiet) {
    rs.on('receive-data', function (data) {
      console.error('receive-data: ' + data)
    })

    rs.on('receive-snapshot', function (hash) {
      console.error('receive-snapshot: ' + hash)
    })

    rs.on('send-data', function (data) {
      console.error('send-data: ' + data)
    })

    rs.on('send-snapshot', function (hash) {
      console.error('send-snapshot: ' + hash)
    })
  }

  stream.pipe(rs).pipe(stream)
  return
}

if (cmd === 'exec') {
  if (!argv._[1]) throw new Error('volume required')
  var folder = argv.mnt || path.join(s, 'mnt', argv._[1])

  mkdirp(folder, function (err) {
    if (err) throw err
    var mnt = cauf.mount(argv._[1], folder, argv)

    mnt.on('ready', function () {
      var proc = execspawn(argv._[2], {
        cwd: folder
      })

      proc.stdout.pipe(process.stdout)
      proc.stderr.pipe(process.stderr)
      process.stdin.pipe(proc.stdin)

      proc.on('exit', function (code) {
        cauf.unmount(folder, function () {
          process.exit(code)
        })
      })
    })

    process.on('SIGINT', function () {
      cauf.unmount(folder, function () {
        process.exit()
      })
    })
  })
  return
}

if (cmd === 'mount') {
  if (!argv._[1]) throw new Error('volume required')
  var mnt = cauf.mount(argv._[1], argv._[2] || 'mnt', argv)
  mnt.on('ready', function () {
    console.log(mnt.id, 'mounted')
    ;[].concat(mnt.nodes).reverse().forEach(function (l) {
      console.log('<-- ' + l)
    })
  })
  process.on('SIGINT', function () {
    cauf.unmount(argv._[2] || 'mnt', function () {
      process.exit()
    })
  })
  return
}

if (cmd === 'snapshot') {
  var snapshot = cauf.snapshot(argv._[1], argv)
  snapshot.on('index', function (name) {
    console.log('Indexing ' + name)
  })
  snapshot.on('snapshot', function (name) {
    console.log('Snapshotting ' + name)
  })
  snapshot.on('finish', function () {
    console.log('Snapshot complete: ' + snapshot.node)
  })
  return
}

console.log(fs.readFileSync(__dirname + '/help.txt', 'utf-8'))<commit_msg>just use stdio inherit<commit_after>#!/usr/bin/env node

var fs = require('fs')
var minimist = require('minimist')
var mkdirp = require('mkdirp')
var path = require('path')
var transports = require('transport-stream')({command: 'hyperfs replicate -'})
var execspawn = require('execspawn')
var argv = minimist(process.argv.slice(2), {alias: {message: 'm', quiet: 'q', debug: 'D', store: 's', node: 'n'}})
var s = argv.store || 'hyperfs'

mkdirp.sync(s)

var cauf = require('./')(s)

var cmd = argv._[0]

if (cmd === 'list' || cmd === 'ls') {
  cauf.list().on('data', console.log)
  return
}

if (cmd === 'show') {
  cauf.show(argv._[1], function (err, val) {
    if (err) throw err
    cauf.readSnapshot(val.snapshot, function (err, rs) {
      if (err) throw err
      rs.on('data', function (data) {
        console.log(JSON.stringify(data))
      })
    })
  })
  return
}

if (cmd === 'version') {
  console.log(require('./package.json').version)
  return
}

if (cmd === 'nodes') {
  cauf.nodes().on('data', function (data) {
    console.log(data.key+': ' + (data.value.message || '(no message)'))
  })
  return
}

if (cmd === 'remove' || cmd === 'rm') {
  cauf.remove(argv._[1], function () {
    console.log(argv._[1] + ' removed')
  })
  return
}

if (cmd === 'info') {
  cauf.info(argv._[1], console.log)
  return
}

if (cmd === 'create') {
  if (!argv._[1]) throw new Error('volume required')
  cauf.create(argv._[1], argv, console.log)
  return
}

if (cmd === 'replicate') {
  var stream = transports(argv._[1])
  var rs = cauf.replicate(argv)

  stream.on('warn', console.error)

  if (argv._[1] !== '-' && !argv.quiet) {
    rs.on('receive-data', function (data) {
      console.error('receive-data: ' + data)
    })

    rs.on('receive-snapshot', function (hash) {
      console.error('receive-snapshot: ' + hash)
    })

    rs.on('send-data', function (data) {
      console.error('send-data: ' + data)
    })

    rs.on('send-snapshot', function (hash) {
      console.error('send-snapshot: ' + hash)
    })
  }

  stream.pipe(rs).pipe(stream)
  return
}

if (cmd === 'exec') {
  if (!argv._[1]) throw new Error('volume required')
  var folder = argv.mnt || path.join(s, 'mnt', argv._[1])

  mkdirp(folder, function (err) {
    if (err) throw err
    var mnt = cauf.mount(argv._[1], folder, argv)

    mnt.on('ready', function () {
      var proc = execspawn(argv._[2], {
        cwd: folder,
        stdio: 'inherit'
      })

      proc.on('exit', function (code) {
        cauf.unmount(folder, function () {
          process.exit(code)
        })
      })
    })

    process.on('SIGINT', function () {
      cauf.unmount(folder, function () {
        process.exit()
      })
    })
  })
  return
}

if (cmd === 'mount') {
  if (!argv._[1]) throw new Error('volume required')
  var mnt = cauf.mount(argv._[1], argv._[2] || 'mnt', argv)
  mnt.on('ready', function () {
    console.log(mnt.id, 'mounted')
    ;[].concat(mnt.nodes).reverse().forEach(function (l) {
      console.log('<-- ' + l)
    })
  })
  process.on('SIGINT', function () {
    cauf.unmount(argv._[2] || 'mnt', function () {
      process.exit()
    })
  })
  return
}

if (cmd === 'snapshot') {
  var snapshot = cauf.snapshot(argv._[1], argv)
  snapshot.on('index', function (name) {
    console.log('Indexing ' + name)
  })
  snapshot.on('snapshot', function (name) {
    console.log('Snapshotting ' + name)
  })
  snapshot.on('finish', function () {
    console.log('Snapshot complete: ' + snapshot.node)
  })
  return
}

console.log(fs.readFileSync(__dirname + '/help.txt', 'utf-8'))<|endoftext|>


<commit_before>/*
	Each Enyo-provided library will annotate this structure with its own
	version info. Why? In general, Enyo and its libraries are versioned
	and released together, but libraries may be versioned separately in
	the future. Also, since libraries are checked out and updated
	individually, a project may be using "mismatched" libraries at any
	given time (e.g., the last stable release of Enyo, but an
	unreleased checkout from the master branch of layout).

	Enyo uses semantic versioning. Official releases have version
	numbers	of the form "X.y.z". Prereleases are indicated by a suffix
	of the form "-pre.N" where N is incremented for each prerelease.
	Between releases, version numbers include an additional "-dev"
	suffix.
*/

enyo.version = {
	enyo: "2.5.0-pre.1"
};
<commit_msg>Update version string to 2.5.0<commit_after>/*
	Each Enyo-provided library will annotate this structure with its own
	version info. Why? In general, Enyo and its libraries are versioned
	and released together, but libraries may be versioned separately in
	the future. Also, since libraries are checked out and updated
	individually, a project may be using "mismatched" libraries at any
	given time (e.g., the last stable release of Enyo, but an
	unreleased checkout from the master branch of layout).

	Enyo uses semantic versioning. Official releases have version
	numbers	of the form "X.y.z". Prereleases are indicated by a suffix
	of the form "-pre.N" where N is incremented for each prerelease.
	Between releases, version numbers include an additional "-dev"
	suffix.
*/

enyo.version = {
	enyo: "2.5.0"
};
<|endoftext|>


<commit_before>import { has } from 'lodash';
import Log from './log';
import WarningAndLog from './messages/warning_and_log';
import SuccessAndLog from './messages/success_and_log';
import WatcherHandler from './watcher_handler';
import logHistory from './log_history';

/**
* Helper class to handle watchers
*/
export default class WatcherWizardHandler extends WatcherHandler {
  constructor(server, client, config) {
    super(server, client, config);
  }

  /**
  * Execute condition
  *
  * @param {object} payload data from Elasticsearch
  * @param {object} condition
  * @param {boolean} isAnomaly
  * @param {boolean} isRange
  * @return {object} null or warning message
  */
  _executeCondition(payload, condition) {
    this.log.debug(`condition: ${JSON.stringify(condition, null, 2)}`);

    // script
    if (has(condition, 'script.script')) {
      try {
        if (!eval(condition.script.script)) { // eslint-disable-line no-eval
          return new WarningAndLog(this.log, 'no data satisfy condition');
        }
      } catch (err) {
        throw new Error('apply condition "script": ' + err.toString());
      }
    }
    return new SuccessAndLog(this.log, 'successfully applied condition', { payload });
  }

  /**
  * Execute watcher
  *
  * @param {object} task watcher
  * @param {string} ES search method name
  * @param {object} ES search request of watcher
  * @param {object} condition of watcher
  * @param {object} transform of watcher
  * @param {object} actions of watcher
  * @return {object} success or warning message
  */
  async _execute(task, method, request, condition, transform, actions) {
    let payload;

    try {
      payload = await this.search(request, method); // data from Elasticsearch
      // this.log.debug(`payload: ${JSON.stringify(payload)}`);
    } catch (err) {
      throw err;
    }

    try {
      const resp = this._executeCondition(payload, condition);
      if (resp && resp.warning) {
        return resp; // payload is empty, do not execute actions
      }
      if (resp.payload) {
        payload = resp.payload;
      }
    } catch (err) {
      throw err;
    }

    this.doActions(payload, this.server, actions, task);
    return new SuccessAndLog(this.log, 'successfuly executed');
  }

  /**
  * Execute watcher.
  *
  * @param {object} task - Elasticsearch watcher object
  */
  async execute(task) {
    try {
      const {method, request, condition, transform, actions} = this._checkWatcher(task);
      if (this.config.settings.authentication.impersonate || task._source.impersonate) {
        this.client = await this.getImpersonatedClient(task._id);
      }
      return await this._execute(task, method, request, condition, transform, actions);
    } catch (err) {
      logHistory({
        server: this.server,
        watcherTitle: task._source.title,
        message: 'execute wizard watcher: ' + err.toString(),
        level: 'high',
        isError: true,
      });
      throw new Error('execute wizard watcher: ' + err.toString());
    }
  }
}
<commit_msg>Use correct ES request.<commit_after>import { has } from 'lodash';
import Log from './log';
import WarningAndLog from './messages/warning_and_log';
import SuccessAndLog from './messages/success_and_log';
import WatcherHandler from './watcher_handler';
import logHistory from './log_history';

/**
* Helper class to handle watchers
*/
export default class WatcherWizardHandler extends WatcherHandler {
  constructor(server, client, config) {
    super(server, client, config);
  }

  /**
  * Execute condition
  *
  * @param {object} payload data from Elasticsearch
  * @param {object} condition
  * @param {boolean} isAnomaly
  * @param {boolean} isRange
  * @return {object} null or warning message
  */
  _executeCondition(payload, condition) {
    this.log.debug(`condition: ${JSON.stringify(condition, null, 2)}`);

    // script
    if (has(condition, 'script.script')) {
      try {
        if (!eval(condition.script.script)) { // eslint-disable-line no-eval
          return new WarningAndLog(this.log, 'no data satisfy condition');
        }
      } catch (err) {
        throw new Error('apply condition "script": ' + err.toString());
      }
    }
    return new SuccessAndLog(this.log, 'successfully applied condition', { payload });
  }

  /**
  * Execute watcher
  *
  * @param {object} task watcher
  * @param {string} ES search method name
  * @param {object} ES search request of watcher
  * @param {object} condition of watcher
  * @param {object} transform of watcher
  * @param {object} actions of watcher
  * @return {object} success or warning message
  */
  async _execute(task, method, request, condition, transform, actions) {
    let payload;

    try {
      payload = await this.search(request, method); // data from Elasticsearch
      // this.log.debug(`payload: ${JSON.stringify(payload)}`);
    } catch (err) {
      throw err;
    }

    try {
      const resp = this._executeCondition(payload, condition);
      if (resp && resp.warning) {
        return resp; // payload is empty, do not execute actions
      }
      if (resp.payload) {
        payload = resp.payload;
      }
    } catch (err) {
      throw err;
    }

    this.doActions(payload, this.server, actions, task);
    return new SuccessAndLog(this.log, 'successfuly executed');
  }

  /**
  * Execute watcher.
  *
  * @param {object} task - Elasticsearch watcher object
  */
  async execute(task) {
    try {
      const {method, search, condition, transform, actions} = this._checkWatcher(task);
      if (this.config.settings.authentication.impersonate || task._source.impersonate) {
        this.client = await this.getImpersonatedClient(task._id);
      }
      return await this._execute(task, method, search.request, condition, transform, actions);
    } catch (err) {
      logHistory({
        server: this.server,
        watcherTitle: task._source.title,
        message: 'execute wizard watcher: ' + err.toString(),
        level: 'high',
        isError: true,
      });
      throw new Error('execute wizard watcher: ' + err.toString());
    }
  }
}
<|endoftext|>


<commit_before>/*
# harness
This file can be used to very quickly set up a mocha-based browser testing
environment, and is compatible with `grunt-mocha`. You'll just need to set the path
for three files in `requirejs`:

```
paths: {
  'thehelp-test': '<your path>',
  'thehelp-test-coverage': '<required for code coverage>',
  'grunt-mocha-bridge': '<required if using with grunt-mocha'
}
```
*/

define(['thehelp-test'], function(test) {
  /*jshint maxcomplexity: 9 */

  'use strict';

  // Because PhantomJS doesn't support function.bind we polyfill it
  // https://groups.google.com/forum/#!msg/phantomjs/r0hPOmnCUpc/uxusqsl2LNoJ
  // https://github.com/ariya/phantomjs/issues/10522
  Function.prototype.bind = Function.prototype.bind || function(target) {
    var _this = this;
    return function() {
      return _this.apply(target, arguments);
    };
  };

  // `setupMocha` prepares `mocha` for tests to be loaded. It must be run before
  // we run test-defining code. If we don't, `describe` and `it` will not yet be defined.
  test.mocha.setup('bdd');

  // Prepare and verify settings, put defaults in place.
  var thehelp = window.thehelp || {};
  var settings = thehelp.test || {};
  if (typeof settings.coverage === 'undefined') {
    settings.coverage = true;
  }
  if (typeof settings.blanket === 'undefined') {
    settings.blanket = {
      filter: '/src/',
      antifilter: '["/bower_components/", "node_modules", "/test/","/lib/"]'
    };
  }

  if (typeof settings.files === 'undefined') {
    throw new Error('Specify test files with an array at window.thehelp.test.files');
  }
  if (typeof settings.mochaCss === 'undefined') {
    throw new Error(
      'Provide the path to the mocha.css file window.thehelp.test.mochaCss'
    );
  }

  // `loadTests` actually pulls in your test files, then installs `window.runTests()`,
  // which adds the mocha div to your page and runs the tests.
  var loadTests = function loadTests(settings, mocha) {
    require(settings.files, function() {
      window.runTests = function() {
        if (!document.getElementById('mocha')) {
          //Doing this without jquery to reduce dependencies :0)
          var body = document.getElementsByTagName('body')[0];
          var div = document.createElement('div');
          div.setAttribute('id', 'mocha');
          body.appendChild(div);

          var head = document.getElementsByTagName('head')[0];
          var link = document.createElement('link');
          link.setAttribute('rel', 'stylesheet');
          link.setAttribute('href', settings.mochaCss);
          head.appendChild(link);
        }

        mocha.run();
        return true;
      };

      if (window.PHANTOMJS) {
        require(['grunt-mocha-bridge'], function() {
          mocha.run();
        });
      }
      else if (!settings.waitToRun) {
        window.runTests();
      }
    });
  };

  // Sets up code coverage if configured. No code coverage under phantomjs since we're not
  // using a grunt plugin that understands code coverage.
  if (settings.coverage && !window.PHANTOMJS) {
    require(['thehelp-test-coverage'], function(blanket) {

      if (settings.blanket) {
        //Doing this without lodash to reduce dependencies :0)
        var keys = Object.keys(settings.blanket);

        for (var i = 0, max = keys.length; i < max; i += 1) {
          var key = keys[i];
          blanket.options(key, settings.blanket[key]);
        }
      }

      loadTests(settings, test.mocha);
    });
  }
  else {
    loadTests(settings, test.mocha);
  }

});
<commit_msg>harness.js: Doc tweak<commit_after>/*
# harness
This file can be used to very quickly set up a mocha-based browser testing
environment, and is compatible with `grunt-mocha`. You'll just need to set the path
for three files in `requirejs`:

```
paths: {
  'thehelp-test': '<your path>',
  'thehelp-test-coverage': '<required for code coverage>',
  'grunt-mocha-bridge': '<required if using with grunt-mocha'
}
```
*/

define(['thehelp-test'], function(test) {
  /*jshint maxcomplexity: 9 */

  'use strict';

  // Because PhantomJS doesn't support function.bind we polyfill it
  // <https://groups.google.com/forum/#!msg/phantomjs/r0hPOmnCUpc/uxusqsl2LNoJ>
  // <https://github.com/ariya/phantomjs/issues/10522>
  Function.prototype.bind = Function.prototype.bind || function(target) {
    var _this = this;
    return function() {
      return _this.apply(target, arguments);
    };
  };

  // `setupMocha` prepares `mocha` for tests to be loaded. It must be run before
  // we run test-defining code. If we don't, `describe` and `it` will not yet be defined.
  test.mocha.setup('bdd');

  // Prepare and verify settings, put defaults in place.
  var thehelp = window.thehelp || {};
  var settings = thehelp.test || {};
  if (typeof settings.coverage === 'undefined') {
    settings.coverage = true;
  }
  if (typeof settings.blanket === 'undefined') {
    settings.blanket = {
      filter: '/src/',
      antifilter: '["/bower_components/", "node_modules", "/test/","/lib/"]'
    };
  }

  if (typeof settings.files === 'undefined') {
    throw new Error('Specify test files with an array at window.thehelp.test.files');
  }
  if (typeof settings.mochaCss === 'undefined') {
    throw new Error(
      'Provide the path to the mocha.css file window.thehelp.test.mochaCss'
    );
  }

  // `loadTests` actually pulls in your test files, then installs `window.runTests()`,
  // which adds the mocha div to your page and runs the tests.
  var loadTests = function loadTests(settings, mocha) {
    require(settings.files, function() {
      window.runTests = function() {
        if (!document.getElementById('mocha')) {
          //Doing this without jquery to reduce dependencies :0)
          var body = document.getElementsByTagName('body')[0];
          var div = document.createElement('div');
          div.setAttribute('id', 'mocha');
          body.appendChild(div);

          var head = document.getElementsByTagName('head')[0];
          var link = document.createElement('link');
          link.setAttribute('rel', 'stylesheet');
          link.setAttribute('href', settings.mochaCss);
          head.appendChild(link);
        }

        mocha.run();
        return true;
      };

      if (window.PHANTOMJS) {
        require(['grunt-mocha-bridge'], function() {
          mocha.run();
        });
      }
      else if (!settings.waitToRun) {
        window.runTests();
      }
    });
  };

  // Sets up code coverage if configured. No code coverage under phantomjs since we're not
  // using a grunt plugin that understands code coverage.
  if (settings.coverage && !window.PHANTOMJS) {
    require(['thehelp-test-coverage'], function(blanket) {

      if (settings.blanket) {
        //Doing this without lodash to reduce dependencies :0)
        var keys = Object.keys(settings.blanket);

        for (var i = 0, max = keys.length; i < max; i += 1) {
          var key = keys[i];
          blanket.options(key, settings.blanket[key]);
        }
      }

      loadTests(settings, test.mocha);
    });
  }
  else {
    loadTests(settings, test.mocha);
  }

});
<|endoftext|>


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

'use strict';

var concat = require('concat-stream')
  , prompt = require('cli-prompt')
  , uniq = require('uniq')
  , output = require('simple-output');

var spawn = require('child_process').spawn
  , util = require('util');

output.stdout = output.stderr;

(function (argv) {
  if (argv.length != 1) {
    output.info('Usage: ' + process.argv[1] + ' <name>');
    process.exit(1);
  }
  var procname = argv[0];

  spawn('pgrep', ['-x', procname], {
    stdio: 'pipe'
  }).stdout.pipe(concat({ encoding: 'string' }, function (pids) {
    pids = pids.trim().split(/\s+/).map(Number);

    if (10 <= pids.length) {
      output.error('More than 10 processes found. I can\'t handle it.');
      process.exit(1);
    }

    (function printPstrees(pids, index, cb) {
      if (index < pids.length) {
        spawn('pstree', [pids[index]], {
          stdio: 'pipe'
        }).stdout.pipe(concat({ encoding: 'string' }, function (tree) {
          util.puts(index + ') ' + tree.trim().replace(/\n/g, '\n   '));
          printPstrees(pids, index + 1, cb);
        }));
      }
      else {
        cb();
      }
    }(pids, 0, function () {

      prompt('kill: ', function (indices) {
        indices = uniq(indices.trim().split(''));

        (function killLoop() {
          if (indices.length) {
            spawn('kill', [pids[indices.shift()]]).on('exit', killLoop);
          }
        }());
      });
    }));
  }));
}(process.argv.slice(2)));<commit_msg>Split input by commas and spaces<commit_after>#!/usr/bin/env node

'use strict';

var concat = require('concat-stream')
  , prompt = require('cli-prompt')
  , uniq = require('uniq')
  , output = require('simple-output');

var spawn = require('child_process').spawn
  , util = require('util');

output.stdout = output.stderr;

(function (argv) {
  if (argv.length != 1) {
    output.info('Usage: ' + process.argv[1] + ' <name>');
    process.exit(1);
  }
  var procname = argv[0];

  spawn('pgrep', ['-x', procname], {
    stdio: 'pipe'
  }).stdout.pipe(concat({ encoding: 'string' }, function (pids) {
    pids = pids.trim().split(/\s+/).map(Number);

    (function printPstrees(pids, index, cb) {
      if (index < pids.length) {
        spawn('pstree', [pids[index]], {
          stdio: 'pipe'
        }).stdout.pipe(concat({ encoding: 'string' }, function (tree) {
          util.puts(index + ') ' + tree.trim().replace(/\n/g, '\n   '));
          printPstrees(pids, index + 1, cb);
        }));
      }
      else {
        cb();
      }
    }(pids, 0, function () {

      prompt('kill: ', function (indices) {
        // If there are no more than 10 matches, a string of digits is a perfectly valid input.
        // Otherwise, choices must be separated by commas or spaces.

        if (pids.length <= 10) {
          indices = indices.match(/\d/g);
        }
        else {
          indices = indices.replace(/,/g, ' ')
                           .replace(/[^\d\s]+/g, '')
                           .trim()
                           .split(/\s+/)
          // Mapping to Number will equate 1 and 01.
                           .map(Number);
        }

        indices = uniq(indices);

        (function killLoop() {
          if (indices.length) {
            spawn('kill', [pids[indices.shift()]]).on('exit', killLoop);
          }
        }());
      });
    }));
  }));
}(process.argv.slice(2)));<|endoftext|>


<commit_before>var shapetime = {};
var nodelete = false;

function stateUpdated() {
  // 'state' is an object of key-value pairs that map ids to JSON serialization of SVG elements
  // 'keys' is an array of all the keys in the state
  var state = wave.getState();
  var keys = state.getKeys();
  svgCanvas.each(function(e) {
    // 'this' is the SVG DOM element node (ellipse, rect, etc)
    // 'e' is an integer describing the position within the document
    var k = this.id;
    var v = state.get(k);
    if (v) {
      var ob = JSON.parse(v);
      if (ob) {
        // do nothing
      } else {
        //var node = document.getElementById(k);
        //if (node) node.parentNode.removeChild(node);
      }
      //keys.remove(k);

    } else if(this.id != "selectorParentGroup" && !nodelete){
      //console.log(this)

      this.parentNode.removeChild(this);
    }
  });

  // New nodes
  for (var k in keys) {
    var v = state.get(keys[k]);
    var ob = JSON.parse(v);
    if (ob){
      if(!shapetime[k] || ob.time > shapetime[k]){
        var a;
        if(a = document.getElementById(k)){
          var attrs = {};
          for(var i = a.length; i--;){
            attrs[a.item(i).nodeName] = a.item(i).nodeValue;
          }
          if(JSON.stringify(attrs) != JSON.stringify(ob.attr)){
            shapetime[k] = ob.time
            svgCanvas.updateElementFromJson(ob)
          }
        }else{
          shapetime[k] = ob.time
          svgCanvas.updateElementFromJson(ob)
        }

      }
    }
  }
}

function getId(canvas, objnum) {
  var id = wave.getViewer().getId().split("@")[0];
  var extra = SHA256(wave.getViewer().getId()); //in case the next step kills all the characters
  for(var i = 0, l = id.length, n = ""; i < l; i++){
    if("abcdefghijklmnopqrstuvwxyz0123456789".indexOf(id[i]) != -1){
      n+=i;
    }
  }
  return "svg_"+n+"_"+extra.substr(0,5)+"_"+objnum;
}

function main() {
  $(document).ready(function(){
    if (wave && wave.isInWaveContainer()) {
      wave.setStateCallback(stateUpdated);
    }

    var oldchanged = svgCanvas.bind("changed", function(canvas, elem){
      if(oldchanged)oldchanged.apply(this, [canvas,elem]);

      var delta = {}
      $.each(elem, function(){

        var attrs = {};
        var a = this.attributes;
        if(a){
          for(var i = a.length; i--;){
            attrs[a.item(i).nodeName] = a.item(i).nodeValue;
          }
          var ob = {element: this.nodeName, attr: attrs};

          ob.time = shapetime[this.id] = (new Date).getTime()
          delta[this.id] = JSON.stringify(ob);
        }
      })
      wave.getState().submitDelta(delta)
      //sendDelta(canvas, elem)
    });
    var oldselected = svgCanvas.bind("selected", function(canvas, elem){

      if(oldselected)oldselected.apply(this, [canvas,elem]);

      var delta = {}
      var deletions = 0;
      $.each(elem, function(){
        if(!this.parentNode){
          delta[this.id] = null;

          deletions ++
        }
      });
      if(deletions > 0){
        wave.getState().submitDelta(delta)
      }
    });
    svgCanvas.bind("cleared", function(){
      //alert("cleared")
        var state = {}, keys = wave.getState().getKeys()
        for(var i = 0; i < keys.length; i++){
          state[keys[i]] = null;
        }
        wave.getState().submitDelta(state)
    });
    svgCanvas.bind("getid", getId);
  })
}

gadgets.util.registerOnLoadHandler(main);

//and why not use my stuff?
function SHA256(b){function h(j,k){return(j>>e)+(k>>e)+((p=(j&o)+(k&o))>>e)<<e|p&o}function f(j,k){return j>>>k|j<<32-k}var g=[],d,c=3,l=[2],p,i,q,a,m=[],n=[];i=b.length*8;for(var e=16,o=65535,r="";c<312;c++){for(d=l.length;d--&&c%l[d]!=0;);d<0&&l.push(c)}b+="\u0080";for(c=0;c<=i;c+=8)n[c>>5]|=(b.charCodeAt(c/8)&255)<<24-c%32;n[(i+64>>9<<4)+15]=i;for(c=8;c--;)m[c]=parseInt(Math.pow(l[c],0.5).toString(e).substr(2,8),e);for(c=0;c<n.length;c+=e){a=m.slice(0);for(b=0;b<64;b++){g[b]=b<e?n[b+c]:h(h(h(f(g[b-2],17)^f(g[b-2],19)^g[b-2]>>>10,g[b-7]),f(g[b-15],7)^f(g[b-15],18)^g[b-15]>>>3),g[b-e]);i=h(h(h(h(a[7],f(a[4],6)^f(a[4],11)^f(a[4],25)),a[4]&a[5]^~a[4]&a[6]),parseInt(Math.pow(l[b],1/3).toString(e).substr(2,8),e)),g[b]);q=(f(a[0],2)^f(a[0],13)^f(a[0],22))+(a[0]&a[1]^a[0]&a[2]^a[1]&a[2]);for(d=8;--d;)a[d]=d==4?h(a[3],i):a[d-1];a[0]=h(i,q)}for(d=8;d--;)m[d]+=a[d]}for(c=0;c<8;c++)for(b=8;b--;)r+=(m[c]>>>b*4&15).toString(e);return r}

<commit_msg>SVG edit wave should work now (hopefully)<commit_after>var shapetime = {};
var nodelete = false;

function stateUpdated() {

  // 'state' is an object of key-value pairs that map ids to JSON serialization of SVG elements
  // 'keys' is an array of all the keys in the state
  var state = wave.getState();
  var keys = state.getKeys();
  svgCanvas.each(function(e) {
    // 'this' is the SVG DOM element node (ellipse, rect, etc)
    // 'e' is an integer describing the position within the document
    var k = this.id;
    var v = state.get(k);
    if(k == "selectorParentGroup" || k == "svgcontent"){
      //meh
    }else if (v) {
      var ob = JSON.parse(v);
      if (ob) {
        // do nothing
      } else {
        //var node = document.getElementById(k);
        //if (node) node.parentNode.removeChild(node);
      }
      //keys.remove(k);

    } else if(!nodelete){

      this.parentNode.removeChild(this);
    }
  });

  // New nodes
  for (var k in keys) {
    var v = state.get(keys[k]);
    var ob = JSON.parse(v);
    if (ob){
      if(!shapetime[k] || ob.time > shapetime[k]){
        var a;
        if(a = document.getElementById(k)){
          var attrs = get_attrs(a);
          if(JSON.stringify(attrs) != JSON.stringify(ob.attr)){
            shapetime[k] = ob.time
            svgCanvas.updateElementFromJson(ob)
          }
        }else{
          shapetime[k] = ob.time
          svgCanvas.updateElementFromJson(ob)
        }

      }
    }
  }
}

function getId(canvas, objnum) {
  var id = wave.getViewer().getId().split("@")[0];
  var extra = SHA256(wave.getViewer().getId()); //in case the next step kills all the characters
  for(var i = 0, l = id.length, n = ""; i < l; i++){
    if("abcdefghijklmnopqrstuvwxyz0123456789".indexOf(id[i]) != -1){
      n+=id[i];
    }
  }
  return "svg_"+n+"_"+extra.substr(0,5)+"_"+objnum;
}

function get_attrs(a){
  var attrs = {};
    for(var i = a.length; i--;){
      var attr = a.item(i).nodeName;
      if(",style,".indexOf(","+attr+",") == -1){
        attrs[attr] = a.item(i).nodeValue;
      }
    }
    return attrs
}

function main() {
  $(document).ready(function(){
    if (wave && wave.isInWaveContainer()) {
      wave.setStateCallback(function(){setTimeout(stateUpdated,10)});
    }

    var oldchanged = svgCanvas.bind("changed", function(canvas, elem){
      if(oldchanged)oldchanged.apply(this, [canvas,elem]);

      var delta = {}
      $.each(elem, function(){

        var attrs = {};
        var a = this.attributes;
        if(a){
          var attrs = get_attrs(a)
          var ob = {element: this.nodeName, attr: attrs};

          ob.time = shapetime[this.id] = (new Date).getTime()
          delta[this.id] = JSON.stringify(ob);
        }
      })

      wave.getState().submitDelta(delta)
      //sendDelta(canvas, elem)

    });
    //*

    var oldselected = svgCanvas.bind("selected", function(canvas, elem){

      if(oldselected)oldselected.apply(this, [canvas,elem]);

      var delta = {}
      var deletions = 0;
      $.each(elem, function(){
        if(!this.parentNode && this != window){
          delta[this.id] = null;
          deletions ++
        }
      });
      if(deletions > 0){
        wave.getState().submitDelta(delta)
      }
    });
    ///
    svgCanvas.bind("cleared", function(){
      //alert("cleared")
        var state = {}, keys = wave.getState().getKeys()
        for(var i = 0; i < keys.length; i++){
          state[keys[i]] = null;
        }
        wave.getState().submitDelta(state)
    });
    //*/
    svgCanvas.bind("getid", getId);
  })
}

window.wave={
_state: {},
callback: function(){},
state: {
get: function(r){return wave._state[r]},
set: function(r,v){wave._state[r]=v},
getKeys: function(){var a=[];for(var i in wave._state)a.push(i);return a},
submitDelta: function(d){for(var i in d)wave.state.set(i,d[i]);wave.callback()}
},
viewer: {
id: "local@example.com",
getId: function(){return wave.viewer.id}
},
getState:function(){return wave.state},
getViewer:function(){return wave.viewer},
isInWaveContainer:function(){return true},
setStateCallback:function(c){wave.callback=c}
}

if(window.gadgets) gadgets.util.registerOnLoadHandler(main);

$(main)

//and why not use my stuff?
function SHA256(b){function h(j,k){return(j>>e)+(k>>e)+((p=(j&o)+(k&o))>>e)<<e|p&o}function f(j,k){return j>>>k|j<<32-k}var g=[],d,c=3,l=[2],p,i,q,a,m=[],n=[];i=b.length*8;for(var e=16,o=65535,r="";c<312;c++){for(d=l.length;d--&&c%l[d]!=0;);d<0&&l.push(c)}b+="\u0080";for(c=0;c<=i;c+=8)n[c>>5]|=(b.charCodeAt(c/8)&255)<<24-c%32;n[(i+64>>9<<4)+15]=i;for(c=8;c--;)m[c]=parseInt(Math.pow(l[c],0.5).toString(e).substr(2,8),e);for(c=0;c<n.length;c+=e){a=m.slice(0);for(b=0;b<64;b++){g[b]=b<e?n[b+c]:h(h(h(f(g[b-2],17)^f(g[b-2],19)^g[b-2]>>>10,g[b-7]),f(g[b-15],7)^f(g[b-15],18)^g[b-15]>>>3),g[b-e]);i=h(h(h(h(a[7],f(a[4],6)^f(a[4],11)^f(a[4],25)),a[4]&a[5]^~a[4]&a[6]),parseInt(Math.pow(l[b],1/3).toString(e).substr(2,8),e)),g[b]);q=(f(a[0],2)^f(a[0],13)^f(a[0],22))+(a[0]&a[1]^a[0]&a[2]^a[1]&a[2]);for(d=8;--d;)a[d]=d==4?h(a[3],i):a[d-1];a[0]=h(i,q)}for(d=8;d--;)m[d]+=a[d]}for(c=0;c<8;c++)for(b=8;b--;)r+=(m[c]>>>b*4&15).toString(e);return r}

<|endoftext|>