<commit_before>module.exports = function (grunt) {
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-jscs-checker');
    grunt.loadNpmTasks('grunt-mocha-cli');
    grunt.loadNpmTasks('grunt-bump');

    grunt.initConfig({
        jshint: {
            all: ['{lib,test}/**/*.js', 'index.js', '!test/fixtures/*.js'],
            options: {
                jshintrc: '.jshintrc'
            }
        },

        jscs: {
            src: {
                options: {
                    config: '.jscs.json'
                },
                files: {
                    src: ['*.{js,json}', '{lib,test}/**/*.js', '!test/fixtures/custom_marker_name.js']
                }
            }
        },

        clean: {
            tmp: ['tmp']
        },

        watch: {
            test: {
                files: ['lib/**.js', 'test/**/*.{js,coffee}'],
                tasks: ['test']
            }
        },

        mochacli: {
            options: {
                files: 'test/*_test.coffee',
                compilers: ['coffee:coffee-script/register']
            },
            spec: {
                options: {
                    reporter: 'spec'
                }
            }
        },

        bump: {
            options: {
                files: ['package.json'],
                commitFiles: ['-a'],
                pushTo: 'origin'
            }
        }
    });

    grunt.registerTask('default', ['test']);
    grunt.registerTask('build', ['clean', 'jshint', 'jscs']);
    grunt.registerTask('test', ['build', 'mochacli']);
};
<commit_msg>Ignore JSCS for fixtures.<commit_after>module.exports = function (grunt) {
    grunt.loadNpmTasks('grunt-contrib-clean');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-jscs-checker');
    grunt.loadNpmTasks('grunt-mocha-cli');
    grunt.loadNpmTasks('grunt-bump');

    grunt.initConfig({
        jshint: {
            all: ['{lib,test}/**/*.js', 'index.js', '!test/fixtures/*.js'],
            options: {
                jshintrc: '.jshintrc'
            }
        },

        jscs: {
            src: {
                options: {
                    config: '.jscs.json'
                },
                files: {
                    src: ['*.{js,json}', '{lib,test}/**/*.js', '!test/fixtures/*.js']
                }
            }
        },

        clean: {
            tmp: ['tmp']
        },

        watch: {
            test: {
                files: ['lib/**.js', 'test/**/*.{js,coffee}'],
                tasks: ['test']
            }
        },

        mochacli: {
            options: {
                files: 'test/*_test.coffee',
                compilers: ['coffee:coffee-script/register']
            },
            spec: {
                options: {
                    reporter: 'spec'
                }
            }
        },

        bump: {
            options: {
                files: ['package.json'],
                commitFiles: ['-a'],
                pushTo: 'origin'
            }
        }
    });

    grunt.registerTask('default', ['test']);
    grunt.registerTask('build', ['clean', 'jshint', 'jscs']);
    grunt.registerTask('test', ['build', 'mochacli']);
};
<|endoftext|>


<commit_before>var xmlHttpRequest;
var startws; // ゲームの開始ボタンを押すまでのWebSocket変数
var updatews; // ゲームプレイ中のWebSocket変数
var myName; // 自分のuser名
var userList;
var playerFlag; // 書き手かどうかの判別
var LOCATION = "localhost:8080/isp2";
// "ecl.info.kindai.ac.jp/16/isp2/warup/servlet/B17";
// "localhost:8080/isp2";
// School:

function checkStartRequest() {
    // 開始ボタンのレスポンス処理部分
    if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
        receiveStartResponse();
    }
}

// 返信データの処理
function receiveStartResponse() {
    var response = JSON.parse(xmlHttpRequest.responseText);
    myName = response.userName;
    if (!myName) {
        // alert("プレイヤー名を入力してからアクセスしてください");
        location.replace('index.html');
    }
    sendToStartWebSocket(myName);
}

function sendToStartWebSocket(userName) {
    startws = new WebSocket('ws://' + LOCATION + '/project/drawwordchain/startbroadcast');
    startws.onopen = function() {
        startws.send(userName);
    };

    startws.onmessage = function(receive) {
        userList = (receive.data).split(",");
        console.log("startwsのonmessage");
        var userAreaElement = document.getElementById("user_name");

        // データの削除
        while (userAreaElement.lastChild) {
            userAreaElement.removeChild(userAreaElement.lastChild);
        }

        // プレイヤーの挿入
        userList.forEach(function(user) {
            var userElement = document.createElement("div");
            userElement.appendChild(document.createTextNode(user));
            userAreaElement.appendChild(userElement);
            // userAreaElement.appendChild(userElement);
            // userElement.innerHTML = user;
        });
    };
}

function sendToStartServlet() {
    var url = "start";
    xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.onreadystatechange = checkStartRequest;
    xmlHttpRequest.open("GET", url, true);
    xmlHttpRequest.send(null);
}

// ページ読み込み時
window.addEventListener("load", function() {

    // サーブレットからユーザ名を取得
    sendToStartServlet();

    // 開始ボタンのEventListener
    document.getElementById("start_button").addEventListener("click", function () {
        updatews = new WebSocket('ws://' + LOCATION + '/project/drawwordchain/updatebroadcast');

        updatews.onopen = function() {
            // userListJson = a", "b", "c"
            var userListJson = "";

            for(var i = 0; i < userList.length; i++) {
                userListJson += "\""+userList[i]+"\"";
                if (i == userList.length - 1) {
                } else {
                    userListJson += ",";
                }
            }

            // json = {"playerName":"myName","userList":["test","test2"],"imgName":"","img":""}
            var json = "{\"playerName\": \""+myName+"\",\"userList\":["+userListJson+"],\"imgName\": \"\",\"img\": \"\"}";
            updatews.send(json);
        };

        updatews.onmessage = function(receive) {
            console.log("updatewsのonmessage");
            // receive.data = {"playerName" : "Name", "firstChar" : "文字"}
            var response = JSON.parse(receive.data);
            //firstCharをplay_displayの最初に表示
            var firstChar = response.firstChar;
            var playerName = response.playerName;

            //初めの文字を表示
            var element = document.createElement('p');
            element.style.cssText="font-size:100pt;"+"display:table-cell;"+"vertical-align:middle;";
            element.appendChild(document.createTextNode("["+firstChar+"]"));
            document.getElementById("pict_display").appendChild(element);

            //矢印を表示
            var arrow = document.createElement('p');
            arrow.style.cssText="display:table-cell;"+"vertical-align:middle;"+"font-size:100px;"+"color:white;";
            var arrowText = document.createTextNode("→");
            arrow.appendChild(arrowText);
            document.getElementById('pict_display').appendChild(arrow);

            // 以下やること
            // 4行目:myName==playerNameを照合して一致したらプレイヤー名の色を替える処理に変更させる
            // 開始ボタンを無効にする
            // キャンバス初期化
            // playerFlagをtrueにする．

            // element.appendChild(document.createTextNode(playerName));
            // document.getElementById("pict_display").appendChild(element);
        };
    }, false);

    // 送信ボタンのEventListener
    document.getElementById("send_button").addEventListener("click",function () {
        // 絵のタイトル未入力の際の動作
        var drawWord = document.getElementById("word");
        if (!drawWord.value) {
            alert("絵の名前を入力してください");
            return;
        }
        // textformに日本語のみが入力されているかの判定
        // for(var i=0;i<drawWord.value.length;i++){
        if (!(drawWord.value.match(/^[\u3040-\u309F]+$/)) && !drawWord.value.match(/ー/)) {
            alert("平仮名のみで入力してください");
            return;
        }
        var lastWord = drawWord.value.slice(-1);
        if (lastWord.match(/ん/)) {
            alert("勝手にしりとりを終わらせないでください");
            return;
        }
        // }

        // プレイヤー名の中に絵のタイトルを表示(一時的なもの)
        var userName = document.getElementById("user_name");
        // //---------------あとで消す----------------------------
        // var drawTitle = document.createElement('div');
        // var text = document.createTextNode(drawWord.value+"→");
        // drawTitle.appendChild(text);
        // userName.appendChild(drawTitle);
        // //----------------------------------------------------

        // 画像->base64データに変換
        var data = canvas.toDataURL("image/jpeg");
        // alert(data);

        // 画像送信用
        // json = {"playerName":"myName","userList":[],"imgName":"絵の名前","img":"絵のデータ"}
        var json = "{\"playerName\": \""+myName+"\",\"userList\":[],\"imgName\": \"drawWord.value\",\"img\": \""+data+"\"}";
        updatews.send(json);

        // imgデータの受取
        updatews.onmessage = function(receive) {
            var response = JSON.parse(receive.data);
            var imgData = response.img;
            var img = new Image();
            img.src = imgData;
            img.width = 250;
            img.height = 250;

            var newImg = document.createElement('p');
            newImg.style.cssText="display:table-cell;"+"vertical-align:middle;"+"border: 1px solid black;";
            newImg.appendChild(img);
            document.getElementById('pict_display').appendChild(newImg);
            //画像と画像の間に矢印
            var arrow = document.createElement('p');
            arrow.style.cssText="display:table-cell;"+"vertical-align:middle;"+"font-size:100px;"+"color:white;";
            var arrowText = document.createTextNode("→");
            arrow.appendChild(arrowText);
            document.getElementById('pict_display').appendChild(arrow);
        };

        //がめんクリア
        ctx.beginPath();
        ctx.fillStyle = "#f5f5f5";
        ctx.globalAlpha = 1.0;
        ctx.fillRect(0, 0, 500, 500);

        //
        // var image = new Image();
        // image.src = data;
        // image.onload = function() {
        //   ctx2.drawImage(image, 0, 0);
        // }

        // 画像送信の記述なし
    }, false);

}, false);

// // ページ終了時
// window.addEventListener("beforeunload", function() {
//
// }, false);
<commit_msg>main.jsの不要処理(コメントアウト部分)を削除<commit_after>var xmlHttpRequest;
var startws; // ゲームの開始ボタンを押すまでのWebSocket変数
var updatews; // ゲームプレイ中のWebSocket変数
var myName; // 自分のuser名
var userList;
var playerFlag; // 書き手かどうかの判別
var LOCATION = "localhost:8080/isp2";
// "ecl.info.kindai.ac.jp/16/isp2/warup/servlet/B17";
// "localhost:8080/isp2";
// School:

function checkStartRequest() {
    // 開始ボタンのレスポンス処理部分
    if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
        receiveStartResponse();
    }
}

// 返信データの処理
function receiveStartResponse() {
    var response = JSON.parse(xmlHttpRequest.responseText);
    myName = response.userName;
    if (!myName) {
        // alert("プレイヤー名を入力してからアクセスしてください");
        location.replace('index.html');
    }
    sendToStartWebSocket(myName);
}

function sendToStartWebSocket(userName) {
    startws = new WebSocket('ws://' + LOCATION + '/project/drawwordchain/startbroadcast');
    startws.onopen = function() {
        startws.send(userName);
    };

    startws.onmessage = function(receive) {
        userList = (receive.data).split(",");
        console.log("startwsのonmessage");
        var userAreaElement = document.getElementById("user_name");

        // データの削除
        while (userAreaElement.lastChild) {
            userAreaElement.removeChild(userAreaElement.lastChild);
        }

        // プレイヤーの挿入
        userList.forEach(function(user) {
            var userElement = document.createElement("div");
            userElement.appendChild(document.createTextNode(user));
            userAreaElement.appendChild(userElement);
            // userAreaElement.appendChild(userElement);
            // userElement.innerHTML = user;
        });
    };
}

function sendToStartServlet() {
    var url = "start";
    xmlHttpRequest = new XMLHttpRequest();
    xmlHttpRequest.onreadystatechange = checkStartRequest;
    xmlHttpRequest.open("GET", url, true);
    xmlHttpRequest.send(null);
}

// ページ読み込み時
window.addEventListener("load", function() {

    // サーブレットからユーザ名を取得
    sendToStartServlet();

    // 開始ボタンのEventListener
    document.getElementById("start_button").addEventListener("click", function () {
        updatews = new WebSocket('ws://' + LOCATION + '/project/drawwordchain/updatebroadcast');

        updatews.onopen = function() {
            // userListJson = a", "b", "c"
            var userListJson = "";

            for(var i = 0; i < userList.length; i++) {
                userListJson += "\""+userList[i]+"\"";
                if (i == userList.length - 1) {
                } else {
                    userListJson += ",";
                }
            }

            // json = {"playerName":"myName","userList":["test","test2"],"imgName":"","img":""}
            var json = "{\"playerName\": \""+myName+"\",\"userList\":["+userListJson+"],\"imgName\": \"\",\"img\": \"\"}";
            updatews.send(json);
        };

        updatews.onmessage = function(receive) {
            console.log("updatewsのonmessage");
            // receive.data = {"playerName" : "Name", "firstChar" : "文字"}
            var response = JSON.parse(receive.data);
            //firstCharをplay_displayの最初に表示
            var firstChar = response.firstChar;
            var playerName = response.playerName;

            //初めの文字を表示
            var element = document.createElement('p');
            element.style.cssText="font-size:100pt;"+"display:table-cell;"+"vertical-align:middle;";
            element.appendChild(document.createTextNode("["+firstChar+"]"));
            document.getElementById("pict_display").appendChild(element);

            //矢印を表示
            var arrow = document.createElement('p');
            arrow.style.cssText="display:table-cell;"+"vertical-align:middle;"+"font-size:100px;"+"color:white;";
            var arrowText = document.createTextNode("→");
            arrow.appendChild(arrowText);
            document.getElementById('pict_display').appendChild(arrow);

            // 以下やること
            // 4行目:myName==playerNameを照合して一致したらプレイヤー名の色を替える処理に変更させる
            // 開始ボタンを無効にする
            // キャンバス初期化
            // playerFlagをtrueにする．

            // element.appendChild(document.createTextNode(playerName));
            // document.getElementById("pict_display").appendChild(element);
        };
    }, false);

    // 送信ボタンのEventListener
    document.getElementById("send_button").addEventListener("click",function () {
        // 絵のタイトル未入力の際の動作
        var drawWord = document.getElementById("word");
        if (!drawWord.value) {
            alert("絵の名前を入力してください");
            return;
        }
        // textformに日本語のみが入力されているかの判定
        // for(var i=0;i<drawWord.value.length;i++){
        if (!(drawWord.value.match(/^[\u3040-\u309F]+$/)) && !drawWord.value.match(/ー/)) {
            alert("平仮名のみで入力してください");
            return;
        }
        var lastWord = drawWord.value.slice(-1);
        if (lastWord.match(/ん/)) {
            alert("勝手にしりとりを終わらせないでください");
            return;
        }
        // }

        // プレイヤー名の中に絵のタイトルを表示(一時的なもの)
        var userName = document.getElementById("user_name");
        // //---------------あとで消す----------------------------
        // var drawTitle = document.createElement('div');
        // var text = document.createTextNode(drawWord.value+"→");
        // drawTitle.appendChild(text);
        // userName.appendChild(drawTitle);
        // //----------------------------------------------------

        // 画像->base64データに変換
        var data = canvas.toDataURL("image/jpeg");
        // alert(data);

        // 画像送信用
        // json = {"playerName":"myName","userList":[],"imgName":"絵の名前","img":"絵のデータ"}
        var json = "{\"playerName\": \""+myName+"\",\"userList\":[],\"imgName\": \"drawWord.value\",\"img\": \""+data+"\"}";
        updatews.send(json);

        // imgデータの受取
        updatews.onmessage = function(receive) {
            var response = JSON.parse(receive.data);
            var imgData = response.img;
            var img = new Image();
            img.src = imgData;
            img.width = 250;
            img.height = 250;

            var newImg = document.createElement('p');
            newImg.style.cssText="display:table-cell;"+"vertical-align:middle;"+"border: 1px solid black;";
            newImg.appendChild(img);
            document.getElementById('pict_display').appendChild(newImg);
            //画像と画像の間に矢印
            var arrow = document.createElement('p');
            arrow.style.cssText="display:table-cell;"+"vertical-align:middle;"+"font-size:100px;"+"color:white;";
            var arrowText = document.createTextNode("→");
            arrow.appendChild(arrowText);
            document.getElementById('pict_display').appendChild(arrow);
        };

        //がめんクリア
        ctx.beginPath();
        ctx.fillStyle = "#f5f5f5";
        ctx.globalAlpha = 1.0;
        ctx.fillRect(0, 0, 500, 500);

        // 画像送信の記述なし
    }, false);

}, false);

// // ページ終了時
// window.addEventListener("beforeunload", function() {
//
// }, false);
<|endoftext|>


<commit_before>"use strict";

var _ = require('underscore');

module.exports = function(grunt) {

    let additionalMetadata;
    let allCweDescriptions;

    function getAllRules() {
        const contribRules = grunt.file.expand('dist/build/*Rule.js');
        const baseRules = grunt.file.expand('node_modules/tslint/lib/rules/*Rule.js');
        return contribRules.concat(baseRules);
    }

    function hash(input) {
        // initialized with a prime number
        let hash = 31;
        let i = 0;
        for (i = 0; i < input.length; i++) {
            // multiply by prime so to get the better distribution of the values
            hash = 31 * hash + input.charCodeAt(i); // run the hash function on all chars
            hash = hash | 0; // convert to 32 bit signed integer
        }
        return Math.abs(hash).toString(32).toUpperCase();
    }

    function getMetadataFromFile(ruleFile) {
        const moduleName = './' + ruleFile.replace(/\.js$/, '');
        const module = require(moduleName);
        if (module.Rule.metadata == null) {
            grunt.fail.warn('No metadata found for ' + moduleName);
            return;
        }
        return module.Rule.metadata;
    }

    function createCweDescription(metadata) {
        allCweDescriptions = allCweDescriptions || grunt.file.readJSON('./cwe_descriptions.json', {encoding: 'UTF-8'});

        const cwe = getMetadataValue(metadata, 'commonWeaknessEnumeration', true, true);
        if (cwe === '') {
            return '';
        }

        let result = '';
        cwe.split(',').forEach(function (cweNumber) {
            cweNumber = cweNumber.trim();
            const description = allCweDescriptions[cweNumber];
            if (description == null) {
                grunt.fail.warn(`Cannot find description of ${cweNumber} for rule ${metadata['ruleName']} in cwe_descriptions.json`)
            }
            if (result !== '') {
                result = result + '\n';
            }
            result = result + `CWE ${cweNumber} - ${description}`
        });
        if (result !== '') {
            return '"' + result + '"';
        }
        return result;
    }

    function getMetadataValue(metadata, name, allowEmpty, doNotEscape) {
        additionalMetadata = additionalMetadata || grunt.file.readJSON('./additional_rule_metadata.json', {encoding: 'UTF-8'});

        let value = metadata[name];
        if (value == null) {
            if (additionalMetadata[metadata.ruleName] == null) {
                if (allowEmpty == false) {
                    grunt.fail.warn(`Could not read metadata for rule ${metadata.ruleName} from additional_rule_metadata.json`);
                } else {
                    return '';
                }
            }
            value = additionalMetadata[metadata.ruleName][name];
            if (value == null) {
                if (allowEmpty == false) {
                    grunt.fail.warn(`Could not read attribute ${name} of rule ${metadata.ruleName}`);
                }
                return '';
            }
        }
        if (doNotEscape == true) {
            return value;
        }
        value = value.replace(/^\n+/, ''); // strip leading newlines
        value = value.replace(/\n/, ' '); // convert newlines
        if (value.indexOf(',') > -1) {
            return '"' + value + '"';
        } else {
            return value;
        }
    }

    function camelize(input) {
        return _(input).reduce(function(memo, element) {
            if (element.toLowerCase() === element) {
                memo = memo + element;
            } else {
                memo = memo + '-' + element.toLowerCase();
            }
            return memo;
        }, '');
    }

    function getAllRuleNames(options) {
        options = options || { skipTsLintRules: false }

        var convertToRuleNames = function(filename) {
            filename = filename
                .replace(/Rule\..*/, '')  // file extension plus Rule name
                .replace(/.*\//, '');     // leading path
            return camelize(filename);
        };

        var contribRules = _(grunt.file.expand('src/*Rule.ts')).map(convertToRuleNames);
        var baseRules = [];
        if (!options.skipTsLintRules) {
            baseRules = _(grunt.file.expand('node_modules/tslint/lib/rules/*Rule.js')).map(convertToRuleNames);
        }
        var allRules = baseRules.concat(contribRules);
        allRules.sort();
        return allRules;
    }

    function getAllFormatterNames() {

        var convertToRuleNames = function(filename) {
            filename = filename
                .replace(/Formatter\..*/, '')  // file extension plus Rule name
                .replace(/.*\//, '');     // leading path
            return camelize(filename);
        };

        var formatters = _(grunt.file.expand('src/*Formatter.ts')).map(convertToRuleNames);
        formatters.sort();
        return formatters;
    }

    function camelCase(input) {
        return input.toLowerCase().replace(/-(.)/g, function(match, group1) {
            return group1.toUpperCase();
        });
    }

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        clean: {
            src: ['dist'],
            options: {
                force: true
            }
        },

        copy: {
            options: {
                encoding: 'UTF-8'
            },
            package: {
                files: [
                    {
                        expand: true,
                        cwd: 'dist/src',
                        src: [
                            '**/*.js',
                            '**/*.json',
                            '!tests/**',
                            'tests/TestHelper.js',
                            'tests/TestHelper.d.ts',
                            '!references.js'
                        ],
                        dest: 'dist/build'
                    },
                    {
                        expand: true,
                        cwd: '.',
                        src: [
                            'README.md',
                            'recommended_ruleset.js'
                        ],
                        dest: 'dist/build'
                    }
                ]
            },
            json: {
                expand: true,
                cwd: '.',
                src: ['src/**/*.json'],
                dest: 'dist'
            }
        },

        mochaTest: {
            test: {
                src: ['dist/src/tests/**/*.js']
            }
        },

        ts: {
            default: {
                src: [
                    './src/**/*.ts{,x}'
                ],
                outDir: 'dist/src',
                options: {
                    module: 'commonjs',
                    target: 'es5',
                    declaration: true,
                    failOnTypeErrors: true,
                    jsx: 'react'
                }
            },
            'test-data': {
                src: [
                    './test-data/**/*.ts{,x}'
                ],
                outDir: 'dist/test-data',
                options: {
                    module: 'commonjs',
                    target: 'es5',
                    declaration: false,
                    failOnTypeErrors: true,
                    jsx: 'react'
                }
            }
        },

        tslint: {
            options: {
                rulesDirectory: 'dist/src'
            },
            prod: {
                options: {
                    configuration: grunt.file.readJSON("tslint.json", { encoding: 'UTF-8' })
                },
                files: {
                    src: [
                        'src/**/*.ts',
                        '!src/tests/**'
                    ]
                }
            },
            tests: {
                options: {
                    configuration: (function() {
                        let tslintJson = grunt.file.readJSON("tslint.json", { encoding: 'UTF-8' });
                        tslintJson.rules['no-multiline-string'] = false;
                        tslintJson.rules['quotemark'] = false;
                        tslintJson.rules['max-func-body-length'] = false;
                        return tslintJson;
                    })()
                },
                files: {
                    src: [
                        'src/tests/**/*.ts',
                        '!src/tests/references.ts'
                    ]
                }
            }
        },

        watch: {
            scripts: {
                files: [
                    './src/**/*.ts',
                    './tests/**/*.ts'
                ],
                tasks: [
                    'ts',
                    'mochaTest',
                    'tslint'
                ]
            }
        }

    });

    require('load-grunt-tasks')(grunt); // loads all grunt-* npm tasks
    require('time-grunt')(grunt);

    grunt.registerTask('create-package-json-for-npm', 'A task that creates a package.json file for the npm module', function () {
        var basePackageJson = grunt.file.readJSON('package.json', { encoding: 'UTF-8' });
        delete basePackageJson.devDependencies;
        grunt.file.write('dist/build/package.json', JSON.stringify(basePackageJson, null, 2), { encoding: 'UTF-8' });
    });

    grunt.registerTask('validate-debug-mode', 'A task that makes sure ErrorTolerantWalker.DEBUG is false', function () {
        // DON'T MAKE A RELEASE IN DEBUG MODE
        var fileText = grunt.file.read('src/utils/ErrorTolerantWalker.ts', { encoding: 'UTF-8' });
        if (fileText.indexOf('DEBUG: boolean = false') === -1) {
            grunt.fail.warn('ErrorTolerantWalker.DEBUG is turned on. Turn off debugging to make a release');
        }
    });

    grunt.registerTask('validate-documentation', 'A task that validates that all rules defined in src are documented in README.md\n' +
        'and validates that the package.json version is the same version defined in README.md', function () {

        var readmeText = grunt.file.read('README.md', { encoding: 'UTF-8' });
        var packageJson = grunt.file.readJSON('package.json', { encoding: 'UTF-8' });
        getAllRuleNames({ skipTsLintRules: true }).forEach(function(ruleName) {
            if (readmeText.indexOf(ruleName) === -1) {
                grunt.fail.warn('A rule was found that is not documented in README.md: ' + ruleName);
            }
        });
        getAllFormatterNames().forEach(function(formatterName) {
            if (readmeText.indexOf(formatterName) === -1) {
                grunt.fail.warn('A formatter was found that is not documented in README.md: ' + formatterName);
            }
        });

        if (readmeText.indexOf('\nVersion ' + packageJson.version + ' ') === -1) {
            grunt.fail.warn('Version not documented in README.md correctly.\n' +
                'package.json declares: ' + packageJson.version + '\n' +
                'README.md declares something different.');
        }
    });

    grunt.registerTask('validate-config', 'A task that makes sure all the rules in the project are defined to run during the build.', function () {

        var tslintConfig = grunt.file.readJSON('tslint.json', { encoding: 'UTF-8' });
        var rulesToSkip = {
            'no-unexternalized-strings': true,
            'object-literal-key-quotes': true,
            'no-relative-imports': true,
            'no-empty-line-after-opening-brace': true
        };
        var errors = [];
        getAllRuleNames().forEach(function(ruleName) {
            if (rulesToSkip[ruleName]) {
                return;
            }
            if (tslintConfig.rules[ruleName] !== true && tslintConfig.rules[ruleName] !== false) {
                if (tslintConfig.rules[ruleName] == null || tslintConfig.rules[ruleName][0] !== true) {
                    errors.push('A rule was found that is not enabled on the project: ' + ruleName);
                }
            }
        });

        if (errors.length > 0) {
            grunt.fail.warn(errors.join('\n'));
        }
    });

    grunt.registerTask('generate-sdl-report', 'A task that generates an SDL report in csv format', function () {

        const rows = [];
        const resolution = 'See description on the tslint or tslint-microsoft-contrib website';
        const procedure = 'TSLint Procedure';
        const header = 'Title,Description,ErrorID,Tool,IssueClass,IssueType,SDL Bug Bar Severity,' +
            'SDL Level,Resolution,SDL Procedure,CWE,CWE Description';
        getAllRules().forEach(function(ruleFile) {
            const metadata = getMetadataFromFile(ruleFile);

            const issueClass = getMetadataValue(metadata, 'issueClass');
            if (issueClass === 'Ignored') {
                return;
            }
            const ruleName = getMetadataValue(metadata, 'ruleName');
            const errorId = 'TSLINT' + hash(ruleName);
            const issueType = getMetadataValue(metadata, 'issueType');
            const severity = getMetadataValue(metadata, 'severity');
            const level = getMetadataValue(metadata, 'level');
            const description = getMetadataValue(metadata, 'description');
            const cwe = getMetadataValue(metadata, 'commonWeaknessEnumeration', true, false);
            const cweDescription = createCweDescription(metadata);

            const row = `${ruleName},${description},${errorId},tslint,${issueClass},${issueType},${severity},${level},${resolution},${procedure},${cwe},${cweDescription}`;
            rows.push(row);
        });
        rows.sort();
        rows.unshift(header);
        grunt.file.write('tslint-warnings.csv', rows.join('\n'), {encoding: 'UTF-8'});

    });

    grunt.registerTask('generate-recommendations', 'A task that generates the recommended_ruleset.js file', function () {

        const groupedRows = {};

        getAllRules().forEach(function(ruleFile) {
            const metadata = getMetadataFromFile(ruleFile);

            const groupName = getMetadataValue(metadata, 'group');
            if (groupName === 'Ignored') {
                return;
            }
            if (groupedRows[groupName] == null) {
                groupedRows[groupName] = [];
            }

            let recommendation = getMetadataValue(metadata, 'recommendation', true, true);
            if (recommendation === '') {
                recommendation = 'true,';
            }
            const ruleName = getMetadataValue(metadata, 'ruleName');
            groupedRows[groupName].push(`        "${ruleName}": ${recommendation}`);
        });

        _.values(groupedRows).forEach(function (element) { element.sort(); });

        let data = grunt.file.read('./templates/recommended_ruleset.js.snippet', {encoding: 'UTF-8'});
        data = data.replace('%security_rules%',       groupedRows['Security'].join('\n'));
        data = data.replace('%correctness_rules%',    groupedRows['Correctness'].join('\n'));
        data = data.replace('%clarity_rules%',        groupedRows['Clarity'].join('\n'));
        data = data.replace('%whitespace_rules%',     groupedRows['Whitespace'].join('\n'));
        data = data.replace('%configurable_rules%',   groupedRows['Configurable'].join('\n'));
        data = data.replace('%deprecated_rules%',     groupedRows['Deprecated'].join('\n'));
        data = data.replace('%accessibilityy_rules%', groupedRows['Accessibility'].join('\n'));
        grunt.file.write('recommended_ruleset.js', data, {encoding: 'UTF-8'});
    });

    grunt.registerTask('generate-default-tslint-json', 'A task that converts recommended_ruleset.js to ./dist/build/tslint.json', function () {
        const data = require('./recommended_ruleset.js');
        grunt.file.write('./dist/build/tslint.json', JSON.stringify(data, null, 2), {encoding: 'UTF-8'});
    });

    grunt.registerTask('create-rule', 'A task that creates a new rule from the rule templates. --rule-name parameter required', function () {

        function applyTemplates(source) {
            return source.replace(/%RULE_NAME%/gm, ruleName)
                .replace(/%RULE_FILE_NAME%/gm, ruleFile)
                .replace(/%WALKER_NAME%/gm, walkerName);
        }

        var ruleName = grunt.option('rule-name');
        if (!ruleName) {
            grunt.fail.warn('--rule-name parameter is required');
        } else {

            var ruleFile = camelCase(ruleName) + 'Rule';
            var sourceFileName = './src/' + ruleFile + '.ts';
            var testFileName = './src/tests/' + ruleFile.charAt(0).toUpperCase() + ruleFile.substr(1) + 'Tests.ts';
            var walkerName = ruleFile.charAt(0).toUpperCase() + ruleFile.substr(1) + 'Walker';

            var ruleTemplateText = grunt.file.read('./templates/rule.snippet', {encoding: 'UTF-8'});
            var testTemplateText = grunt.file.read('./templates/rule-tests.snippet', {encoding: 'UTF-8'});

            grunt.file.write(sourceFileName, applyTemplates(ruleTemplateText), {encoding: 'UTF-8'});
            grunt.file.write(testFileName, applyTemplates(testTemplateText), {encoding: 'UTF-8'});

            var currentRuleset = grunt.file.readJSON('./tslint.json', {encoding: 'UTF-8'});
            currentRuleset.rules[ruleName] = true;
            grunt.file.write('./tslint.json', JSON.stringify(currentRuleset, null, 2), {encoding: 'UTF-8'});
        }
    });

    grunt.registerTask('all', 'Performs a cleanup and a full build with all tasks', [
        'clean',
        'copy:json',
        'ts',
        'mochaTest',
        'tslint',
        'validate-documentation',
        'validate-config',
        'validate-debug-mode',
        'copy:package',
        'generate-recommendations',
        'generate-default-tslint-json',
        'generate-sdl-report',
        'create-package-json-for-npm'
    ]);

    grunt.registerTask('default', ['all']);

};
<commit_msg>[#268] Make extends tslint.json easier by adding "rulesDirectory": "./".<commit_after>"use strict";

var _ = require('underscore');

module.exports = function(grunt) {

    let additionalMetadata;
    let allCweDescriptions;

    function getAllRules() {
        const contribRules = grunt.file.expand('dist/build/*Rule.js');
        const baseRules = grunt.file.expand('node_modules/tslint/lib/rules/*Rule.js');
        return contribRules.concat(baseRules);
    }

    function hash(input) {
        // initialized with a prime number
        let hash = 31;
        let i = 0;
        for (i = 0; i < input.length; i++) {
            // multiply by prime so to get the better distribution of the values
            hash = 31 * hash + input.charCodeAt(i); // run the hash function on all chars
            hash = hash | 0; // convert to 32 bit signed integer
        }
        return Math.abs(hash).toString(32).toUpperCase();
    }

    function getMetadataFromFile(ruleFile) {
        const moduleName = './' + ruleFile.replace(/\.js$/, '');
        const module = require(moduleName);
        if (module.Rule.metadata == null) {
            grunt.fail.warn('No metadata found for ' + moduleName);
            return;
        }
        return module.Rule.metadata;
    }

    function createCweDescription(metadata) {
        allCweDescriptions = allCweDescriptions || grunt.file.readJSON('./cwe_descriptions.json', {encoding: 'UTF-8'});

        const cwe = getMetadataValue(metadata, 'commonWeaknessEnumeration', true, true);
        if (cwe === '') {
            return '';
        }

        let result = '';
        cwe.split(',').forEach(function (cweNumber) {
            cweNumber = cweNumber.trim();
            const description = allCweDescriptions[cweNumber];
            if (description == null) {
                grunt.fail.warn(`Cannot find description of ${cweNumber} for rule ${metadata['ruleName']} in cwe_descriptions.json`)
            }
            if (result !== '') {
                result = result + '\n';
            }
            result = result + `CWE ${cweNumber} - ${description}`
        });
        if (result !== '') {
            return '"' + result + '"';
        }
        return result;
    }

    function getMetadataValue(metadata, name, allowEmpty, doNotEscape) {
        additionalMetadata = additionalMetadata || grunt.file.readJSON('./additional_rule_metadata.json', {encoding: 'UTF-8'});

        let value = metadata[name];
        if (value == null) {
            if (additionalMetadata[metadata.ruleName] == null) {
                if (allowEmpty == false) {
                    grunt.fail.warn(`Could not read metadata for rule ${metadata.ruleName} from additional_rule_metadata.json`);
                } else {
                    return '';
                }
            }
            value = additionalMetadata[metadata.ruleName][name];
            if (value == null) {
                if (allowEmpty == false) {
                    grunt.fail.warn(`Could not read attribute ${name} of rule ${metadata.ruleName}`);
                }
                return '';
            }
        }
        if (doNotEscape == true) {
            return value;
        }
        value = value.replace(/^\n+/, ''); // strip leading newlines
        value = value.replace(/\n/, ' '); // convert newlines
        if (value.indexOf(',') > -1) {
            return '"' + value + '"';
        } else {
            return value;
        }
    }

    function camelize(input) {
        return _(input).reduce(function(memo, element) {
            if (element.toLowerCase() === element) {
                memo = memo + element;
            } else {
                memo = memo + '-' + element.toLowerCase();
            }
            return memo;
        }, '');
    }

    function getAllRuleNames(options) {
        options = options || { skipTsLintRules: false }

        var convertToRuleNames = function(filename) {
            filename = filename
                .replace(/Rule\..*/, '')  // file extension plus Rule name
                .replace(/.*\//, '');     // leading path
            return camelize(filename);
        };

        var contribRules = _(grunt.file.expand('src/*Rule.ts')).map(convertToRuleNames);
        var baseRules = [];
        if (!options.skipTsLintRules) {
            baseRules = _(grunt.file.expand('node_modules/tslint/lib/rules/*Rule.js')).map(convertToRuleNames);
        }
        var allRules = baseRules.concat(contribRules);
        allRules.sort();
        return allRules;
    }

    function getAllFormatterNames() {

        var convertToRuleNames = function(filename) {
            filename = filename
                .replace(/Formatter\..*/, '')  // file extension plus Rule name
                .replace(/.*\//, '');     // leading path
            return camelize(filename);
        };

        var formatters = _(grunt.file.expand('src/*Formatter.ts')).map(convertToRuleNames);
        formatters.sort();
        return formatters;
    }

    function camelCase(input) {
        return input.toLowerCase().replace(/-(.)/g, function(match, group1) {
            return group1.toUpperCase();
        });
    }

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        clean: {
            src: ['dist'],
            options: {
                force: true
            }
        },

        copy: {
            options: {
                encoding: 'UTF-8'
            },
            package: {
                files: [
                    {
                        expand: true,
                        cwd: 'dist/src',
                        src: [
                            '**/*.js',
                            '**/*.json',
                            '!tests/**',
                            'tests/TestHelper.js',
                            'tests/TestHelper.d.ts',
                            '!references.js'
                        ],
                        dest: 'dist/build'
                    },
                    {
                        expand: true,
                        cwd: '.',
                        src: [
                            'README.md',
                            'recommended_ruleset.js'
                        ],
                        dest: 'dist/build'
                    }
                ]
            },
            json: {
                expand: true,
                cwd: '.',
                src: ['src/**/*.json'],
                dest: 'dist'
            }
        },

        mochaTest: {
            test: {
                src: ['dist/src/tests/**/*.js']
            }
        },

        ts: {
            default: {
                src: [
                    './src/**/*.ts{,x}'
                ],
                outDir: 'dist/src',
                options: {
                    module: 'commonjs',
                    target: 'es5',
                    declaration: true,
                    failOnTypeErrors: true,
                    jsx: 'react'
                }
            },
            'test-data': {
                src: [
                    './test-data/**/*.ts{,x}'
                ],
                outDir: 'dist/test-data',
                options: {
                    module: 'commonjs',
                    target: 'es5',
                    declaration: false,
                    failOnTypeErrors: true,
                    jsx: 'react'
                }
            }
        },

        tslint: {
            options: {
                rulesDirectory: 'dist/src'
            },
            prod: {
                options: {
                    configuration: grunt.file.readJSON("tslint.json", { encoding: 'UTF-8' })
                },
                files: {
                    src: [
                        'src/**/*.ts',
                        '!src/tests/**'
                    ]
                }
            },
            tests: {
                options: {
                    configuration: (function() {
                        let tslintJson = grunt.file.readJSON("tslint.json", { encoding: 'UTF-8' });
                        tslintJson.rules['no-multiline-string'] = false;
                        tslintJson.rules['quotemark'] = false;
                        tslintJson.rules['max-func-body-length'] = false;
                        return tslintJson;
                    })()
                },
                files: {
                    src: [
                        'src/tests/**/*.ts',
                        '!src/tests/references.ts'
                    ]
                }
            }
        },

        watch: {
            scripts: {
                files: [
                    './src/**/*.ts',
                    './tests/**/*.ts'
                ],
                tasks: [
                    'ts',
                    'mochaTest',
                    'tslint'
                ]
            }
        }

    });

    require('load-grunt-tasks')(grunt); // loads all grunt-* npm tasks
    require('time-grunt')(grunt);

    grunt.registerTask('create-package-json-for-npm', 'A task that creates a package.json file for the npm module', function () {
        var basePackageJson = grunt.file.readJSON('package.json', { encoding: 'UTF-8' });
        delete basePackageJson.devDependencies;
        grunt.file.write('dist/build/package.json', JSON.stringify(basePackageJson, null, 2), { encoding: 'UTF-8' });
    });

    grunt.registerTask('validate-debug-mode', 'A task that makes sure ErrorTolerantWalker.DEBUG is false', function () {
        // DON'T MAKE A RELEASE IN DEBUG MODE
        var fileText = grunt.file.read('src/utils/ErrorTolerantWalker.ts', { encoding: 'UTF-8' });
        if (fileText.indexOf('DEBUG: boolean = false') === -1) {
            grunt.fail.warn('ErrorTolerantWalker.DEBUG is turned on. Turn off debugging to make a release');
        }
    });

    grunt.registerTask('validate-documentation', 'A task that validates that all rules defined in src are documented in README.md\n' +
        'and validates that the package.json version is the same version defined in README.md', function () {

        var readmeText = grunt.file.read('README.md', { encoding: 'UTF-8' });
        var packageJson = grunt.file.readJSON('package.json', { encoding: 'UTF-8' });
        getAllRuleNames({ skipTsLintRules: true }).forEach(function(ruleName) {
            if (readmeText.indexOf(ruleName) === -1) {
                grunt.fail.warn('A rule was found that is not documented in README.md: ' + ruleName);
            }
        });
        getAllFormatterNames().forEach(function(formatterName) {
            if (readmeText.indexOf(formatterName) === -1) {
                grunt.fail.warn('A formatter was found that is not documented in README.md: ' + formatterName);
            }
        });

        if (readmeText.indexOf('\nVersion ' + packageJson.version + ' ') === -1) {
            grunt.fail.warn('Version not documented in README.md correctly.\n' +
                'package.json declares: ' + packageJson.version + '\n' +
                'README.md declares something different.');
        }
    });

    grunt.registerTask('validate-config', 'A task that makes sure all the rules in the project are defined to run during the build.', function () {

        var tslintConfig = grunt.file.readJSON('tslint.json', { encoding: 'UTF-8' });
        var rulesToSkip = {
            'no-unexternalized-strings': true,
            'object-literal-key-quotes': true,
            'no-relative-imports': true,
            'no-empty-line-after-opening-brace': true
        };
        var errors = [];
        getAllRuleNames().forEach(function(ruleName) {
            if (rulesToSkip[ruleName]) {
                return;
            }
            if (tslintConfig.rules[ruleName] !== true && tslintConfig.rules[ruleName] !== false) {
                if (tslintConfig.rules[ruleName] == null || tslintConfig.rules[ruleName][0] !== true) {
                    errors.push('A rule was found that is not enabled on the project: ' + ruleName);
                }
            }
        });

        if (errors.length > 0) {
            grunt.fail.warn(errors.join('\n'));
        }
    });

    grunt.registerTask('generate-sdl-report', 'A task that generates an SDL report in csv format', function () {

        const rows = [];
        const resolution = 'See description on the tslint or tslint-microsoft-contrib website';
        const procedure = 'TSLint Procedure';
        const header = 'Title,Description,ErrorID,Tool,IssueClass,IssueType,SDL Bug Bar Severity,' +
            'SDL Level,Resolution,SDL Procedure,CWE,CWE Description';
        getAllRules().forEach(function(ruleFile) {
            const metadata = getMetadataFromFile(ruleFile);

            const issueClass = getMetadataValue(metadata, 'issueClass');
            if (issueClass === 'Ignored') {
                return;
            }
            const ruleName = getMetadataValue(metadata, 'ruleName');
            const errorId = 'TSLINT' + hash(ruleName);
            const issueType = getMetadataValue(metadata, 'issueType');
            const severity = getMetadataValue(metadata, 'severity');
            const level = getMetadataValue(metadata, 'level');
            const description = getMetadataValue(metadata, 'description');
            const cwe = getMetadataValue(metadata, 'commonWeaknessEnumeration', true, false);
            const cweDescription = createCweDescription(metadata);

            const row = `${ruleName},${description},${errorId},tslint,${issueClass},${issueType},${severity},${level},${resolution},${procedure},${cwe},${cweDescription}`;
            rows.push(row);
        });
        rows.sort();
        rows.unshift(header);
        grunt.file.write('tslint-warnings.csv', rows.join('\n'), {encoding: 'UTF-8'});

    });

    grunt.registerTask('generate-recommendations', 'A task that generates the recommended_ruleset.js file', function () {

        const groupedRows = {};

        getAllRules().forEach(function(ruleFile) {
            const metadata = getMetadataFromFile(ruleFile);

            const groupName = getMetadataValue(metadata, 'group');
            if (groupName === 'Ignored') {
                return;
            }
            if (groupedRows[groupName] == null) {
                groupedRows[groupName] = [];
            }

            let recommendation = getMetadataValue(metadata, 'recommendation', true, true);
            if (recommendation === '') {
                recommendation = 'true,';
            }
            const ruleName = getMetadataValue(metadata, 'ruleName');
            groupedRows[groupName].push(`        "${ruleName}": ${recommendation}`);
        });

        _.values(groupedRows).forEach(function (element) { element.sort(); });

        let data = grunt.file.read('./templates/recommended_ruleset.js.snippet', {encoding: 'UTF-8'});
        data = data.replace('%security_rules%',       groupedRows['Security'].join('\n'));
        data = data.replace('%correctness_rules%',    groupedRows['Correctness'].join('\n'));
        data = data.replace('%clarity_rules%',        groupedRows['Clarity'].join('\n'));
        data = data.replace('%whitespace_rules%',     groupedRows['Whitespace'].join('\n'));
        data = data.replace('%configurable_rules%',   groupedRows['Configurable'].join('\n'));
        data = data.replace('%deprecated_rules%',     groupedRows['Deprecated'].join('\n'));
        data = data.replace('%accessibilityy_rules%', groupedRows['Accessibility'].join('\n'));
        grunt.file.write('recommended_ruleset.js', data, {encoding: 'UTF-8'});
    });

    grunt.registerTask('generate-default-tslint-json', 'A task that converts recommended_ruleset.js to ./dist/build/tslint.json', function () {
        const data = require('./recommended_ruleset.js');
        data['rulesDirectory'] = './';
        grunt.file.write('./dist/build/tslint.json', JSON.stringify(data, null, 2), {encoding: 'UTF-8'});
    });

    grunt.registerTask('create-rule', 'A task that creates a new rule from the rule templates. --rule-name parameter required', function () {

        function applyTemplates(source) {
            return source.replace(/%RULE_NAME%/gm, ruleName)
                .replace(/%RULE_FILE_NAME%/gm, ruleFile)
                .replace(/%WALKER_NAME%/gm, walkerName);
        }

        var ruleName = grunt.option('rule-name');
        if (!ruleName) {
            grunt.fail.warn('--rule-name parameter is required');
        } else {

            var ruleFile = camelCase(ruleName) + 'Rule';
            var sourceFileName = './src/' + ruleFile + '.ts';
            var testFileName = './src/tests/' + ruleFile.charAt(0).toUpperCase() + ruleFile.substr(1) + 'Tests.ts';
            var walkerName = ruleFile.charAt(0).toUpperCase() + ruleFile.substr(1) + 'Walker';

            var ruleTemplateText = grunt.file.read('./templates/rule.snippet', {encoding: 'UTF-8'});
            var testTemplateText = grunt.file.read('./templates/rule-tests.snippet', {encoding: 'UTF-8'});

            grunt.file.write(sourceFileName, applyTemplates(ruleTemplateText), {encoding: 'UTF-8'});
            grunt.file.write(testFileName, applyTemplates(testTemplateText), {encoding: 'UTF-8'});

            var currentRuleset = grunt.file.readJSON('./tslint.json', {encoding: 'UTF-8'});
            currentRuleset.rules[ruleName] = true;
            grunt.file.write('./tslint.json', JSON.stringify(currentRuleset, null, 2), {encoding: 'UTF-8'});
        }
    });

    grunt.registerTask('all', 'Performs a cleanup and a full build with all tasks', [
        'clean',
        'copy:json',
        'ts',
        'mochaTest',
        'tslint',
        'validate-documentation',
        'validate-config',
        'validate-debug-mode',
        'copy:package',
        'generate-recommendations',
        'generate-default-tslint-json',
        'generate-sdl-report',
        'create-package-json-for-npm'
    ]);

    grunt.registerTask('default', ['all']);

};
<|endoftext|>


<commit_before>// Generated on 2015-02-03 using generator-angular-php 0.6.2
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

    // Load grunt tasks automatically
    require('load-grunt-tasks')(grunt);

    // Configurable paths for the application
    var appConfig = {
        name: require('./package.json').name,
        version: require('./package.json').version
    };

    // Define the configuration for all the tasks
    grunt.initConfig({
        // Project settings
        appEnv: appConfig,
        composer: {
            options: {
                usePhp: false,
                cwd: '.',
                flags: ['ignore-platform-reqs']
            }
        },
        clean: {
            deploy: {
                src: ['deploy/*.rpm', 'deploy/*.deb']
            }
        },
        chmod: {
            options: {
                mode: '755'
            },
            pharbits: {
                // Target-specific file/dir lists and/or options go here.
                src: ['bin/visorclient.phar']
            }
        },
        shell: {
            options: {
                stdout: true,
                stderr: true,
                failOnError: true
            },
            buildcmd: {
                command: './build.sh'
            },
            mkdeploy: {
                command: 'mkdir -p deploy'
            },
            for_centos7: {
              "command": [
                [
                  '/usr/local/bin/fpm -s dir -t rpm -n \'<%= appEnv.name %>\' -v <%= appEnv.version %> '
                ].join(' -d '),
                '--description "<%= appEnv.description %>"',
                '--url "<%= appEnv.homepage %>"',
                '--license "<%= appEnv.license %>"',
                '--vendor "University of South Florida"',
                '--iteration "<%= appEnv.release %>"',
                '--config-files /usr/local/etc/idm_config/VisorClient.yml',
                '-p public ./bin/visorclient.phar=/usr/local/bin/visorclient ./config/VisorClient.yml=/usr/local/etc/idm_config/VisorClient.yml'
              ].join(' ')
            },
            fpmrpm: {
                "command": [
                    [
                        '/usr/local/bin/fpm -s dir -t rpm -n \'<%= appEnv.name %>\' -v <%= appEnv.version %> ',
                        '"php"',
                        '"php-common"',
                        '"php-mysqlnd"',
                        '"php-pdo"',
                        '"php-devel"',
                        '"php-pear"',
                        '"php-gd"',
                        '"php-mcrypt"',
                        '"php-xml"',
                        '"php-mbstring"',
                        '"php-xml"',
                        '"php-cli"'
                    ].join(' -d '),
                    '--after-install app/setupconfig.sh -p deploy ./bin/visorclient.phar=/usr/local/bin/visorclient'
                ].join(' ')
            }
        }
    });

    grunt.registerTask('build', [
        'composer:update',
        "shell:buildcmd"
    ]);

    grunt.registerTask('buildrpm', [
        "chmod:pharbits",
        "clean:deploy",
        "shell:mkdeploy",
        "shell:fpmrpm"
    ]);

};
<commit_msg>Stubbing the visorclient command line utility<commit_after>// Generated on 2015-02-03 using generator-angular-php 0.6.2
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

    // Load grunt tasks automatically
    require('load-grunt-tasks')(grunt);

    // Configurable paths for the application
    var appConfig = {
        name: require('./package.json').name,
        version: require('./package.json').version
    };

    // Define the configuration for all the tasks
    grunt.initConfig({
        // Project settings
        appEnv: appConfig,
        composer: {
            options: {
                usePhp: false,
                cwd: '.',
                flags: ['ignore-platform-reqs']
            }
        },
        clean: {
            deploy: {
                src: ['deploy/*.rpm', 'deploy/*.deb']
            }
        },
        chmod: {
            options: {
                mode: '755'
            },
            pharbits: {
                // Target-specific file/dir lists and/or options go here.
                src: ['bin/visorclient.phar']
            }
        },
        shell: {
            options: {
                stdout: true,
                stderr: true,
                failOnError: true
            },
            buildcmd: {
                command: './build.sh'
            },
            mkdeploy: {
                command: 'mkdir -p deploy'
            },
            for_centos7: {
              "command": [
                [
                  '/usr/local/bin/fpm -s dir -t rpm -n \'<%= appEnv.name %>\' -v <%= appEnv.version %> '
                ].join(' -d '),
                '--description "<%= appEnv.description %>"',
                '--url "<%= appEnv.homepage %>"',
                '--license "<%= appEnv.license %>"',
                '--vendor "University of South Florida"',
                '--iteration "<%= appEnv.release %>"',
                '--config-files /usr/local/etc/idm_config/VisorClient.yml',
                '-p deploy ./bin/visorclient.phar=/usr/local/bin/visorclient ./config/VisorClient.yml=/usr/local/etc/idm_config/VisorClient.yml'
              ].join(' ')
            },
            fpmrpm: {
                "command": [
                    [
                        '/usr/local/bin/fpm -s dir -t rpm -n \'<%= appEnv.name %>\' -v <%= appEnv.version %> ',
                        '"php"',
                        '"php-common"',
                        '"php-mysqlnd"',
                        '"php-pdo"',
                        '"php-devel"',
                        '"php-pear"',
                        '"php-gd"',
                        '"php-mcrypt"',
                        '"php-xml"',
                        '"php-mbstring"',
                        '"php-xml"',
                        '"php-cli"'
                    ].join(' -d '),
                    '--after-install app/setupconfig.sh -p deploy ./bin/visorclient.phar=/usr/local/bin/visorclient'
                ].join(' ')
            }
        }
    });

    grunt.registerTask('build', [
        'composer:update',
        "shell:buildcmd"
    ]);

    grunt.registerTask('buildrpm', [
        "chmod:pharbits",
        "clean:deploy",
        "shell:mkdeploy",
        "shell:fpmrpm"
    ]);

};
<|endoftext|>


<commit_before>module.exports = function(grunt) {
  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    revision: {
      options: {
        property: 'meta.revision',
        ref: 'HEAD',
        short: true
      }
    },
    meta: {
      banner: '/**\n' +
        ' * @name <%= pkg.name %>\n' +
        ' * @version <%= pkg.version %>\n' +
        ' * @description\n' +
        ' * <%= pkg.description %>\n' +
        ' * Created at <%= grunt.template.today("yyyy-mm-dd") %>\n' +
        ' * Revision <%= meta.revision %>\n' +
        ' */\n'
    },
    jshint: {
      files: [
        'Gruntfile.js',
        'src/anol/**/*.js',
        'src/modules/**/*.js'
      ],
      options: {
        globals: {
          jQuery: true,
          console: true,
          module: true
        }
      }
    },
    concat: {
      options: {
        banner: '<%= meta.banner %>',
        separator: ';\n'
      },
      dev: {
        src: [
          'src/anol/anol.js',
          'src/anol/helper.js',
          'src/anol/layer.js',
          'src/anol/layer/feature.js',
          'src/anol/layer/staticgeojson.js',
          'src/anol/**/*.js',
          'src/modules/module.js',
          'src/modules/**/module.js',
          'src/modules/**/*.js'
        ],
        dest: 'build/<%= pkg.name %>.js'
      }
    },
    clean: {
      prebuild: {
        src: [ 'build' ]
      },
      docs: {
        src: [ 'docs' ]
      },
      'openlayers-build-config': {
        src: [
          'build/openlayers.build.debug.json',
          'build/openlayers.build.json'
        ]
      }
    },
    copy: {
      dev: {
        files: [
          {
            flatten: true,
            expand: true,
            src: [
              'node_modules/jquery/dist/jquery.js',
              'node_modules/angular/angular.js',
              'node_modules/angular-ui-bootstrap/ui-bootstrap-tpls.js',
              'node_modules/angular-translate/dist/angular-translate.js',
              'node_modules/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
              'node_modules/openlayers/build/ol-custom.js',
            ],
            dest: 'build'
          },
          {
            flatten: true,
            expand: true,
            src: [
              'node_modules/bootstrap/dist/css/bootstrap.css',
              'node_modules/bootstrap/dist/css/bootstrap.css.map',
              'node_modules/openlayers/dist/ol.css'
            ],
            dest: 'build/css/'
          },
          {
            flatten: true,
            expand: true,
            src: [
              'node_modules/bootstrap/dist/fonts/*'
            ],
            dest: 'build/fonts'
          },
          {
            flatten: true,
            expand: true,
            src: 'static/img/*',
            dest: 'build/img'
          }
        ]
      }
    },
    'merge-json': {
        'openlayers-build': {
            src: ['config/openlayers.exports.json', 'config/openlayers.compile.json'],
            dest: 'build/openlayers.build.json'
        }
    },
    shell: {
      'build-ol3': {
        command: [
          'cd node_modules/openlayers',
          'make build',
          'node tasks/build.js ../../build/openlayers.build.json build/ol-custom.js',
          'cd -'
        ].join('&&')
      }
    },
    connect: {
      server: {
        options: {
          hostname: '*',
          port: 7000
        }
      }
    },
    watch: {
      scripts: {
        files: ['src/anol/**/*.js', 'src/modules/**/*.js', 'src/modules/**/*.html'],
        tasks: ['ngtemplates', 'concat:dev'],
        options: {
          spawn: false,
        },
      },
      sass: {
        files: ['static/css/*.sass'],
        tasks: ['sass'],
        options: {
          spawn: false,
        },
      },
      ol: {
        files: [
          'config/openlayers.exports.json',
          'config/openlayers.compile.json'
        ],
        tasks: ['build-ol3', 'copy:dev']
      }
    },
    karma: {
        unit: {
          configFile: 'config/karma.conf.js',
        }
    },
    ngdocs: {
      options: {
        dest: 'docs',
        html5Mode: false,
        startPage: '/api',
        title: 'AnOl Documentation',
        editLink: false,
        editExample: false,
        demoExample: false,
        scripts: [
          '../node_modules/openlayers/dist/ol-debug.js',
          '../node_modules/jquery/dist/jquery.min.js',
          '../node_modules/angular/angular.min.js',
          '../node_modules/angular-animate/angular-animate.min.js',
          '../build/anol.js',
          '../build/templates.js'
        ]
      },
      api: {
        title: 'AnOl API',
        src: ['src/modules/**/*.js'],
      },
      wrappers: {
        title: 'Ol3 Wrappers',
        src: ['src/anol/**/*.js']
      }
    },
    ngtemplates:  {
      main: {
        options: {
          module: '<%= pkg.name %>'
        },
        src: ['src/**/templates/*.html'],
        dest: 'build/templates.js'
      }
    },
    sass: {
        options: {
            sourceMap: true
        },
        dist: {
            files: {
                'build/css/anol.css': 'static/css/*.sass'
            }
        }
    },
    concurrent: {
      options: {
        logConcurrentOutput: true
      },
      dev: {
        tasks: ['watch:scripts', 'watch:sass', 'watch:ol']
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  //grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-sass');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-git-revision');
  grunt.loadNpmTasks('grunt-angular-templates');
  //grunt.loadNpmTasks('grunt-ngmin');
  grunt.loadNpmTasks('grunt-ngdocs');
  grunt.loadNpmTasks('grunt-concurrent');
  grunt.loadNpmTasks('grunt-shell');
  grunt.loadNpmTasks('grunt-merge-json');

  grunt.loadNpmTasks('grunt-karma');

  grunt.registerTask('build-ol3', [
    'merge-json:openlayers-build',
    'shell:build-ol3',
    'clean:openlayers-build-config'
  ]);

  grunt.registerTask('test', ['karma:unit']);
  grunt.registerTask('dev', [
    'clean:prebuild',
    'sass:dist',
    'ngtemplates',
    'concat:dev',
    'build-ol3',
    'copy:dev',
    'connect:server',
    'concurrent:dev'
  ]);

  grunt.registerTask('build-dev', [
    'clean:prebuild',
    'jshint',
    'sass:dist',
    'ngtemplates',
    'concat:dev',
    'build-ol3',
    'copy:dev'
  ]);

  grunt.registerTask('build-doc', ['clean:docs', 'ngdocs']);
};
<commit_msg>Added basewms.js to gruntfile concat<commit_after>module.exports = function(grunt) {
  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    revision: {
      options: {
        property: 'meta.revision',
        ref: 'HEAD',
        short: true
      }
    },
    meta: {
      banner: '/**\n' +
        ' * @name <%= pkg.name %>\n' +
        ' * @version <%= pkg.version %>\n' +
        ' * @description\n' +
        ' * <%= pkg.description %>\n' +
        ' * Created at <%= grunt.template.today("yyyy-mm-dd") %>\n' +
        ' * Revision <%= meta.revision %>\n' +
        ' */\n'
    },
    jshint: {
      files: [
        'Gruntfile.js',
        'src/anol/**/*.js',
        'src/modules/**/*.js'
      ],
      options: {
        globals: {
          jQuery: true,
          console: true,
          module: true
        }
      }
    },
    concat: {
      options: {
        banner: '<%= meta.banner %>',
        separator: ';\n'
      },
      dev: {
        src: [
          'src/anol/anol.js',
          'src/anol/helper.js',
          'src/anol/layer.js',
          'src/anol/layer/basewms.js',
          'src/anol/layer/feature.js',
          'src/anol/layer/staticgeojson.js',
          'src/anol/**/*.js',
          'src/modules/module.js',
          'src/modules/**/module.js',
          'src/modules/**/*.js'
        ],
        dest: 'build/<%= pkg.name %>.js'
      }
    },
    clean: {
      prebuild: {
        src: [ 'build' ]
      },
      docs: {
        src: [ 'docs' ]
      },
      'openlayers-build-config': {
        src: [
          'build/openlayers.build.debug.json',
          'build/openlayers.build.json'
        ]
      }
    },
    copy: {
      dev: {
        files: [
          {
            flatten: true,
            expand: true,
            src: [
              'node_modules/jquery/dist/jquery.js',
              'node_modules/angular/angular.js',
              'node_modules/angular-ui-bootstrap/ui-bootstrap-tpls.js',
              'node_modules/angular-translate/dist/angular-translate.js',
              'node_modules/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
              'node_modules/openlayers/build/ol-custom.js',
            ],
            dest: 'build'
          },
          {
            flatten: true,
            expand: true,
            src: [
              'node_modules/bootstrap/dist/css/bootstrap.css',
              'node_modules/bootstrap/dist/css/bootstrap.css.map',
              'node_modules/openlayers/dist/ol.css'
            ],
            dest: 'build/css/'
          },
          {
            flatten: true,
            expand: true,
            src: [
              'node_modules/bootstrap/dist/fonts/*'
            ],
            dest: 'build/fonts'
          },
          {
            flatten: true,
            expand: true,
            src: 'static/img/*',
            dest: 'build/img'
          }
        ]
      }
    },
    'merge-json': {
        'openlayers-build': {
            src: ['config/openlayers.exports.json', 'config/openlayers.compile.json'],
            dest: 'build/openlayers.build.json'
        }
    },
    shell: {
      'build-ol3': {
        command: [
          'cd node_modules/openlayers',
          'make build',
          'node tasks/build.js ../../build/openlayers.build.json build/ol-custom.js',
          'cd -'
        ].join('&&')
      }
    },
    connect: {
      server: {
        options: {
          hostname: '*',
          port: 7000
        }
      }
    },
    watch: {
      scripts: {
        files: ['src/anol/**/*.js', 'src/modules/**/*.js', 'src/modules/**/*.html'],
        tasks: ['ngtemplates', 'concat:dev'],
        options: {
          spawn: false,
        },
      },
      sass: {
        files: ['static/css/*.sass'],
        tasks: ['sass'],
        options: {
          spawn: false,
        },
      },
      ol: {
        files: [
          'config/openlayers.exports.json',
          'config/openlayers.compile.json'
        ],
        tasks: ['build-ol3', 'copy:dev']
      }
    },
    karma: {
        unit: {
          configFile: 'config/karma.conf.js',
        }
    },
    ngdocs: {
      options: {
        dest: 'docs',
        html5Mode: false,
        startPage: '/api',
        title: 'AnOl Documentation',
        editLink: false,
        editExample: false,
        demoExample: false,
        scripts: [
          '../node_modules/openlayers/dist/ol-debug.js',
          '../node_modules/jquery/dist/jquery.min.js',
          '../node_modules/angular/angular.min.js',
          '../node_modules/angular-animate/angular-animate.min.js',
          '../build/anol.js',
          '../build/templates.js'
        ]
      },
      api: {
        title: 'AnOl API',
        src: ['src/modules/**/*.js'],
      },
      wrappers: {
        title: 'Ol3 Wrappers',
        src: ['src/anol/**/*.js']
      }
    },
    ngtemplates:  {
      main: {
        options: {
          module: '<%= pkg.name %>'
        },
        src: ['src/**/templates/*.html'],
        dest: 'build/templates.js'
      }
    },
    sass: {
        options: {
            sourceMap: true
        },
        dist: {
            files: {
                'build/css/anol.css': 'static/css/*.sass'
            }
        }
    },
    concurrent: {
      options: {
        logConcurrentOutput: true
      },
      dev: {
        tasks: ['watch:scripts', 'watch:sass', 'watch:ol']
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-contrib-connect');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  //grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-sass');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-git-revision');
  grunt.loadNpmTasks('grunt-angular-templates');
  //grunt.loadNpmTasks('grunt-ngmin');
  grunt.loadNpmTasks('grunt-ngdocs');
  grunt.loadNpmTasks('grunt-concurrent');
  grunt.loadNpmTasks('grunt-shell');
  grunt.loadNpmTasks('grunt-merge-json');

  grunt.loadNpmTasks('grunt-karma');

  grunt.registerTask('build-ol3', [
    'merge-json:openlayers-build',
    'shell:build-ol3',
    'clean:openlayers-build-config'
  ]);

  grunt.registerTask('test', ['karma:unit']);
  grunt.registerTask('dev', [
    'clean:prebuild',
    'sass:dist',
    'ngtemplates',
    'concat:dev',
    'build-ol3',
    'copy:dev',
    'connect:server',
    'concurrent:dev'
  ]);

  grunt.registerTask('build-dev', [
    'clean:prebuild',
    'jshint',
    'sass:dist',
    'ngtemplates',
    'concat:dev',
    'build-ol3',
    'copy:dev'
  ]);

  grunt.registerTask('build-doc', ['clean:docs', 'ngdocs']);
};
<|endoftext|>


<commit_before>
gnt['opensocial_people'] = {};

/*
This function retrives a list of person objects. The list of people
that is returned has a connection from user and belongs to group.

*/
gnt.opensocial_people['get_list_of_persons'] =
function(user, group, callback_function) {

    $.ajax({
        url: "{% url people %}/" + user + "/" + group,
        type: "GET",
        contentType: "application/json",
        success: function(data, textStatus, jqXHR){
            if(callback_function !== undefined) {
                callback_function(data, textStatus, jqXHR);
                }
            },
        error: function(jqXHR, textStatus, errorThrown) {
            if(callback_function !== undefined) {
                callback_function(jqXHR, textStatus, errorThrown);
            }
        },
        dataType: "json",
        beforeSend: function(xhr){
            //for cross site authentication using CORS
            xhr.withCredentials = true;
            }
    });
};

/*
 This function retrieves one person object from the server.
 The argument given is the user name which is unique.

*/
gnt.opensocial_people['get_person'] =
function(user, callback_function) {

    gnt.opensocial_people.get_list_of_persons(user,
                                              '@self',
                                              callback_function);
};

/*
 This function updates the information of a person with the unique
 username,
*/
gnt.opensocial_people['update_person'] =
function(user, person_object, callback_function) {

    $.ajax({
        url: "{% url people %}/" + user + "/@self",
        type: "PUT",
        data: JSON.stringify(person_object),
        contentType: "application/json",
        success: function(data, textStatus, jqXHR) {
            if(callback_function !== undefined) {
                callback_function(data, textStatus, jqXHR);
                }
            },
        error: function(jqXHR, textStatus, errorThrown) {
            if(callback_function !== undefined) {
                callback_function(jqXHR, textStatus, errorThrown);
            }
        },
        dataType: "json",
        beforeSend: function(xhr) {
            //for cross site authentication using CORS
            xhr.withCredentials = true;
            }
    });
};

/*
 This function returns a array of key names
 or a JSON object where keys are connected
 with the type of the value.

 The types follow the JSON types defined
 at json.org
*/
gnt.opensocial_people['get_supported_fields'] =
function(with_values, callback_function) {

    if(with_values === undefined) {
        with_values = false;
    }
    $.ajax({
        url: "{% url people %}/@supportedFields?types=" + with_values,
        type: "GET",
        contentType: "application/json",
        success: function(data, textStatus, jqXHR){
            if(callback_function !== undefined) {
                callback_function(data, textStatus, jqXHR);
                }
            },
        error: function(jqXHR, textStatus, errorThrown) {
            if(callback_function !== undefined) {
                callback_function(jqXHR, textStatus, errorThrown);
            }
        },
        dataType: "json",
        beforeSend: function(xhr){
            //for cross site authentication using CORS
            xhr.withCredentials = true;
            }
    });
}

/*
 This function creates a relationship between two persons
*/
gnt.opensocial_people['create_relationship'] =
function(initial_user,
         group,
         target_user_person_object,
         callback_function) {

    $.ajax({
        url: "{% url people %}/" + initial_user + "/" + group,
        type: "POST",
        data: JSON.stringify(target_user_person_object),
        contentType: "application/json",
        success: function(data, textStatus, jqXHR){
            if(callback_function !== undefined) {
                callback_function(data, textStatus, jqXHR);
                }
            },
        error: function(jqXHR, textStatus, errorThrown) {
            if(callback_function !== undefined) {
                callback_function(jqXHR, textStatus, errorThrown);
            }
        },
        dataType: "json",
        beforeSend: function(xhr){
            //for cross site authentication using CORS
            xhr.withCredentials = true;
            }
    });
};

/*
 This function deletes a relationship
*/
gnt.opensocial_people['delete_relationship'] =
function(initial_user,
         group,
         target_user,
         callback_function) {

    $.ajax({
        url: "{% url people %}/" + initial_user + "/" + group + "/" + target_user,
        type: "DELETE",
        contentType: "application/json",
        success: function(data, textStatus, jqXHR){
            if(callback_function !== undefined) {
                callback_function(data, textStatus, jqXHR);
                }
            },
        error: function(jqXHR, textStatus, errorThrown) {
            if(callback_function !== undefined) {
                callback_function(jqXHR, textStatus, errorThrown);
            }
        },
        dataType: "json",
        beforeSend: function(xhr){
            //for cross site authentication using CORS
            xhr.withCredentials = true;
            }
    });
};
<commit_msg>in get people default value for user is now '@me'<commit_after>
gnt['opensocial_people'] = {};

/*
This function retrives a list of person objects. The list of people
that is returned has a connection from user and belongs to group.

*/
gnt.opensocial_people['get_list_of_persons'] =
function(user, group, callback_function) {

    $.ajax({
        url: "{% url people %}/" + user + "/" + group,
        type: "GET",
        contentType: "application/json",
        success: function(data, textStatus, jqXHR){
            if(callback_function !== undefined) {
                callback_function(data, textStatus, jqXHR);
                }
            },
        error: function(jqXHR, textStatus, errorThrown) {
            if(callback_function !== undefined) {
                callback_function(jqXHR, textStatus, errorThrown);
            }
        },
        dataType: "json",
        beforeSend: function(xhr){
            //for cross site authentication using CORS
            xhr.withCredentials = true;
            }
    });
};

/*
 This function retrieves one person object from the server.
 The argument given is the user name which is unique.

*/
gnt.opensocial_people['get_person'] =
function(user, callback_function) {

    if(user === undefined) {
        user = '@me';
    }

    gnt.opensocial_people.get_list_of_persons(user,
                                              '@self',
                                              callback_function);
};

/*
 This function updates the information of a person with the unique
 username,
*/
gnt.opensocial_people['update_person'] =
function(user, person_object, callback_function) {

    $.ajax({
        url: "{% url people %}/" + user + "/@self",
        type: "PUT",
        data: JSON.stringify(person_object),
        contentType: "application/json",
        success: function(data, textStatus, jqXHR) {
            if(callback_function !== undefined) {
                callback_function(data, textStatus, jqXHR);
                }
            },
        error: function(jqXHR, textStatus, errorThrown) {
            if(callback_function !== undefined) {
                callback_function(jqXHR, textStatus, errorThrown);
            }
        },
        dataType: "json",
        beforeSend: function(xhr) {
            //for cross site authentication using CORS
            xhr.withCredentials = true;
            }
    });
};

/*
 This function returns a array of key names
 or a JSON object where keys are connected
 with the type of the value.

 The types follow the JSON types defined
 at json.org
*/
gnt.opensocial_people['get_supported_fields'] =
function(with_values, callback_function) {

    if(with_values === undefined) {
        with_values = false;
    }
    $.ajax({
        url: "{% url people %}/@supportedFields?types=" + with_values,
        type: "GET",
        contentType: "application/json",
        success: function(data, textStatus, jqXHR){
            if(callback_function !== undefined) {
                callback_function(data, textStatus, jqXHR);
                }
            },
        error: function(jqXHR, textStatus, errorThrown) {
            if(callback_function !== undefined) {
                callback_function(jqXHR, textStatus, errorThrown);
            }
        },
        dataType: "json",
        beforeSend: function(xhr){
            //for cross site authentication using CORS
            xhr.withCredentials = true;
            }
    });
}

/*
 This function creates a relationship between two persons
*/
gnt.opensocial_people['create_relationship'] =
function(initial_user,
         group,
         target_user_person_object,
         callback_function) {

    $.ajax({
        url: "{% url people %}/" + initial_user + "/" + group,
        type: "POST",
        data: JSON.stringify(target_user_person_object),
        contentType: "application/json",
        success: function(data, textStatus, jqXHR){
            if(callback_function !== undefined) {
                callback_function(data, textStatus, jqXHR);
                }
            },
        error: function(jqXHR, textStatus, errorThrown) {
            if(callback_function !== undefined) {
                callback_function(jqXHR, textStatus, errorThrown);
            }
        },
        dataType: "json",
        beforeSend: function(xhr){
            //for cross site authentication using CORS
            xhr.withCredentials = true;
            }
    });
};

/*
 This function deletes a relationship
*/
gnt.opensocial_people['delete_relationship'] =
function(initial_user,
         group,
         target_user,
         callback_function) {

    $.ajax({
        url: "{% url people %}/" + initial_user + "/" + group + "/" + target_user,
        type: "DELETE",
        contentType: "application/json",
        success: function(data, textStatus, jqXHR){
            if(callback_function !== undefined) {
                callback_function(data, textStatus, jqXHR);
                }
            },
        error: function(jqXHR, textStatus, errorThrown) {
            if(callback_function !== undefined) {
                callback_function(jqXHR, textStatus, errorThrown);
            }
        },
        dataType: "json",
        beforeSend: function(xhr){
            //for cross site authentication using CORS
            xhr.withCredentials = true;
            }
    });
};
<|endoftext|>


<commit_before>"use strict";

var matches = document.querySelectorAll(".matches");
//console.log(matches);

for (var ii=0; ii<matches.length; ii++) {
  var match = matches[ii];

  match.onclick = function (event) {
    var match = event.target;
    match.classList.add("removed");
  };
}

function reset() {
  var matches = document.querySelectorAll(".matches img.removed");

  for (var ii=0; ii<matches.length; ii++) {
    var match = matches[ii];
    match.classList.remove("removed");
  }
}<commit_msg>08 modified to use `row` rather than `match`for the <div>s that contain match images<commit_after>"use strict";

var rows = document.querySelectorAll(".matches");
//console.log(matches);

for (var ii=0; ii<rows.length; ii++) {
  var row = rows[ii];

  row.onclick = function (event) {
    var match = event.target;
    match.classList.add("removed");
  };
}

function reset() {
  var matches = document.querySelectorAll(".matches img.removed");

  for (var ii=0; ii<matches.length; ii++) {
    var match = matches[ii];
    match.classList.remove("removed");
  }
}<|endoftext|>


<commit_before>cdb.geo.ui.Widget.HistogramModel = cdb.geo.ui.Widget.Model.extend({

  options: {
    page: 0,
    per_page: 100
  },

  defaults: {
    data: [],
    columns: []
  },

  initialize: function() {
    this._data = new Backbone.Collection(this.get('data'));

    cdb.geo.ui.Widget.Model.prototype.initialize.call(this);
  },

  _createUrlOptions: function() {
    return _.compact(_(this.options).map(
      function(v, k) {
        return k + "=" + encodeURIComponent(v);
      }
    )).join('&');
  },

  getData: function() {
    return this._data;
  },

  getSize: function() {
    return this._data.size();
  },

  getDataSerialized: function() {
    return this.get('data');
  },

  fetch: function(opts) {
    this.trigger("loading", this);
    return cdb.core.Model.prototype.fetch.call(this,opts);
  },

  parse: function(r) {
    this._data.reset(r);
    return {
      data: r
    };
  }

});
<commit_msg>Removed unnecesary methods within widget histogram model<commit_after>cdb.geo.ui.Widget.HistogramModel = cdb.geo.ui.Widget.Model.extend({

  initialize: function() {
    this._data = new Backbone.Collection(this.get('data'));
    cdb.geo.ui.Widget.Model.prototype.initialize.call(this);
  },

  getData: function() {
    return this._data;
  },

  getSize: function() {
    return this._data.size();
  },

  getDataSerialized: function() {
    return this.get('data');
  },

  parse: function(r) {
    this._data.reset(r);
    return {
      data: r
    };
  }

});
<|endoftext|>