<commit_before>
import * as types from '../constants/ActionTypes';
import * as values from '../constants/DefaultValues';

import { push } from 'react-router-redux';
import fetch from 'isomorphic-fetch';
import Config from '../config';
import Mixins from '../mixins/global';
import { setSubject } from './subject';

export function setSurveyID(data) {
    return {
        type: types.SET_SURVEYID,
        surveyID: data
    };
}

export function finishEdit() {
    return (dispatch) => {
        dispatch(setSurveyID(''));
        dispatch(setSubject(''));
        dispatch({ type: types.INIT_QUESTIONS });
        dispatch({ type: types.INIT_SURVEY_POLICY });
        dispatch(push('/'));
    };
}

export function addQuestion(page, data) {
    return (dispatch, getState) => {
        const pageIdx = page - 1;
        const newQuestions = [...getState().questions];
        // if this page already existed, edit this page content
        // object and array need copy reference
        const pageData = Object.assign({}, newQuestions[pageIdx]);
        pageData.question = [...pageData.question];
        pageData.question.push(data);
        newQuestions[pageIdx] = pageData;

        dispatch({
            type: types.ADD_QUESTION,
            questions: newQuestions
        });
    };
}

export function updateQuestionItem() {
    return (dispatch, getState) => {
        const { questions, editQuestion } = getState();
        const newQuestions = [];
        for (const obj of questions) {
            const newPages = Object.assign({}, obj);
            newPages.question = [];
            for (const que of obj.question) {
                let newItems = Object.assign({}, que);
                if (que.id === editQuestion.id) {
                    newItems = Object.assign(newItems, editQuestion);
                    if (!editQuestion.hasOwnProperty('input')) {
                        delete newItems.input;
                    }
                }
                newPages.question.push(newItems);
            }
            newQuestions.push(newPages);
        }

        dispatch({
            type: types.EDIT_QUESTION,
            questions: newQuestions
        });
    };
}

export function copyQuestion(page, queId) {
    return (dispatch, getState) => {
        const { questions } = getState();
        const pageIdx = page - 1;
        const newQuestions = [...questions];
        const duplicateQue = Object.assign({}, newQuestions[pageIdx].question[queId],
            { id: Mixins.generateQuestionID() });
        newQuestions[pageIdx] = Object.assign({}, questions[pageIdx]);
        newQuestions[pageIdx].question = [...questions[pageIdx].question];
        newQuestions[pageIdx].question.splice(queId, 0, duplicateQue);

        dispatch({
            type: types.COPY_QUESTION,
            questions: newQuestions
        });
    };
}

export function deleteQuestion(page, queId) {
    return (dispatch, getState) => {
        const { questions } = getState();
        const pageIdx = page - 1;
        const newQuestions = [...questions];
        newQuestions[pageIdx] = Object.assign({}, questions[pageIdx]);
        newQuestions[pageIdx].question = [...questions[pageIdx].question];
        newQuestions[pageIdx].question.splice(queId, 1);

        dispatch({
            type: types.DELETE_QUESTION,
            questions: newQuestions
        });
    };
}

export function exchangeQuestion(bfPage, bfIdx, afPage, afIdx, data) {
    return (dispatch, getState) => {
        const { questions } = getState();
        const newQuestions = [];
        if (bfPage !== afPage) {
            for (const obj of questions) {
                const newPages = Object.assign({}, obj);
                newPages.question = [...obj.question];
                if (obj.page === bfPage) {
                    newPages.question.splice(bfIdx, 1);
                } else if (obj.page === afPage) {
                    newPages.question.splice(afIdx, 0, data);
                }
                newQuestions.push(newPages);
            }
        } else {
            for (const obj of questions) {
                const newPages = Object.assign({}, obj);
                newPages.question = [...obj.question];
                if (obj.page === afPage) {
                    newPages.question.splice(bfIdx, 1);
                    newPages.question.splice(afIdx, 0, data);
                }
                newQuestions.push(newPages);
            }
        }

        dispatch({
            type: types.EXCHANGE_QUESTION,
            questions: newQuestions
        });
    };
}

export function addPage(page) {
    const newPage = {
        page: page,
        description: values.PAGE_TITLE,
        question: []
    };

    return {
        type: types.ADD_PAGE,
        page: newPage
    };
}

export function copyPage(pageId) {
    return (dispatch, getState) => {
        const newQuestions = [...getState().questions];
        const originPage = newQuestions[pageId - 1];
        const duplicateQues = [];
        for (const que of originPage.question) {
            // regenerate question id
            duplicateQues.push(Object.assign({}, que, { id: Mixins.generateQuestionID() }));
        }
        newQuestions.splice(pageId, 0, Object.assign({}, originPage, { question: duplicateQues }));
        newQuestions.forEach((page, idx) => {
            Object.assign(page, { page: idx + 1 });
        });

        dispatch({
            type: types.COPY_PAGE,
            questions: newQuestions
        });
    };
}

export function editPageTitle() {
    return (dispatch, getState) => {
        const { page, description } = getState().editPage;
        const newQuestions = [...getState().questions];
        newQuestions[page - 1] = Object.assign({}, newQuestions[page - 1],
            { description: description });

        dispatch({
            type: types.EDIT_PAGE_TITLE,
            questions: newQuestions
        });
    };
}

export function deletePage(pageId) {
    return (dispatch, getState) => {
        const newQuestions = [...getState().questions];
        newQuestions.splice(pageId - 1, 1);
        newQuestions.forEach((page, idx) => {
            Object.assign(page, { page: idx + 1 });
        });

        dispatch({
            type: types.DELETE_PAGE,
            questions: newQuestions
        });
    };
}

export function exchangePage() {
    return (dispatch, getState) => {
        const { questions, orderPage } = getState();
        const newQuestions = [];
        orderPage.forEach((pageNum, idx) => {
            const page = Object.assign({}, questions[pageNum - 1]);
            page.page = idx + 1;
            newQuestions.push(page);
        });

        dispatch({
            type: types.EXCHANGE_PAGE,
            questions: newQuestions
        });
    };
}

function saveQuestionsSuccess() {
    return {
        type: types.SAVE_QUESTIONS_SUCCESS
    };
}

function saveQuestionsFailure(err) {
    return {
        type: types.SAVE_QUESTIONS_FAILURE,
        errorMsg: err
    };
}

export function saveQuestion() {
    return (dispatch, getState) => {
        const { account, surveyID, subject, questions, surveyPolicy, token } = getState();
        const postData = {
            subject: subject,
            survey: { content: [...questions], thankyou: surveyPolicy }
        };

        return fetch(`${Config.baseURL}/api/v1/mgnt/surveys/${account.accountid}/${surveyID}`, {
            method: 'PUT',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/json',
                authorization: token
            },
            body: JSON.stringify(postData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.datetime) {
                dispatch(saveQuestionsSuccess());
            } else {
                dispatch(saveQuestionsFailure(data));
            }
        })
        .catch(err => saveQuestionsFailure(err.responseJSON));
    };
}

function setSurveyPolicy(data) {
    return {
        type: types.SET_SURVEY_POLICY,
        surveyPolicy: data
    };
}

export function editSurveyPolicy(flag) {
    const data = Object.assign({},
        {
            description: 'Thanks for sharing your feedback with Trend Micro.',
            privacy: {}
        });

    if (flag) {
        const label = 'If Trend Micro has a follow-up survey on the Email Scan,'
            + ' would you like to participate?';
        const privacy = {
            label: label,
            terms: 'Yes, Trend Micro can reach me at this address: ',
            input: 'Please enter your email address.'
        };
        data.privacy = privacy;
    }

    return (dispatch) => {
        dispatch(setSurveyPolicy(data));
        return dispatch(saveQuestion());
    };
}

function receiveQuestionsSuccess(data) {
    return {
        type: types.RECIEVE_QUESTIONS_SUCCESS,
        questions: data
    };
}

function receiveQuestionsFailure(err) {
    return {
        type: types.RECIEVE_QUESTIONS_FAILURE,
        errorMsg: err
    };
}

export function getQuestion(surveyID) {
    return (dispatch, getState) => {
        const { account } = getState();

        // TODOS: temporarily
        // const dt = new Date(window.localStorage[surveyID]).toGMTString();
        const dt = new Date().toGMTString();
        return fetch(`${Config.baseURL}/api/v1/surveys/${account.accountid}/${surveyID}`, {
            method: 'GET',
            credentials: 'same-origin',
            headers: {
                'If-Modified-Since': dt
            }
        })
        .then(response => {
            console.log(response.status);
            return response.json();
        })
        .then(data => {
            if (data.surveyid) {
                // console.log(data.datetime);
                // window.localStorage[surveyID] = data.datetime;
                dispatch(setSurveyID(data.surveyid));
                dispatch(setSubject(data.subject));
                dispatch(receiveQuestionsSuccess(data.survey.content));
                dispatch(setSurveyPolicy(data.survey.thankyou));
                dispatch(push('/create'));
            } else {
                dispatch(receiveQuestionsFailure(data));
            }
        })
        .catch(err => receiveQuestionsFailure(err.responseJSON));
    };
}
<commit_msg>Change timestamp<commit_after>
import * as types from '../constants/ActionTypes';
import * as values from '../constants/DefaultValues';

import { push } from 'react-router-redux';
import fetch from 'isomorphic-fetch';
import Config from '../config';
import Mixins from '../mixins/global';
import { setSubject } from './subject';

export function setSurveyID(data) {
    return {
        type: types.SET_SURVEYID,
        surveyID: data
    };
}

export function finishEdit() {
    return (dispatch) => {
        dispatch(setSurveyID(''));
        dispatch(setSubject(''));
        dispatch({ type: types.INIT_QUESTIONS });
        dispatch({ type: types.INIT_SURVEY_POLICY });
        dispatch(push('/'));
    };
}

export function addQuestion(page, data) {
    return (dispatch, getState) => {
        const pageIdx = page - 1;
        const newQuestions = [...getState().questions];
        // if this page already existed, edit this page content
        // object and array need copy reference
        const pageData = Object.assign({}, newQuestions[pageIdx]);
        pageData.question = [...pageData.question];
        pageData.question.push(data);
        newQuestions[pageIdx] = pageData;

        dispatch({
            type: types.ADD_QUESTION,
            questions: newQuestions
        });
    };
}

export function updateQuestionItem() {
    return (dispatch, getState) => {
        const { questions, editQuestion } = getState();
        const newQuestions = [];
        for (const obj of questions) {
            const newPages = Object.assign({}, obj);
            newPages.question = [];
            for (const que of obj.question) {
                let newItems = Object.assign({}, que);
                if (que.id === editQuestion.id) {
                    newItems = Object.assign(newItems, editQuestion);
                    if (!editQuestion.hasOwnProperty('input')) {
                        delete newItems.input;
                    }
                }
                newPages.question.push(newItems);
            }
            newQuestions.push(newPages);
        }

        dispatch({
            type: types.EDIT_QUESTION,
            questions: newQuestions
        });
    };
}

export function copyQuestion(page, queId) {
    return (dispatch, getState) => {
        const { questions } = getState();
        const pageIdx = page - 1;
        const newQuestions = [...questions];
        const duplicateQue = Object.assign({}, newQuestions[pageIdx].question[queId],
            { id: Mixins.generateQuestionID() });
        newQuestions[pageIdx] = Object.assign({}, questions[pageIdx]);
        newQuestions[pageIdx].question = [...questions[pageIdx].question];
        newQuestions[pageIdx].question.splice(queId, 0, duplicateQue);

        dispatch({
            type: types.COPY_QUESTION,
            questions: newQuestions
        });
    };
}

export function deleteQuestion(page, queId) {
    return (dispatch, getState) => {
        const { questions } = getState();
        const pageIdx = page - 1;
        const newQuestions = [...questions];
        newQuestions[pageIdx] = Object.assign({}, questions[pageIdx]);
        newQuestions[pageIdx].question = [...questions[pageIdx].question];
        newQuestions[pageIdx].question.splice(queId, 1);

        dispatch({
            type: types.DELETE_QUESTION,
            questions: newQuestions
        });
    };
}

export function exchangeQuestion(bfPage, bfIdx, afPage, afIdx, data) {
    return (dispatch, getState) => {
        const { questions } = getState();
        const newQuestions = [];
        if (bfPage !== afPage) {
            for (const obj of questions) {
                const newPages = Object.assign({}, obj);
                newPages.question = [...obj.question];
                if (obj.page === bfPage) {
                    newPages.question.splice(bfIdx, 1);
                } else if (obj.page === afPage) {
                    newPages.question.splice(afIdx, 0, data);
                }
                newQuestions.push(newPages);
            }
        } else {
            for (const obj of questions) {
                const newPages = Object.assign({}, obj);
                newPages.question = [...obj.question];
                if (obj.page === afPage) {
                    newPages.question.splice(bfIdx, 1);
                    newPages.question.splice(afIdx, 0, data);
                }
                newQuestions.push(newPages);
            }
        }

        dispatch({
            type: types.EXCHANGE_QUESTION,
            questions: newQuestions
        });
    };
}

export function addPage(page) {
    const newPage = {
        page: page,
        description: values.PAGE_TITLE,
        question: []
    };

    return {
        type: types.ADD_PAGE,
        page: newPage
    };
}

export function copyPage(pageId) {
    return (dispatch, getState) => {
        const newQuestions = [...getState().questions];
        const originPage = newQuestions[pageId - 1];
        const duplicateQues = [];
        for (const que of originPage.question) {
            // regenerate question id
            duplicateQues.push(Object.assign({}, que, { id: Mixins.generateQuestionID() }));
        }
        newQuestions.splice(pageId, 0, Object.assign({}, originPage, { question: duplicateQues }));
        newQuestions.forEach((page, idx) => {
            Object.assign(page, { page: idx + 1 });
        });

        dispatch({
            type: types.COPY_PAGE,
            questions: newQuestions
        });
    };
}

export function editPageTitle() {
    return (dispatch, getState) => {
        const { page, description } = getState().editPage;
        const newQuestions = [...getState().questions];
        newQuestions[page - 1] = Object.assign({}, newQuestions[page - 1],
            { description: description });

        dispatch({
            type: types.EDIT_PAGE_TITLE,
            questions: newQuestions
        });
    };
}

export function deletePage(pageId) {
    return (dispatch, getState) => {
        const newQuestions = [...getState().questions];
        newQuestions.splice(pageId - 1, 1);
        newQuestions.forEach((page, idx) => {
            Object.assign(page, { page: idx + 1 });
        });

        dispatch({
            type: types.DELETE_PAGE,
            questions: newQuestions
        });
    };
}

export function exchangePage() {
    return (dispatch, getState) => {
        const { questions, orderPage } = getState();
        const newQuestions = [];
        orderPage.forEach((pageNum, idx) => {
            const page = Object.assign({}, questions[pageNum - 1]);
            page.page = idx + 1;
            newQuestions.push(page);
        });

        dispatch({
            type: types.EXCHANGE_PAGE,
            questions: newQuestions
        });
    };
}

function saveQuestionsSuccess() {
    return {
        type: types.SAVE_QUESTIONS_SUCCESS
    };
}

function saveQuestionsFailure(err) {
    return {
        type: types.SAVE_QUESTIONS_FAILURE,
        errorMsg: err
    };
}

export function saveQuestion() {
    return (dispatch, getState) => {
        const { account, surveyID, subject, questions, surveyPolicy, token } = getState();
        const postData = {
            subject: subject,
            survey: { content: [...questions], thankyou: surveyPolicy }
        };

        return fetch(`${Config.baseURL}/api/v1/mgnt/surveys/${account.accountid}/${surveyID}`, {
            method: 'PUT',
            credentials: 'same-origin',
            headers: {
                'Content-Type': 'application/json',
                authorization: token
            },
            body: JSON.stringify(postData)
        })
        .then(response => response.json())
        .then(data => {
            if (data.datetime) {
                dispatch(saveQuestionsSuccess());
            } else {
                dispatch(saveQuestionsFailure(data));
            }
        })
        .catch(err => saveQuestionsFailure(err.responseJSON));
    };
}

function setSurveyPolicy(data) {
    return {
        type: types.SET_SURVEY_POLICY,
        surveyPolicy: data
    };
}

export function editSurveyPolicy(flag) {
    const data = Object.assign({},
        {
            description: 'Thanks for sharing your feedback with Trend Micro.',
            privacy: {}
        });

    if (flag) {
        const label = 'If Trend Micro has a follow-up survey on the Email Scan,'
            + ' would you like to participate?';
        const privacy = {
            label: label,
            terms: 'Yes, Trend Micro can reach me at this address: ',
            input: 'Please enter your email address.'
        };
        data.privacy = privacy;
    }

    return (dispatch) => {
        dispatch(setSurveyPolicy(data));
        return dispatch(saveQuestion());
    };
}

function receiveQuestionsSuccess(data) {
    return {
        type: types.RECIEVE_QUESTIONS_SUCCESS,
        questions: data
    };
}

function receiveQuestionsFailure(err) {
    return {
        type: types.RECIEVE_QUESTIONS_FAILURE,
        errorMsg: err
    };
}

export function getQuestion(surveyID) {
    return (dispatch, getState) => {
        const { account } = getState();

        // TODOS: temporarily
        // const dt = new Date(window.localStorage[surveyID]).toGMTString();
        const dt = new Date().getTime();
        return fetch(`${Config.baseURL}/api/v1/surveys/${account.accountid}/${surveyID}`, {
            method: 'GET',
            credentials: 'same-origin',
            headers: {
                'If-Modified-Since': dt
            }
        })
        .then(response => {
            console.log(response.status);
            return response.json();
        })
        .then(data => {
            if (data.surveyid) {
                // console.log(data.datetime);
                // window.localStorage[surveyID] = data.datetime;
                dispatch(setSurveyID(data.surveyid));
                dispatch(setSubject(data.subject));
                dispatch(receiveQuestionsSuccess(data.survey.content));
                dispatch(setSurveyPolicy(data.survey.thankyou));
                dispatch(push('/create'));
            } else {
                dispatch(receiveQuestionsFailure(data));
            }
        })
        .catch(err => receiveQuestionsFailure(err.responseJSON));
    };
}
<|endoftext|>


<commit_before>
function DropdownCtrl($scope, $http, Data) {
    $scope.data = Data;

    $scope.indices = [];
    $scope.types = [];

    var path = $scope.data.host + "/_mapping";
    $http.get(path).then(function(response){
        $scope.data.mapping = response.data;

        for (i in response.data){

            //set the currentIndex to the first index we encounter
            //if ($scope.data.currentIndex === "")
            //    $scope.data.currentIndex = i;

            $scope.indices.push(i)
            $scope.types[i] = [];
            for (j in response.data[i]){
                //set the currentType to the first type we encounter
                //if ($scope.data.currentType === "")
                //    $scope.data.currentType = j;

                $scope.types[i].push(j);
            }
        }
    });
}
<commit_msg>Add Alias support<commit_after>
function DropdownCtrl($scope, $http, Data) {
    $scope.data = Data;

    $scope.indices = [];
    $scope.types = [];

    var path = $scope.data.host + "/_mapping";
    $http.get(path).then(function(response){
        $scope.data.mapping = response.data;

        for (i in response.data){

            $scope.indices.push(i)
            $scope.types[i] = [];
            for (j in response.data[i]){

                $scope.types[i].push(j);
            }
        }

        path = $scope.data.host + "/_aliases";
        $http.get(path).then(function(response){

          for (i in response.data){
            for (j in response.data[i].aliases) {
              $scope.indices.push(j);
              $scope.types[j] = $scope.types[i];
              $scope.data.mapping[j] = $scope.data.mapping[i];
            }
          }
        });
    });

}
<|endoftext|>


<commit_before>/* HostsController
 * Displays details for a specific host
 */
(function(){
    "use strict";

    controlplane.controller("HostsController", ["$scope", "$routeParams", "$location",
        "$filter", "resourcesFactory", "authService", "$modalService",
        "$interval", "$timeout", "$translate", "$notification", "miscUtils", "hostsFactory",
        "poolsFactory", "servicesFactory", "areUIReady",
    function($scope, $routeParams, $location, $filter, resourcesFactory,
    authService, $modalService, $interval, $timeout, $translate, $notification,
    utils, hostsFactory, poolsFactory, servicesFactory, areUIReady){
        // Ensure logged in
        authService.checkLogin($scope);

        $scope.indent = utils.indentClass;

        $scope.resetNewHost = function(){
            $scope.newHost = {
                port: $translate.instant('placeholder_port')
            };
            if ($scope.pools && $scope.pools.length > 0){
                $scope.newHost.PoolID = $scope.pools[0].id;
            }
        };

        $scope.modalAddHost = function() {
            areUIReady.lock();
            $scope.resetNewHost();
            $modalService.create({
                templateUrl: "add-host.html",
                model: $scope,
                title: "add_host",
                actions: [
                    {
                        role: "cancel",
                    },{
                        role: "ok",
                        label: "Next",
                        icon: "glyphicon-chevron-right",
                        action: function(){
                            if(this.validate()){
                                // disable ok button, and store the re-enable function
                                var enableSubmit = this.disableSubmitButton();
                                if ($scope.newHost.RAMLimit === undefined || $scope.newHost.RAMLimit === '') {
                                    $scope.newHost.RAMLimit = "100%";
                                }

                                $scope.newHost.IPAddr = $scope.newHost.host + ':' + $scope.newHost.port;

                                resourcesFactory.addHost($scope.newHost)
                                    .success(function(data, status){
                                        $scope.modal_displayHostKeys(data.PrivateKey, $scope.newHost.host, data.Detail);
                                        update();
                                    }.bind(this))
                                    .error(function(data, status){
                                        // TODO - form error highlighting
                                        this.createNotification("", data.Detail).error();
                                        // reenable button
                                        enableSubmit();
                                    }.bind(this));
                            }
                        }
                    }
                ],
                validate: function(){
                    var err = utils.validateHostName($scope.newHost.host, $translate) ||
                        utils.validatePortNumber($scope.newHost.port, $translate) ||
                        utils.validateRAMLimit($scope.newHost.RAMLimit);
                    if(err){
                        this.createNotification("Error", err).error();
                        return false;
                    }
                    return true;
                },
                onShow: () => {
                    areUIReady.unlock();
                }
            });
        };

        $scope.modal_displayHostKeys = function(keys, name, message) {
            let model = $scope.$new(true);
            model.keys = keys;
            model.name = name;

            $modalService.create({
                templateUrl: "display-host-keys.html",
                model: model,
                title: "Host Keys",
                actions: [
                    {
                        label: "Download Keys",
                        action: function(){
                            utils.downloadText(name + ".keys", keys);
                        },
                        icon: "glyphicon-download"
                    },{
                        role: "ok"
                    }
                ],
                onShow: function(){
                    if(message){
                        this.createNotification("", message).success();
                    }

                    // TODO - dont touch the DOM!
                    let keysWrapEl = this.$el.find(".keys-wrap"),
                        keysEl = keysWrapEl.find(".keys");
                    keysWrapEl.on("click", e => {
                        // TODO - if already selected, this deselects
                        keysEl.select();
                        try {
                            let success = document.execCommand('copy');
                            if(success){
                                this.createNotification("", "Keys copied to clipboard").info();
                            } else {
                                this.createNotification("", "Press Ctrl+C or Cmd+C to copy keys").info();
                            }
                        } catch(e) {
                            this.createNotification("", "Press Ctrl+C or Cmd+C to copy keys").info();
                        }
                    });
                }
            });
        };

        $scope.remove_host = function(hostId) {
            $modalService.create({
                template: $translate.instant("confirm_remove_host") + " "+ hostsFactory.get(hostId).name +"",
                model: $scope,
                title: "remove_host",
                actions: [
                    {
                        role: "cancel"
                    },{
                        role: "ok",
                        label: "remove_host",
                        classes: "btn-danger",
                        action: function(){

                            resourcesFactory.removeHost(hostId)
                                .success(function(data, status) {
                                    $notification.create("Removed host", hostId).success();
                                    // After removing, refresh our list
                                    update();
                                    this.close();
                                }.bind(this))
                                .error(function(data, status){
                                    $notification.create("Removing host failed", data.Detail).error();
                                    this.close();
                                }.bind(this));
                        }
                    }
                ]
            });
        };

        $scope.clickHost = function(hostId) {
            resourcesFactory.routeToHost(hostId);
        };

        $scope.clickPool = function(poolID) {
            resourcesFactory.routeToPool(poolID);
        };

        function update(){
            hostsFactory.update()
                .then(() => {
                    $scope.hosts = hostsFactory.hostList;
                }, () => {
                    // wait a sec and try again
                    $timeout(update, 1000);
                });

            poolsFactory.update()
                .then(() => {
                    $scope.pools = poolsFactory.poolList;
                    $scope.resetNewHost();
                }, () => {
                    // wait a sec and try again
                    $timeout(update, 1000);
                });
        }

        function init(){
            $scope.name = "hosts";
            $scope.params = $routeParams;

            $scope.breadcrumbs = [
                { label: 'breadcrumb_hosts', itemClass: 'active' }
            ];

            $scope.hostsTable = {
                sorting: {
                    name: "asc"
                },
                watchExpression: function(){
                    return hostsFactory.lastUpdate;
                }
            };

            $scope.dropped = [];

            // update hosts
            update();

            servicesFactory.activate();
            hostsFactory.activate();
            poolsFactory.activate();
        }

        init();

        $scope.$on("$destroy", function(){
            hostsFactory.deactivate();
            servicesFactory.deactivate();
            poolsFactory.deactivate();
        });
    }]);
})();
<commit_msg>avoid yucko linter error<commit_after>/* HostsController
 * Displays details for a specific host
 */
(function(){
    "use strict";

    controlplane.controller("HostsController", ["$scope", "$routeParams", "$location",
        "$filter", "resourcesFactory", "authService", "$modalService",
        "$interval", "$timeout", "$translate", "$notification", "miscUtils", "hostsFactory",
        "poolsFactory", "servicesFactory", "areUIReady",
    function($scope, $routeParams, $location, $filter, resourcesFactory,
    authService, $modalService, $interval, $timeout, $translate, $notification,
    utils, hostsFactory, poolsFactory, servicesFactory, areUIReady){
        // Ensure logged in
        authService.checkLogin($scope);

        $scope.indent = utils.indentClass;

        $scope.resetNewHost = function(){
            $scope.newHost = {
                port: $translate.instant('placeholder_port')
            };
            if ($scope.pools && $scope.pools.length > 0){
                $scope.newHost.PoolID = $scope.pools[0].id;
            }
        };

        $scope.modalAddHost = function() {
            areUIReady.lock();
            $scope.resetNewHost();
            $modalService.create({
                templateUrl: "add-host.html",
                model: $scope,
                title: "add_host",
                actions: [
                    {
                        role: "cancel",
                    },{
                        role: "ok",
                        label: "Next",
                        icon: "glyphicon-chevron-right",
                        action: function(){
                            if(this.validate()){
                                // disable ok button, and store the re-enable function
                                var enableSubmit = this.disableSubmitButton();
                                if ($scope.newHost.RAMLimit === undefined || $scope.newHost.RAMLimit === '') {
                                    $scope.newHost.RAMLimit = "100%";
                                }

                                $scope.newHost.IPAddr = $scope.newHost.host + ':' + $scope.newHost.port;

                                resourcesFactory.addHost($scope.newHost)
                                    .success(function(data, status){
                                        $scope.modal_displayHostKeys(data.PrivateKey, $scope.newHost.host, data.Detail);
                                        update();
                                    }.bind(this))
                                    .error(function(data, status){
                                        // TODO - form error highlighting
                                        this.createNotification("", data.Detail).error();
                                        // reenable button
                                        enableSubmit();
                                    }.bind(this));
                            }
                        }
                    }
                ],
                validate: function(){
                    var err = utils.validateHostName($scope.newHost.host, $translate) ||
                        utils.validatePortNumber($scope.newHost.port, $translate) ||
                        utils.validateRAMLimit($scope.newHost.RAMLimit);
                    if(err){
                        this.createNotification("Error", err).error();
                        return false;
                    }
                    return true;
                },
                onShow: () => {
                    areUIReady.unlock();
                }
            });
        };

        $scope.modal_displayHostKeys = function(keys, name, message) {
            let model = $scope.$new(true);
            model.keys = keys;
            model.name = name;

            $modalService.create({
                templateUrl: "display-host-keys.html",
                model: model,
                title: "Host Keys",
                actions: [
                    {
                        label: "Download Keys",
                        action: function(){
                            utils.downloadText(name + ".keys", keys);
                        },
                        icon: "glyphicon-download"
                    },{
                        role: "ok"
                    }
                ],
                onShow: function(){
                    if(message){
                        this.createNotification("", message).success();
                    }

                    // TODO - dont touch the DOM!
                    let keysWrapEl = this.$el.find(".keys-wrap"),
                        keysEl = keysWrapEl.find(".keys");
                    keysWrapEl.on("click", e => {
                        // TODO - if already selected, this deselects
                        keysEl.select();
                        try {
                            let success = document.execCommand('copy');
                            if(success){
                                this.createNotification("", "Keys copied to clipboard").info();
                            } else {
                                this.createNotification("", "Press Ctrl+C or Cmd+C to copy keys").info();
                            }
                        } catch(err) {
                            this.createNotification("", "Press Ctrl+C or Cmd+C to copy keys").info();
                        }
                    });
                }
            });
        };

        $scope.remove_host = function(hostId) {
            $modalService.create({
                template: $translate.instant("confirm_remove_host") + " "+ hostsFactory.get(hostId).name +"",
                model: $scope,
                title: "remove_host",
                actions: [
                    {
                        role: "cancel"
                    },{
                        role: "ok",
                        label: "remove_host",
                        classes: "btn-danger",
                        action: function(){

                            resourcesFactory.removeHost(hostId)
                                .success(function(data, status) {
                                    $notification.create("Removed host", hostId).success();
                                    // After removing, refresh our list
                                    update();
                                    this.close();
                                }.bind(this))
                                .error(function(data, status){
                                    $notification.create("Removing host failed", data.Detail).error();
                                    this.close();
                                }.bind(this));
                        }
                    }
                ]
            });
        };

        $scope.clickHost = function(hostId) {
            resourcesFactory.routeToHost(hostId);
        };

        $scope.clickPool = function(poolID) {
            resourcesFactory.routeToPool(poolID);
        };

        function update(){
            hostsFactory.update()
                .then(() => {
                    $scope.hosts = hostsFactory.hostList;
                }, () => {
                    // wait a sec and try again
                    $timeout(update, 1000);
                });

            poolsFactory.update()
                .then(() => {
                    $scope.pools = poolsFactory.poolList;
                    $scope.resetNewHost();
                }, () => {
                    // wait a sec and try again
                    $timeout(update, 1000);
                });
        }

        function init(){
            $scope.name = "hosts";
            $scope.params = $routeParams;

            $scope.breadcrumbs = [
                { label: 'breadcrumb_hosts', itemClass: 'active' }
            ];

            $scope.hostsTable = {
                sorting: {
                    name: "asc"
                },
                watchExpression: function(){
                    return hostsFactory.lastUpdate;
                }
            };

            $scope.dropped = [];

            // update hosts
            update();

            servicesFactory.activate();
            hostsFactory.activate();
            poolsFactory.activate();
        }

        init();

        $scope.$on("$destroy", function(){
            hostsFactory.deactivate();
            servicesFactory.deactivate();
            poolsFactory.deactivate();
        });
    }]);
})();
<|endoftext|>


<commit_before>$(document).ready(function() {

    $('a.blog-button').click(function() {
        currentWidth = $('.panel-cover').width();
        if (currentWidth < 960) {
            $('.panel-cover').animate({
                'max-width': '100%',
                'width': '100%'
            }, 400, swing = 'swing', function() {});
            window.location.hash = "#";
        } else {
            $('.panel-cover').css('max-width', currentWidth);
            $('.panel-cover').animate({
                'max-width': '700px',
                'width': '30%'
            }, 400, swing = 'swing', function() {});
            window.location.hash = "#blog";
        }
        // If already in blog, return early without animate overlay panel again.
        if (location.hash && location.hash == "#blog") {
            $('.panel-cover').removeClass('panel-cover--collapsed');
            $('.main-post-list').removeClass('hidden');
        }else {
            $('.panel-cover').addClass('panel-cover--collapsed');
            $('.main-post-list').addClass('hidden');
        }
    });
    $('a.blog-index').click(function () {
        $('.panel-cover').css('max-width', currentWidth);
        $('.panel-cover').css({
            'max-width': '700px',
            'width': '30%'
        });
    });
    if (window.location.hash && (window.location.hash == "#blog" || window.location.hash == "###")) {
        $('.panel-cover').addClass('panel-cover--collapsed');
        $('.main-post-list').removeClass('hidden');
    }

    if (window.location.pathname.substring(0, 5) == "/tag/") {
        $('.panel-cover').addClass('panel-cover--collapsed');
    }

    $('.btn-mobile-menu__icon').click(function() {
        if ($('.navigation-wrapper').css('display') == "block") {
            $('.navigation-wrapper').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
                $('.navigation-wrapper').toggleClass('visible animated bounceOutUp');
            });
            $('.navigation-wrapper').toggleClass('animated bounceInDown animated bounceOutUp');

        } else {
            $('.navigation-wrapper').toggleClass('visible animated bounceInDown');
        }
        $('.btn-mobile-menu__icon').toggleClass('fa fa-list fa fa-angle-up animated fadeIn');
    });

    $('.navigation-wrapper .blog-button').click(function() {
        if ($('.navigation-wrapper').css('display') == "block") {
            $('.navigation-wrapper').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
                $('.navigation-wrapper').toggleClass('visible animated bounceOutUp');
            });

            $('.navigation-wrapper').toggleClass('animated bounceInDown animated bounceOutUp');
        }

        $('.btn-mobile-menu__icon').toggleClass('fa fa-list fa fa-angle-up animated fadeIn');
    });
});
$(document.links).filter(function() {
    return this.hostname != window.location.hostname;
}).attr('target', '_blank');<commit_msg>修改博客交互bug<commit_after>$(document).ready(function() {

    $('a.blog-button').click(function() {
        currentWidth = $('.panel-cover').width();
        if (currentWidth < 960) {
            $('.panel-cover').animate({
                'max-width': '100%',
                'width': '100%'
            }, 400, swing = 'swing', function() {});
            window.location.hash = "#";
        } else {
            $('.panel-cover').css('max-width', currentWidth);
            $('.panel-cover').animate({
                'max-width': '700px',
                'width': '30%'
            }, 400, swing = 'swing', function() {});
            window.location.hash = "#blog";
        }
        // If already in blog, return early without animate overlay panel again.
        if (location.hash && location.hash == "#blog") {
            $('.panel-cover').removeClass('panel-cover--collapsed');
            $('.main-post-list').removeClass('hidden');
        }else {
            $('.panel-cover').addClass('panel-cover--collapsed');
            $('.main-post-list').addClass('hidden');
        }
    });
    $('a.blog-index').click(function () {
        currentWidth = $('.panel-cover').width();
        $('.panel-cover').css('max-width', currentWidth);
        $('.panel-cover').css({
            'max-width': '700px',
            'width': '30%'
        });
        $('.main-post-list').removeClass('hidden');
    });
    if (window.location.hash && (window.location.hash == "#blog" || window.location.hash == "###")) {
        $('.panel-cover').addClass('panel-cover--collapsed');
        $('.main-post-list').removeClass('hidden');
    }

    if (window.location.pathname.substring(0, 5) == "/tag/") {
        $('.panel-cover').addClass('panel-cover--collapsed');
    }

    $('.btn-mobile-menu__icon').click(function() {
        if ($('.navigation-wrapper').css('display') == "block") {
            $('.navigation-wrapper').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
                $('.navigation-wrapper').toggleClass('visible animated bounceOutUp');
            });
            $('.navigation-wrapper').toggleClass('animated bounceInDown animated bounceOutUp');

        } else {
            $('.navigation-wrapper').toggleClass('visible animated bounceInDown');
        }
        $('.btn-mobile-menu__icon').toggleClass('fa fa-list fa fa-angle-up animated fadeIn');
    });

    $('.navigation-wrapper .blog-button').click(function() {
        if ($('.navigation-wrapper').css('display') == "block") {
            $('.navigation-wrapper').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function() {
                $('.navigation-wrapper').toggleClass('visible animated bounceOutUp');
            });

            $('.navigation-wrapper').toggleClass('animated bounceInDown animated bounceOutUp');
        }

        $('.btn-mobile-menu__icon').toggleClass('fa fa-list fa fa-angle-up animated fadeIn');
    });
});
$(document.links).filter(function() {
    return this.hostname != window.location.hostname;
}).attr('target', '_blank');<|endoftext|>


<commit_before>const path = require('path');
const assert = require('assert');
const compare = require('./utils/compare.js');

process.chdir(__dirname);

describe('cases', () => {
    it('should resolve quotes in transform step', () => {
        return compare(
            `background: svg-load('fixtures/font.svg');`,
            `background: url("data:image/svg+xml;charset=utf-8,<svg font='%22Nelvetica Neue%22, sans-serif'/>");`
        );
    });

    it('should stringify all values after ast transformation', () => {
        return compare(
            `
            @svg-load icon url(fixtures/basic.svg) {}
            background: svg-inline(icon);
            background: svg-load('fixtures/basic.svg');
            `,
            `
            background: url("data:image/svg+xml;charset=utf-8,<svg id='basic'/>");
            background: url("data:image/svg+xml;charset=utf-8,<svg id='basic'/>");
            `
        ).then(result => {
            result.root.walkDecls(decl => {
                assert.equal(typeof decl.value, 'string');
            });
        });
    });

    it('should warn on not found file', () => {
        return compare(
            `background: svg-load('fixtures/not-found.svg');`,
            `background: svg-load('fixtures/not-found.svg');`,
            [
                `Can't load '${path.resolve('fixtures/not-found.svg')}'`
            ]
        );
    });

    it('should add message about dependency', () => {
        return compare(
            `
            background: svg-load('fixtures/basic.svg');
            @svg-load icon url('fixtures/basic-black.svg') {}
            `,
            `
            background: url("data:image/svg+xml;charset=utf-8,<svg id='basic'/>")
            `
        ).then(result => {
            const messages = result.messages
                .filter(message => message.type === 'dependency')
                .map(message => message.file);
            assert.deepEqual(messages, [
                path.resolve('fixtures/basic.svg'),
                path.resolve('fixtures/basic-black.svg')
            ]);
        });
    });

    it('should not add message about not found dependency', () => {
        return compare(
            `
            background: svg-load('fixtures/not-found.svg');
            @svg-load icon url('fixtures/not-found.svg') {}
            `,
            `
            background: svg-load('fixtures/not-found.svg');
            @svg-load icon url('fixtures/not-found.svg') {}
            `,
            [
                `Can't load '${path.resolve('fixtures/not-found.svg')}'`,
                `Can't load '${path.resolve('fixtures/not-found.svg')}'`
            ]
        ).then(result => {
            const messages = result.messages
                .filter(message => message.type === 'dependency')
                .map(message => message.file);
            assert.deepEqual(messages, []);
        });
    });
});
<commit_msg>Fix messages order<commit_after>const path = require('path');
const assert = require('assert');
const compare = require('./utils/compare.js');

process.chdir(__dirname);

describe('cases', () => {
    it('should resolve quotes in transform step', () => {
        return compare(
            `background: svg-load('fixtures/font.svg');`,
            `background: url("data:image/svg+xml;charset=utf-8,<svg font='%22Nelvetica Neue%22, sans-serif'/>");`
        );
    });

    it('should stringify all values after ast transformation', () => {
        return compare(
            `
            @svg-load icon url(fixtures/basic.svg) {}
            background: svg-inline(icon);
            background: svg-load('fixtures/basic.svg');
            `,
            `
            background: url("data:image/svg+xml;charset=utf-8,<svg id='basic'/>");
            background: url("data:image/svg+xml;charset=utf-8,<svg id='basic'/>");
            `
        ).then(result => {
            result.root.walkDecls(decl => {
                assert.equal(typeof decl.value, 'string');
            });
        });
    });

    it('should warn on not found file', () => {
        return compare(
            `background: svg-load('fixtures/not-found.svg');`,
            `background: svg-load('fixtures/not-found.svg');`,
            [
                `Can't load '${path.resolve('fixtures/not-found.svg')}'`
            ]
        );
    });

    it('should add message about dependency', () => {
        return compare(
            `
            background: svg-load('fixtures/basic.svg');
            @svg-load icon url('fixtures/basic-black.svg') {}
            `,
            `
            background: url("data:image/svg+xml;charset=utf-8,<svg id='basic'/>")
            `
        ).then(result => {
            const messages = result.messages
                .filter(message => message.type === 'dependency')
                .map(message => message.file)
                .sort();
            assert.deepEqual(messages, [
                path.resolve('fixtures/basic-black.svg'),
                path.resolve('fixtures/basic.svg')
            ]);
        });
    });

    it('should not add message about not found dependency', () => {
        return compare(
            `
            background: svg-load('fixtures/not-found.svg');
            @svg-load icon url('fixtures/not-found.svg') {}
            `,
            `
            background: svg-load('fixtures/not-found.svg');
            @svg-load icon url('fixtures/not-found.svg') {}
            `,
            [
                `Can't load '${path.resolve('fixtures/not-found.svg')}'`,
                `Can't load '${path.resolve('fixtures/not-found.svg')}'`
            ]
        ).then(result => {
            const messages = result.messages
                .filter(message => message.type === 'dependency')
                .map(message => message.file)
                .sort();
            assert.deepEqual(messages, []);
        });
    });
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

let assert = require('assert');

let readFileSync = require('../readFileSync');

let total = 0;
let pass = 0;
let fail = 0;

readFileSync('/dev/stdin').split('\n').forEach(function(line) {
    line = line.trim();

    if(line.indexOf('%%%') === -1) {
        return;
    }

    let slices = line.split('%%%').map(function(value) {
        return value.trim();
    });

    ++total;

    if(slices[0] === slices[1]) {
        ++pass;
        process.stdout.write("[Pass] ");
    }
    else {
        ++fail;
        process.stdout.write("[Fail] ");
    }

    console.log(line);
});

console.log();

console.log(total + " tests ran.");
console.log(pass + " tests pass (" + (pass / total * 100).toFixed(2) + "%).");
console.log(fail + " tests fail (" + (fail / total * 100).toFixed(2) + "%).");
<commit_msg>test/check.js: Also print lines that don't contain a separator token (%%%).<commit_after>#!/usr/bin/env node
'use strict';

let assert = require('assert');

let readFileSync = require('../readFileSync');

let total = 0;
let pass = 0;
let fail = 0;

readFileSync('/dev/stdin').split('\n').forEach(function(line) {
    line = line.trim();

    if(line.indexOf('%%%') === -1) {
        console.log(line);
        return;
    }

    let slices = line.split('%%%').map(function(value) {
        return value.trim();
    });

    ++total;

    if(slices[0] === slices[1]) {
        ++pass;
        process.stdout.write("[Pass] ");
    }
    else {
        ++fail;
        process.stdout.write("[Fail] ");
    }

    console.log(line);
});

console.log();

console.log(total + " tests ran.");
console.log(pass + " tests pass (" + (pass / total * 100).toFixed(2) + "%).");
console.log(fail + " tests fail (" + (fail / total * 100).toFixed(2) + "%).");
<|endoftext|>


<commit_before>'use strict';

require('assert');
const should = require('should');
const cash = require('../dist/index.js');

describe('clear', function () {
  it('should exist and be a function', function () {
    should.exist(cash.clear);
  });

  (function () {
    cash.clear;
  }).should.not.throw();
});
<commit_msg>throw test<commit_after>'use strict';

require('assert');
const should = require('should');
const cash = require('../dist/index.js');

describe('clear', function () {
  it('should exist and be a function', function () {
    should.exist(cash.clear);
  });

  it('should run without throwing', function () {
    (function () {
      cash.clear();
    }).should.not.throw();
  });
});
<|endoftext|>


<commit_before>/* global describe, it */
var assert = require('assert');

var ECKey = require('../src/eckey.js').ECKey;
var ECPubKey = require('../src/eckey.js').ECPubKey;

var convert = require('../src/convert.js');
var bytesToHex = convert.bytesToHex;
var hexToBytes = convert.hexToBytes;
var Address = require('../src/address');
var Network = require('../src/network')
var testnet = Network.testnet.addressVersion

describe('ECKey', function() {
    describe('constructor', function() {
        it('parses hex', function() {
            var priv = '18e14a7b6a307f426a94f8114701e7c8e774e7f9a47e2c2035db29a206321725';
            var pub = '0450863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b235' +
                      '22cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6';
            var key = new ECKey(priv);

            assert.equal(key.getPub().toHex(), pub);
            assert.equal(key.compressed, false);
        })

        it('parses base64', function() {
            var priv = 'VYdB+iv47y5FaUVIPdQInkgATrABeuD1lACUoM4x7tU=';
            var pub = '042f43c16c08849fed20a35bb7b1947bbf0923c52d613ee13b5c665a1e10d24b2' +
                      '8be909a70f5f87c1adb79fbcd1b3f17d20aa91c04fc355112dba2ce9b1cbf013b';
            var key = new ECKey(priv);

            assert.equal(key.getPub().toHex(), pub);
            assert.equal(key.compressed, false);
        })

        it('parses WIF', function() {
            var priv = '5HwoXVkHoRM8sL2KmNRS217n1g8mPPBomrY7yehCuXC1115WWsh';
            var pub = '044f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0' +
                      'f0b704075871aa385b6b1b8ead809ca67454d9683fcf2ba03456d6fe2c4abe2b07f0fbdbb2f1c1';
            var addr = '1MsHWS1BnwMc3tLE8G35UXsS58fKipzB7a';
            var key = new ECKey(priv);

            assert.equal(key.compressed, false);
            assert.equal(key.getPub().toHex(), pub);
            assert.equal(key.getAddress().toString(), addr);
        })

        it('parses compressed WIF', function() {
            var priv = 'KwntMbt59tTsj8xqpqYqRRWufyjGunvhSyeMo3NTYpFYzZbXJ5Hp';
            var pub = '034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa'
            var addr = '1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9';
            var key = new ECKey(priv);

            assert.equal(key.compressed, true);
            assert.equal(key.getPub().toHex(), pub);
            assert.equal(key.getAddress().toString(), addr);
        })

        it('alternative constructor syntax', function() {
            var priv = 'ca48ec9783cf3ad0dfeff1fc254395a2e403cbbc666477b61b45e31d3b8ab458';
            var pub = '044b12d9d7c77db68388b6ff7c89046174c871546436806bcd80d07c28ea81199' +
                      '283fbec990dad6fb98f93f712d50cb874dd717de6a184158d63886dda3090f566';
            var key = ECKey(priv, false);

            assert.equal(key.getPub().toHex(), pub);
            assert.equal(key.compressed, false);
            assert.equal(key.toHex(), priv);
        })
    })

    describe('toAddress', function() {
        var privkeys = [
            'CA48EC9783CF3AD0DFEFF1FC254395A2E403CBBC666477B61B45E31D3B8AB458',
            '1111111111111111111111111111111111111111111111111111111111111111',
            '18E14A7B6A307F426A94F8114701E7C8E774E7F9A47E2C2035DB29A206321725'
        ];

        // compressed pubkeys
        var cpubkeys = [
            '024B12D9D7C77DB68388B6FF7C89046174C871546436806BCD80D07C28EA811992',
            '034F355BDCB7CC0AF728EF3CCEB9615D90684BB5B2CA5F859AB0F0B704075871AA',
            '0250863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352'
        ];

        var pubkeys = cpubkeys.map(function(x) {
            return new ECPubKey(x).pub.getEncoded(false);
        });

        it('mainnet', function() {
            var addresses = [
                '19SgmoUj4xowEjwtXvNAtYTAgbvR9iBCui',
                '1MsHWS1BnwMc3tLE8G35UXsS58fKipzB7a',
                '16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM'
            ];
            var compressedAddresses = [
                '1AA4sjKW2aUmbtN3MtegdvhYtDBbDEke1q',
                '1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9',
                '1PMycacnJaSqwwJqjawXBErnLsZ7RkXUAs',
            ];

            for (var i = 0; i < addresses.length; ++i) {
                var priv = new ECKey(privkeys[i], false);
                var pubcomp = new ECPubKey(cpubkeys[i], true);
                var pub = new ECPubKey(pubkeys[i], false);

                var addr = addresses[i];
                var caddr = compressedAddresses[i];

                assert.equal(priv.getAddress().toString(), addr);
                assert.equal(pub.getAddress().toString(), addr);
                assert.equal(pubcomp.getAddress().toString(), caddr);
            }
        })

        it('testnet', function() {
            var addresses = [
                '19SgmoUj4xowEjwtXvNAtYTAgbvR9iBCui',
                '1MsHWS1BnwMc3tLE8G35UXsS58fKipzB7a',
                '16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM'
            ];
            var compressedAddresses = [
                '1AA4sjKW2aUmbtN3MtegdvhYtDBbDEke1q',
                '1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9',
                '1PMycacnJaSqwwJqjawXBErnLsZ7RkXUAs',
            ];

            for (var i = 0; i < addresses.length; ++i) {
                var priv = new ECKey(privkeys[i], false);
                var pubcomp = new ECPubKey(cpubkeys[i], true);
                var pub = new ECPubKey(pubkeys[i], false);

                var addr = addresses[i];
                var caddr = compressedAddresses[i];

                assert.equal(priv.getAddress().toString(), addr);
                assert.equal(pub.getAddress().toString(), addr);
                assert.equal(pubcomp.getAddress().toString(), caddr);
            }
        })
    });
})
<commit_msg>Adds some ECKey tests<commit_after>/* global describe, it */
var assert = require('assert');

var ECKey = require('../src/eckey.js').ECKey;
var ECPubKey = require('../src/eckey.js').ECPubKey;

var convert = require('../src/convert.js');
var bytesToHex = convert.bytesToHex;
var hexToBytes = convert.hexToBytes;
var Address = require('../src/address');
var Network = require('../src/network')
var testnet = Network.testnet.addressVersion

describe('ECKey', function() {
    describe('constructor', function() {
        it('parses hex', function() {
            var priv = '18e14a7b6a307f426a94f8114701e7c8e774e7f9a47e2c2035db29a206321725';
            var pub = '0450863ad64a87ae8a2fe83c1af1a8403cb53f53e486d8511dad8a04887e5b235' +
                      '22cd470243453a299fa9e77237716103abc11a1df38855ed6f2ee187e9c582ba6';
            var key = new ECKey(priv);

            assert.equal(key.getPub().toHex(), pub);
            assert.equal(key.compressed, false);
        })

        it('parses base64', function() {
            var priv = 'VYdB+iv47y5FaUVIPdQInkgATrABeuD1lACUoM4x7tU=';
            var pub = '042f43c16c08849fed20a35bb7b1947bbf0923c52d613ee13b5c665a1e10d24b2' +
                      '8be909a70f5f87c1adb79fbcd1b3f17d20aa91c04fc355112dba2ce9b1cbf013b';
            var key = new ECKey(priv);

            assert.equal(key.getPub().toHex(), pub);
            assert.equal(key.compressed, false);
        })

        it('parses WIF', function() {
            var priv = '5HwoXVkHoRM8sL2KmNRS217n1g8mPPBomrY7yehCuXC1115WWsh';
            var pub = '044f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0' +
                      'f0b704075871aa385b6b1b8ead809ca67454d9683fcf2ba03456d6fe2c4abe2b07f0fbdbb2f1c1';
            var addr = '1MsHWS1BnwMc3tLE8G35UXsS58fKipzB7a';
            var key = new ECKey(priv);

            assert.equal(key.compressed, false);
            assert.equal(key.getPub().toHex(), pub);
            assert.equal(key.getAddress().toString(), addr);
        })

        it('parses compressed WIF', function() {
            var priv = 'KwntMbt59tTsj8xqpqYqRRWufyjGunvhSyeMo3NTYpFYzZbXJ5Hp';
            var pub = '034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa'
            var addr = '1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9';
            var key = new ECKey(priv);

            assert.equal(key.compressed, true);
            assert.equal(key.getPub().toHex(), pub);
            assert.equal(key.getAddress().toString(), addr);
        })

        it('alternative constructor syntax', function() {
            var priv = 'ca48ec9783cf3ad0dfeff1fc254395a2e403cbbc666477b61b45e31d3b8ab458';
            var pub = '044b12d9d7c77db68388b6ff7c89046174c871546436806bcd80d07c28ea81199' +
                      '283fbec990dad6fb98f93f712d50cb874dd717de6a184158d63886dda3090f566';
            var key = ECKey(priv, false);

            assert.equal(key.getPub().toHex(), pub);
            assert.equal(key.compressed, false);
            assert.equal(key.toHex(), priv);
        })
    })

    describe('toAddress', function() {
        var privkeys = [
            'CA48EC9783CF3AD0DFEFF1FC254395A2E403CBBC666477B61B45E31D3B8AB458',
            '1111111111111111111111111111111111111111111111111111111111111111',
            '18E14A7B6A307F426A94F8114701E7C8E774E7F9A47E2C2035DB29A206321725'
        ];

        // compressed pubkeys
        var cpubkeys = [
            '024B12D9D7C77DB68388B6FF7C89046174C871546436806BCD80D07C28EA811992',
            '034F355BDCB7CC0AF728EF3CCEB9615D90684BB5B2CA5F859AB0F0B704075871AA',
            '0250863AD64A87AE8A2FE83C1AF1A8403CB53F53E486D8511DAD8A04887E5B2352'
        ];

        var pubkeys = cpubkeys.map(function(x) {
            return new ECPubKey(x).pub.getEncoded(false);
        });

        it('mainnet', function() {
            var addresses = [
                '19SgmoUj4xowEjwtXvNAtYTAgbvR9iBCui',
                '1MsHWS1BnwMc3tLE8G35UXsS58fKipzB7a',
                '16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM'
            ];
            var compressedAddresses = [
                '1AA4sjKW2aUmbtN3MtegdvhYtDBbDEke1q',
                '1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9',
                '1PMycacnJaSqwwJqjawXBErnLsZ7RkXUAs',
            ];

            for (var i = 0; i < addresses.length; ++i) {
                var priv = new ECKey(privkeys[i], false);
                var pubcomp = new ECPubKey(cpubkeys[i], true);
                var pub = new ECPubKey(pubkeys[i], false);

                var addr = addresses[i];
                var caddr = compressedAddresses[i];

                assert.equal(priv.getAddress().toString(), addr);
                assert.equal(pub.getAddress().toString(), addr);
                assert.equal(pubcomp.getAddress().toString(), caddr);
            }
        })

        it('testnet', function() {
            var addresses = [
                '19SgmoUj4xowEjwtXvNAtYTAgbvR9iBCui',
                '1MsHWS1BnwMc3tLE8G35UXsS58fKipzB7a',
                '16UwLL9Risc3QfPqBUvKofHmBQ7wMtjvM'
            ];
            var compressedAddresses = [
                '1AA4sjKW2aUmbtN3MtegdvhYtDBbDEke1q',
                '1Q1pE5vPGEEMqRcVRMbtBK842Y6Pzo6nK9',
                '1PMycacnJaSqwwJqjawXBErnLsZ7RkXUAs',
            ];

            for (var i = 0; i < addresses.length; ++i) {
                var priv = new ECKey(privkeys[i], false);
                var pubcomp = new ECPubKey(cpubkeys[i], true);
                var pub = new ECPubKey(pubkeys[i], false);

                var addr = addresses[i];
                var caddr = compressedAddresses[i];

                assert.equal(priv.getAddress().toString(), addr);
                assert.equal(pub.getAddress().toString(), addr);
                assert.equal(pubcomp.getAddress().toString(), caddr);
            }
        })
    });

    describe('signing', function() {
      var hpriv = 'ca48ec9783cf3ad0dfeff1fc254395a2e403cbbc666477b61b45e31d3b8ab458'
      var hcpub = '024b12d9d7c77db68388b6ff7c89046174c871546436806bcd80d07c28ea811992'
      var message = 'Vires in numeris'

      it('should verify against the private key', function() {
        var priv = new ECKey(hpriv)
        var signature = priv.sign(message)

        assert(priv.verify(message, signature))
      })

      it('should verify against the public key', function() {
        var priv = new ECKey(hpriv)
        var pub = new ECPubKey(hcpub, true)
        var signature = priv.sign(message)

        assert(pub.verify(message, signature))
      })

      it('should not verify against the wrong private key', function() {
        var priv1 = new ECKey(hpriv)
        var priv2 = new ECKey('1111111111111111111111111111111111111111111111111111111111111111')

        var signature = priv1.sign(message)

        assert(!priv2.verify(message, signature))
      })
    })
})
<|endoftext|>


<commit_before>module.exports = {

	//---------------------------------------------------------------------
	// Action Name
	//
	// This is the name of the action displayed in the editor.
	//---------------------------------------------------------------------

	name: "Store Bot Client Info",

	//---------------------------------------------------------------------
	// Action Section
	//
	// This is the section the action will fall into.
	//---------------------------------------------------------------------

	section: "Bot Client Control",

	//---------------------------------------------------------------------
	// Action Subtitle
	//
	// This function generates the subtitle displayed next to the name.
	//---------------------------------------------------------------------

	subtitle: function (data) {
		const info = ['Uptime in Milliseconds', 'Ready At?', 'Ping', 'Guild Amount', 'User Amount', 'Rounded Ping', 'Uptime in Seconds', 'Uptime in Minutes', 'Bot\'s Token', 'Voice Connections Amount', 'Total Amount of Channels', 'Total Amount of Emojis', 'Bot\'s Previous Pings', 'Uptime in Days', 'Uptime in Days (Rounded)', 'Memory (RAM) Usage', 'Bot Guilds Objects', 'Bot Guilds Names', 'Bot Guilds IDs', 'Bot Current Prefix', 'Bot Client ID', 'Discord JS Version', 'Uptime in Hours', 'Refreshing Uptime in Days', 'Refreshing Uptime in Hours', 'Refreshing Uptime in Minutes', 'Refreshing Uptime in Seconds', 'Memory (RAM) Usage in MB', 'Bot\'s OS (Process Platform)', 'CPU Usage in MB', 'Bot\'s Directory', 'Node JS Version', 'Amount of Commands', 'Amount of Events'];
		return `Bot Client - ${info[parseInt(data.info)]}`;
	},

	//---------------------------------------------------------------------
	// DBM Mods Manager Variables (Optional but nice to have!)
	//
	// These are variables that DBM Mods Manager uses to show information
	// about the mods for people to see in the list.
	//---------------------------------------------------------------------

	// Who made the mod (If not set, defaults to "DBM Mods")
	author: "Lasse, EliteArtz and EGGSY",

	// The version of the mod (Defaults to 1.0.0)
	version: "1.8.7",

	// A short description to show on the mod line for this mod (Must be on a single line)
	short_description: "Stores Bot Information like Ping, Total Members or Guilds...",

	// If it depends on any other mods by name, ex: WrexMODS if the mod uses something from WrexMods

	//---------------------------------------------------------------------

	//---------------------------------------------------------------------
	// Action Storage Function
	//
	// Stores the relevant variable info for the editor.
	//---------------------------------------------------------------------

	variableStorage: function (data, varType) {
		const type = parseInt(data.storage);
		if (type !== varType) return;
		const info = parseInt(data.info);
		let dataType = 'Unknown Type';
		switch (info) {
			case 0:
				dataType = "Number";
				break;
			case 1:
				dataType = "Date";
				break;
			case 2:
				dataType = "Number";
				break;
			case 3:
				dataType = "Number";
				break;
			case 4:
				dataType = "Number";
				break;
			case 5:
				dataType = "Number";
				break;
			case 6:
				dataType = "Number";
				break;
			case 7:
				dataType = "Number";
				break;
			case 8:
				dataType = "Token";
				break;
			case 9:
				dataType = "Number";
				break;
			case 10:
				dataType = "Number";
				break;
			case 11:
				dataType = "Number";
				break;
			case 12:
				dataType = "Number";
				break;
			case 13:
				dataType = "Time";
				break;
			case 14:
				dataType = "Time";
				break;
			case 15:
				dataType = "Number";
				break;
			case 16:
				dataType = "Guild";
				break;
			case 17:
				dataType = "Guild Name";
				break;
			case 18:
				dataType = "Guild ID";
				break;
			case 19:
				dataType = "Bot Tag";
				break;
			case 20:
				dataType = "Bot ID";
				break;
			case 21:
				dataType = "Version Number";
				break;
			case 22:
				dataType = "Number";
				break;
			case 23:
				dataType = "Time";
				break;
			case 24:
				dataType = "Time";
				break;
			case 25:
				dataType = "Time";
				break;
			case 26:
				dataType = "Time";
				break;
			case 27:
				dataType = "Number";
				break;
			case 28:
				dataType = "OS Name";
				break;
			case 29:
				dataType = "Number";
				break;
			case 30:
				dataType = "Directory";
				break;
			case 31:
				dataType = "Version Number";
				break;
			case 32:
				dataType = "Number";
				break;
			case 33:
				dataType = "Number";
				break;
		}
		return ([data.varName2, dataType]);
	},

	//---------------------------------------------------------------------
	// Action Fields
	//
	// These are the fields for the action. These fields are customized
	// by creating elements with corresponding IDs in the HTML. These
	// are also the names of the fields stored in the action's JSON data.
	//---------------------------------------------------------------------

	fields: ["info", "storage", "varName2"],

	//---------------------------------------------------------------------
	// Command HTML
	//
	// This function returns a string containing the HTML used for
	// editting actions.
	//
	// The "isEvent" parameter will be true if this action is being used
	// for an event. Due to their nature, events lack certain information,
	// so edit the HTML to reflect this.
	//
	// The "data" parameter stores constants for select elements to use.
	// Each is an array: index 0 for commands, index 1 for events.
	// The names are: sendTargets, members, roles, channels,
	//                messages, servers, variables
	//---------------------------------------------------------------------

	html: function (isEvent, data) {
		return `

				Mod Info:

				Created by EliteArtz, EGGSY and Lasse!

		Source Info:

		<select id="info" class="round">
			<option value="23">Refreshing Uptime in Days</option>
			<option value="24">Refreshing Uptime in Hours</option>
			<option value="25">Refreshing Uptime in Minutes</option>
			<option value="26">Refreshing Uptime in Seconds</option>
			<option value="1">Ready at</option>
			<option value="2">Ping</option>
			<option value="5">Ping Rounded</option>
			<option value="12">Bots Previous Pings</option>
			<option value="9">Total Voice Connections</option>
			<option value="15">Memory (RAM) Usage</option>
			<option value="27">Memory (RAM) Usage in MB</option>
			<option value="21">Discord JS Version</option>
			<option value="29">CPU Usage in MB</option>
			<option value="3">Total Amount of Guilds</option>
			<option value="4">Total Amount of Users</option>
			<option value="10">Total Amount of Channels</option>
			<option value="11">Total Amount of Emojis</option>
                        <option value="32">Total Amount of Commands</option>
                        <option value="33">Total Amount of Events</option>
			<option value="16">Bot Guilds Objects</option>
			<option value="17">Bot Guilds Names</option>
			<option value="18">Bot Guilds IDs</option>
			<option value="19">Bot Current Prefix</option>
			<option value="20">Bot Client ID</option>
			<option value="28">Bot OS (Process Platform)</option>
			<option value="30">Bot Directory</option>
			<option value="8">Bot Token</option>
			<option value="31">Node JS Version</option>
		</select>

			Store In:

			<select id="storage" class="round">
				${data.variables[1]}
			</select>

			Variable Name:

			<input id="varName2" class="round" type="text">

`
	},

	//---------------------------------------------------------------------
	// Action Editor Init Code
	//
	// When the HTML is first applied to the action editor, this code
	// is also run. This helps add modifications or setup reactionary
	// functions for the DOM elements.
	//---------------------------------------------------------------------

	init: function () {},

	//---------------------------------------------------------------------
	// Action Bot Function
	//
	// This is the function for the action within the Bot's Action class.
	// Keep in mind event calls won't have access to the "msg" parameter,
	// so be sure to provide checks for variable existance.
	//---------------------------------------------------------------------

	action: function (cache) {
		const botClient = this.getDBM().Bot.bot;
		const dibiem = this.getDBM(); //EliteArtz... really???? Ugh you guys are meme
		const data = cache.actions[cache.index];
		const info = parseInt(data.info);
		const msToDay = (1000 * 60 * 60 * 24); // Really? Lasse? Did you really forget this? - :blobshh:
		const usedMEMORY = process.memoryUsage().heapUsed / 1024 / 1024; // Sorry about all const things but this is needed, you know.
		const usedCPU = process.cpuUsage().user / 1024 / 1024;
		if (!botClient) {
			this.callNextAction(cache);
			return;
		}
		switch (info) {
			case 0:
				result = botClient.uptime; //Deprecated in 1.8.5
				break;
			case 1:
				result = botClient.readyAt;
				break;
			case 2:
				result = botClient.ping;
				break;
			case 3:
				result = botClient.guilds.array().length;
				break;
			case 4:
				result = botClient.users.array().length;
				break;
			case 5:
				result = Math.round(botClient.ping);
				break;
			case 6:
				result = Math.floor(botClient.uptime / 1000); //Deprecated in 1.8.5
				break;
			case 7:
				result = Math.floor(botClient.uptime / 1000 / 60); //Deprecated in 1.8.5
				break;
			case 8:
				result = botClient.token;
				break;
			case 9:
				result = botClient.voiceConnections.array().length;
				break;
			case 10:
				result = botClient.channels.size;
				break;
			case 11:
				result = botClient.emojis.size;
				break;
			case 12:
				result = botClient.pings;
				break;
			case 13:
				result = botClient.uptime / msToDay; //Deprecated in 1.8.5
				break;
			case 14:
				result = Math.floor(botClient.uptime / msToDay); //Deprecated in 1.8.5
				break;
			case 15:
				result = ((process.memoryUsage().heapUsed / 1024) / 1024).toFixed(2) + "%";
				break;
			case 16:
				result = botClient.guilds;
				break;
			case 17:
				result = botClient.guilds.array();
				break;
			case 18:
				result = botClient.guilds.map(guilds => guilds.id);
				break;
			case 19:
				result = dibiem.Files.data.settings.tag;
				break;
			case 20:
				result = dibiem.Files.data.settings.client;
				break;
			case 21:
				result = dibiem.DiscordJS.version;
				break;
			case 22:
				result = Math.floor(botClient.uptime / 1000 / 60 / 60); //Deprecated in 1.8.5
				break;
			case 23:
				result = Math.floor((process.uptime() % 31536000) / 86400);
				break;
			case 24:
				result = Math.floor((process.uptime() % 86400) / 3600);
				break;
			case 25:
				result = Math.floor((process.uptime() % 3600) / 60);
				break;
			case 26:
				result = Math.round(process.uptime() % 60);
				break;
			case 27:
				result = Math.round((usedMEMORY * 100) / 100) + " MB";
				break;
			case 28:
				if (process.platform) {
					const platform = process.platform;
					if (platform === 'win32') result = 'Windows';
					else if (platform === 'aix') result = 'Aix';
					else if (platform === 'linux') result = 'Linux';
					else if (platform === 'darwin') result = 'Darwin';
					else if (platform === 'openbsd') result = 'OpenBSD';
					else if (platform === 'sunos') result = 'Solaris';
					else if (platform === 'freebsd') result = 'FreeBSD';
				}
				break;
			case 29:
				result = Math.round((usedCPU * 100) / 100) + " MB";
				break;
			case 30:
				result = process.cwd();
				break;
			case 31:
				result = process.versions.node;
				break;
			case 32:
				const commands = dibiem.Files.data.commands;
				result = commands.length;
				break;
			case 33:
				const events = dibiem.Files.data.events;
				result = events.length;
				break;
			default:
				break;
		}
		if (result !== undefined) {
			const storage = parseInt(data.storage);
			const varName2 = this.evalMessage(data.varName2, cache);
			this.storeValue(result, storage, varName2, cache);
		}
		this.callNextAction(cache);
	},

	//---------------------------------------------------------------------
	// Action Bot Mod
	//
	// Upon initialization of the bot, this code is run. Using the bot's
	// DBM namespace, one can add/modify existing functions if necessary.
	// In order to reduce conflictions between mods, be sure to alias
	// functions you wish to overwrite.
	//---------------------------------------------------------------------

	mod: function (DBM) {}

}; // End of module
<commit_msg>Updated and Fixed Some Stuff (Store Bot C. Info)<commit_after>module.exports = {

	//---------------------------------------------------------------------
	// Action Name
	//
	// This is the name of the action displayed in the editor.
	//---------------------------------------------------------------------

	name: "Store Bot Client Info",

	//---------------------------------------------------------------------
	// Action Section
	//
	// This is the section the action will fall into.
	//---------------------------------------------------------------------

	section: "Bot Client Control",

	//---------------------------------------------------------------------
	// Action Subtitle
	//
	// This function generates the subtitle displayed next to the name.
	//---------------------------------------------------------------------

	subtitle: function (data) {
		const info = ['Uptime in Milliseconds', 'Ready At?', 'Ping', 'Guild Amount', 'User Amount', 'Rounded Ping', 'Uptime in Seconds', 'Uptime in Minutes', 'Bot\'s Token', 'Voice Connections Amount', 'Total Amount of Channels', 'Total Amount of Emojis', 'Bot\'s Previous Pings', 'Uptime in Days', 'Uptime in Days (Rounded)', 'Memory (RAM) Usage', 'Bot Guilds Objects', 'Bot Guilds Names', 'Bot Guilds IDs', 'Bot Current Prefix', 'Bot Client ID', 'Discord JS Version', 'Uptime in Hours', 'Refreshing Uptime in Days', 'Refreshing Uptime in Hours', 'Refreshing Uptime in Minutes', 'Refreshing Uptime in Seconds', 'Memory (RAM) Usage in MB', 'Bot\'s OS (Process Platform)', 'CPU Usage in MB', 'Bot\'s Directory', 'Node JS Version', 'Amount of Commands', 'Amount of Events'];
		return `Bot Client - ${info[parseInt(data.info)]}`;
	},

	//---------------------------------------------------------------------
	// DBM Mods Manager Variables (Optional but nice to have!)
	//
	// These are variables that DBM Mods Manager uses to show information
	// about the mods for people to see in the list.
	//---------------------------------------------------------------------

	// Who made the mod (If not set, defaults to "DBM Mods")
	author: "Lasse, EliteArtz and EGGSY",

	// The version of the mod (Defaults to 1.0.0)
	version: "1.8.7",

	// A short description to show on the mod line for this mod (Must be on a single line)
	short_description: "Stores Bot Information like Ping, Total Members or Guilds...",

	// If it depends on any other mods by name, ex: WrexMODS if the mod uses something from WrexMods

	//---------------------------------------------------------------------

	//---------------------------------------------------------------------
	// Action Storage Function
	//
	// Stores the relevant variable info for the editor.
	//---------------------------------------------------------------------

	variableStorage: function (data, varType) {
		const type = parseInt(data.storage);
		if (type !== varType) return;
		const info = parseInt(data.info);
		let dataType = 'Unknown Type';
		switch (info) {
			case 0:
				dataType = "Number";
				break;
			case 1:
				dataType = "Date";
				break;
			case 2:
				dataType = "Number";
				break;
			case 3:
				dataType = "Number";
				break;
			case 4:
				dataType = "Number";
				break;
			case 5:
				dataType = "Number";
				break;
			case 6:
				dataType = "Number";
				break;
			case 7:
				dataType = "Number";
				break;
			case 8:
				dataType = "Token";
				break;
			case 9:
				dataType = "Number";
				break;
			case 10:
				dataType = "Number";
				break;
			case 11:
				dataType = "Number";
				break;
			case 12:
				dataType = "Number";
				break;
			case 13:
				dataType = "Time";
				break;
			case 14:
				dataType = "Time";
				break;
			case 15:
				dataType = "Number";
				break;
			case 16:
				dataType = "Guild";
				break;
			case 17:
				dataType = "Guild Name";
				break;
			case 18:
				dataType = "Guild ID";
				break;
			case 19:
				dataType = "Bot Tag";
				break;
			case 20:
				dataType = "Bot ID";
				break;
			case 21:
				dataType = "Version Number";
				break;
			case 22:
				dataType = "Number";
				break;
			case 23:
				dataType = "Time";
				break;
			case 24:
				dataType = "Time";
				break;
			case 25:
				dataType = "Time";
				break;
			case 26:
				dataType = "Time";
				break;
			case 27:
				dataType = "Number";
				break;
			case 28:
				dataType = "OS Name";
				break;
			case 29:
				dataType = "Number";
				break;
			case 30:
				dataType = "Directory";
				break;
			case 31:
				dataType = "Version Number";
				break;
			case 32:
				dataType = "Number";
				break;
			case 33:
				dataType = "Number";
				break;
		}
		return ([data.varName2, dataType]);
	},

	//---------------------------------------------------------------------
	// Action Fields
	//
	// These are the fields for the action. These fields are customized
	// by creating elements with corresponding IDs in the HTML. These
	// are also the names of the fields stored in the action's JSON data.
	//---------------------------------------------------------------------

	fields: ["info", "storage", "varName2"],

	//---------------------------------------------------------------------
	// Command HTML
	//
	// This function returns a string containing the HTML used for
	// editting actions.
	//
	// The "isEvent" parameter will be true if this action is being used
	// for an event. Due to their nature, events lack certain information,
	// so edit the HTML to reflect this.
	//
	// The "data" parameter stores constants for select elements to use.
	// Each is an array: index 0 for commands, index 1 for events.
	// The names are: sendTargets, members, roles, channels,
	//                messages, servers, variables
	//---------------------------------------------------------------------

	html: function (isEvent, data) {
		return `

				Mod Info:

				Created by EliteArtz, EGGSY and Lasse!

		Source Info:

		<select id="info" class="round">
			<option value="23">Refreshing Uptime in Days</option>
			<option value="24">Refreshing Uptime in Hours</option>
			<option value="25">Refreshing Uptime in Minutes</option>
			<option value="26">Refreshing Uptime in Seconds</option>
			<option value="1">Ready at</option>
			<option value="2">Ping</option>
			<option value="5">Ping Rounded</option>
			<option value="12">Bots Previous Pings</option>
			<option value="9">Total Voice Connections</option>
			<option value="27">Memory (RAM) Usage in MB</option>
			<option value="21">Discord JS Version</option>
			<option value="29">CPU Usage in MB</option>
			<option value="3">Total Amount of Guilds</option>
			<option value="4">Total Amount of Users</option>
			<option value="10">Total Amount of Channels</option>
			<option value="11">Total Amount of Emojis</option>
            <option value="32">Total Amount of Commands</option>
            <option value="33">Total Amount of Events</option>
			<option value="16">Bot Guilds Objects</option>
			<option value="17">Bot Guilds Names</option>
			<option value="18">Bot Guilds IDs</option>
			<option value="19">Bot Current Prefix</option>
			<option value="20">Bot Client ID</option>
			<option value="28">Bot OS (Process Platform)</option>
			<option value="30">Bot Directory</option>
			<option value="8">Bot Token</option>
			<option value="31">Node JS Version</option>
		</select>

			Store In:

			<select id="storage" class="round">
				${data.variables[1]}
			</select>

			Variable Name:

			<input id="varName2" class="round" type="text">

`
	},

	//---------------------------------------------------------------------
	// Action Editor Init Code
	//
	// When the HTML is first applied to the action editor, this code
	// is also run. This helps add modifications or setup reactionary
	// functions for the DOM elements.
	//---------------------------------------------------------------------

	init: function () { },

	//---------------------------------------------------------------------
	// Action Bot Function
	//
	// This is the function for the action within the Bot's Action class.
	// Keep in mind event calls won't have access to the "msg" parameter,
	// so be sure to provide checks for variable existance.
	//---------------------------------------------------------------------

	action: function (cache) {
		const botClient = this.getDBM().Bot.bot;
		const dibiem = this.getDBM(); //EliteArtz... really???? Ugh you guys are meme
		const data = cache.actions[cache.index];
		const info = parseInt(data.info);
		const msToDay = (1000 * 60 * 60 * 24); // Really? Lasse? Did you really forget this? - :blobshh:
		if (!botClient) {
			this.callNextAction(cache);
			return;
		}
		switch (info) {
			case 0:
				result = botClient.uptime; //Deprecated in 1.8.5
				break;
			case 1:
				result = botClient.readyAt;
				break;
			case 2:
				result = botClient.ping;
				break;
			case 3:
				result = botClient.guilds.array().length;
				break;
			case 4:
				result = botClient.users.array().length;
				break;
			case 5:
				result = Math.round(botClient.ping);
				break;
			case 6:
				result = Math.floor(botClient.uptime / 1000); //Deprecated in 1.8.5
				break;
			case 7:
				result = Math.floor(botClient.uptime / 1000 / 60); //Deprecated in 1.8.5
				break;
			case 8:
				result = botClient.token;
				break;
			case 9:
				result = botClient.voiceConnections.size;
				break;
			case 10:
				result = botClient.channels.size;
				break;
			case 11:
				result = botClient.emojis.size;
				break;
			case 12:
				result = botClient.pings;
				break;
			case 13:
				result = botClient.uptime / msToDay; //Deprecated in 1.8.5
				break;
			case 14:
				result = Math.floor(botClient.uptime / msToDay); //Deprecated in 1.8.5
				break;
			case 15:
				result = ((process.memoryUsage().heapUsed / 1024) / 1024).toFixed(2) + "%"; //Deprecated in 1.8.8
				break;
			case 16:
				result = botClient.guilds;
				break;
			case 17:
				result = botClient.guilds.array();
				break;
			case 18:
				result = botClient.guilds.map(guilds => guilds.id);
				break;
			case 19:
				result = dibiem.Files.data.settings.tag;
				break;
			case 20:
				result = dibiem.Files.data.settings.client;
				break;
			case 21:
				result = dibiem.DiscordJS.version;
				break;
			case 22:
				result = Math.floor(botClient.uptime / 1000 / 60 / 60); //Deprecated in 1.8.5
				break;
			case 23:
				result = Math.floor((process.uptime() % 31536000) / 86400);
				break;
			case 24:
				result = Math.floor((process.uptime() % 86400) / 3600);
				break;
			case 25:
				result = Math.floor((process.uptime() % 3600) / 60);
				break;
			case 26:
				result = Math.round(process.uptime() % 60);
				break;
			case 27:
				result = (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2);
				break;
			case 28:
				if (process.platform) {
					const platform = process.platform;
					if (platform === 'win32') result = 'Windows';
					else if (platform === 'aix') result = 'Aix';
					else if (platform === 'linux') result = 'Linux';
					else if (platform === 'darwin') result = 'Darwin';
					else if (platform === 'openbsd') result = 'OpenBSD';
					else if (platform === 'sunos') result = 'Solaris';
					else if (platform === 'freebsd') result = 'FreeBSD';
				}
				break;
			case 29:
				result = (process.cpuUsage().user / 1024 / 1024).toFixed(2);
				break;
			case 30:
				result = process.cwd();
				break;
			case 31:
				result = process.versions.node;
				break;
			case 32:
				result = dibiem.Files.data.commands.length;
				break;
			case 33:
				result = dibiem.Files.data.events.length;
				break;
			default:
				break;
		}
		if (result !== undefined) {
			const storage = parseInt(data.storage);
			const varName2 = this.evalMessage(data.varName2, cache);
			this.storeValue(result, storage, varName2, cache);
		}
		this.callNextAction(cache);
	},

	//---------------------------------------------------------------------
	// Action Bot Mod
	//
	// Upon initialization of the bot, this code is run. Using the bot's
	// DBM namespace, one can add/modify existing functions if necessary.
	// In order to reduce conflictions between mods, be sure to alias
	// functions you wish to overwrite.
	//---------------------------------------------------------------------

	mod: function (DBM) { }

}; // End of module
<|endoftext|>


<commit_before>var should      = require('should');
var fs          = require('fs');
var SimpleScApi = require('../index.js');

describe('launchd-simple-api userland', function() {
  var ssa = new SimpleScApi()

  it('should not list the fake service', function(done) {
    ssa.list({}, function (err, list) {
      ('fake' in list).should.eql(false);
      done();
    })
  });

  it('should install a fake service', function(done) {
    ssa.nssmInstall('fake', 'C:\\nodejsx64\\node.exe', 'C:\\vagrant\\utils\\fake-service.js', function (err) {
      (err===null).should.eql(true);
      err && console.error(err);
      done();
    })
  });

  it('should start the fake service', function(done) {
    ssa.start('fake', [], function (err) {
      setTimeout(function(){
        done(err);
      }, 500); // this is needed for the system to load and start the program.
    })
  });

  it('should list the fake service', function(done) {
    ssa.list({}, function (err, list) {
      ('fake' in list).should.eql(true);
      list['fake'].name.should.eql('fake');
      done();
    })
  });

  it('should be able to consume the service', function(done) {
    var net = require('net');
    var client = net.connect({port: 8080});
    var d;
    client.on('data', (data) => {
      d = data.toString()
    });
    client.on('end', () => {
      d.should.match(/goodbye/)
      done();
    });
    client.on('error', done);
  });

  it('should stop the fake service', function(done) {
    ssa.stop('fake', done)
  });

  it('should remove the fake service', function(done) {
    var service = {
      id: 'fake',
    }
    ssa.uninstall(service, done)
  });

  it('should not list the fake service', function(done) {
    ssa.list({}, function (err, list) {
      ('fake' in list).should.eql(false);
      done();
    })
  });
});
<commit_msg>fix tests<commit_after>var should      = require('should');
var fs          = require('fs');
var SimpleScApi = require('../index.js');

describe('launchd-simple-api userland', function() {
  var ssa = new SimpleScApi()

  it('should not list the fake service', function(done) {
    ssa.list({}, function (err, list) {
      ('fake' in list).should.eql(false);
      done();
    })
  });

  it('should install a fake service', function(done) {
    ssa.nssmInstall('fake', 'C:\\nodejsx64\\node.exe', 'C:\\vagrant\\utils\\fake-service.js', function (err) {
      (err===null).should.eql(true);
      err && console.error(err);
      done();
    })
  });

  it.skip('should list the fake service', function(done) {
    ssa.list({}, function (err, list) {
      console.log(list['fake']);
      ('fake' in list).should.eql(true);
      done();
    })
  });

  it('should start the fake service', function(done) {
    ssa.start('fake', [], function (err) {
      setTimeout(function(){
        done(err);
      }, 500); // this is needed for the system to load and start the program.
    })
  });

  it('should list the fake service', function(done) {
    ssa.list({}, function (err, list) {
      ('fake' in list).should.eql(true);
      list['fake'].name.should.eql('fake');
      done();
    })
  });

  it('should be able to consume the service', function(done) {
    var net = require('net');
    var client = net.connect({port: 8080});
    var d;
    client.on('data', (data) => {
      d = data.toString()
    });
    client.on('end', () => {
      d.should.match(/goodbye/)
      done();
    });
    client.on('error', done);
  });

  it('should stop the fake service', function(done) {
    ssa.stop('fake', done)
  });

  it('should remove the fake service', function(done) {
    var service = {
      id: 'fake',
    }
    ssa.uninstall(service, done)
  });

  it('should not list the fake service', function(done) {
    ssa.list({}, function (err, list) {
      ('fake' in list).should.eql(false);
      done();
    })
  });
});
<|endoftext|>