text:
$(function(){
    //加载编辑工具已保存rules
    $("textarea#saveSpace").val(window.localStorage.getItem("rulesData"));
    //左侧导航按钮事件绑定
    $(".unit-nav").children("li").each(function(){
        $(this).on("click",function(){
            $(this).addClass("active").siblings().removeClass("active");
            hideElse(this);
        });
    });

    //顶部菜单保存文件按钮事件绑定
    //保存文件界面保存按钮事件绑定
    $("a#saveFileTxt").on("click",function(){
        $("div#panel-importFile").hide();
        $("div#panel-importFileTxt").hide();
        $("div#panel-saveFile").hide();
        $("div#panel-saveFileTxt").show();
    });
    $("button#btnToSaveFileTxt").on("click",function(){
        saveFile("txt");
    });
    //保存文件到cookies或到本地
    function saveFile(method){
        var textToWrite = document.getElementById("txt_rules").value+"\n$$RULES"+
            "\n"+document.getElementById("txt_actions").value+"\n$$ACTIONS"+
            "\n"+document.getElementById("txt_knowledge").value+"\n$$KNOWLEDGE"+
            "\n"+document.getElementById("txt_keywords").value+"\n$$KEYWORDS"+
            "\n"+document.getElementById("txt_test").value+"\n"+"$$TEST";
        if(method=="cookie"){
            var contextSaveFile=$("div#panel-saveFile");
            var fileName=$(contextSaveFile).find("input").val();
            if(!fileName){
                alert("文件名不能为空");
                return;
            }
            var name="FileName&"+fileName;
            var allCookie=document.cookie;
            if(allCookie.indexOf(name)!==-1){
                if(!confirm("已存在同名文件,是否覆盖?"))return;
            }
            var day=$(contextSaveFile).find("select").val();
            setCookie(name,textToWrite,day);
            if(document.cookie.indexOf(name)!==-1){
                $(contextSaveFile).hide();
                alert("保存成功");
            }
        }
        if(method=="txt"){
            var contextSaveFileTxt=$("div#panel-saveFileTxt");
            var txtfileName=$(contextSaveFileTxt).find("input").val();
            var blob = new Blob([textToWrite], {type: "text/plain;charset=utf-8"});
            saveAs(blob, txtfileName+".txt");
            $(contextSaveFileTxt).hide();
        }
        if(method=="auto"){
            setCookie("FileName&default",textToWrite,30);
        }
    }

    $("a#importFileTxt").on("click",function () {
        $("div#panel-saveFile").hide();
        $("div#panel-importFile").hide();
        $("div#panel-saveFileTxt").hide();
        $("div#panel-importFileTxt").show();
    });
    $("button#btnToImportFileTxt").on("click",function(){
        importFile();
    });

    //导入文件
    function importFile() {
        handleFiles(document.getElementById("txtImport").files);
    }
    function handleFiles(files) {
        if (files.length) {
            var file = files[0];
            var reader = new FileReader();
            if (/text\/\w+/.test(file.type)) {

                reader.onload = function() {
                    var fileValue=this.result;
                    $("textarea#txt_actions").val(fileValue.substring(fileValue.indexOf("#actions"),fileValue.indexOf("$$ACTIONS")));
                    $("textarea#txt_rules").val(fileValue.substring(fileValue.indexOf("#rules"),fileValue.indexOf("$$RULES")));
                    $("textarea#txt_keywords").val(fileValue.substring(fileValue.indexOf("#keywords"),fileValue.indexOf("$$KEYWORDS")));
                    $("textarea#txt_test").val(fileValue.substring(fileValue.indexOf("#test"),fileValue.indexOf("$$TEST")));
                    $("textarea#txt_knowledge").val(fileValue.substring(fileValue.indexOf("#knowledge"),fileValue.indexOf("$$KNOWLEDGE")));
                    $("div#panel-importFileTxt").hide();
                    refreshLineNum();
                };
                reader.readAsText(file);
            }
        }
    }

    //取消按钮事件绑定
    $("button.btnCancel").each(function () {
        $(this).on("click",function () {
            $(this).parent().parent("div.panel-file").hide();
        })
    });
    //话题生成按钮事件绑定
    $("#btn-createActions").on("click",function () {
        buttonToCreateAction();
    });

    //规则编辑页关闭按钮事件绑定
    $("button.closeRuleEditor").on("click",function(){
        $("div#ruleEditor").hide();
    });
    //规则编辑工具关闭按钮事件绑定
    $("button.closeRuleEditorTool").on("click",function(){
        $("div#ruleEditorTool").hide();
    });

    //添加语义规则按钮事件绑定
    $("button#addRulesIntoRuleUnit").on("click",function(){
        var unitRuls=$("textarea#txt_rules");
        var rules=$("textarea#saveSpace");
        unitRuls.val(unitRuls.val()+"\n"+rules.val());
    });
    //保存rule按钮事件绑定
    $("button#saveRules").on("click",function(){
        var saveSpace=$("textarea#saveSpace");
        var rule=$("textarea#rule");
        if(saveSpace.val().indexOf(rule.val())===-1){
            saveSpace.val(saveSpace.val()+"\n"+rule.val());
            window.localStorage.setItem("rulesData",saveSpace.val());
        }else {
            alert("rules已存在");
        }
        $("em#ruleNumTag").text((!saveSpace.val().match(/#visitorname/))?"0":saveSpace.val().match(/#visitorname/gi).length);
    });
    //左侧导航隐藏显示按钮事件绑定
    $("#nav-button").on("click",function(){
        //alert($("#side-nav").html());
        var nav=$("#side-nav");
        var status=nav.attr("aria-expanded");
        if(status!="true") {
            nav.attr("aria-expanded","true");
            nav.attr("style","height:1px");
            nav.removeClass("in");
            nav.attr("display","block");
            $(".side-nav").hide();
            $("div#wrapper").attr("style","padding-left:0px");
        } else{
            nav.attr("aria-expanded","false");
            nav.attr("style","");
            nav.addClass("in");
            nav.attr("display","none")
            /*nav.find("ul").show();*/
            $("div#wrapper").attr("style","padding-left:150px");
            $(".side-nav").show();
        }
    });

    //加载完执行
    $(function () {
        //话题生成单元按钮事件绑定
        bandForButton($("div#actionEditor-context"));
        //自适应刷新页面高度
        refreshHeight();
    });

    setInterval(refreshHeight,500);
    //刷新页面高度函数
    function refreshHeight() {
        var h=document.documentElement.clientHeight;
        /*var pageElement=document.getElementById("page-wrapper");*/
        $("div.edit-space textarea").each(function () {
            this.style.minHeight=(h-134)+"px";
        })
    }
    //按钮事件绑定函数
    function bandForButton(obj){
        $(obj).find("button.addChildAction").on("click",function(){
            childAction(this);
        });
        $(obj).find("button.delAction").on("click",function(){
            delAction(this);
        });
        $(obj).find("button.expand").on("click",function(){
            showInfo(this);
        });
        $(obj).find("button.compress").on("click",function(){
            hideInfo(this);
        });
        $(obj).find("select.status").on("change",function(){
            actionStatusChange(this);
        })
    }
    //隐藏除选中外的其他单元内容
    function hideElse(obj) {
        var name = $(obj).children("a").attr("data-target");
        if(name!=="ruleEditor-context"){
            $(".unit-context").each(function () {
                var idname = $(this).attr("id");
                if (name === idname) {
                    $(this).show();
                } else {
                    $(this).hide();
                    $("div#ruleEditor").hide();
                    $("div#ruleEditorTool").hide();
                }
            });
        }else{

            $(".unit-context").each(function () {
                var idname = $(this).attr("id");
                if ("test-context"=== idname) {
                    $(this).show().find("div#ruleEditor").show();
                } else {
                    $(this).hide();
                }
            });
            getRulesInfo();
        }
    }

    function getRulesInfo(){
        var text=$("#txt_test").val();
        var testSentence=text.split("\n");
        var testInfo="";
        for( var i=1;i<testSentence.length;i++){
            if(testSentence[i])testInfo+="
"+testSentence[i]+"	<button class='btn btn-default btn-xs btn-ruleEdit'>编辑</button>
";
        }
        $("div#ruleEditor").find("table#testInfo").html(testInfo);
        btnRuleEditOnClick();
    }

    //规则编辑页编辑按钮事件绑定函数
    function btnRuleEditOnClick(){
        $("button.btn-ruleEdit").each(function(){
            $(this).on("click",function(){
                $("div#ruleEditorTool").show();
                editRules(this);
            });
        });
    }
    //生成编辑工具
    function editRules(objBtnRuleEdit){
        //要编辑的语句
        var sentence=$(objBtnRuleEdit).parent().prev().text();
        //全部测试结果文字
        var txtInfoTest=$("textarea#info_test").val();
        //分割后的测试结果数组
        var infoSentence=txtInfoTest.split("Sen:");
        //测试结果显示位置
        var ruleInfo= $("div#ruleInfo");
        //编辑工具显示位置
        var ruleEditTool=$("div#ruleEditTool");
        ruleEditTool.html("");
        //根据测试结果获取的词组数组
        var words=[];
        //标点符号数组
        var symbol=[",","。","、","?","!",",",".","?","!"];
        var rulesNum=$("textarea#saveSpace").val().match(/#visitorname/gi);
        //显示现有rules
        $("em#ruleNumTag").text((!rulesNum)?"0":rulesNum.length);
        //编辑工具按钮组字符串
        var ruleEditBtns="";
        for(var i=1;i<infoSentence.length;i++){
            if(infoSentence[i].indexOf(sentence)!==-1){
                var actions=$("textarea#txt_actions").val();
                /*var ruleInActions=actions.match(/\|#visitorname,rule-find-[^|]*,?\|/gi);*/
                //获取所有rule-find-***
                var ruleFindInActions=actions.match(/rule-find-[\w]*,/gi);
                var ruleListeningInActions=actions.match(/rule-listening-[\w]*,/gi);
                var resFind=[];
                var resListening=[];
                var jsonFind={};
                var jsonListening={};
                if(ruleFindInActions){
                    ruleFindInActions.forEach(function(ru,index,rules){
                        rules[index]=ru.substring(0,ru.length-1);
                        if(!jsonFind[rules[index]]){
                            resFind.push(rules[index]);
                            jsonFind[rules[index]]=1;
                        }
                    });
                }
                if(ruleListeningInActions){
                    ruleListeningInActions.forEach(function(ru,index,rules){
                        rules[index]=ru.substring(0,ru.length-1);
                        if(!jsonListening[rules[index]]){
                            resListening.push(rules[index]);
                            jsonListening[rules[index]]=1;
                        }
                    });
                }
                //对匹配到的测试结果进行处理
                var infoHtml="";
                var info1=infoSentence[i].split("RELs");
                var info2=info1[1].split("sub:");
                infoHtml="
"+info1[0]+"
";
                for( var info=0;info<info2.length;info++){
                    infoHtml+="
"+info2[info]+"
";
                }
                //显示匹配到的测试结果
                ruleInfo.show().html(infoHtml);
                //提取括号包含的内容
                var ruleWords=infoSentence[i].match(/\([^)]*\)/gi);
                //遍历括号内容数组,去掉括号并按逗号拆分词组 不重复的存入words数组
                for(var j=0;j<ruleWords.length;j++){
                    ruleWords[j]=ruleWords[j].substring(1,ruleWords[j].length-1);
                    var word=ruleWords[j].split(",");
                    for(var k=0;k<word.length;k++){
                        if(words.indexOf(word[k])===-1)words.push(word[k]);
                    }
                }
                //按语句顺序匹配words中的关键词,生成rules编辑工具
                var loopNum=0;
                //QA按钮
                ruleEditTool.append("<button class='btn btn-default btn-sm' id='qa'>QA:</button>");
                //匹配关键词 生成词组及词组控制按钮
                do{
                    for (var w = 0; w < words.length; w++) {
                        if (sentence.indexOf(words[w]) === 0) {
                            sentence = sentence.substring(words[w].length, sentence.length);
                            ruleEditTool.append((symbol.indexOf(words[w])!==-1)?""+words[w]+"":""+words[w]+""+ruleEditBtns);
                        }
                    }
                    if(loopNum++===100){
                        ruleEditTool.html("");
                        $("div#ruleEditorTool").show();
                        $("textarea#rule").val("关键词匹配错误,请检查\""+sentence.substring(0,4)+"\"位置");
                        return;
                    }
                }while(sentence.length!==0);
                //生成编辑工具输入框及下拉框组件
                var inputAndSelectHtml="";
                inputAndSelectHtml+="

<input id='keywordRestrict' placeholder='词语限定'>	";
                if(resFind.length!==0){
                    var ruleFindNameSelect="";
                    var ruleListeningNameSelect="";
                    ruleFindNameSelect+="<select id='ruleFindName' class='ruleName' data-status='true'>";
                    ruleListeningNameSelect+="<select id='ruleListeningName' class='ruleName' data-status='false' style='display: none'>";
                    resFind.forEach(function(name){
                        ruleFindNameSelect+="<option value='"+name+"'>"+name+"</option>";
                    });
                    resListening.forEach(function(name){
                        ruleListeningNameSelect+="<option value='"+name+"'>"+name+"</option>";
                    });
                    ruleFindNameSelect+="</select>";
                    ruleListeningNameSelect+="</select>";
                    inputAndSelectHtml+="<button class='btn btn-default btn-xs' id='ruleNameSelect'></button>";
                    inputAndSelectHtml+=ruleFindNameSelect;
                    inputAndSelectHtml+=ruleListeningNameSelect+"	";
                }else{
                    inputAndSelectHtml+="<input class='ruleName' data-status='true' placeholder='规则名'>	";
                }
                inputAndSelectHtml+="关键词序号:<select id='keywordNum'><option value='[1]'>1</option><option value='[2]'>2</option><option value='[3]'>3</option><option value='[4]'>4</option><option value='[5]'>5</option><option value='[6]'>6</option></select>

";
                ruleEditTool.append(inputAndSelectHtml);
                ruleEditTool.show();
                bandForRuleEditBtns();
                createRule();
                return;
            }
        }
        ruleInfo.show().html("未匹配到结果");
        ruleEditTool.html("").hide();
        $("textarea#rule").val("");
    }
    //为编辑工具按钮绑定事件
    function bandForRuleEditBtns(){
        //关键词后按钮事件绑定
        $("i.property").each(function(){
            $(this).on("click",function(){
                makeWordProperty(this);
            })
        });
        $("i.ignore").each(function(){
            $(this).on("click",function(){
                makeWordIgnore(this);
            })
        });
        //QA按钮事件绑定
        $("button#qa").on("click",function () {
            var spanTag=$(this).prev("span");
            spanTag.attr("data-status",(spanTag.attr("data-status")==="false")?"true":"false");
            //alert(spanTag.attr("data-status"));
            createRule();
        });
        //选择框事件绑定
        $("select.ruleName,select#keywordNum").each(function(){
            $(this).on("change",function(){
                createRule();
            });
        });
        //切换选择框按钮事件绑定
        $("button#ruleNameSelect").on("click",function () {
            $("select.ruleName").each(function () {
                var status=$(this).attr("data-status");
                $(this).attr("data-status",(status==="false")?"true":"false");
            });
            $("select.ruleName[data-status='false']").hide();
            $("select.ruleName[data-status='true']").show();
            createRule();
        });
        //关键词序号选择框事件绑定
        $("input.ruleName,input#keywordRestrict").on("keyup",function () {
            createRule();
        });

    }
    //生成rules
    function createRule(){
        var propertyNum=0;
        var rules="";
        var context=$("div#ruleEditTool");
        var everyWord=$(context).find("strong");
        var qaTag=context.find("span");
        var ruleName=$(context).find(".ruleName[data-status='true']").val();
        var restrict=$(context).find("input#keywordRestrict").val();
        var keywordNum=$(context).find("select#keywordNum").val();
        rules+=(qaTag.attr("data-status")==="false")?"":"QA:";
        for(var wd=0;wd<everyWord.length;wd++){
            var word=everyWord[wd];
            if($(word).attr("data-type")=="ignore"){
                rules+=$(word).text()+"[NA]";
            }else if($(word).attr("data-type")=="property"){
                propertyNum++;
                if(propertyNum>6){
                    alert("变量最多能有6个");
                    $(word).attr("data-type","ignore");
                    rules+=$(word).text()+"[NA]";
                }else{
                    rules+=$(word).text()+"["+propertyNum+"]";
                }
            }else if($(word).attr("data-type")=="symbol"){
                rules+=$(word).text();
            }
        }
        rules+="|"+restrict+"~#visitorname,"+ruleName+","+keywordNum+".";
        $("textarea#rule").val(rules);
    }
    //关键字转成变量函数
    function makeWordProperty(btnProperty){
        $(btnProperty).prev("strong").attr("data-type","property");
        $(btnProperty).hide().next("i").show();
        createRule();
    }
    //忽略关键字函数
    function makeWordIgnore(btnIgnore){
        $(btnIgnore).hide().prev("i").show().prev("strong").attr("data-type","ignore");
        createRule();
    }

    //展开话题详细信息
    function hideInfo(obj){
        $(obj).parent().parent().find("div.action-info").hide();
    }
    //收起话题详细信息
    function showInfo(obj){
        $(obj).parent().parent().find("div.action-info").show();
    }
    //删除话题
    function delAction(obj){
        $(obj).parent().parent().parent().parent("li.childAction").remove();
    }
    //添加子话题及为新增按钮绑定事件
    function childAction(obj){
        var html="
" +
            "
" +
            "
" +
            "               <input type=\"text\" placeholder=\"话题标识\">" +
            "
" +
            "                    <button class=\"btn btn-default btn-xs expand\"></button>" +
            "                    <button class=\"btn btn-default btn-xs compress\"></button>" +
            "                    <button class=\"btn btn-default btn-xs addChildAction\"></button>" +
            "                    <button class=\"btn btn-danger btn-xs delAction\"></button>" +
            "
" +
            "
" +
            "
" +
            "                    <input type=\"text\" class=\"childActionName\" placeholder=\"话题名\">
" +
            "                    <input type=\"text\" class=\"rule\"  placeholder=\"话题规则名\">
" +
            "                     话题状态" +
            "                    <select class=\"status\" name=\"status\">" +
            "                       <option value=\"active\">active</option>" +
            "                       <option value=\"waiting\" selected=\"selected\">waiting</option>" +
            "                       <option value=\"listening\">listening</option>" +
            "                       <option value=\"end\">结尾</option>" +
            "                    </select>
" +
            "                    <input type=\"text\" class=\"sentence\" placeholder=\"话题提示语句\">
" +
            "                    <input type=\"text\" class=\"behavior\" placeholder=\"话题行为描述\">
" +
            "                    <input type=\"text\" class=\"keywords\"  placeholder=\"跳转到此话题关键字\">
" +
            "                    <input type=\"text\" class=\"endSentence\" style=\"display: none\" placeholder=\"结束语\">
" +
            "
" +
            "
" +
            "

" +
            "
" +
            "
";
        bandForButton($(obj).parent().parent().next("ul").append(html).children("li:last"));
    }
    //话题类型改变事件
    function actionStatusChange(obj){
        var thisAction=$(obj).parent().parent("div.begin");
        var status=$(obj).val();
        if(status==="end"){
            thisAction.find("input.childActionName").attr("placeholder","结束后激活话题名");
            thisAction.find("input.rule").hide();
            thisAction.find("input.sentence").hide();
            thisAction.find("input.endSentence").show();
        }
        else{
            thisAction.find("input.childActionName").attr("placeholder","话题名");
            thisAction.find("input.rule").show();
            thisAction.find("input.sentence").show();
            thisAction.find("input.endSentence").hide();
        }

    }

    //点击生成话题按钮事件
    function buttonToCreateAction(){
        var mainAction=$("div#begin");
        var actions="#actions
";
        mainActionName="name="+mainAction.find("input.mainActionName").val()+"
";
        actions+=mainActionName;
        actions+="action=select
";
        actions+="status="+mainAction.find("select").val()+"
";
        actions+="condition=ask|#visitorname,";
        actions+=mainAction.find("input.rule").val()+",?|";
        actions+=mainAction.find("input.sentence").val()+"|";
        actions+=createProcess(mainAction);
        mainAction.next().children("li").each(function(){
            var status=$(this).children("div.action").children("div.begin").find("select").val();
            if(status!=="end")actions+=createAction(this);
        });
        updateLineNum($("textarea#actionEditor-info").html(actions).attr("id"));
        $("#status_actionEditor").text("已生成");

    }
    //生成话题函数
    function createAction(obj){
        var action=$(obj).children("div.action").children("div.begin");
        var actionInfo={
            name:action.find("input.childActionName").val(),
            status:action.find("select").val(),
            rule:action.find("input.rule").val(),
            sentence:action.find("input.sentence").val(),
            keywords:action.find("input.keywords").val()
        };
        var actions="";
        actions="name="+actionInfo.name+"
";
        actions+="action=select
";
        actions+="status="+actionInfo.status+"
";
        actions+="condition=ask|#visitorname,"+actionInfo.rule+",?|"+actionInfo.sentence+"|";
        actions+=createProcess(action);
        action.next().children("li").each(function(){
            var status=$(this).children().children("div.begin").find("select").val();
            if(status!=="end")actions+=createAction(this);
        });
        return actions;
    }
    //生成 用户行为及 process
    function createProcess(obj){
        var active="";
        var processes="";
        var keywords="";
        var actionName="";
        var behavior="";
        var childActions=$(obj).next().children("li");
        childActions.each(function(){
            var childAction=$(this);
            keywords=childAction.find("input.keywords").val();
            actionName=childAction.find("input.childActionName").val();
            behavior=childAction.find("input.behavior").val();
            endSentence=childAction.find("input.endSentence").val();
            status=childAction.find("select.status").val();
            active+="#visitorname"+behavior+"。=+"+keywords+"~";
            processes+="process=ask=+"+keywords+"|"+actionName+"=active|"+((status==="end")?endSentence:"好的。")+"
";
        });
        processes=active.substring(0,active.length-1)+"
"+processes+"
";
        return processes;
    }

    //加载完成更新各文本域行号 且为各文本域绑定函数
    $("textarea.txt").each(function(){
        var textareaId=$(this).attr("id");
        updateLineNum(textareaId);
        $(this).on("input propertychange",function(){
            updateLineNum(textareaId);
        }).on("scroll",function () {
            G("li_"+$(this).attr("id")).scrollTop=this.scrollTop;
        });
    });
    //刷新行号
    function refreshLineNum() {
        $("textarea.txt").each(function(){
            updateLineNum($(this).attr("id"));
        });
    }

    String.prototype.trim2 = function(){
        return this.replace(/(^\s*)|(\s*$)/g, "");
    };

    function G(objid){
        return document.getElementById(objid);
    }
    function updateLineNum(objid){
        var obj=G(objid);
        var str=obj.value;
        str=str.replace(/\r/gi,"");
        str=str.split("\n");
        n=str.length;
        line(n , "li_"+objid);
    }
    function line(n , liId){
        var num="";
        var lineobj=G(liId);
        for(var i=1;i<=n;i++){
            if(document.all){
                num+=i+"\r\n";
            }else{
                num+=i+"\n";
            }
        }
        lineobj.value=num;
    }
    //hours为空字符串时,cookie的生存期至浏览器会话结束。
    //hours为数字0时,建立的是一个失效的cookie,
    //这个cookie会覆盖已经建立过的同名、同path的cookie(如果这个cookie存在)。
    function setCookie(name,value,day){
        var expires = new Date();
        if(!day)day=1;
        expires.setTime(expires.getTime() + day*24*60*60*1000);
        _expires =";expires=" + expires.toUTCString();
        document.cookie = name + "=" + value + _expires;
    }
    //cookie名获取值
    function getCookieValue(name){
        //读cookie属性,这将返回文档的所有cookie
        var allcookies = document.cookie;
        //查找名为name的cookie的开始位置
        name += "=";
        var pos = allcookies.indexOf(name);
        //如果找到了具有该名字的cookie,那么提取并使用它的值
        if (pos != -1){    //如果pos值为-1则说明搜索"version="失败
            var start = pos + name.length;   //cookie值开始的位置
            var end = allcookies.indexOf(";",start); //从cookie值开始的位置起搜索第一个";"的位置,即cookie值结尾的位置
            if (end == -1) end = allcookies.length; //如果end值为-1说明cookie列表里只有一个cookie
            var value = allcookies.substring(start,end);  //提取cookie的值
            return (value);       //对它解码
        }
        else return "";    //搜索失败,返回空字符串
    }
});


text:
package com.crayon.easysmokes.builder;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.crayon.easysmokes.R;
import com.crayon.easysmokes.SwipeLauncher;
import com.crayon.easysmokes.animation.NotificationHelper;
import com.crayon.easysmokes.data.DataBase;
import com.crayon.easysmokes.data.sqlimports.NadeData;
import com.crayon.easysmokes.model.BundleKey;

import java.security.PublicKey;

/**
 * Created by Jay on 7/12/2016.
 */

public class NadeCursorAdapter extends CursorAdapter {

    NotificationHelper notificationHelper;

    public NadeCursorAdapter(Context context, Cursor cursor, NotificationHelper notificationHelper) {
        super(context, cursor, 0);
        this.notificationHelper = notificationHelper;
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
        return LayoutInflater.from(context).inflate(R.layout.button_nade, viewGroup, false);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        RelativeLayout buttonMain = (RelativeLayout) view.findViewById(R.id.nade_button_main);
        TextView textMain = (TextView) view.findViewById(R.id.nade_button_text);
        Button buttonFav = (Button) view.findViewById(R.id.nade_button_fav);

        final String nadeID = cursor.getString(cursor.getColumnIndex(NadeData.ATT_ID));
        final String nadeName = cursor.getString(cursor.getColumnIndex(NadeData.ATT_NAME));
        final String nadeLevel = cursor.getString(cursor.getColumnIndex(NadeData.ATT_LEVEL));
        final String nadeSide = cursor.getString(cursor.getColumnIndex(NadeData.ATT_SIDE));

        // Set Favorite Icon
        DataBase database = new DataBase(context);
        setHeartIcon(buttonFav, context, database.isFavourited(nadeID));

        textMain.setText(nadeID + " : " + nadeName);

        listener(context, view, nadeID, buttonMain);
        favListener(context, view, nadeID, buttonFav, notificationHelper, (LinearLayout) view.getParent());
    }

    public static void listener(final Context context, final View view,
                                 final String nade, final View button) {

        button.setOnTouchListener(new NadeTouchListener(nade));
    }

    private void favListener(final Context context, final View view,
                             final String nadeID, final Button button,
                             final NotificationHelper notificationHelper,
                             final LinearLayout layout) {

        button.setOnTouchListener(new View.OnTouchListener() {

            DataBase database = new DataBase(context);
            int pressColour = context.getResources().getColor(R.color.colorPrimary);
            int greenNoti = context.getResources().getIdentifier
                    ("shape_notification_green", "drawable", context.getPackageName());
            int redNoti = context.getResources().getIdentifier
                    ("shape_notification_red", "drawable", context.getPackageName());

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN: {
                        Button buttonInstance = (Button) view.findViewById(button.getId());
                        buttonInstance.getBackground()
                                .setColorFilter(pressColour, PorterDuff.Mode.SRC_ATOP);
                        break;
                    }

                    case MotionEvent.ACTION_UP: {
                        Button buttonInstance = (Button) view.findViewById(button.getId());
                        buttonInstance.getBackground().clearColorFilter();
                        if (database.isFavourited(nadeID)) {
                            database.removeFavourite(nadeID);
                            notificationHelper.getNotification("Removed from Favs", redNoti);
                            setHeartIcon(button, context, false);
                        } else {
                            database.addFavourite(nadeID);
                            notificationHelper.getNotification("Added to Favs", greenNoti);
                            setHeartIcon(button, context, true);
                        }
                        buttonInstance.invalidate();
                    }

                    case MotionEvent.ACTION_CANCEL: {
                        Button buttonInstance = (Button) view.findViewById(button.getId());
                        buttonInstance.getBackground().clearColorFilter();
                        buttonInstance.invalidate();
                        break;
                    }
                }
                return true;
            }
        });
    }

    private void setHeartIcon(Button button, Context context, boolean fill) {
        if (fill) {
            button.setBackgroundResource(context.getResources()
                    .getIdentifier("ic_fav_full",
                            "drawable", context.getPackageName()));
        } else {
            button.setBackgroundResource(context.getResources()
                    .getIdentifier("ic_fav_empty",
                            "drawable", context.getPackageName()));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#ifndef _FRAMEWORK_TEXT_H_
#define _FRAMEWORK_TEXT_H_

#include "Macros.h"

/**
 *
 *
 *
 */
namespace framework {

  /**
   *
   *
   *
   */
  class Text : public Label
  {
    /**
     *
     *
     *
     */
    public:
    static const char* FONT;

    /**
     *
     *
     *
     */
    protected:
    string id;

    /**
     *
     *
     *
     */
   public:
    Text(string id, Node* parent = nullptr, bool autocreate = false);
    Text(string id, Node* parent, TextHAlignment textHAlignment, bool autocreate = false);
   ~Text();

    virtual void setText(string id);

    virtual float getWidth();
    virtual float getHeight();
    virtual float getWidthScaled();
    virtual float getHeightScaled();

    virtual const char* data(initializer_list<int> datas);
    virtual const char* data(int data);
    virtual const char* data(int data1, int data2);
    virtual const char* data(int data1, int data2, int data3);

    virtual const char* data(initializer_list<const char*> datas);
    virtual const char* data(const char* data);
    virtual const char* data(const char* data1, const char* data2);
    virtual const char* data(const char* data1, const char* data2, const char* data3);
    virtual const char* data(const char* data1, const char* data2, const char* data3, const char* data4);
    virtual const char* data(string data1, string data2);
    virtual const char* data(string data1, string data2, string data3);

    virtual void addTranslator();
    virtual void removeTranslator();

    Text* deepCopy();
 };
};

#endif


text:
' Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

Imports System.Collections.Immutable
Imports System.IO
Imports System.Threading
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Documents
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
Imports Microsoft.VisualStudio.TableControl
Imports Microsoft.VisualStudio.TableManager
Imports Roslyn.Test.Utilities
Imports Roslyn.Utilities

Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Diagnostics
    Public Class DiagnosticTableDataSourceTests
        <Fact>
        Public Sub TestCreation()
            Using workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(String.Empty)
                Dim provider = New TestDiagnosticService()
                Dim tableManagerProvider = New TestTableManagerProvider()

                Dim table = New VisualStudioDiagnosticListTable(workspace, provider, tableManagerProvider)
                Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)

                Assert.Equal(manager.Identifier, StandardTables.ErrorsTable)
                Assert.Equal(1, manager.Sources.Count())

                Dim source = DirectCast(manager.Sources.First(), AbstractTableDataSource(Of DiagnosticsUpdatedArgs, DiagnosticData))
                AssertEx.SetEqual(table.Columns, manager.GetColumnsForSources(SpecializedCollections.SingletonEnumerable(source)))

                Assert.Equal(ServicesVSResources.DiagnosticsTableSourceName, source.DisplayName)
                Assert.Equal(StandardTableDataSources.ErrorTableDataSource, source.SourceTypeIdentifier)

                Assert.Equal(1, manager.Sinks_TestOnly.Count())

                Dim sinkAndSubscription = manager.Sinks_TestOnly.First()
                Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
                Dim subscription = sinkAndSubscription.Value

                Assert.Equal(0, sink.Entries.Count())
                Assert.Equal(1, source.NumberOfSubscription_TestOnly)

                subscription.Dispose()
                Assert.Equal(0, source.NumberOfSubscription_TestOnly)
            End Using
        End Sub

        <Fact>
        Public Sub TestInitialEntries()
            Using workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(String.Empty)
                Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
                Dim provider = New TestDiagnosticService(CreateItem(workspace, documentId))
                Dim tableManagerProvider = New TestTableManagerProvider()

                Dim table = New VisualStudioDiagnosticListTable(workspace, provider, tableManagerProvider)
                provider.RaiseDiagnosticsUpdated(workspace)

                Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
                Dim source = DirectCast(manager.Sources.First(), AbstractTableDataSource(Of DiagnosticsUpdatedArgs, DiagnosticData))
                Dim sinkAndSubscription = manager.Sinks_TestOnly.First()

                Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
                Assert.Equal(1, sink.Entries.Count)
            End Using
        End Sub

        <Fact>
        Public Sub TestEntryChanged()
            Using workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(String.Empty)
                Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
                Dim provider = New TestDiagnosticService()
                Dim tableManagerProvider = New TestTableManagerProvider()

                Dim table = New VisualStudioDiagnosticListTable(workspace, provider, tableManagerProvider)
                Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)

                Dim source = DirectCast(manager.Sources.First(), AbstractTableDataSource(Of DiagnosticsUpdatedArgs, DiagnosticData))
                Dim sinkAndSubscription = manager.Sinks_TestOnly.First()

                Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)

                provider.Items = New DiagnosticData() {CreateItem(workspace, documentId)}
                provider.RaiseDiagnosticsUpdated(workspace)
                Assert.Equal(1, sink.Entries.Count)

                provider.Items = New DiagnosticData() {}
                provider.RaiseClearDiagnosticsUpdated(workspace, documentId.ProjectId, documentId)
                Assert.Equal(0, sink.Entries.Count)
            End Using
        End Sub

        <Fact>
        Public Sub TestEntry()
            Using workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(String.Empty)
                Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()

                Dim item = CreateItem(workspace, documentId)
                Dim provider = New TestDiagnosticService(item)
                Dim tableManagerProvider = New TestTableManagerProvider()

                Dim table = New VisualStudioDiagnosticListTable(workspace, provider, tableManagerProvider)
                provider.RaiseDiagnosticsUpdated(workspace)

                Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
                Dim source = DirectCast(manager.Sources.First(), AbstractTableDataSource(Of DiagnosticsUpdatedArgs, DiagnosticData))
                Dim sinkAndSubscription = manager.Sinks_TestOnly.First()

                Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
                Dim subscription = sinkAndSubscription.Value

                Dim snapshot = sink.Entries.First().GetCurrentSnapshot()

                Assert.Equal(1, snapshot.Count)

                Dim filename = Nothing
                Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.DocumentName, filename))
                Assert.Equal(Path.Combine(item.OriginalFilePath, item.OriginalFilePath), filename)

                Dim text = Nothing
                Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.Text, text))
                Assert.Equal(item.Message, text)

                Dim line = Nothing
                Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.Line, line))
                Assert.Equal(item.MappedStartLine, line)

                Dim column = Nothing
                Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.Column, column))
                Assert.Equal(item.MappedStartColumn, column)
            End Using
        End Sub

        <Fact>
        Public Sub TestSnapshotEntry()
            Using workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(String.Empty)
                Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()

                Dim item = CreateItem(workspace, documentId)
                Dim provider = New TestDiagnosticService(item)
                Dim tableManagerProvider = New TestTableManagerProvider()

                Dim table = New VisualStudioDiagnosticListTable(workspace, provider, tableManagerProvider)
                provider.RaiseDiagnosticsUpdated(workspace)

                Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
                Dim source = DirectCast(manager.Sources.First(), AbstractTableDataSource(Of DiagnosticsUpdatedArgs, DiagnosticData))
                Dim sinkAndSubscription = manager.Sinks_TestOnly.First()

                Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
                Dim subscription = sinkAndSubscription.Value

                Dim factory = TryCast(sink.Entries.First(), AbstractTableEntriesFactory(Of DiagnosticData))
                Dim snapshot1 = factory.GetCurrentSnapshot()

                factory.OnUpdated(snapshot1.Count)

                Dim snapshot2 = factory.GetCurrentSnapshot()

                Assert.Equal(snapshot1.VersionNumber + 1, snapshot2.VersionNumber)

                Assert.Equal(1, snapshot1.Count)

                Dim filename = Nothing
                Assert.True(snapshot1.TryGetValue(0, StandardTableKeyNames.DocumentName, filename))
                Assert.Equal(Path.Combine(item.OriginalFilePath, item.OriginalFilePath), filename)

                Dim text = Nothing
                Assert.True(snapshot1.TryGetValue(0, StandardTableKeyNames.Text, text))
                Assert.Equal(item.Message, text)

                Dim line = Nothing
                Assert.True(snapshot1.TryGetValue(0, StandardTableKeyNames.Line, line))
                Assert.Equal(item.MappedStartLine, line)

                Dim column = Nothing
                Assert.True(snapshot1.TryGetValue(0, StandardTableKeyNames.Column, column))
                Assert.Equal(item.MappedStartColumn, column)
            End Using
        End Sub

        <Fact>
        Public Sub TestInvalidEntry()
            Using workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(String.Empty)
                Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()

                Dim item = CreateItem(workspace, documentId)
                Dim provider = New TestDiagnosticService(item)
                Dim tableManagerProvider = New TestTableManagerProvider()

                Dim table = New VisualStudioDiagnosticListTable(workspace, provider, tableManagerProvider)
                provider.RaiseDiagnosticsUpdated(workspace)

                Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
                Dim source = DirectCast(manager.Sources.First(), AbstractTableDataSource(Of DiagnosticsUpdatedArgs, DiagnosticData))
                Dim sinkAndSubscription = manager.Sinks_TestOnly.First()

                Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
                Dim subscription = sinkAndSubscription.Value

                Dim snapshot = sink.Entries.First().GetCurrentSnapshot()

                Assert.Equal(1, snapshot.Count)

                Dim temp = Nothing
                Assert.False(snapshot.TryGetValue(-1, StandardTableKeyNames.DocumentName, temp))
                Assert.False(snapshot.TryGetValue(1, StandardTableKeyNames.DocumentName, temp))
                Assert.False(snapshot.TryGetValue(0, "Test", temp))
            End Using
        End Sub

        <Fact>
        Public Sub TestNoHiddenEntry()
            Using workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(String.Empty)
                Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()

                Dim item = CreateItem(workspace, documentId, DiagnosticSeverity.Error)
                Dim item2 = CreateItem(workspace, documentId, DiagnosticSeverity.Hidden)
                Dim provider = New TestDiagnosticService(item, item2)

                Dim tableManagerProvider = New TestTableManagerProvider()

                Dim table = New VisualStudioDiagnosticListTable(workspace, provider, tableManagerProvider)
                provider.RaiseDiagnosticsUpdated(workspace)

                Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
                Dim source = DirectCast(manager.Sources.First(), AbstractTableDataSource(Of DiagnosticsUpdatedArgs, DiagnosticData))
                Dim sinkAndSubscription = manager.Sinks_TestOnly.First()

                Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
                Dim subscription = sinkAndSubscription.Value

                Dim snapshot = sink.Entries.First().GetCurrentSnapshot()

                Assert.Equal(1, snapshot.Count)
            End Using
        End Sub

        <Fact>
        Public Sub TestProjectEntry()
            Using workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(String.Empty)
                Dim projectId = workspace.CurrentSolution.Projects.First().Id

                Dim item = CreateItem(workspace, projectId, Nothing, DiagnosticSeverity.Error)
                Dim provider = New TestDiagnosticService(item)

                Dim tableManagerProvider = New TestTableManagerProvider()

                Dim table = New VisualStudioDiagnosticListTable(workspace, provider, tableManagerProvider)
                provider.RaiseDiagnosticsUpdated(workspace)

                Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
                Dim source = DirectCast(manager.Sources.First(), AbstractTableDataSource(Of DiagnosticsUpdatedArgs, DiagnosticData))
                Dim sinkAndSubscription = manager.Sinks_TestOnly.First()

                Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
                Dim subscription = sinkAndSubscription.Value

                Dim snapshot = sink.Entries.First().GetCurrentSnapshot()

                Assert.Equal(1, snapshot.Count)
            End Using
        End Sub

        <Fact>
        Public Sub TestMultipleWorkspace()
            Using workspace1 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(String.Empty)
                Using workspace2 = CSharpWorkspaceFactory.CreateWorkspaceFromLines(String.Empty)
                    Dim documentId = workspace1.CurrentSolution.Projects.First().DocumentIds.First()
                    Dim projectId = documentId.ProjectId

                    Dim item1 = CreateItem(workspace1, projectId, documentId, DiagnosticSeverity.Error)
                    Dim provider = New TestDiagnosticService(item1)

                    Dim tableManagerProvider = New TestTableManagerProvider()

                    Dim table = New VisualStudioDiagnosticListTable(workspace1, provider, tableManagerProvider)
                    provider.RaiseDiagnosticsUpdated(workspace1)

                    Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
                    Dim source = DirectCast(manager.Sources.First(), AbstractTableDataSource(Of DiagnosticsUpdatedArgs, DiagnosticData))
                    Dim sinkAndSubscription = manager.Sinks_TestOnly.First()

                    Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
                    Dim snapshot = sink.Entries.First().GetCurrentSnapshot()
                    Assert.Equal(1, snapshot.Count)

                    Dim item2 = CreateItem(workspace2, projectId, documentId, DiagnosticSeverity.Error)
                    provider.RaiseDiagnosticsUpdated(workspace2, item2)
                    Assert.Equal(1, sink.Entries.Count)

                    Dim item3 = CreateItem(workspace1, projectId, Nothing, DiagnosticSeverity.Error)
                    provider.RaiseDiagnosticsUpdated(workspace1, item3)

                    Assert.Equal(2, sink.Entries.Count)
                End Using
            End Using
        End Sub

        <Fact>
        Public Sub TestDetailExpander()
            Using workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(String.Empty)
                Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
                Dim projectId = documentId.ProjectId

                Dim item1 = CreateItem(workspace, projectId, documentId, DiagnosticSeverity.Error)
                Dim provider = New TestDiagnosticService(item1)

                Dim tableManagerProvider = New TestTableManagerProvider()

                Dim table = New VisualStudioDiagnosticListTable(workspace, provider, tableManagerProvider)
                provider.RaiseDiagnosticsUpdated(workspace)

                Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
                Dim source = DirectCast(manager.Sources.First(), AbstractTableDataSource(Of DiagnosticsUpdatedArgs, DiagnosticData))
                Dim sinkAndSubscription = manager.Sinks_TestOnly.First()

                Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
                Dim snapshot = sink.Entries.First().GetCurrentSnapshot()
                Assert.Equal(1, snapshot.Count)

                Dim wpfTableEntriesSnapshot = TryCast(snapshot, IWpfTableEntriesSnapshot)
                Assert.NotNull(wpfTableEntriesSnapshot)

                Assert.True(wpfTableEntriesSnapshot.CanCreateDetailsContent(0))

                Dim ui As FrameworkElement = Nothing
                Assert.True(wpfTableEntriesSnapshot.TryCreateDetailsContent(0, ui))

                Dim textBlock = TryCast(ui, TextBlock)
                Assert.Equal(item1.Description, textBlock.Text)
                Assert.Equal(New Thickness(10, 6, 10, 8), textBlock.Padding)
                Assert.Equal(Nothing, textBlock.Background)
            End Using
        End Sub

        <Fact>
        Public Sub TestHyperLink()
            Using workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(String.Empty)
                Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
                Dim projectId = documentId.ProjectId

                Dim item1 = CreateItem(workspace, projectId, documentId, DiagnosticSeverity.Error, "http://link")
                Dim provider = New TestDiagnosticService(item1)

                Dim tableManagerProvider = New TestTableManagerProvider()

                Dim table = New VisualStudioDiagnosticListTable(workspace, provider, tableManagerProvider)
                provider.RaiseDiagnosticsUpdated(workspace)

                Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
                Dim source = DirectCast(manager.Sources.First(), AbstractTableDataSource(Of DiagnosticsUpdatedArgs, DiagnosticData))
                Dim sinkAndSubscription = manager.Sinks_TestOnly.First()

                Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
                Dim snapshot = sink.Entries.First().GetCurrentSnapshot()
                Assert.Equal(1, snapshot.Count)

                Dim wpfTableEntriesSnapshot = TryCast(snapshot, IWpfTableEntriesSnapshot)
                Assert.NotNull(wpfTableEntriesSnapshot)

                Dim ui As FrameworkElement = Nothing
                Assert.True(wpfTableEntriesSnapshot.TryCreateColumnContent(0, ShimTableKeyNames.ErrorCode, False, ui))

                Dim textBlock = TryCast(ui, TextBlock)
                Assert.NotNull(textBlock)
                Assert.Equal(1, textBlock.Inlines.Count)

                Dim hyperLink = TryCast(textBlock.Inlines(0), Hyperlink)
                Assert.NotNull(hyperLink)
                Assert.Equal(1, hyperLink.Inlines.Count)
                Assert.Equal(item1.HelpLink, hyperLink.NavigateUri.OriginalString)

                Dim run = TryCast(hyperLink.Inlines(0), Run)
                Assert.NotNull(run)
                Assert.Equal(item1.Id, run.Text)
            End Using
        End Sub

        <Fact>
        Public Sub TestBingHyperLink()
            Using workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(String.Empty)
                Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
                Dim projectId = documentId.ProjectId

                Dim item1 = CreateItem(workspace, projectId, documentId, DiagnosticSeverity.Error)
                Dim provider = New TestDiagnosticService(item1)

                Dim tableManagerProvider = New TestTableManagerProvider()

                Dim table = New VisualStudioDiagnosticListTable(workspace, provider, tableManagerProvider)
                provider.RaiseDiagnosticsUpdated(workspace)

                Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
                Dim source = DirectCast(manager.Sources.First(), AbstractTableDataSource(Of DiagnosticsUpdatedArgs, DiagnosticData))
                Dim sinkAndSubscription = manager.Sinks_TestOnly.First()

                Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
                Dim snapshot = sink.Entries.First().GetCurrentSnapshot()
                Assert.Equal(1, snapshot.Count)

                Dim wpfTableEntriesSnapshot = TryCast(snapshot, IWpfTableEntriesSnapshot)
                Assert.NotNull(wpfTableEntriesSnapshot)

                Dim ui As FrameworkElement = Nothing
                Assert.True(wpfTableEntriesSnapshot.TryCreateColumnContent(0, ShimTableKeyNames.ErrorCode, False, ui))

                Dim textBlock = TryCast(ui, TextBlock)
                Assert.NotNull(textBlock)
                Assert.Equal(1, textBlock.Inlines.Count)

                Dim hyperLink = TryCast(textBlock.Inlines(0), Hyperlink)
                Assert.NotNull(hyperLink)
                Assert.Equal(1, hyperLink.Inlines.Count)
                Assert.Equal("http://www.bing.com/search?form=VSHELP&q=test test format", hyperLink.NavigateUri.OriginalString)

                Dim run = TryCast(hyperLink.Inlines(0), Run)
                Assert.NotNull(run)
                Assert.Equal(item1.Id, run.Text)
            End Using
        End Sub

        <Fact>
        Public Sub TestHelpLink()
            Using workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(String.Empty)
                Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
                Dim projectId = documentId.ProjectId

                Dim item1 = CreateItem(workspace, projectId, documentId, DiagnosticSeverity.Error, "http://link/")
                Dim provider = New TestDiagnosticService(item1)

                Dim tableManagerProvider = New TestTableManagerProvider()

                Dim table = New VisualStudioDiagnosticListTable(workspace, provider, tableManagerProvider)
                provider.RaiseDiagnosticsUpdated(workspace)

                Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
                Dim source = DirectCast(manager.Sources.First(), AbstractTableDataSource(Of DiagnosticsUpdatedArgs, DiagnosticData))
                Dim sinkAndSubscription = manager.Sinks_TestOnly.First()

                Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
                Dim snapshot = sink.Entries.First().GetCurrentSnapshot()
                Assert.Equal(1, snapshot.Count)

                Dim helpLink As Object = Nothing
                Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.HelpLink, helpLink))

                Assert.Equal(item1.HelpLink, helpLink.ToString())
            End Using
        End Sub

        <Fact>
        Public Sub TestBingHelpLink()
            Using workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(String.Empty)
                Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
                Dim projectId = documentId.ProjectId

                Dim item1 = CreateItem(workspace, projectId, documentId, DiagnosticSeverity.Error)
                Dim provider = New TestDiagnosticService(item1)

                Dim tableManagerProvider = New TestTableManagerProvider()

                Dim table = New VisualStudioDiagnosticListTable(workspace, provider, tableManagerProvider)
                provider.RaiseDiagnosticsUpdated(workspace)

                Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
                Dim source = DirectCast(manager.Sources.First(), AbstractTableDataSource(Of DiagnosticsUpdatedArgs, DiagnosticData))
                Dim sinkAndSubscription = manager.Sinks_TestOnly.First()

                Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
                Dim snapshot = sink.Entries.First().GetCurrentSnapshot()
                Assert.Equal(1, snapshot.Count)

                Dim helpLink As Object = Nothing
                Assert.True(snapshot.TryGetValue(0, StandardTableKeyNames.HelpLink, helpLink))

                Assert.Equal("http://www.bing.com/search?form=VSHELP&q=test%20test%20format", helpLink.ToString())
            End Using
        End Sub

        <Fact>
        Public Sub TestProjectRank()
            Using workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(String.Empty)
                Dim documentId = workspace.CurrentSolution.Projects.First().DocumentIds.First()
                Dim projectId = documentId.ProjectId

                Dim item1 = CreateItem(workspace, projectId, documentId, DiagnosticSeverity.Error)
                Dim provider = New TestDiagnosticService(item1)

                Dim tableManagerProvider = New TestTableManagerProvider()

                Dim table = New VisualStudioDiagnosticListTable(workspace, provider, tableManagerProvider)
                provider.RaiseDiagnosticsUpdated(workspace)

                Dim manager = DirectCast(table.TableManager, TestTableManagerProvider.TestTableManager)
                Dim source = DirectCast(manager.Sources.First(), AbstractTableDataSource(Of DiagnosticsUpdatedArgs, DiagnosticData))
                Dim sinkAndSubscription = manager.Sinks_TestOnly.First()

                Dim sink = DirectCast(sinkAndSubscription.Key, TestTableManagerProvider.TestTableManager.TestSink)
                Dim snapshot = sink.Entries.First().GetCurrentSnapshot()
                Assert.Equal(1, snapshot.Count)

                Dim content As Object = Nothing
                Assert.True(snapshot.TryGetValue(0, ShimTableKeyNames.ProjectRank, content))
                Assert.NotNull(content)
                Assert.Equal(CType(content, Integer), 0)
            End Using
        End Sub

        Private Function CreateItem(workspace As Workspace, documentId As DocumentId, Optional severity As DiagnosticSeverity = DiagnosticSeverity.Error) As DiagnosticData
            Return CreateItem(workspace, documentId.ProjectId, documentId, severity)
        End Function

        Private Function CreateItem(workspace As Workspace, projectId As ProjectId, documentId As DocumentId, Optional severity As DiagnosticSeverity = DiagnosticSeverity.Error, Optional link As String = Nothing) As DiagnosticData
            Return New DiagnosticData("test", "test", "test", "test format", severity, True, 0,
                                      workspace, projectId, documentId, TextSpan.FromBounds(0, 10), "test", 20, 20, 20, 20,
                                      title:="Title", description:="Description", helpLink:=link)
        End Function

        Private Class TestDiagnosticService
            Implements IDiagnosticService

            Public Items As DiagnosticData()

            Public Sub New(ParamArray items As DiagnosticData())
                Me.Items = items
            End Sub

            Public Event DiagnosticsUpdated As EventHandler(Of DiagnosticsUpdatedArgs) Implements IDiagnosticService.DiagnosticsUpdated

            Public Function GetDiagnostics(workspace As Workspace, projectId As ProjectId, documentId As DocumentId, id As Object, cancellationToken As CancellationToken) As IEnumerable(Of DiagnosticData) Implements IDiagnosticService.GetDiagnostics
                Assert.NotNull(workspace)

                If documentId IsNot Nothing Then
                    Return Items.Where(Function(t) t.DocumentId Is documentId).ToImmutableArrayOrEmpty()
                End If

                If projectId IsNot Nothing Then
                    Return Items.Where(Function(t) t.ProjectId Is projectId).ToImmutableArrayOrEmpty()
                End If

                Return ImmutableArray(Of DiagnosticData).Empty
            End Function

            Public Sub RaiseDiagnosticsUpdated(workspace As Workspace, ParamArray items As DiagnosticData())
                Dim item = items(0)

                Dim id = If(CObj(item.DocumentId), item.ProjectId)
                RaiseEvent DiagnosticsUpdated(Me, New DiagnosticsUpdatedArgs(
                        ValueTuple.Create(Of IDiagnosticService, Object)(Me, id), workspace, workspace.CurrentSolution, item.ProjectId, item.DocumentId, items.ToImmutableArray()))
            End Sub

            Public Sub RaiseDiagnosticsUpdated(workspace As Workspace)
                Dim documentMap = Items.Where(Function(t) t.DocumentId IsNot Nothing).Where(Function(t) t.Workspace Is workspace).ToLookup(Function(t) t.DocumentId)

                For Each group In documentMap
                    RaiseEvent DiagnosticsUpdated(Me, New DiagnosticsUpdatedArgs(
                        ValueTuple.Create(Of IDiagnosticService, Object)(Me, group.Key), workspace, workspace.CurrentSolution, group.Key.ProjectId, group.Key, group.ToImmutableArrayOrEmpty()))
                Next

                Dim projectMap = Items.Where(Function(t) t.DocumentId Is Nothing).Where(Function(t) t.Workspace Is workspace).ToLookup(Function(t) t.ProjectId)

                For Each group In projectMap
                    RaiseEvent DiagnosticsUpdated(Me, New DiagnosticsUpdatedArgs(
                        ValueTuple.Create(Of IDiagnosticService, Object)(Me, group.Key), workspace, workspace.CurrentSolution, group.Key, Nothing, group.ToImmutableArrayOrEmpty()))
                Next
            End Sub

            Public Sub RaiseClearDiagnosticsUpdated(workspace As Workspace, projectId As ProjectId, documentId As DocumentId)
                RaiseEvent DiagnosticsUpdated(Me, New DiagnosticsUpdatedArgs(
                    ValueTuple.Create(Of IDiagnosticService, Object)(Me, documentId), workspace, workspace.CurrentSolution, projectId, documentId, ImmutableArray(Of DiagnosticData).Empty))
            End Sub
        End Class
    End Class
End Namespace


text:
var Injector = require('medic-injector').Injector;
var CommandMap = require('./CommandMap');
var EventDispatcher = require('./EventDispatcher');
var Express = require('express');
module.exports = Context;

function Context() {
    this.injector = new Injector();
    this.eventDispatcher = new EventDispatcher();

    this.injector.addMapping('eventDispatcher').toValue(this.eventDispatcher);

    this.commandMap = new CommandMap(this.injector);

    return this;
}

Context.prototype.startup = function() {
    this.eventDispatcher.emit('STARTUP_COMPLETE');
};

Context.prototype.shutdown = function() {
    this.eventDispatcher.emit('SHUTDOWN_COMPLETE');
};


text:
{-# OPTIONS_GHC -XRankNTypes -XTransformListComp #-}

module RnFail048 where

functions :: [forall a. [a] -> [a]]
functions = [take 4, take 5]

output = [() | f <- functions, then f]


text:
import pytest
import sys
import os
import re
os.environ['SENTINEL_ENV'] = 'test'
os.environ['SENTINEL_CONFIG'] = os.path.normpath(os.path.join(os.path.dirname(__file__), '../test_sentinel.conf'))
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'lib'))
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))
import config

from dashd import DashDaemon
from dash_config import DashConfig

def test_dashd():
    config_text = DashConfig.slurp_config_file(config.dash_conf)
    network = 'mainnet'
    is_testnet = False
    genesis_hash = u'00000ffd590b1485b3caadc19b22e6379c733355108f107a430458cdf3407ab6'
    for line in config_text.split("\n"):
        if line.startswith('testnet=1'):
            network = 'testnet'
            is_testnet = True
            genesis_hash = u'00000bafbc94add76cb75e2ec92894837288a481e5c005f6563d91623bf8bc2c'

    creds = DashConfig.get_rpc_creds(config_text, network)
    dashd = DashDaemon(**creds)
    assert dashd.rpc_command is not None

    assert hasattr(dashd, 'rpc_connection')

    # Dash testnet block 0 hash == 00000bafbc94add76cb75e2ec92894837288a481e5c005f6563d91623bf8bc2c
    # test commands without arguments
    info = dashd.rpc_command('getinfo')
    info_keys = [
        'blocks',
        'connections',
        'difficulty',
        'errors',
        'protocolversion',
        'proxy',
        'testnet',
        'timeoffset',
        'version',
    ]
    for key in info_keys:
        assert key in info
    assert info['testnet'] is is_testnet

    # test commands with args
    assert dashd.rpc_command('getblockhash', 0) == genesis_hash


text:
title: Navigation
page_title: Navigation | RadTileList for ASP.NET AJAX Documentation
description: Navigation
slug: tilelist/functionality/navigation
tags: navigation
published: True
position: 0
---

# Navigation

The main purpose of the **RadTileList** control is to create a navigation menu. This is why all **Tile** types have the **NavigateUrl** and **Target** properties. They are used to set the URL to which each respective tile will navigate the browser and precisely how this is done.

The possible targets for the navigation are similar to those a standard *anchor* element offers:

* _blank - opens a new browser window with the designated URL.

* _parent - attempts to navigate the parent frame to the designated URL. If the current frame is the topmost frame it will be navigated.

* _search - uses the search pane, if supported by the browser. Use _blank instead.

* _self - navigates the current frame/window to the designated URL.

* _top - navigates the topmost frame to the designated URL

* any name - navigates the frame from the current window with the given name to the designated URL.

>note Navigation is done with JavaScript which means that all standard limitations apply:
* In order to navigate the topmost or parent frame both pages must come from the same domain to satisfy the same-origin policy.
* Popup blocker programs on the user's machine can prevent opening a new browser window.

>note If the **AutoPostBack** property of the **RadTileList** control is set to **true** a postback will occur instead of navigation. By default (AutoPostBack=false) each tile will act like a large hyperlink.
>To allow certain tiles to navigate to a page while keeping AutoPostBack=true for the TileList, examine the [Allow Tile Navigation with AutoPostBack=true in RadTileList](http://www.telerik.com/support/kb/aspnet-ajax/tilelist/details/allow-tile-navigation-with-autopostback=true-in-radtilelist) KB article.

The following code snippet examines the possible values of the the Tiles' **Target** property and the ways **NavigateUrl** paths can be specified.

````ASP.NET
<telerik:RadTileList runat="server" ID="RadTileList1" Width="1030px" TileRows="3"
	SelectionMode="Multiple">
	<Groups>
		<telerik:TileGroup>
			<telerik:RadImageAndTextTile Shape="Wide" NavigateUrl="http://www.telerik.com/developer-productivity-tools.aspx"
				Target="_blank" Text="UI controls for ASP.NET AJAX, MVC, WPF, Silverlight, Windows 8 and Windows Phone"
				ImageUrl="../../DevTools.png">
			</telerik:RadImageAndTextTile>

			<telerik:RadContentTemplateTile NavigateUrl="http://www.telerik.com/community/forums/aspnet-ajax.aspx"
				Target="_blank" Shape="Wide">
				<ContentTemplate>
					<div style="padding: 10px;">
						<p>Peer-to-Peer Forums</p>
						<p>
							We've been developing controls for ASP.NET AJAX since the technology's inception
							& the contributions from the community prove that.
						</p>
					</div>
				</ContentTemplate>
			</telerik:RadContentTemplateTile>

			<telerik:RadImageTile NavigateUrl="http://www.telerik.com/help/aspnet-ajax/introduction.html"
				 ImageUrl="../../img_documentation.png" Shape="Wide">
				<Title Text="Documentation"></Title>
			</telerik:RadImageTile>
		</telerik:TileGroup>

		<telerik:TileGroup>
			<telerik:RadIconTile Name="About" NavigateUrl="AboutUs.aspx"
				Shape="Square" ImageUrl="../images/AboutUs.png">
				<Title Text="About Us"></Title>
			</telerik:RadIconTile>

			<telerik:RadIconTile Name="Contacts" NavigateUrl="ContactUs.aspx"
				Shape="Square" ImageUrl="../ContactUs.png">
				<Title Text="Contact Us"></Title>
			</telerik:RadIconTile>
		</telerik:TileGroup>

		<telerik:TileGroup>
			<telerik:RadTextTile Name="Telerik" NavigateUrl="http://www.telerik.com" Shape="Wide">
				<Title Text="Visit Telerik"></Title>
			</telerik:RadTextTile>

			<telerik:RadTextTile Name="Empty" Shape="Square" Target="_top">
				<Title Text="I will not navigate"></Title>
			</telerik:RadTextTile>
		</telerik:TileGroup>
	</Groups>
</telerik:RadTileList>
````

The **OnClientTileClicking** event can be used to prevent navigation (according to given criteria) by cancelling the event itself:

````JavaScript
<telerik:RadTileList runat="server" ID="RadTileList1" OnClientTileClicking="OnClientTileClicking">
	<Groups>
		<telerik:TileGroup>
			<telerik:RadIconTile NavigateUrl="somePage.aspx" Target="_blank"></telerik:RadIconTile>
		</telerik:TileGroup>
	</Groups>
</telerik:RadTileList>
<script type="text/javascript">
	function OnClientTileClicking(sender, args)
	{
		var shouldCancel = true; //set according to the desired logic
		args.set_cancel(shouldCancel);
	}
</script>
````


text:
class UserEjb < ActiveRecord::Base
  set_table_name 'UserEJB'

  belongs_to :user, :primary_key => :user, :foreign_key => :id

  TOKEN_PASSWORD = 'tokenpwd'
end


text:
set -e;

__EXE_FILE='Credit_linux/bin/Debug/Credit_linux.exe'

if test -e "$__EXE_FILE";then
  rm "$__EXE_FILE"
fi

zsh ~/Git_Clones/TimePass-Projects/colorPlusPlus/src/run.sh xbuild /nologo Credit_linux/Credit_linux.sln;

echo "\n";
if test -e "$__EXE_FILE";then
  Credit_linux/bin/Debug/Credit_linux.exe;
else
  echo -e "\033[0;36mErrors are there. Fix them"
fi


text:
require 'faraday'
require 'json'

module Dynamiq
  class Client
    # 100ms connection timeout
    DEFAULT_CONNECTION_TIMEOUT = 0.1
    DEFAULT_RETRY_COUNT = 2
    API_VERSION = 'v1'

    class DynamiqError < RuntimeError; end
    class ConnectionError < DynamiqError; end
    class TimeoutError < DynamiqError; end
    class MessageDeliveryError < DynamiqError; end
    class MessageAcknowledgementError < DynamiqError; end
    class ObjectDoesNotExistError < DynamiqError; end
    class ObjectAlreadyExistsError < DynamiqError; end

    attr_reader :connection_timeout, :retry_count, :persistent_connection

    def initialize(url, port, opts={})
      @url = url
      @port = port
      @connection_timeout = opts[:connection_timeout] || DEFAULT_CONNECTION_TIMEOUT
      @retry_count = opts[:retry_count] || DEFAULT_RETRY_COUNT
      # Can't use the || idiom if the value is false
      @persistent_connection = opts.fetch(:persistent_connection, true)
    end

    # Create a Dynamiq topic, if it does not already exist on the server
    # @param topic [String] name of the topic
    # @param opts [Hash] optional parameters
    # @example
    #   @rqs = Dynamiq::Client.new('http://example.io', '9999')
    #   @rqs.create_topic('my_topic')
    # =>
    # true
    #
    def create_topic(topic, opts={})
      resp = retry_unless([201,422]) { connection.put("topics/#{topic}") }
      raise ObjectAlreadyExistsError, JSON.parse(resp.body)["error"] if resp.status == 422
      raise ConnectionError, "Failed to create topic. status: #{resp.status} response: #{resp.body}" unless resp.status == 201
      # No meaningful data in response
      true
    end

    # Create a Dynamiq queue, if it does not already exist on the server
    # @param queue [String] name of the queue
    # @param opts [Hash] optional parameters
    # @example
    #   @rqs = Dynamiq::Client.new('http://example.io', '9999')
    #   @rqs.create_queue('my_queue')
    # =>
    # true
    #
    def create_queue(queue, opts={})
      resp = retry_unless([201,422]) { connection.put("queues/#{queue}") }
      raise ObjectAlreadyExistsError, JSON.parse(resp.body)["error"] if resp.status == 422
      raise ConnectionError, "Failed to create queue. status: #{resp.status} response: #{resp.body}" unless resp.status == 201
      # No meaningful data in response
      true
    end

    # Delete a Dynamiq topic, if it exists on the server
    # @param topic [String] name of the topic
    # @example
    #   @rqs = Dynamiq::Client.new('http://example.io', '9999')
    #   @rqs.delete_topic('my_topic')
    # =>
    # true
    #
    def delete_topic(topic)
      resp = retry_unless([200,404]) { connection.delete("topics/#{topic}") }
      raise ObjectDoesNotExistError, JSON.parse(resp.body) if resp.status == 404
      raise ConnectionError, "Failed to create queue. status: #{resp.status} response: #{resp.body}" unless resp.status == 200
      true
    end

    # Subscribe a queue to a topic
    # @param topic [String] name of the topic
    # @param queue [String] name of the queue
    # @example
    #   @rqs = Dynamiq::Client.new('http://example.io', '9999')
    #   @rqs.assign_queue('my_topic','my_queue')
    # =>
    # List of subscribed queues
    #
    def subscribe_queue(topic, queue)
      resp = retry_unless([200,422]) { connection.put("topics/#{topic}/queues/#{queue}") }
      raise ObjectDoesNotExistError, JSON.parse(resp.body)["error"] if resp.status == 422
      raise ConnectionError, "Failed to subscribe queue to topic. status: #{resp.status} response: #{resp.body}" unless resp.status == 200
      JSON.parse(resp.body)["Queues"]
    end

    # Configure a queue
    # @param queue [String] name of the queue
    # @param opts [Integer] :visibility_timeout The number of seconds to wait before making a message available again
    # @param opts [Integer] :min_partitions The minimum number of partitions for a Queue to serve messages from
    # @param opts [Integer] :max_partitions The maximum number of partitions for a Queue to serve messages from
    # @example
    #   @rqs = Dynamiq::Client.new('http://example.io', '9999')
    #   @rqs.assign_queue('my_topic','my_queue')
    # =>
    # true
    #
    def configure_queue(queue, opts={})
      resp = retry_unless(200) do
        connection.patch do |req|
          req.url "queues/#{queue}"
          req.headers["Content-Type"] = "application/json"
          req.body = JSON.dump(opts)
        end
      end
      raise ConnectionError, "Failed to configure queue. status: #{resp.status} response: #{resp.body}" unless resp.status == 200
      # There is no valuable information in the request body
      true
    end

    # Publish to a Dynamiq topic, which will enqueue to all subscribed queues
    # @param topic [String] name of the topic
    # @param data [Hash] message data
    # @example
    #   @rqs = Dynamiq::Client.new('http://example.io', '9999')
    #   @rqs.publish('my_topic', {:k=>'v'})
    # =>
    # true
    #
    def publish(topic, data)
      resp = retry_unless(200) { connection.put("topics/#{topic}/message", data) }
      raise MessageDeliveryError, "status: #{resp.status} response: #{resp.body}" unless resp.status == 200
      JSON.parse(resp.body)
    end

    # Enqueue to a Dynamiq queue directly
    # @param queue [String] name of the queue
    # @param data [Hash] message data
    # @example
    #   @rqs = Dynamiq::Client.new('http://example.io', '9999')
    #   @rqs.publish('my_topic', {:k=>'v'})
    # =>
    # true
    #
    def enqueue(queue, data)
      resp = retry_unless(200) { connection.put("queues/#{queue}/message", data) }
      raise MessageDeliveryError, "status: #{resp.status} response: #{resp.body}" unless resp.status == 200
      resp.body
    end

    # Ack a Dynamiq message
    # @param queue [String] name of the queue
    # @param message_id [String] id of the message
    # @example
    #   @rqs = Dynamiq::Client.new('http://example.io', '9999')
    #   @rqs.acknowledge('my_queue', 'a3df32')
    # =>
    # true
    #
    def acknowledge(queue, message_id)
      resp = retry_unless(200) { connection.delete("queues/#{queue}/message/#{message_id}") }
      raise MessageAcknowledgementError, "status: #{resp.status} response: #{resp.body}" unless resp.status == 200
      # There is no valuable information in the request body
      true
    end

    # Ack multiple Dynamiq messages
    # @param queue [String] name of the queue
    # @param message_ids [Array] ids of the messages
    # @example
    #   @rqs = Dynamiq::Client.new('http://example.io', '9999')
    #   @rqs.acknowledge_many('my_queue', ['a3df32','zz43545fd','hd65343'])
    # =>
    # {"deleted":3}
    #
    def acknowledge_many(queue, message_ids)
      resp = retry_unless(200) { connection.delete("queues/#{queue}/messages/#{message_ids.join(',')}") }
      raise MessageAcknowledgementError, "status: #{resp.status} response: #{resp.body}" unless resp.status == 200
      # There is no valuable information in the request body
      JSON.parse(resp.body)
    end

    # Receive a batch of Dynamiq messages
    # @param queue [String] name of the queue
    # @param batch_size [Integer] the size of the batch
    # @example
    #   @rqs = Dynamiq::Client.new('http://example.io', '9999')
    #   @rqs.receive('my_queue', 20)
    # =>
    # {...message data}
    #
    def receive(queue, batch_size=10)
      resp = retry_unless([200,404,422]) { connection.get("queues/#{queue}/messages/#{batch_size}") }
      raise ArgumentError, "status: #{resp.status} response: #{resp.body}" if resp.status == 422
      raise ObjectDoesNotExistError, "status: #{resp.status} response: #{resp.body}" if resp.status == 404
      raise StandardError, "status: #{resp.status} response: #{resp.body}" unless resp.status == 200
      JSON.parse(resp.body)
    end

    # Read a Dynamiq queue details
    # @param queue [String] name of the queue
    # @example
    #   @rqs = Dynamiq::Client.new('http://example.io', '9999')
    #   @rqs.queue_details('my_queue')
    # =>
    # {...queue details}
    #
    def queue_details(queue)
      resp = retry_unless([200,404]) { connection.get("queues/#{queue}") }
      raise ObjectDoesNotExistError, "status: #{resp.status} response: #{resp.body}" if resp.status == 404
      raise ConnectionError, "Failed to get queue details. status: #{resp.status} response: #{resp.body}" unless resp.status == 200
      JSON.parse(resp.body)
    end

    # List known Dynamiq queues
    # @example
    #   @rqs = Dynamiq::Client.new('http://example.io', '9999')
    #   @rqs.known_queues
    # =>
    # [...queues]
    #
    def known_queues
      resp = retry_unless(200) { connection.get("queues") }
      raise ConnectionError, "Failed to list known queues. status: #{resp.status} response: #{resp.body}" unless resp.status == 200
      JSON.parse(resp.body)["queues"]
    end

    # List known Dynamiq topics
    # @example
    #   @rqs = Dynamiq::Client.new('http://example.io', '9999')
    #   @rqs.known_topics
    # =>
    # [...topics]
    #
    def known_topics
      resp = retry_unless(200) { connection.get("topics") }
      raise ConnectionError, "Failed to list known topics. status: #{resp.status} response: #{resp.body}" unless resp.status == 200
      JSON.parse(resp.body)["topics"]
    end

    def connection
      @connection ||= Faraday.new(:url=>"#{@url}:#{@port}") do |c|
        c.options.timeout = self.connection_timeout
        # There is a bug somewhere that causes Faraday Retry Middleware to retry 2 * max+1
        # 0 will result in 2 calls (original + 1 retry), which is closer to what we intend
        c.request :retry, :max => 0
        if persistent_connection
          c.adapter :net_http_persistent
        else
          c.adapter Faraday.default_adapter
        end
        c.path_prefix = API_VERSION
      end
    end

    def retry_unless(status_code)
      # Don't modify a value the user passes in
      codes = status_code
      # If it was only a single code passed in, make it an array
      codes = [codes] unless codes.is_a?(Array)

      retries_left = self.retry_count
      result = yield
      # If we haven't seen a known status code, and we have retries left, keep trying
      while !codes.include?(result.status) && retries_left > 0
        retries_left = retries_left - 1
        # Because we're not using a rescue, we can't use the retry keyword
        result = yield
      end
      return result
      rescue Faraday::Error::ConnectionFailed => e
        raise ConnectionError, e
      rescue Faraday::Error::TimeoutError => e
        raise TimeoutError, e
    end
  end
end


text:
Pricing
------------

This corresponds to the recording endpoint

https://www.plivo.com/docs/api/recording/

Provides these calls

    recording = client.Recording.get(recording_id)
    recordings = client.Recording.get_all(...)


text:
import { PurchaseApp_me } from "v2/__generated__/PurchaseApp_me.graphql"
import { AppContainer } from "v2/Apps/Components/AppContainer"
import { SystemContext } from "v2/Artsy"
import { ErrorPage } from "v2/Components/ErrorPage"
import React, { useContext } from "react"
import { Title } from "react-head"
import { createFragmentContainer, graphql } from "react-relay"
import { userIsAdmin } from "v2/Utils/user"
import { PurchaseHistoryFragmentContainer as PurchaseHistory } from "./Components/PurchaseHistory"

export interface PurchaseAppProps {
  me: PurchaseApp_me
}

export const PurchaseApp = (props: any) => {
  const { me } = props
  const { user } = useContext(SystemContext)
  const isAdmin = userIsAdmin(user)
  if (isAdmin) {
    return (
      <AppContainer>
        <Title>My Orders | Artsy</Title>
        <PurchaseHistory me={me} />
      </AppContainer>
    )
  } else {
    // not an admin
    return <ErrorPage code={404} />
  }
}

export const PurchaseAppFragmentContainer = createFragmentContainer(
  PurchaseApp,
  {
    me: graphql`
      fragment PurchaseApp_me on Me {
        ...PurchaseHistory_me
      }
    `,
  }
)


text:
package org.apache.felix.mosgi.jmx.agent.mx4j;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/**
 * Default implementation for the MBeanDescription interface.
 *
 * @author Simone Bordet
 * @version $Revision: 1.1.1.1 $
 */
public class MBeanDescriptionAdapter implements MBeanDescription
{
	public String getMBeanDescription()
	{
		return "Manageable Bean";
	}

	public String getConstructorDescription(Constructor ctor)
	{
		return "Constructor exposed for management";
	}

	public String getConstructorParameterName(Constructor ctor, int index)
	{
		return "param" + (index + 1);
	}

	public String getConstructorParameterDescription(Constructor ctor, int index)
	{
		return "Constructor's parameter n. " + (index + 1);
	}

	public String getAttributeDescription(String attribute)
	{
		return "Attribute exposed for management";
	}

	public String getOperationDescription(Method operation)
	{
		return "Operation exposed for management";
	}

	public String getOperationParameterName(Method method, int index)
	{
		return "param" + (index + 1);
	}

	public String getOperationParameterDescription(Method method, int index)
	{
		return "Operation's parameter n. " + (index + 1);
	}
}


text:
<form>

    {{ widget.display_navigation.id_hidden_field }}
    <input type="hidden"
      id="{{ widget.display_navigation.value_field_id }}_false"
      name="{{ widget.display_navigation.value_field_name }}"
      value="false"
    />
    <input type="checkbox"
      id="{{ widget.display_navigation.value_field_id }}"
      name="{{ widget.display_navigation.value_field_name }}"
      value="true"
      {% if widget.display_navigation.value == "true" %}
      checked="checked"
      {% endif %}
    />

      Display Navigation

    {{ widget.text.id_hidden_field }}

      Enter text

    <textarea
      id="ckeditor"
      name="{{ widget.text.value_field_name }}"
     >
      {{ widget.text.value }}
    </textarea>

    {% for location in widget.client_locations %}
      {{ widget.included_locations.id_hidden_field }}
      <input type="checkbox"
        id="{{ widget.included_locations.value_field_id }}{{ location.id}}"
        name="{{ widget.included_locations.value_field_name }}[]"
        value="{{ location.id }}"
        {% assign locations_array = widget.included_locations.value %}
        {% if locations_array contains location.id %}
         checked
        {% endif %}
      />

        {{ location.name }}
        {{ location.id }}

    {% endfor %}

  <input type="submit" value="Save" class="btn" />
</form>


text:
* relay container(s)

#### PROJECTS LIST
* graphs above table

#### REPOSITORY (cases + files)
* custom facets
* summary section

#### ENTITY PAGES
* relay container(s)

#### CART PAGE
* cart state (redux + localstorage)
* cart buttons on various pages

#### SMART SEARCH

#### QUICK SEARCH


text:
package mil.nga.giat.geowave.ingest.local;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import mil.nga.giat.geowave.accumulo.AccumuloDataStore;
import mil.nga.giat.geowave.accumulo.AccumuloOperations;
import mil.nga.giat.geowave.ingest.AccumuloCommandLineOptions;
import mil.nga.giat.geowave.ingest.GeoWaveData;
import mil.nga.giat.geowave.ingest.IngestTypePluginProviderSpi;
import mil.nga.giat.geowave.store.CloseableIterator;
import mil.nga.giat.geowave.store.DataStore;
import mil.nga.giat.geowave.store.IndexWriter;
import mil.nga.giat.geowave.store.adapter.WritableDataAdapter;

import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.log4j.Logger;

/**
 * This extends the local file driver to directly ingest data into GeoWave
 * utilizing the LocalFileIngestPlugin's that are discovered by the system.
 */
public class LocalFileIngestDriver extends
		AbstractLocalFileDriver<LocalFileIngestPlugin<?>, IngestRunData>
{
	private final static Logger LOGGER = Logger.getLogger(LocalFileIngestDriver.class);
	protected AccumuloCommandLineOptions accumulo;

	public LocalFileIngestDriver(
			final String operation ) {
		super(
				operation);
	}

	@Override
	public void parseOptions(
			final CommandLine commandLine )
			throws ParseException {
		accumulo = AccumuloCommandLineOptions.parseOptions(commandLine);
		super.parseOptions(commandLine);
	}

	@Override
	public void applyOptions(
			final Options allOptions ) {
		AccumuloCommandLineOptions.applyOptions(allOptions);
		super.applyOptions(allOptions);
	}

	@Override
	protected void runInternal(
			final String[] args,
			final List<IngestTypePluginProviderSpi<?, ?>> pluginProviders ) {
		// first collect the local file ingest plugins
		final Map<String, LocalFileIngestPlugin<?>> localFileIngestPlugins = new HashMap<String, LocalFileIngestPlugin<?>>();
		final List<WritableDataAdapter<?>> adapters = new ArrayList<WritableDataAdapter<?>>();
		for (final IngestTypePluginProviderSpi<?, ?> pluginProvider : pluginProviders) {
			LocalFileIngestPlugin<?> localFileIngestPlugin = null;
			try {
				localFileIngestPlugin = pluginProvider.getLocalFileIngestPlugin();

				if (localFileIngestPlugin == null) {
					LOGGER.warn("Plugin provider for ingest type '" + pluginProvider.getIngestTypeName() + "' does not support local file ingest");
					continue;
				}
			}
			catch (final UnsupportedOperationException e) {
				LOGGER.warn(
						"Plugin provider '" + pluginProvider.getIngestTypeName() + "' does not support local file ingest",
						e);
				continue;
			}
			final boolean indexSupported = (accumulo.getIndex(localFileIngestPlugin.getSupportedIndices()) != null);
			if (!indexSupported) {
				LOGGER.warn("Local file ingest plugin for ingest type '" + pluginProvider.getIngestTypeName() + "' does not support dimensionality type '" + accumulo.getType().name() + "'");
				continue;
			}
			localFileIngestPlugins.put(
					pluginProvider.getIngestTypeName(),
					localFileIngestPlugin);
			adapters.addAll(Arrays.asList(localFileIngestPlugin.getDataAdapters(accumulo.getVisibility())));
		}

		AccumuloOperations operations;
		try {
			operations = accumulo.getAccumuloOperations();

		}
		catch (AccumuloException | AccumuloSecurityException e) {
			LOGGER.fatal(
					"Unable to connect to Accumulo with the specified options",
					e);
			return;
		}
		if (localFileIngestPlugins.isEmpty()) {
			LOGGER.fatal("There were no local file ingest type plugin providers found");
			return;
		}
		final DataStore dataStore = new AccumuloDataStore(
				operations);
		try (IngestRunData runData = new IngestRunData(
				adapters,
				dataStore)) {
			processInput(
					localFileIngestPlugins,
					runData);
		}
		catch (final IOException e) {
			LOGGER.fatal(
					"Unexpected I/O exception when reading input files",
					e);
		}
	}

	@Override
	protected void processFile(
			final File file,
			final String typeName,
			final LocalFileIngestPlugin plugin,
			final IngestRunData ingestRunData )
			throws IOException {
		final IndexWriter indexWriter = ingestRunData.getIndexWriter(accumulo.getIndex(plugin.getSupportedIndices()));
		try (CloseableIterator<GeoWaveData<?>> geowaveDataIt = plugin.toGeoWaveData(
				file,
				indexWriter.getIndex().getId(),
				accumulo.getVisibility())) {
			while (geowaveDataIt.hasNext()) {
				final GeoWaveData<?> geowaveData = geowaveDataIt.next();
				final WritableDataAdapter adapter = ingestRunData.getDataAdapter(geowaveData);
				if (adapter == null) {
					LOGGER.warn("Adapter not found for " + geowaveData.getValue());
					continue;
				}
				indexWriter.write(
						adapter,
						geowaveData.getValue());
			}
		}

	}
}


text:
cd "$(dirname "$0")"
cargo update


text:
def store_raw_images():
    neg_images_link = '//image-net.org/api/text/imagenet.synset.geturls?wnid=n07942152'
    neg_image_urls = urllib.request.urlopen(neg_images_link).read().decode()
    pic_num = 953

    if not os.path.exists('neg'):
        os.makedirs('neg')

    for i in neg_image_urls.split('\n'):
        try:
            print(i)
            urllib.request.urlretrieve(i, "neg/"+str(pic_num)+".jpg")
            img = cv2.imread("neg/"+str(pic_num)+".jpg",cv2.IMREAD_GRAYSCALE)
            # should be larger than samples / pos pic (so we can place our image on it)
            resized_image = cv2.resize(img, (100, 100))
            cv2.imwrite("neg/"+str(pic_num)+".jpg",resized_image)
            pic_num += 1

        except Exception as e:
            print(str(e)


text:
<?php

namespace GuzzleHttp;

/**
 * Manages query string variables and can aggregate them into a string
 */
class Query extends Collection
{
    const RFC3986 = 'RFC3986';
    const RFC1738 = 'RFC1738';

    /** @var bool URL encode fields and values */
    private $encoding = self::RFC3986;

    /** @var callable */
    private $aggregator;

    /**
     * Parse a query string into a Query object
     *
     * $urlEncoding is used to control how the query string is parsed and how
     * it is ultimately serialized. The value can be set to one of the
     * following:
     *
     * - true: (default) Parse query strings using RFC 3986 while still
     *   converting "+" to " ".
     * - false: Disables URL decoding of the input string and URL encoding when
     *   the query string is serialized.
     * - 'RFC3986': Use RFC 3986 URL encoding/decoding
     * - 'RFC1738': Use RFC 1738 URL encoding/decoding
     *
     * @param string      $query       Query string to parse
     * @param bool|string $urlEncoding Controls how the input string is decoded
     *                                 and encoded.
     * @return self
     */
    public static function fromString($query, $urlEncoding = true)
    {
        static $qp;
        if (!$qp) {
            $qp = new QueryParser();
        }

        $q = new static();

        if ($urlEncoding !== true) {
			/** @var Query $q */
            $q->setEncodingType($urlEncoding);
        }

        $qp->parseInto($q, $query, $urlEncoding);

        return $q;
    }

    /**
     * Convert the query string parameters to a query string string
     *
     * @return string
     */
    public function __toString()
    {
        if (!$this->data) {
            return '';
        }

        // The default aggregator is statically cached
        static $defaultAggregator;

        if (!$this->aggregator) {
            if (!$defaultAggregator) {
                $defaultAggregator = self::phpAggregator();
            }
            $this->aggregator = $defaultAggregator;
        }

        $result = '';
        $aggregator = $this->aggregator;

        foreach (call_user_func_array($aggregator, array($this->data)) as $key => $values) {
            foreach ($values as $value) {
                if ($result) {
                    $result .= '&';
                }
                if ($this->encoding == self::RFC1738) {
                    $result .= urlencode($key);
                    if ($value !== null) {
                        $result .= '=' . urlencode($value);
                    }
                } elseif ($this->encoding == self::RFC3986) {
                    $result .= rawurlencode($key);
                    if ($value !== null) {
                        $result .= '=' . rawurlencode($value);
                    }
                } else {
                    $result .= $key;
                    if ($value !== null) {
                        $result .= '=' . $value;
                    }
                }
            }
        }

        return $result;
    }

    /**
     * Controls how multi-valued query string parameters are aggregated into a
     * string.
     *
     *     $query->setAggregator($query::duplicateAggregator());
     *
     * @param callable $aggregator Callable used to convert a deeply nested
     *     array of query string variables into a flattened array of key value
     *     pairs. The callable accepts an array of query data and returns a
     *     flattened array of key value pairs where each value is an array of
     *     strings.
     *
     * @return self
     */
    public function setAggregator($aggregator)
    {
        $this->aggregator = $aggregator;

        return $this;
    }

    /**
     * Specify how values are URL encoded
     *
     * @param string|bool $type One of 'RFC1738', 'RFC3986', or false to disable encoding
     *
     * @return self
     * @throws \InvalidArgumentException
     */
    public function setEncodingType($type)
    {
        if ($type === false || $type === self::RFC1738 || $type === self::RFC3986) {
            $this->encoding = $type;
        } else {
            throw new \InvalidArgumentException('Invalid URL encoding type');
        }

        return $this;
    }

    /**
     * Query string aggregator that does not aggregate nested query string
     * values and allows duplicates in the resulting array.
     *
     * Example: http://test.com?q=1&q=2
     *
     * @return callable
     */
    public static function duplicateAggregator()
    {
        return function (array $data) {
            return Query::walkQuery($data, '', function ($key, $prefix) {
                return is_int($key) ? $prefix : "{$prefix}[{$key}]";
            });
        };
    }

    /**
     * Aggregates nested query string variables using the same technique as
     * ``http_build_query()``.
     *
     * @param bool $numericIndices Pass false to not include numeric indices
     *     when multi-values query string parameters are present.
     *
     * @return callable
     */
    public static function phpAggregator($numericIndices = true)
    {
        return function (array $data) use ($numericIndices) {
            return Query::walkQuery(
                $data,
                '',
                function ($key, $prefix) use ($numericIndices) {
                    return !$numericIndices && is_int($key)
                        ? "{$prefix}[]"
                        : "{$prefix}[{$key}]";
                }
            );
        };
    }

    /**
     * Easily create query aggregation functions by providing a key prefix
     * function to this query string array walker.
     *
     * @param array    $query     Query string to walk
     * @param string   $keyPrefix Key prefix (start with '')
     * @param callable $prefixer  Function used to create a key prefix
     *
     * @return array
     */
    public static function walkQuery(array $query, $keyPrefix, $prefixer)
    {
        $result = array();
        foreach ($query as $key => $value) {
            if ($keyPrefix) {
                $key = call_user_func_array($prefixer, array($key, $keyPrefix));
            }
            if (is_array($value)) {
                $result += self::walkQuery($value, $key, $prefixer);
            } elseif (isset($result[$key])) {
                $result[$key][] = $value;
            } else {
                $result[$key] = array($value);
            }
        }

        return $result;
    }
}


text:
#if !defined(BOOST_FUSION_DEQUE_DETAIL_DEQUE_INITIAL_SIZE_26112006_2139)
#define BOOST_FUSION_DEQUE_DETAIL_DEQUE_INITIAL_SIZE_26112006_2139

#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/mpl/find.hpp>
#include <boost/mpl/begin.hpp>
#include <boost/mpl/distance.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/vector.hpp>

namespace boost { namespace fusion {

    struct void_;

namespace detail {

    template<BOOST_PP_ENUM_PARAMS(FUSION_MAX_DEQUE_SIZE, typename T)>
    struct deque_initial_size
    {
        typedef mpl::vector<BOOST_PP_ENUM_PARAMS(FUSION_MAX_DEQUE_SIZE, T)> args;
        typedef typename mpl::find<args, void_>::type first_void;
        typedef typename mpl::distance<typename mpl::begin<args>::type, first_void>::type type;
    };
}}}

#endif


text:
require 'json'

module SensuHelper
  def self.loadChecks()
    result = `/etc/init.d/sensu-server restart && /etc/init.d/sensu-api restart`
    return result
  end
end


text:
.ng-touched.ng-invalid {
    border: 1px solid red !important;
}

.ng-submitted .ng-invalid {
    border: 1px solid red !important;
}
.error {
  color:red;
}

select.ng-valid, input.ng-valid {
  background-color: #c8ffd6 !important;
  background-color: rgba(233, 255, 48, 0.27) !important;
}