text:
function SplitType() {
    this.XOR = "XOR",
       this.OR = "OR",
       this.AND = "AND"
}
function JoinType() {
    this.XOR = "XOR",
      this.OR = "OR",
      this.AND = "AND"
}
function WorkItemNumStrategy() {
    this.ParticipantNumber = "ParticipantNumber";
    this.OperatorNumber = "OperatorNumber";
}
function FinishRule() {
    this.FinishAll = "FinishAll";
    this.SpecifyNum = "SpecifyNum";
    this.SpecifyPercent = "SpecifyPercent";
}
function ParticipantorType() {
    this.Person = "Person";
    this.Role = "Role";
    this.Org = "Org";
}
function ParticipantType() {
    this.Participantor = "Participantor";
    this.ProcessStarter = "ProcessStarter";
    this.SpecialActivity = "SpecialActivity";
    this.RelevantData = "RelevantData";
    this.CustomRegular = "CustomRegular";
    this.ProcessExecutor = "ProcessExecutor";
    this.RelateRegular = "RelateRegular";
}
function FreeRangeStrategy() {
    this.FreeWithinProcess = "FreeWithinProcess";
    this.FreeWithinActivities = "FreeWithinActivities";
    this.FreeWithinNextActivites = "FreeWithinNextActivites";
}
function TimeLimitStrategy() {
    this.LimitTime = "setLimit";
    this.RelevantLimitTime = "RelevantLimitTime";
}
function RemindStrategy() {
    this.RemindLimtTime = "RemindLimtTime";
    this.RemindRelevantLimitTime = "RemindRelevantLimitTime";
}
function InvokePattern() {
    this.Synchronous = "Synchronous";
    this.Asynchronous = "Asynchronous";
}
function TriggerEventType() {
    ActivityBeforeCreate = 1;
    ActivityBeforeStart = 2;
    ActivityAfterStart = 3;
    ActivityAfterOverTime = 4;
    ActivityAfterTerminate = 5;
    ActivityCompleted = 6;
    ActivityBeforeRemind = 7;
    WorkItemBeforeCreate = 21;
    WorkItemAtferCreate = 22;
    WorkItemExecuting = 23;
    WorkItemCompleted = 24;
    WorkItemError = 25;
    WorkItemCanncel = 26;
    WorkItemOverTime = 27;
    WorkItemSuspended = 28;
}
function ActionPattern() {
    this.Method = "Method";
    this.WebService = "WebService";
    this.BusinessOperation = "BusinessOperation";
}
function ParameterDirection() {
    this.In = "In";
    this.Out = "Out";
    this.Ref = "Ref";
}
function ActivateRuleType() {
    this.DirectRunning = "DirectRunning";
    this.WaitActivate = "WaitActivate";
    this.AutoSkip = "AutoSkip";
}
function ResetParticipant() {
    this.FirstParticipantor = 1;// "FirstParticipantor";
    this.LastParticipantor = 2;// "LastParticipantor";
}

function removeTab(remove) {
    var tabs = $('#tabcontainer').find("li");
    tabs.each(function (i) {
        if (i > 0) {
            $("#tab" + this.id).hide();
            if (remove) $(this).remove();
        }
        else {
            this.className = "tabBg7";
        }
    });
}
function initStartActivity(activity) {
    removeTab(true);
    $("#row_joinType").remove();
    $("#row_propertyandproxy").remove();
    $("#row_priority").remove();
    $("#row_businessSet").remove();
    $("#row_isSpecifyURL").remove();
    $("#row_urltype").remove();
    $("#row_CustomizeURL").remove();
    $("#row_description").css("clear", "both");
}
function initManualActivity(activity) {
    if (activity.participant && activity.participant.participantType) {
        switch (activity.participant.participantType) {
            case "Participantor":
                $("#rblOrganization").prop('checked', true);
                $("#txtParticipantRule").attr("disabled", "disabled");
                $("#txtspecialActivity").attr("disabled", "disabled");
                $("#txtParticipantRule").val("");
                $("#txtspecialActivity").val("");
                break;
            case "ProcessStarter":
                $("#rblProcessStarter").prop('checked', true);
                $("#txtParticipantRule").attr("disabled", "disabled");
                $("#txtspecialActivity").attr("disabled", "disabled");
                $("#txtParticipantRule").val("");
                $("#txtspecialActivity").val(""); break;
            case "ProcessExecutor":
                $("#rblSpecialActivity").prop('checked', true);
                $("#txtspecialActivity").val(activity.participant.participantValue);
                $("#txtParticipantRule").val("");
                $("#txtParticipantRule").attr("disabled", "disabled");
                $("#txtspecialActivity").removeAttr("disabled");
                $("#orgorrole").attr("disabled", "disabled");
                break;
            case "CustomRegular":
                $("#rblParticipantRule").prop('checked', true);
                $("#txtParticipantRule").val(activity.participant.participantValue);
                $("#txtspecialActivity").val("");
                $("#txtspecialActivity").attr("disabled", "disabled");
                $("#txtParticipantRule").removeAttr("disabled");
                $("#orgorrole").attr("disabled", "disabled");
              //  $scope.Participant().ParticipantType = Type.CustomRegular;
                break;
        }
    }
    else {
        activity.participant.participantType = "Participantor";
        $("#txtParticipantRule").attr("disabled", "disabled");
        $("#txtspecialActivity").attr("disabled", "disabled");
        $("#txtParticipantRule").val("");
        $("#txtspecialActivity").val("");
    }
    if ($("#chbIsTimeLimitSet").attr("Checked")) {
        $("#txtLimitTimeHour").removeAttr("disabled");
        $("#txtLimitTimeMinute").removeAttr("disabled");
        $("#txtRelevantData").removeAttr("disabled");
        $("#chbIsSendMessageForOvertime").removeAttr("disabled");
        $("#txtRemindLimtTimeHour").removeAttr("disabled");
        $("#txtRemindLimtTimeMinute").removeAttr("disabled");
        $("#txtRemindRelevantData").removeAttr("disabled");
        $("#chbisSendMessageForRemind").removeAttr("disabled");
        $("#rabRelevantLimitTime").removeAttr("disabled");
        $("#rabTimeLimitStrategy").removeAttr("disabled");
        $("#rabRemindLimtTime").removeAttr("disabled");
        $("#rabRemindRelevantLimitTime").removeAttr("disabled");
    }
    else {
        $("#txtLimitTimeHour").attr("disabled", "disabled");
        $("#txtLimitTimeMinute").attr("disabled", "disabled");
        $("#txtRelevantData").attr("disabled", "disabled");
        $("#chbIsSendMessageForOvertime").attr("disabled", "disabled");
        $("#txtRemindLimtTimeHour").attr("disabled", "disabled");
        $("#txtRemindLimtTimeMinute").attr("disabled", "disabled");
        $("#txtRemindRelevantData").attr("disabled", "disabled");
        $("#chbisSendMessageForRemind").attr("disabled", "disabled");
        $("#rabRelevantLimitTime").attr("disabled", "disabled");
        $("#rabTimeLimitStrategy").attr("disabled", "disabled");
        $("#rabRemindLimtTime").attr("disabled", "disabled");
        $("#rabRemindRelevantLimitTime").attr("disabled", "disabled");

    }
    if (activity.customURL) {
        if (activity.customURL.urlType == "CustomURL") {
            $("#rbCustomizeURL").prop('checked', true);
            $("#txtSpecifyURL").removeAttr("disabled");
            activity.customURL.urlType = "CustomURL";
        }
        else {
            $("#rbDefaultURL").prop('checked', true);
            $("#txtSpecifyURL").attr("disabled", "disabled");
            activity.customURL.urlType = "DefaultURL";
        }
    }
    var activateRuleType = new ActivateRuleType();
    var resetParticipant = new ResetParticipant();
    if (activity.activateRule) {
        if (activity.activateRule.activateRuleType == activateRuleType.DirectRunning) {
            $("#rblDirectRunning").attr("Checked", "checked");
        }
        else if (activity.activateRule.activateRuleType == activateRuleType.WaitActivate) {
            $("#rblDisenabled").attr("Checked", "checked");
        }
        else if (activity.activateRule.activateRuleType == activateRuleType.AutoSkip)//可选规则
        {
            $("#rblAutoAfter").attr("Checked", "checked");
        }
        if (activity.resetParticipant == resetParticipant.FirstParticipantor) {
            $("#rbFirstParticipantor").attr("Checked", "checked");
        }
        else if (activity.resetParticipant == resetParticipant.LastParticipantor)  //重新启动规则
        {
            $("#rbLastParticipantor").attr("Checked", "checked");
        }
    }
    if (activity.freeFlowRule) {
        var freeRangeStrategy = new FreeRangeStrategy();
        if (activity.freeFlowRule.freeRangeStrategy == freeRangeStrategy.FreeWithinProcess) {
            $("#rblFreeWithinProcess").attr("Checked", "checked");
        }
        else if (activity.freeFlowRule.freeRangeStrategy == freeRangeStrategy.FreeWithinActivities) {
            $("#rblFreeWithinActivities").attr("Checked", "checked");
        }
        else if (activity.freeFlowRule.freeRangeStrategy == freeRangeStrategy.FreeWithinNextActivites) {
            $("#rblFreeWithinNextActivites").attr("Checked", "checked");
        }; //自由范围设置策略
    }

    if ($("#chbIsFreeActivity").attr("checked")) {
        $(".FreeActivity").find("input").removeAttr("disabled");
    }
    else {
        $(".FreeActivity").find("input").attr("disabled", "disabled");
    }
    if ($("#chbIsMulWIValid").attr("checked")) {
        $(".MulWIValidConfigure").find("input:radio").removeAttr("disabled");
        $(".MulWIValidConfigure").find("input:checkbox").removeAttr("disabled");
    }
    else {
        $(".MulWIValidConfigure").find("input").attr("disabled", "disabled");
    }
    if (activity.multiWorkItem && activity.multiWorkItem.workItemNumStrategy) {
        var workItemNumStrategy = new WorkItemNumStrategy();
        var finishRule = new FinishRule();
        if (activity.multiWorkItem.workItemNumStrategy == workItemNumStrategy.ParticipantNumber) {
            $("#rblParticipantNumber").prop('checked', true);
        }
        else {
            $("#rblOperatorNumber").prop('checked', true);
        }
        if (activity.multiWorkItem.isSequentialExecute)//顺序执行工作项
        {
            $("#rabYIsSequentialExecute").prop('checked', true);
        }
        else {
            $("#rabNIsSequentialExecute").prop('checked', true);
        }
        if (activity.multiWorkItem.finishRule == finishRule.FinishAll)  //完成规则设定
        {
            $("#rblFinishAll").prop('checked', true);
        }
        else if (activity.multiWorkItem.finishRule == finishRule.SpecifyNum) {
            $("#rblSpecifyNum").prop('checked', true);
        }
        else {
            $("#rblSpecifyPercent").prop('checked', true);
        }
        if (activity.multiWorkItem.isAutoCancel)//顺序执行工作项
        {
            $("#rabYIsAutoCancel").prop('checked', true);
        }
        else {
            $("#rabNIsAutoCancel").prop('checked', true);
        }
    }
    if (activity.timeLimit.timeLimitInfo) {
        var timeLimitStrategy = new TimeLimitStrategy();
        if (activity.timeLimit.timeLimitInfo.timeLimitStrategy == timeLimitStrategy.LimitTime) {
            $("#rabTimeLimitStrategy").prop('checked', true);
        }
        else {
            $("#rabRelevantLimitTime").prop('checked', true);
        }
    }
    if (activity.timeLimit.RemindInfo) {
        var remindStrategy = new RemindStrategy();
        if (activity.timeLimit.remindInfo.remindStrategy == remindStrategy.RemindLimtTime) {
            $("#rabRemindLimtTime").prop('checked', true);
        }
        else {
            $("#rabRemindRelevantLimitTime").prop('checked', true);
        }
    }
}
function initRouterActivity() {
    removeTab(true);
    $("#row_propertyandproxy").remove();
    $("#row_priority").remove();
    $("#row_businessSet").remove();
    $("#row_isSpecifyURL").remove();
    $("#row_urltype").remove();
    $("#row_CustomizeURL").remove();
}
function initSubflowActivity(activity) {
    initManualActivity(activity);
}
function initAutoActivity(activity) {
    $("#participantor").remove();
    $("#tabparticipantor").hide();
    $("#task").remove();
    $("#tabtask").hide();
    $("#limit").remove();
    $("#tablimit").hide();
    $("#task").remove();
    $("#tabtask").hide();
    $("#event").remove();
    $("#tabevent").hide();
    $("#freeActivity").remove();
    $("#tabfreeActivity").hide();
    $("#row_propertyandproxy").remove();
    $("#row_priority").remove();
}
function initEndActivity(activity) {
    removeTab(true);
    $("#row_splitType").remove();
    $("#row_propertyandproxy").remove();
    $("#row_priority").remove();
    $("#row_businessSet").remove();
    $("#row_isSpecifyURL").remove();
    $("#row_urltype").remove();
    $("#row_CustomizeURL").remove();
    $("#row_joinType").css("clear", "both");
    $("#row_description").css("clear", "both");
}
function initProcessActivity(activity) {
    initManualActivity(activity);
}
function ActivityDetailCtrl($scope) {
    $scope.processDefine = window.parent.$("#actionDialog").find("#bg_div_iframe")[0].contentWindow.processDefine;
    $scope.activity = function () {
        var currentActivity = "";
        //var processDefID = $.query.get("processDefID");
        var activityID = $.query.get("activityID");
        angular.forEach($scope.processDefine.activities, function (activitie) {
            if (activitie.id == activityID) {//&&processDefID == $scope.processDefine.id) {
            	currentActivity= activitie;
               if (activitie.newID==null) {
            	   activitie.newID = activityID;
                }
                if (!activitie.splitType) {
                    var splitType = new SplitType();
                    activitie.splitType = splitType.XOR;
                }
                if (!activitie.joinType) {
                    var joinType = new JoinType();
                    activitie.joinType = joinType.AND;
                }
                if (activitie.multiWorkItem) {
                    if (!activitie.multiWorkItem.finishRquiredNum) {
                    	activitie.multiWorkItem.finishRquiredNum = 0;
                    }
                    if (!activitie.multiWorkItem.finishRequiredPercent) {
                    	activitie.multiWorkItem.finishRequiredPercent = 0;
                    }
                }
                    window.parent.$("#actionDialog").find("#bg_div_iframe")[0].contentWindow.editActivityName(activitie.id, activitie.name);
            }
        });
        return currentActivity;
    };
    $scope.participant = function () {
        var participant = new Object();
        if ($scope.activity().participant) {
            participant = $scope.activity().participant;
        }
        else {
            if ($scope.activity().activityType == "ManualActivity" || $scope.activity().activityType == 2) {
                $scope.activity().participant = participant;
            }
        }
        return participant;
    };
    $scope.customURL = function () {
        var customURL = new Object();
        if ($scope.activity().customURL) {
        	customURL = $scope.activity().customURL;
        }
        else {
            if ($scope.activity().activityType == "ManualActivity" || $scope.activity().activityType == 2) {
                $scope.activity().customURL = customURL;
            }
        }
        return customURL;
    }
    $scope.businessSet = function (url) {
        if (url == "rbCustomizeURL") {
            $("#rbCustomizeURL").prop('checked', true);
            $("#txtSpecifyURL").removeAttr("disabled");
            //  $("#rbDefaultURL").attr("disabled", "disabled");
            $scope.customURL().urlType = "CustomURL";

        }
        else {
            $("#rbDefaultURL").prop('checked', true);
            $("#txtSpecifyURL").attr("disabled", "disabled");
            $scope.customURL().urlType = "DefaultURL";
        }
    }
    $scope.addParticipant = function () {
        //var participantors = openOperateDialog("添加参与者", "../../Workflow/ChooseParticipantor.aspx", 980, 700, true, 1);
        var participantors = openTopDialog("actionDialog3", "workflow/designer/participantor", "添加参与者",980, 700, true);
        if (participantors == null) return;
        if (participantors.length != 0) {
            var tbody = $("tbody", "#gvOrgizationOrRole_container");
            var index = $("tr", tbody).length;
            var count = participantors.length;
            for (var i = 0; i < participantors.length; i++) {
                if ($("tr", tbody).find("td:contains('" + participantors[i].id + "')").length > 0)//存在的不添加
                    continue;
                var participantorType = new ParticipantorType();
                switch (participantors[i].type) {
                    case "人员": participantors[i].type = participantorType.Person; break;
                    case "角色": participantors[i].type = participantorType.Role; break;
                    case "组织": participantors[i].type = participantorType.Org; break;
                }
                if (!$scope.participant().participantors) {
                    var tmpParticipantors = new Array();
                    tmpParticipantors.push({ id: participantors[i].id, name: participantors[i].name, sortOrder: count + index - i, participantorType: participantors[i].type });
                    $scope.activity().participant = new Object();
                    $scope.activity().participant.participantors = tmpParticipantors;
                }
                else {
                    $scope.activity().participant.participantors.push({ id: participantors[i].id, name: participantors[i].name, sortOrder: count + index - i, participantorType: participantors[i].type });
                }
            }
        }
    };
    $scope.delParticipantor = function () {
        if (!confirm("是否确定删除记录?")) {
            return false;
        }
        var table = $("#gvOrgizationOrRole_container");
        var rad = table.find(":checked ").first();
        //alert($(rad).val());
        angular.forEach($scope.participant().participantors, function (participantor) {
            if ($(rad).val() == participantor.id) {
                var position = $scope.activity().participant.participantors.indexOf(participantor);
                // alert("xuan");
                $scope.activity().participant.participantors.splice(position, 1);
            }
        });

    };
    $scope.chooseParticipantorType = function (participantorType) {
        var type = new ParticipantType();
        if ("rblParticipantRule" == participantorType) {
            $("#txtParticipantRule").val($scope.participant().participantValue);
            $("#txtspecialActivity").val("");
            $("#txtspecialActivity").attr("disabled", "disabled");
            $("#txtParticipantRule").removeAttr("disabled");
            $("#orgorrole").attr("disabled", "disabled");
            $scope.participant().participantType = type.CustomRegular;
        }
        else if ("rblSpecialActivity" == participantorType) {
            $("#txtspecialActivity").val($scope.participant().participantValue);
            $("#txtParticipantRule").val("");
            $("#txtParticipantRule").attr("disabled", "disabled");
            $("#txtspecialActivity").removeAttr("disabled");
            $("#orgorrole").attr("disabled", "disabled");
            $scope.participant().participantType = type.ProcessExecutor;
        }
        else {
            if ("rblProcessStarter" == participantorType) {

                $scope.participant().participantType = type.ProcessExecutor;
            }
            else {
                $scope.participant().participantType = type.Participantor;
            }
            $("#txtParticipantRule").attr("disabled", "disabled");
            $("#txtspecialActivity").attr("disabled", "disabled");
            $("#txtParticipantRule").val("");
            $("#txtspecialActivity").val("");
        }
    };
    $scope.timeLimit = function () {
        var timeLimit = new Object();
        // alert($scope.activity().Participant);
        if ($scope.activity().timeLimit) {
            timeLimit = $scope.activity().timeLimit;
        }
        else {
            if ($scope.activity().activityType == "ManualActivity" || $scope.activity().activityType == 2) {

                $scope.activity().timeLimit = timeLimit;
            }
        }
        return timeLimit;
    };
    $scope.setLimit = function () {
        if ($("#chbIsTimeLimitSet").attr("Checked")) {
            $("#txtLimitTimeHour").removeAttr("disabled");
            $("#txtLimitTimeMinute").removeAttr("disabled");
            $("#txtRelevantData").removeAttr("disabled");
            $("#chbIsSendMessageForOvertime").removeAttr("disabled");
            $("#txtRemindLimtTimeHour").removeAttr("disabled");
            $("#txtRemindLimtTimeMinute").removeAttr("disabled");
            $("#txtRemindRelevantData").removeAttr("disabled");
            $("#chbisSendMessageForRemind").removeAttr("disabled");
            $("#rabRelevantLimitTime").removeAttr("disabled");
            $("#rabTimeLimitStrategy").removeAttr("disabled");
            $("#rabRemindLimtTime").removeAttr("disabled");
            $("#rabRemindRelevantLimitTime").removeAttr("disabled");
        }
        else {
            $("#txtLimitTimeHour").attr("disabled", "disabled");
            $("#txtLimitTimeMinute").attr("disabled", "disabled");
            $("#txtRelevantData").attr("disabled", "disabled");
            $("#chbIsSendMessageForOvertime").attr("disabled", "disabled");
            $("#txtRemindLimtTimeHour").attr("disabled", "disabled");
            $("#txtRemindLimtTimeMinute").attr("disabled", "disabled");
            $("#txtRemindRelevantData").attr("disabled", "disabled");
            $("#chbisSendMessageForRemind").attr("disabled", "disabled");
            $("#rabRelevantLimitTime").attr("disabled", "disabled");
            $("#rabTimeLimitStrategy").attr("disabled", "disabled");
            $("#rabRemindLimtTime").attr("disabled", "disabled");
            $("#rabRemindRelevantLimitTime").attr("disabled", "disabled");

        }
    };
    $scope.chooseLimit = function (id) {
        var timeLimitStrategy = new TimeLimitStrategy();
        if (id == "rabTimeLimitStrategy") {
            $("#txtRelevantData").attr("disabled", "disabled");
            $("#txtLimitTimeHour").removeAttr("disabled");
            $("#txtLimitTimeMinute").removeAttr("disabled");
            if (!$scope.timeLimit().timeLimitInfo) {
                $scope.timeLimit().timeLimitInfo = new Object();
            }
            $scope.timeLimit().timeLimitInfo.timeLimitStrategy = timeLimitStrategy.setLimit;
        }
        else {
            $("#txtLimitTimeHour").attr("disabled", "disabled");
            $("#txtLimitTimeMinute").attr("disabled", "disabled");
            //alert("1");
            $("#txtRelevantData").removeAttr("disabled");
            if (!$scope.timeLimit().timeLimitInfo) {
                $scope.timeLimit().timeLimitInfo = new Object();
            }
            $scope.timeLimit().timeLimitInfo.timeLimitStrategy = timeLimitStrategy.RelevantLimitTime;
        }
    };
    $scope.chooseRemind = function (id) {
        var remindStrategy = new RemindStrategy();
        if (id == "rabRemindLimtTime") {
            $("#txtRemindRelevantData").attr("disabled", "disabled");
            $("#txtRemindLimtTimeMinute").removeAttr("disabled");
            $("#txtRemindLimtTimeHour").removeAttr("disabled");
            if (!$scope.timeLimit().remindInfo) {
                $scope.timeLimit().remindInfo = new Object();
            }
            $scope.timeLimit().remindInfo.remindStrategy = remindStrategy.RemindLimtTime;
        }
        else {
            $("#txtRemindLimtTimeHour").attr("disabled", "disabled");
            $("#txtRemindLimtTimeMinute").attr("disabled", "disabled");
            $("#txtRemindRelevantData").removeAttr("disabled");
            if (!$scope.timeLimit().remindInfo) {
                $scope.timeLimit().remindInfo = new Object();
            }
            $scope.timeLimit().remindInfo.remindStrategy = remindStrategy.RemindRelevantLimitTime;
        }
    };
    $scope.triggerEvents = function () {
        var triggerEvents = $scope.activity().triggerEvents;
        return triggerEvents;
    };
    $scope.addTriggerEvent = function () {
        //var tbody = $("tbody", "#tblTriggerEvent");
        if (!$scope.triggerEvents()) {
            $scope.activity().triggerEvents = new Array();
        }
        //alert($scope.triggerEvents());
        // $scope.triggerEvents().push({ ID: new Date().getTime()});
        $scope.triggerEvents().push({ id: new Date().getTime(), eventAction: "", invokePattern: "Synchronous", triggerEventType: "ActivityBeforeCreate" });
    };
    $scope.delTriggerEvent = function () {
        if (!confirm("是否确定删除记录?")) {
            return false;
        }
        var table = $("#tblTriggerEvent");
        var rad = table.find("input:checked ").first();
        // alert($(rad).val());
        angular.forEach($scope.triggerEvents(), function (triggerEvent) {
            if ($(rad).val() == triggerEvent.id) {
                var position = $scope.triggerEvents().indexOf(triggerEvent);
                // alert("xuan");
                $scope.triggerEvents().splice(position, 1);
            }
        });
    };
    $scope.rollBack = function () {
        var rollBack = new Object();
        // alert($scope.activity().Participant);
        if ($scope.activity().rollBack) {
            rollBack = $scope.activity().rollBack;
        }
        else {
            if ($scope.activity().activityType == "ManualActivity" || $scope.activity().activityType == 2) {

                $scope.activity().rollBack = rollBack;
            }
        }
        return rollBack;
    };
    $scope.activateRule = function () {
        var activateRule = new Object();
        if ($scope.activity().activateRule) {
            activateRule = $scope.activity().activateRule;
        }
        else {
            if ($scope.activity().activityType == "ManualActivity" || $scope.activity().activityType == 2) {
                $scope.activity().activateRule = activateRule;
            }
        }
        return activateRule;
    };
    $scope.activateRuleType = function (id) {
        var activateRuleType = new ActivateRuleType();
        if (id == "rblDirectRunning") {
            $scope.activateRule().activateRuleType = activateRuleType.DirectRunning;
        }
        else if (id == "rblDisenabled") {
            $scope.activateRule().activateRuleType = activateRuleType.WaitActivate;
        }
        else {
            $scope.activateRule().activateRuleType = activateRuleType.AutoSkip;
        }
    };
    $scope.resetParticipant = function (id) {
        var resetParticipant = new ResetParticipant();
        if (id == "rbFirstParticipantor") {
            $scope.activity().resetParticipant = resetParticipant.FirstParticipantor;
        } else {
            $scope.activity().resetParticipant = resetParticipant.LastParticipantor;
        }
    }
    $scope.resetURL = function () {
        var resetURL = new Object();
        if ($scope.activity().resetURL) {
            resetURL = $scope.activity().resetURL;
        }
        else {
            if ($scope.activity().activityType == "ManualActivity" || $scope.activity().activityType == 2) {
                $scope.activity().resetURL = resetURL;
            }
        }
        return resetURL;
    };

    $scope.freeFlowRule = function () {
        var freeFlowRule = new Object();
        if ($scope.activity().freeFlowRule) {
            freeFlowRule = $scope.activity().freeFlowRule;
        }
        else {
            if ($scope.activity().activityType == "ManualActivity" || $scope.activity().activityType == 2) {
                $scope.activity().freeFlowRule = freeFlowRule;
            }
        }
        return freeFlowRule;
    };
    $scope.addFreeRange = function () {
        //var tbody = $("tbody", "#tblTriggerEvent");
        if (!$scope.freeFlowRule().freeRangeActivities) {
            $scope.activity().freeFlowRule.freeRangeActivities = new Array();
        }
        //  alert($scope.freeFlowRule().freeRangeActivities);
        // $scope.triggerEvents().push({ ID: new Date().getTime()});
        $scope.freeFlowRule().freeRangeActivities.push({ id: new Date().getTime() });
    };
    $scope.delFreeRange = function () {
        if (!confirm("是否确定删除记录?")) {
            return false;
        }
        var table = $("#tblFreeRange");
        var rad = table.find("input:checked ").first();
        angular.forEach($scope.freeFlowRule().freeRangeActivities, function (freeRangeActivity) {
            if ($(rad).val() == freeRangeActivity.id) {
                var position = $scope.freeFlowRule().freeRangeActivities.indexOf(freeRangeActivity);
                // alert("xuan");
                $scope.freeFlowRule().freeRangeActivities.splice(position, 1);
            }
        });
    };
    $scope.chooseFree = function () {
        if ($("#chbIsFreeActivity").prop("checked")) {
            //$(".FreeActivity").find("input:radio").removeAttr("disabled");
            //$(".FreeActivity").find("input:checkbox").removeAttr("disabled");
            $(".FreeActivity").find("input").removeAttr("disabled");
        }
        else {
            //$(".FreeActivity").find("input:radio").attr("disabled", "disabled");
            //$(".FreeActivity").find("input:checkbox").attr("disabled", "disabled");
            $(".FreeActivity").find("input").attr("disabled", "disabled");
        }
    };
    $scope.choosescopeFree = function (id) {
        var freeRangeStrategy = new FreeRangeStrategy();
        if (id == "rblFreeWithinProcess") {
            $scope.freeFlowRule().freeRangeStrategy = freeRangeStrategy.FreeWithinProcess;
        }
        else if (id == "rblFreeWithinActivities") {
            $scope.freeFlowRule().freeRangeStrategy = freeRangeStrategy.FreeWithinActivities;
        }
        else {
            $scope.freeFlowRule().freeRangeStrategy = freeRangeStrategy.FreeWithinNextActivites;
        }
    };
    $scope.form = function () {
        var form = new Object();
        if ($scope.activity().form) {
            form = $scope.activity().form;
        }
        else {
            if ($scope.activity().activityType == "ManualActivity" || $scope.activity().activityType == 2) {
                $scope.activity().form = form;
            }
        }
        return form;
    };
    $scope.formDesigner = function () {
       // var form = window.parent.parent.parent.showDialog("actionDialog3", "表单设计器", "/FormDesigner/Home/FormDesigner", 1250, 700);
      // var form = openOperateDialog("表单设计器", "/FormDesigner/Home/FormDesigner?ActivityID=" + $scope.activity().id+"&&ProcessDefID=" + $.query.get("ProcessDefID"), 1250, 700, true, 1);
        var form = openDialog2({ title: "表单设计器", url: "/FormDesigner/Home/FormDesigner?ActivityID=" + $scope.activity().id + "&&ProcessDefID=" + $.query.get("ProcessDefID"), dialogType: 1, showModal: true,height:screen.height-80,width:screen.width-10,windowStyle: { style: "dialogLeft:0;dialogTop:-100;edge: Raised; center: Yes; resizable: Yes; status: no;scrollbars=no;", auguments: window } });
        //alert(formResult);
       //alert(form);
        if (!form || !form.fields || form.fields.length == 0) return;
        $scope.activity().form = form;
    };
    $scope.executeOperate = function (field) {
    	var fieldName="";
        if (field.indexOf("up$#") > 0) {
            fieldName = field.substring(0, field.indexOf("up$#"));
        }
        else {
            fieldName = field.substring(0, field.indexOf("down$#"));
        }
        angular.forEach($scope.form().fields, function (fieldItem) {
            var i = 0;
            if (fieldItem.name == fieldName) {
                var position = $scope.form().fields.indexOf(fieldItem);
                if (position > 0 && position < $scope.form().fields.length) {
                    $scope.form().fields.splice(position, 1);
                    if (field.indexOf("up$#") > 0) {
                        $scope.form().fields.splice(position - 1, 0, fieldItem);
                        i = 1;
                    }
                    else {
                        $scope.form().fields.splice(position + 1, 0, fieldItem);
                        i = 1;
                    }
                }
                else if (position == 0 && field.indexOf("down$#") > 0) {
                    $scope.form().fields.splice(position, 1);
                    $scope.form().fields.splice(position + 1, 0, fieldItem);
                    i = 1;
                }

            }
            if (i == 1) {
                fieldName = null;
            }
        });

    };
    $scope.chooseParameter = function () {
        var form = openOperateDialog("选择表单来源", "/Workflow/ActivityManager.aspx?Entry=ChooseActivity&ProcessDefID=" + $.query.get("ProcessDefID"), 550, 300, true, 1);
        if (!form || !form.fields || form.fields.length == 0) return;
        //for (var i = 0; i < form.fields.length; i++) {
        //    $scope.form().fields.push({X:form.fields[i],Y:form.Field[i].Y,Width:form.Field[i].Width,Height:form.Field[i].Height, Name: form.fields[i].name, Required: form.fields[i].Required, SortOrder: form.fields[i].SortOrder, Text: form.fields[i].Text, DefaultValue: form.fields[i].DefaultValue, DataType: form.fields[i].DataType, ControlType: form.fields[i].ControlType, AccessPattern: form.fields[i].AccessPattern });
        //}
        $scope.activity().form = form;
        $scope.form().dataSource = form.dataSource;
    };
    $scope.addParameter = function () {
        if (!$scope.form().fields) {
            $scope.activity().form.fields = new Array();
        }
        $scope.form().fields.push({ name: new Date().getTime(), dataType: "Integer", controlType: "TextBox", accessPattern: "Write" });
    };
    $scope.delParameter = function () {
        var table = $("#tblParameter");
        var rad = table.find("input[type='radio']:checked").first();
        if (table.find("input:checked")[0] == undefined) {
            alert("请先选择要删除的记录");
            return false;
        }
        if (!confirm("是否确定删除记录?")) {
            return false;
        }
        angular.forEach($scope.form().fields, function (field) {
            if ($(rad).val() == field.name) {
                var position = $scope.form().fields.indexOf(field);
                $scope.form().fields.splice(position, 1);
            }
        });
    };
    $scope.configureField = function (field) {
        var controlType = $.trim(field.controlType);
        if (controlType == "ChooseBox") {
            var fieldset = openOperateDialog("设置" + controlType + "属性", "/Workflow/FormControlConfigure.aspx?type=ChooseBox&url=" + field.url, 550, 300, true, 1);
            field.url = fieldset.url;
        }
        else if (controlType == "TextBox") {
            var rows = field.rows || 1;
            var cols = field.cols || 1;
            var fieldset = openOperateDialog("设置" + controlType + "属性", "/Workflow/FormControlConfigure.aspx?type=TextBox&rows=" + rows + "&cols=" + cols, 550, 300, true, 1);
            field.cols = fieldset.cols;
            field.rows = fieldset.rows;
        }
        else if (controlType == "SingleCombox" || controlType == "MultiCombox") {
            var datasource = openOperateDialog("设置" + controlType + "属性", "/Plugins/Administration/Pages/ChooseDict.aspx", 550, 300, true, 1);
            if (datasource)
                field.dataSource = datasource;
        }
    };
    $scope.multiWorkItem = function () {
        var multiWorkItem = new Object();
        if ($scope.activity().multiWorkItem) {
            multiWorkItem = $scope.activity().multiWorkItem;
        }
        else {
            if ($scope.activity().activityType == "ManualActivity" || $scope.activity().activityType == 2) {
                $scope.activity().multiWorkItem = multiWorkItem;

            }
        }
        return multiWorkItem;
    };
    $scope.enableMulwi = function () {
        if ($("#chbIsMulWIValid").prop("checked")) {
            $(".MulWIValidConfigure").find("input").removeAttr("disabled");
        }
        else {
            $(".MulWIValidConfigure").find("input").attr("disabled", "disabled");
        }
    };
    $scope.workItemNum = function (id) {
        var workItemNumStrategy = new WorkItemNumStrategy();
        if (id == "rblParticipantNumber") {
            $scope.multiWorkItem().workItemNumStrategy = workItemNumStrategy.ParticipantNumber;
        }
        else {
            $scope.multiWorkItem().workItemNumStrategy = workItemNumStrategy.OperatorNumber;
        }
    };
    $scope.finishRuleType = function (id) {
        var finishRule = new FinishRule();
        if (id == "rblSpecifyNum") {
            $scope.multiWorkItem().finishRule = finishRule.SpecifyNum;
            $("#txtFinishRquiredNum").removeAttr("disabled");
            $("#txtFinishRequiredPercent").attr("disabled", "disabled");
        }
        else if (id == "rblFinishAll") {
            $scope.multiWorkItem().finishRule = finishRule.FinishAll;
            $("#txtFinishRquiredNum").attr("disabled", "disabled");
            $("#txtFinishRequiredPercent").attr("disabled", "disabled");
        } else {
            $scope.multiWorkItem().finishRule = finishRule.SpecifyPercent;
            $("#txtFinishRquiredNum").attr("disabled", "disabled");
            $("#txtFinishRequiredPercent").removeAttr("disabled");
        }
    };
    $scope.sequentialExecute = function (id) {
        if (id == "rabYIsSequentialExecute") {
            $scope.multiWorkItem().isSequentialExecute = true;
        }
        else {
            $scope.multiWorkItem().isSequentialExecute = false;
        }
    };
    $scope.autoCancel = function (id) {
        if (id == "rabYIsAutoCancel") {
            $scope.multiWorkItem().isAutoCancel = true;
        }
        else {
            $scope.multiWorkItem().isAutoCancel = false;
        }
    };
}


text:
package org.terpo.waterworks.network;

import java.util.function.Supplier;

import org.terpo.waterworks.Waterworks;
import org.terpo.waterworks.energy.WaterworksBattery;
import org.terpo.waterworks.tileentity.TileEntityGroundwaterPump;
import org.terpo.waterworks.tileentity.TileWaterworks;

import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.network.PacketBuffer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraftforge.energy.CapabilityEnergy;
import net.minecraftforge.fml.network.NetworkEvent.Context;

public class PumpPacket extends TankPacket {

	private TileEntityGroundwaterPump tileEntityPump = null;
	int energyAmount = 0;
	public PumpPacket() {
		// nothing 2do
	}

	public PumpPacket(TileEntityGroundwaterPump tileEntity) {
		super(tileEntity);
		this.tileEntityPump = tileEntity;
		this.tileEntityPump.getCapability(CapabilityEnergy.ENERGY)
				.ifPresent(e -> this.energyAmount = ((WaterworksBattery) e).getEnergyStored());
	}

	public static PumpPacket decode(PacketBuffer buf) {
		// Reads the int back from the buf. Note that if you have multiple values, you
		// must read in the same order you wrote.
		final PumpPacket pumpPacket = new PumpPacket();
		readPosition(buf, pumpPacket);
		readTankInformation(buf, pumpPacket);
		pumpPacket.energyAmount = buf.readInt();
		return pumpPacket;
	}

	public static void encode(PumpPacket tankPacket, PacketBuffer buf) {
		// Writes the int into the buf
		writePosition(tankPacket, buf);
		writeTankInformation(tankPacket, buf);
		buf.writeInt(tankPacket.energyAmount);
	}

	public static void consume(PumpPacket message, Supplier<Context> ctx) {
		ctx.get().enqueueWork(() -> {
			final BlockPos pos = message.tileEntityPosition;
			final PlayerEntity clientPlayerEntity = Waterworks.proxy.getClientPlayerEntity();
			if (clientPlayerEntity.world.isAreaLoaded(pos, 0)) {
				final TileEntity tileEntity = getTileEntity(clientPlayerEntity.world, pos);
				if (tileEntity instanceof TileWaterworks) {
					handleTankInformation(message, (TileWaterworks) tileEntity);
				}
				if (tileEntity instanceof TileEntityGroundwaterPump) {
					tileEntity.getCapability(CapabilityEnergy.ENERGY)
							.ifPresent(e -> ((WaterworksBattery) e).setEnergyAmount(message.energyAmount));
				}
			}
		});
		ctx.get().setPacketHandled(true);
	}
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <title>Elevation profile example</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width" />
    <meta name="mobile-web-app-capable" content="yes" />

    <gmf-map id="map" gmf-map-map="ctrl.map"></gmf-map>

Longitude: {{ctrl.point.x}}

Latitude: {{ctrl.point.y}}

Elevation: {{ctrl.point.values.mnt}}

Distance: {{ctrl.point.dist}}

      This example shows how to use
      ngeo-profile
      to create a D3-based elevation profile graphic.


text:
import os
import sys
import time

'''
        @author: msune,cbermudo,omoya
	@organization: i2CAT, OFELIA FP7

	PolicyEngine Condition class
	Encapsulates logic of a simple condition
'''

'''Supported operators'''
_collectionOperators= ["in"]
_logicalOperators = ["&&","||"]
_rangeOperators = ["[]","{}"]
_comparisonOperators = ["=","!=",">","<",">=","<="]
_operators = _comparisonOperators + _logicalOperators + _rangeOperators + _collectionOperators

'''Collection inner class'''
class Collection(list):

	def __init__(self,coll):
		self +=coll

	@staticmethod
	def isCollection(x):
		return isinstance(x,Collection)

'''Range inner class'''
class Range():
	upperLimit=None
	lowerLimit=None

	@staticmethod
	def isRange(x):
		return isinstance(x,Range)

	@staticmethod
	def isInRange(x,urange):
		if not Range.isRange(urange):
			raise Exception("Unknown data type; must be a Range instance")
		return urange.lowerLimit <= x <= urange.upperLimit

	@staticmethod
	def isInRangeStrict(x,urange):
		if not Range.isRange(urange):
			raise Exception("Unknown data type; must be a Range instance")
		return urange.lowerLimit < x < urange.upperLimit

	def __init__(self,lower,upper):
		if int(upper)<int(lower):
			raise Exception("Cannot create Range; upper limit must be equal or higher that lower limit")

		self.upperLimit = upper
		self.lowerLimit = lower

	def __str__(self):
	#	return "(%s,%s)"%(str(self.lowerLimit),str(self.upperLimit))
		return "%s,%s"%(str(self.lowerLimit),str(self.upperLimit))

'''Condition class'''
class Condition():

	#Class attributes
	_leftOperand = None
	_rightOperand = None

	_operator=None
	_negate=None

	#Getters
	def getNegate(self):
		return self._negate
	def getOperator(self):
		return self._operator
	def getLeftOperand(self):
		return self._leftOperand
	def getRightOperand(self):
		#return self._rightOperand
		return self._rightOperand

	#Constructor
	def __init__(self, left, right, operator,negate=False):

		self._leftOperand = left
		self._rightOperand = right
		self._operator = operator
		self._negate = negate

		#Make sure user is not comparing Conditions and Literals/Values
		if Condition.isCondition(self._rightOperand) is not Condition.isCondition(self._leftOperand):
			raise Exception("Nested Condition can only be logically operated with another Condition")

		#Check if one of the operands is a Condition
		if ( Condition.isCondition(self._leftOperand) ) and operator not in _logicalOperators:
			raise Exception("Cannot evaluate expression. Only logical operators can be used while using nested Conditions")

		if operator in _logicalOperators and (not Condition.isCondition(self._leftOperand) ):
			raise Exception("Cannot evaluate expression. Logical operators can only be used with nested Conditions")

		#If operator is a range Operator, check left or right is a Range instance
		if self._operator in _rangeOperators and ( not ( Range.isRange(self._rightOperand) or Range.isRange(self._leftOperand) )):
			raise Exception("Cannot operate with a range without using Range instance")

		#If operator is a collection, check right is a Collection instance
		if self._operator in _collectionOperators and not Collection.isCollection(self._rightOperand):
			raise Exception("Cannot operate with a Collection without using Collection instance")

		#Check operator
		if self._operator not in _operators:
			raise Exception("Unknown operator")

		#Check operator
		if not isinstance(self._negate,bool):
			raise Exception("Unknown negate value")

	@staticmethod
	def isCondition(x):
		return isinstance(x,Condition)

	def dump(self):
                if ( Range.isRange(self._rightOperand) ):
			negate=""
			if self._negate:
				negate="not "
			if ( self._operator == '[]' ):
				return " %s %s in range [%s] "%(negate,self._leftOperand,str(self._rightOperand))
			else:
				return " %s %s in range {%s} "%(negate,self._leftOperand,str(self._rightOperand))

		if ( Collection.isCollection(self._rightOperand) ):
			negate = ""
			if self._negate:
				negate="not "
			rightOp = "collection {"
			for item in self._rightOperand:
				rightOp = rightOp + str(item) + ","
			rightOp = rightOp[:-1] + "}"
			return " %s %s in %s "%(negate,self._leftOperand,rightOp)

		if Condition.isCondition(self._leftOperand):
			negate = ""
			if self._negate:
				negate = "not "
			return " %s (%s) %s (%s)  "%(negate,self._leftOperand.dump(),str(self._operator),self._rightOperand.dump())
		else:
			negate=""
			if self._negate:
				negate="not "
			return " %s %s %s %s   "%(negate,self._leftOperand,str(self._operator),str(self._rightOperand))

	#Evaluate condition
	def evaluate(self, metaObj,resolver):
		#Retrieve operand value
		rightValue=None
		leftValue=None

		if Condition.isCondition(self._leftOperand):
			leftValue = self._leftOperand.evaluate(metaObj,resolver)
			rightValue = self._rightOperand.evaluate(metaObj,resolver)
		else:
			#Try to retrieve value from the context (if it is not a literal)

			if Collection.isCollection(self._rightOperand):
				rightValue = self._rightOperand
			else:
				#Try to first resolve (allow string based comparison)
				try:
					rightValue = resolver.resolve(self._rightOperand,metaObj)
				except:
					rightValue =  self._rightOperand

			#Try to first resolve (allow string based comparison)
			try:
				leftValue = resolver.resolve(self._leftOperand,metaObj)
			except:
				leftValue =  self._leftOperand

		#Adjusting types for numeric comparison
		if (type(rightValue) != type(leftValue)) and (self._operator not in _rangeOperators ) and (self._operator not in _collectionOperators):
			if type(leftValue) in [int,float,complex,long] and type(rightValue)==str:
				rightValue = type(leftValue)(rightValue)
			elif type(rightValue) in [int,float,complex,long] and type(leftValue)==str:
				leftValue = type(rightValue)(leftValue)

		#for simple conditions and str Values allow only == or !=
		if (type(leftValue) == str and type(rightValue) == str) and (self._operator not in ["=","!="]):
			raise Exception("Unknown operation over string or unresolvable keyword")

		#Perform comparison and return value
		if self._operator == "=":
			return self._negate ^ (leftValue == rightValue)
		elif self._operator == "!=":
			return self._negate ^ (leftValue != rightValue)
		elif self._operator == ">":
			return self._negate ^ (leftValue > rightValue)
		elif self._operator == "<":
			return self._negate ^ (leftValue < rightValue)
		elif self._operator == ">=":
			return self._negate ^ (leftValue >= rightValue)
		elif self._operator == "<=":
			return self._negate ^ (leftValue <= rightValue)
		elif self._operator == "in":
			return self._negate ^ (leftValue in rightValue)
		elif self._operator == "[]":
			return self._negate ^ (Range.isInRange(leftValue,self._rightOperand))
		elif self._operator == "{}":
			return self._negate ^ (Range.isInRangeStrict(leftValue,self._rightOperand))
		elif self._operator == "&&":
			return self._negate ^ (leftValue and rightValue)
		elif self._operator == "||":
			return self._negate ^ (leftValue or rightValue)
		else:
			raise Exception("Unknown operator??")


text:
from django.db import models

class IOTypes(object):
    boolean = 'B'
    integer = 'I'

# Create your models here.
class MSP430(models.Model):
    name = models.CharField(max_length=200)

    # In format AA:BB:CC:DD:EE:FF
    # Should be unique identifier for MSP430
    mac_address = models.CharField(max_length=17, primary_key=True)
    current_ip = models.IPAddressField()
    online = models.BooleanField(default=False)

    def __str__(self):
        return self.name

class MSP430Interface(models.Model):

    # Return type for reads, input for writes
    IO_TYPE = (
        ('B', 'Boolean'),
        ('I', 'Integer'),
    )

    name = models.CharField(max_length=200)
    description = models.TextField(blank=True, default='')

    # This is used to determine the appropriate displays
    io_type = models.CharField(choices=IO_TYPE, max_length=1)

    # Stored as a list of choices in json
    possible_choices = models.TextField(default='[]')

    msp430 = models.ForeignKey(MSP430)

    def __unicode__(self):
        return self.name

    class Meta:
        unique_together = (("name", "msp430"),)
        abstract = True

class MSP430ReadInterface(MSP430Interface):
    pass

class MSP430WriteInterface(MSP430Interface):
    pass

class Display(models.Model):

    # Channel or port
    channel_port = models.IntegerField()
    msp430 = models.ForeignKey(MSP430)
    equation = models.CharField(max_length=100, blank=True)
    label = models.CharField(max_length=200, blank=True)

    def __unicode__(self):
        return '%s - %d' % (self.__class__.__name__, self.channel_port)

    class Meta:
        abstract = True

class WriteDisplay(Display):
    interface = models.ForeignKey(MSP430WriteInterface)

class ReadDisplay(Display):
    interface = models.ForeignKey(MSP430ReadInterface)

class NumericDisplay(ReadDisplay):
    io_type = (IOTypes.boolean, IOTypes.integer)

class ProgressBarDisplay(ReadDisplay):
    io_type = (IOTypes.integer,)

class GraphDisplay(ReadDisplay):
    io_type = (IOTypes.integer,)

class ButtonDisplay(WriteDisplay):
    io_type = (IOTypes.boolean,)

class SliderDisplay(WriteDisplay):
    io_type = (IOTypes.integer,)

"""Connect signals to ws_comm handler for interface change updates"""
from django.db.models.signals import post_save, post_delete
from tcp_comm.client import config_changed_signal
post_save.connect(config_changed_signal, dispatch_uid="uid_post_save_config")
post_delete.connect(config_changed_signal, dispatch_uid="uid_post_del_config")


text:
							<rzslider rz-slider-model="volSlider.value" rz-slider-options="volSlider.options"></rzslider>

 From the album: {{ currentAlbum.name }}

{{ currentTrack}}

{{ currentArtists[0].name }}

{{ currentTrackPosition }}

{{ currentTrackLengthString }}

							<rzslider rz-slider-model="seekSlider.value" rz-slider-options="seekSlider.options"></rzslider>


text:
from kuryr.schemata import commons

ENDPOINT_CREATE_SCHEMA = {
    u'links': [{
        u'method': u'POST',
        u'href': u'/NetworkDriver.CreateEndpoint',
        u'description': u'Create an Endpoint',
        u'rel': u'self',
        u'title': u'Create'
    }],
    u'title': u'Create endpoint',
    u'required': [u'NetworkID', u'EndpointID', u'Options', u'Interface'],
    u'definitions': {u'commons': {}},
    u'$schema': u'http://json-schema.org/draft-04/hyper-schema',
    u'type': u'object',
    u'properties': {
        u'NetworkID': {
            u'description': u'Network ID',
            u'$ref': u'#/definitions/commons/definitions/id'
        },
        u'Interface': {
            u'$ref': u'#/definitions/commons/definitions/interface',
            u'description': u'Interface information'
        },
        u'Options': {
            u'description': u'Options',
            u'$ref': u'#/definitions/commons/definitions/options'
        },
        u'EndpointID': {
            u'description': u'Endpoint ID',
            u'$ref': u'#/definitions/commons/definitions/id'
        }
    }
}

ENDPOINT_CREATE_SCHEMA[u'definitions'][u'commons'] = commons.COMMONS


text:
'use strict';

const fs = require('fs');
const path = require('path');
const { isCI } = require('@terascope/utils');

const packagesPath = path.join(__dirname, 'packages');
const projects = fs
    .readdirSync(packagesPath)
    .filter((pkgName) => {
        const pkgDir = path.join(packagesPath, pkgName);

        if (!fs.statSync(pkgDir).isDirectory()) return false;
        const pkgPath = path.join(pkgDir, 'package.json');
        const hasPkg = fs.existsSync(pkgPath);
        if (hasPkg) {
            const { terascope = {} } = JSON.parse(fs.readFileSync(pkgPath));
            const { testSuite = 'disabled' } = terascope;
            if (testSuite === 'disabled') {
                return false;
            }
            return true;
        }
        return false;
    })
    .map((pkgName) => `<rootDir>/packages/${pkgName}`);

const coverageReporters = ['lcov', 'html'];
if (!isCI) {
    coverageReporters.push('text-summary');
}

module.exports = {
    rootDir: '.',
    verbose: true,
    projects,
    globals: {
        availableExtensions: ['.js', '.ts', 'mjs']
    },
    testMatch: [
        '<rootDir>/packages/*/test/**/*-spec.{ts,js}',
        '<rootDir>/packages/*/test/*-spec.{ts,js}'
    ],
    testPathIgnorePatterns: [
        '/coverage/',
        '/docs/',
        '<rootDir>/assets/',
        '/examples/',
        '<rootDir>/e2e/',
        '<rootDir>/packages/*/dist',
        '<rootDir>/packages/teraslice-cli/test/fixtures/'
    ],
    collectCoverage: true,
    collectCoverageFrom: [
        '<rootDir>/packages/*/index.js',
        '<rootDir>/packages/*/lib/*.js',
        '<rootDir>/packages/*/lib/**/*.js',
        '<rootDir>/packages/*/cmds/*.js',
        '<rootDir>/packages/*/cmds/**/*.js',
        '<rootDir>/packages/*/src/**/*.ts',
        '<rootDir>/packages/*/src/*.ts',
        '!<rootDir>/packages/**/*.json',
        '!<rootDir>/packages/**/*.d.ts',
        '!<rootDir>/packages/**/dist/**',
        '!<rootDir>/packages/**/coverage/**'
    ],
    coverageReporters,
    coverageDirectory: '<rootDir>/coverage',
    preset: 'ts-jest'
};


text:
				<?php if(!$step || $step == 1) { ?>

Step 1: License Agreement

Step 2

Step 3

Step 4

Step 5

				<?php } ?>

				<?php if($step == 2) { ?>

Step 1

Step 2: Base Settings

Step 3

Step 4

Step 5

				<?php } ?>

				<?php if($step == 3) { ?>

Step 1

Step 2

Step 3: <?php echo APPLICATION_NAME; ?> Settings

Step 4

Step 5

				<?php } ?>

				<?php if($step == 4) { ?>

Step 1

Step 2

Step 3

Step 4: Base Install

Step 5

				<?php } ?>

				<?php if($step == 5) { ?>

Step 1

Step 2

Step 3

Step 4

Step 5: <?php echo APPLICATION_NAME; ?> Wallet

Step 6

				<?php } ?>

				<?php if($step == 6) { ?>

Step 1

Step 2

Step 3

Step 4

Step 5

Step 6: <?php echo APPLICATION_NAME; ?> Installed

				<?php } ?>


text:
ZenIRCBot Motivate
==================

Lets you tell ZenIRCBot_ to praise (or discourage) someone!

.. _ZenIRCBot: https://github.com/zenirc/zenircbot


text:
DROP PROCEDURE IF EXISTS recompute_incremental;
DROP PROCEDURE IF EXISTS cancel_batch;
DROP PROCEDURE IF EXISTS activate_instance;
DROP PROCEDURE IF EXISTS deactivate_instance;
DROP PROCEDURE IF EXISTS mark_instance_deleted;
DROP PROCEDURE IF EXISTS close_batch;
DROP PROCEDURE IF EXISTS schedule_job;
DROP PROCEDURE IF EXISTS unschedule_job;
DROP PROCEDURE IF EXISTS mark_job_started;
DROP PROCEDURE IF EXISTS mark_job_complete;
DROP PROCEDURE IF EXISTS add_attempt;

DROP TRIGGER IF EXISTS instances_before_update;
DROP TRIGGER IF EXISTS attempts_before_update;
DROP TRIGGER IF EXISTS attempts_after_update;
DROP TRIGGER IF EXISTS jobs_after_update;
DROP TRIGGER IF EXISTS attempt_resources_after_insert;

DROP TABLE IF EXISTS `aggregated_billing_project_resources`;
DROP TABLE IF EXISTS `aggregated_batch_resources`;
DROP TABLE IF EXISTS `aggregated_job_resources`;
DROP TABLE IF EXISTS `attempt_resources`;
DROP TABLE IF EXISTS `batch_cancellable_resources`;
DROP TABLE IF EXISTS `globals`;
DROP TABLE IF EXISTS `attempts`;
DROP TABLE IF EXISTS `batch_attributes`;
DROP TABLE IF EXISTS `job_attributes`;
DROP TABLE IF EXISTS `job_parents`;
DROP TABLE IF EXISTS `batch_bunches`;
DROP TABLE IF EXISTS `ready_cores`;
DROP TABLE IF EXISTS `gevents_mark`;
DROP TABLE IF EXISTS `jobs`;
DROP TABLE IF EXISTS `batches_staging`;
DROP TABLE IF EXISTS `batches`;
DROP TABLE IF EXISTS `user_resources`;
DROP TABLE IF EXISTS `instances`;
DROP TABLE IF EXISTS `billing_project_users`;
DROP TABLE IF EXISTS `billing_projects`;
DROP TABLE IF EXISTS `batch_migration_version`;
DROP TABLE IF EXISTS `batch_migrations`;
DROP TABLE IF EXISTS `resources`;


text:
require 'spec_helper'

module OpenLighting
  describe DmxController do
    describe '.initialize' do
      context 'given default values' do
        it 'uses default fps' do
          c = DmxController.new
          c.fps.should == 40
        end
        it 'uses default universe' do
          c = DmxController.new
          c.universe.should == 1
        end
        it 'uses default cmd' do
          c = DmxController.new(:universe => 2)
          c.cmd.should == "ola_streaming_client -u 2"
        end
      end

      context 'given updated values' do
        it 'updates fps value' do
          c = DmxController.new(:fps => 20)
          c.fps.should == 20
        end
      end
    end

    describe ".devices" do
      before(:each) do
        @controller = DmxController.new
      end

      context 'when adding devices' do
        context 'when :start_address is specified' do
          before(:each) do
            @controller << DmxDevice.new(:start_address => 1)
            @controller << DmxDevice.new(:start_address => 6)
          end

          it 'should return devices in the same order as added' do
            @controller.devices.count.should == 2
            @controller.devices.first.start_address.should == 1
            @controller.devices.last.start_address.should == 6
          end

          it 'should attach controller to devices' do
            @controller.devices.first.controller.should == @controller
            @controller.devices.last.controller.should == @controller
          end
        end

        context 'when :start_address is not specified' do
          before(:each) do
            options = {:capabilities => [:pan, :tilt]}
            @controller << DmxDevice.new(options)
            @controller << DmxDevice.new(options)
            @controller << DmxDevice.new(options)
          end

          it 'should add default :start_address' do
            @controller.devices.count.should == 3
            @controller.devices.first.start_address.should == 1
            @controller.devices.last.start_address.should == 5
          end
        end
      end
    end

    describe ".to_dmx" do
      before(:each) do
        @controller = DmxController.new
        @controller << DmxDevice.new(:start_address => 1, :capabilities => [:pan, :tilt, :dimmer], :points => {:center => {:pan => 127, :tilt => 127}})
        @controller << DmxDevice.new(:start_address => 4, :capabilities => [:pan, :tilt, :dimmer], :points => {:center => {:pan => 127, :tilt => 127}})
      end

      it "should report correct capabilities" do
        @controller.capabilities.should == [:pan, :tilt, :dimmer]
      end

      it "should report correct points" do
        @controller.points.should == [:center]
      end

      it "should serialize all DmxDevices" do
        @controller.to_dmx.should == "0,0,0,0,0,0"
        @controller.buffer(:pan => 255)
        @controller.to_dmx.should == "255,0,0,255,0,0"
        @controller.buffer(:point => :center)
        @controller.to_dmx.should == "127,127,0,127,127,0"
      end

      it "should do method_missing magics" do
        @controller.to_dmx.should == "0,0,0,0,0,0"
        @controller.center
        @controller.to_dmx.should == "127,127,0,127,127,0"
        @controller.dimmer(80)
        @controller.to_dmx.should == "127,127,80,127,127,80"
        @controller.pan(25)
        @controller.to_dmx.should == "25,127,80,25,127,80"
        @controller.center
        @controller.to_dmx.should == "127,127,80,127,127,80"
      end

      it "should do method_missing magics" do
        @controller.connect_test_pipe
        @controller.center!
        @controller.read_pipe.gets.should == "127,127,0,127,127,0\n"
        @controller.dimmer!(80)
        @controller.read_pipe.gets.should == "127,127,80,127,127,80\n"
        @controller.close!
      end

      it "but not for incorrect names" do
        lambda { @controller.offcenter }.should raise_error NoMethodError
      end

      it "should honor overlapping start_address" do
        @controller << DmxDevice.new(:start_address => 5, :capabilities => [:pan, :tilt, :dimmer])
        @controller.buffer(:pan => 127)
        @controller.to_dmx.should == "127,0,0,127,127,0,0"
      end

      it "should insert zeros for missing data points" do
        @controller << DmxDevice.new(:start_address => 9, :capabilities => [:pan, :tilt, :dimmer])
        @controller.buffer(:pan => 127)
        @controller.to_dmx.should == "127,0,0,127,0,0,0,0,127,0,0"
      end
    end

    describe ".instant!" do
      before(:each) do
        @controller = DmxController.new(:test => true)
        @controller << DmxDevice.new(:start_address => 1, :capabilities => [:pan, :tilt, :dimmer])
        @controller << DmxDevice.new(:start_address => 4, :capabilities => [:pan, :tilt, :dimmer])
      end

      it "should write to the pipe" do
        @controller.instant!(:pan => 127)
        @controller.read_pipe.gets.should == "127,0,0,127,0,0\n"
        @controller.write_pipe.close
      end
    end

    describe ".ticks" do
      before(:each) do
        @controller = DmxController.new(:fps => 0.1)
      end

      it "should always have at least 1 tick" do
        @controller.ticks(1).should == 1
        @controller.ticks(-1).should == 1
        @controller.ticks(-100000).should == 1
        @controller.ticks(0).should == 1
      end

      it "should round down to fewer ticks" do
        @controller.ticks(25).should == 2
        @controller.ticks(30).should == 3
        @controller.ticks(35).should == 3
      end
    end

    describe ".interpolate" do
      context "with fps equal to one" do
        before(:each) do
          @controller = DmxController.new
        end

        it "should handle one step" do
          @controller.interpolate([1,1,1], [2,2,2], 1, 1).should == [2,2,2]
        end

        it "should handle multiple steps" do
          @controller.interpolate([1,1,1], [2,2,2], 2, 1).should == [1.5,1.5,1.5]
          @controller.interpolate([1,1,1], [2,2,2], 2, 2).should == [2,2,2]
        end

        it "should handle fractional input" do
          @controller.interpolate([1.5,1.5,1.5], [4.5,4.5,4.5], 2, 1).should == [3.0,3.0,3.0]
          @controller.interpolate([1.5,1.5,1.5], [4.5,4.5,4.5], 2, 2).should == [4.5,4.5,4.5]
        end
      end
    end

    describe ".begin_animation!" do
      before(:each) do
        @controller = DmxController.new(:fps => 1, :test => true)
        @controller << DmxDevice.new(:start_address => 1, :capabilities => [:pan, :tilt, :dimmer])
        @controller << DmxDevice.new(:start_address => 4, :capabilities => [:pan, :tilt, :dimmer])
      end

      it "should write interpolated values to the pipe" do
        @controller.animate!(:seconds => 5, :pan => 25)
        @controller.read_pipe.gets.should == "5,0,0,5,0,0\n"
        @controller.read_pipe.gets.should == "10,0,0,10,0,0\n"
        @controller.read_pipe.gets.should == "15,0,0,15,0,0\n"
        @controller.read_pipe.gets.should == "20,0,0,20,0,0\n"
        @controller.read_pipe.gets.should == "25,0,0,25,0,0\n"
        @controller.write_pipe.close
      end

      it "should allow block syntax" do
        @controller.begin_animation!(:seconds => 5) do |devices|
          devices[0].pan(25)
          devices[1].pan(50)
        end
        @controller.read_pipe.gets.should == "5,0,0,10,0,0\n"
        @controller.read_pipe.gets.should == "10,0,0,20,0,0\n"
        @controller.read_pipe.gets.should == "15,0,0,30,0,0\n"
        @controller.read_pipe.gets.should == "20,0,0,40,0,0\n"
        @controller.read_pipe.gets.should == "25,0,0,50,0,0\n"
        @controller.write_pipe.close
      end

      it "should allow sequential calls to method_missing and animate" do
        @controller.dimmer(50)
        @controller.to_dmx.should == "0,0,50,0,0,50"
        @controller.animate!(:seconds => 1, :dimmer => 127)
        @controller.read_pipe.gets.should == "0,0,127,0,0,127\n"
      end
    end
  end
end


text:
package com.fmtech.rxjavaretrofit.util;

import com.fmtech.rxjavaretrofit.model.GankBeauty;
import com.fmtech.rxjavaretrofit.model.GankBeautyResult;
import com.fmtech.rxjavaretrofit.model.Image;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import rx.functions.Func1;

public class GankBeautyResultToItemsMapper implements Func1<GankBeautyResult, List<Image>> {

    private static GankBeautyResultToItemsMapper sInstance = new GankBeautyResultToItemsMapper();

    private GankBeautyResultToItemsMapper(){

    }

    public static GankBeautyResultToItemsMapper getInstance(){
        return sInstance;
    }

    @Override
    public List<Image> call(GankBeautyResult gankBeautyResult) {
        List<GankBeauty> beauties = gankBeautyResult.beauties;
        List<Image> images = new ArrayList<>();
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS'Z'");
        SimpleDateFormat outputFormat = new SimpleDateFormat("yy/MM/dd HH:mm:ss");
        for(GankBeauty beauty : beauties){
            Image image = new Image();
            try {
                Date date = inputFormat.parse(beauty.createdAt);
                image.description = outputFormat.format(date);
            } catch (ParseException e) {
                e.printStackTrace();
                image.description = "Fantastic baby.";
            }
            image.image_url = beauty.url;
            images.add(image);
        }
        return images;
    }
}


text:
    Cancel (L10n)
  <caret>


text:
package de.tr7zw.nbtapi.plugin.tests.injector;

import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;

import de.tr7zw.changeme.nbtapi.NBTCompound;
import de.tr7zw.changeme.nbtapi.NBTTileEntity;
import de.tr7zw.changeme.nbtapi.NbtApiException;
import de.tr7zw.nbtapi.plugin.tests.Test;
import de.tr7zw.nbtinjector.NBTInjector;

public class TilesCustomNBTInjectorTest implements Test {

    @Override
    public void test() throws Exception {
        if (!NBTInjector.isInjected())
            return;
        if (!Bukkit.getWorlds().isEmpty()) {
            World world = Bukkit.getWorlds().get(0);
            try {
                Block block = world.getBlockAt(world.getSpawnLocation().getBlockX(), 255,
                        world.getSpawnLocation().getBlockZ());
                if (block.getType() == Material.AIR) {
                    block.setType(Material.CHEST);
                    NBTCompound comp = NBTInjector.getNbtData(block.getState());
                    comp.setString("Foo", "Bar");
                    if (!new NBTTileEntity(block.getState()).toString().contains("__extraData:{Foo:\"Bar\"}")) {
                        block.setType(Material.AIR);
                        throw new NbtApiException("Custom Data did not save to the Tile!");
                    }
                    block.setType(Material.AIR);
                }
            } catch (Exception ex) {
                throw new NbtApiException("Wasn't able to use NBTTiles!", ex);
            }
        }
    }

}


text:
package com.github.mlk.junit.rules;

import static com.google.common.collect.Lists.newArrayList;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

import com.amazonaws.services.s3.iterable.S3Objects;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.Rule;
import org.junit.Test;

public class S3MockRuleTest {
  @Rule
  public S3MockRule subject = new S3MockRuleBuilder()
      .bucket("bucket-name")
      .file("bucket-name", "fileName", "content")
      .file("bucket-name", "fileName2", "content")
      .file("new-bucket", "fileName", "content")
      .build();

  @Test
  public void createsBuckets() {
    List<String> names = subject.getAmazonS3Client().listBuckets().stream().map(Bucket::getName).sorted().collect(Collectors.toList());
    assertThat(names, is(Arrays.asList("bucket-name", "new-bucket")));
  }

  @Test
  public void createsFile() {
    List<String> names = newArrayList(
        S3Objects.inBucket(subject.getAmazonS3Client(), "bucket-name").iterator())
        .stream().map(
        S3ObjectSummary::getKey).sorted().collect(Collectors.toList());

    assertThat(names, is(Arrays.asList("fileName", "fileName2")));
  }
}


text:
[![build status](https://travis-ci.org/djds23/jApi.svg?branch=master)](https://travis-ci.org/djds23/github-notif-helper)
[![Gem Version](https://badge.fury.io/rb/japi.svg)](https://rubygems.org/gems/japi)
[![YARD docs](https://img.shields.io/badge/yard-docs-blue.svg)](http://www.rubydoc.info/github/djds23/jApi)
[![codecov.io](https://codecov.io/github/djds23/jApi/coverage.svg?branch=master)](https://codecov.io/github/djds23/jApi?branch=master)
[![inch.io](https://inch-ci.org/github/djds23/jApi.svg?branch=master)](https://inch-ci.org/github/djds23/jApi)

A simple ruby interface for the jservice.io API

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'japi'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install japi

## Usage

```ruby
clue = JAPI::Trebek.random.first # ask trebek for a random question!
puts clue.category.title # THE SOLAR SYSTEM
puts clue.question # Only 1 of 9 planets not named for a Greek or Roman mythological figure

answer = gets.chomp
if answer == clue.answer
  puts "The Earth! Correct!"
  puts "Good answer! Thats worth #{clue.value} dollars!"
else
  puts "Too bad!"
end
```

You can host your own jservice.io, and configure the gem to use arbitrary endpoints.

### Example Configuration

```ruby
require 'japi'

JAPI.configuration do |config|
 config.jservice_url = "http://my-selfhosted-jservice.com"
end
```

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/djds23/japi. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
<?php

// Default

l::set('submit', 'Submit');
l::set('cancel', 'Cancel');

// Calendar plugin
// For `strftime` parameters, see http://php.net/manual/en/function.strftime.php

l::set('calendar-time-format', '%d');
l::set('calendar-full-time-format', '%d %X');
l::set('calendar-month-format', '%b %Y');
l::set('calendar-day-month-format', '%e %b');
l::set('calendar-day-month-year-format', '%e %b %Y');
l::set('calendar-no-entry', 'There are currenly no upcoming events…');

l::set('date', 'Date');
l::set('to', 'to');

l::set('title', 'Title');
l::set('description', 'Description');

?>


text:
/* Includes ------------------------------------------------------------------*/
#include "stm32g4xx_hal.h"

/** @addtogroup STM32G4xx_HAL_Driver
  * @{
  */

/** @addtogroup GPIO
  * @{
  */
/** MISRA C:2012 deviation rule has been granted for following rules:
  * Rule-12.2 - Medium: RHS argument is in interval [0,INF] which is out of
  * range of the shift operator in following API :
  * HAL_GPIO_Init
  * HAL_GPIO_DeInit
  */

#ifdef HAL_GPIO_MODULE_ENABLED

/* Private typedef -----------------------------------------------------------*/
/* Private defines ------------------------------------------------------------*/
/** @defgroup GPIO_Private_Constants GPIO Private Constants
  * @{
  */
#define GPIO_MODE             (0x00000003U)
#define EXTI_MODE             (0x10000000U)
#define GPIO_MODE_IT          (0x00010000U)
#define GPIO_MODE_EVT         (0x00020000U)
#define RISING_EDGE           (0x00100000U)
#define FALLING_EDGE          (0x00200000U)
#define GPIO_OUTPUT_TYPE      (0x00000010U)

#define GPIO_NUMBER           (16U)
/**
  * @}
  */

/* Private macros ------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported functions --------------------------------------------------------*/

/** @addtogroup GPIO_Exported_Functions
  * @{
  */

/** @defgroup GPIO_Exported_Functions_Group1 Initialization/de-initialization functions
  *  @brief    Initialization and Configuration functions
  *
@verbatim
 ===============================================================================
              ##### Initialization and de-initialization functions #####
 ===============================================================================

@endverbatim
  * @{
  */

/**
  * @brief  Initialize the GPIOx peripheral according to the specified parameters in the GPIO_Init.
  * @param  GPIOx where x can be (A..G) to select the GPIO peripheral for STM32G4xx family
  * @param  GPIO_Init pointer to a GPIO_InitTypeDef structure that contains
  *         the configuration information for the specified GPIO peripheral.
  * @retval None
  */
void HAL_GPIO_Init(GPIO_TypeDef  *GPIOx, GPIO_InitTypeDef *GPIO_Init)
{
  uint32_t position = 0x00U;
  uint32_t iocurrent;
  uint32_t temp;

  /* Check the parameters */
  assert_param(IS_GPIO_ALL_INSTANCE(GPIOx));
  assert_param(IS_GPIO_PIN(GPIO_Init->Pin));
  assert_param(IS_GPIO_MODE(GPIO_Init->Mode));
  assert_param(IS_GPIO_PULL(GPIO_Init->Pull));

  /* Configure the port pins */
  while (((GPIO_Init->Pin) >> position) != 0U)
  {
    /* Get current io position */
    iocurrent = (GPIO_Init->Pin) & (1UL << position);

    if (iocurrent != 0x00u)
    {
      /*--------------------- GPIO Mode Configuration ------------------------*/
      /* In case of Output or Alternate function mode selection */
      if ((GPIO_Init->Mode == GPIO_MODE_OUTPUT_PP) || (GPIO_Init->Mode == GPIO_MODE_AF_PP) ||
          (GPIO_Init->Mode == GPIO_MODE_OUTPUT_OD) || (GPIO_Init->Mode == GPIO_MODE_AF_OD))
      {
        /* Check the Speed parameter */
        assert_param(IS_GPIO_SPEED(GPIO_Init->Speed));
        /* Configure the IO Speed */
        temp = GPIOx->OSPEEDR;
        temp &= ~(GPIO_OSPEEDR_OSPEED0 << (position * 2U));
        temp |= (GPIO_Init->Speed << (position * 2U));
        GPIOx->OSPEEDR = temp;

        /* Configure the IO Output Type */
        temp = GPIOx->OTYPER;
        temp &= ~(GPIO_OTYPER_OT0 << position) ;
        temp |= (((GPIO_Init->Mode & GPIO_OUTPUT_TYPE) >> 4U) << position);
        GPIOx->OTYPER = temp;
      }

      /* Activate the Pull-up or Pull down resistor for the current IO */
      temp = GPIOx->PUPDR;
      temp &= ~(GPIO_PUPDR_PUPD0 << (position * 2U));
      temp |= ((GPIO_Init->Pull) << (position * 2U));
      GPIOx->PUPDR = temp;

      /* In case of Alternate function mode selection */
      if ((GPIO_Init->Mode == GPIO_MODE_AF_PP) || (GPIO_Init->Mode == GPIO_MODE_AF_OD))
      {
        /* Check the Alternate function parameters */
        assert_param(IS_GPIO_AF_INSTANCE(GPIOx));
        assert_param(IS_GPIO_AF(GPIO_Init->Alternate));

        /* Configure Alternate function mapped with the current IO */
        temp = GPIOx->AFR[position >> 3U];
        temp &= ~(0xFU << ((position & 0x07U) * 4U));
        temp |= ((GPIO_Init->Alternate) << ((position & 0x07U) * 4U));
        GPIOx->AFR[position >> 3U] = temp;
      }

      /* Configure IO Direction mode (Input, Output, Alternate or Analog) */
      temp = GPIOx->MODER;
      temp &= ~(GPIO_MODER_MODE0 << (position * 2U));
      temp |= ((GPIO_Init->Mode & GPIO_MODE) << (position * 2U));
      GPIOx->MODER = temp;

      /*--------------------- EXTI Mode Configuration ------------------------*/
      /* Configure the External Interrupt or event for the current IO */
      if ((GPIO_Init->Mode & EXTI_MODE) == EXTI_MODE)
      {
        /* Enable SYSCFG Clock */
        __HAL_RCC_SYSCFG_CLK_ENABLE();

        temp = SYSCFG->EXTICR[position >> 2U];
        temp &= ~(0x0FUL << (4U * (position & 0x03U)));
        temp |= (GPIO_GET_INDEX(GPIOx) << (4U * (position & 0x03U)));
        SYSCFG->EXTICR[position >> 2U] = temp;

        /* Clear EXTI line configuration */
        temp = EXTI->IMR1;
        temp &= ~(iocurrent);
        if ((GPIO_Init->Mode & GPIO_MODE_IT) == GPIO_MODE_IT)
        {
          temp |= iocurrent;
        }
        EXTI->IMR1 = temp;

        temp = EXTI->EMR1;
        temp &= ~(iocurrent);
        if ((GPIO_Init->Mode & GPIO_MODE_EVT) == GPIO_MODE_EVT)
        {
          temp |= iocurrent;
        }
        EXTI->EMR1 = temp;

        /* Clear Rising Falling edge configuration */
        temp = EXTI->RTSR1;
        temp &= ~(iocurrent);
        if ((GPIO_Init->Mode & RISING_EDGE) == RISING_EDGE)
        {
          temp |= iocurrent;
        }
        EXTI->RTSR1 = temp;

        temp = EXTI->FTSR1;
        temp &= ~(iocurrent);
        if ((GPIO_Init->Mode & FALLING_EDGE) == FALLING_EDGE)
        {
          temp |= iocurrent;
        }
        EXTI->FTSR1 = temp;
      }
    }

    position++;
  }
}

/**
  * @brief  De-initialize the GPIOx peripheral registers to their default reset values.
  * @param  GPIOx where x can be (A..G) to select the GPIO peripheral for STM32G4xx family
  * @param  GPIO_Pin specifies the port bit to be written.
  *         This parameter can be any combination of GPIO_PIN_x where x can be (0..15).
  * @retval None
  */
void HAL_GPIO_DeInit(GPIO_TypeDef  *GPIOx, uint32_t GPIO_Pin)
{
  uint32_t position = 0x00U;
  uint32_t iocurrent;
  uint32_t tmp;

  /* Check the parameters */
  assert_param(IS_GPIO_ALL_INSTANCE(GPIOx));
  assert_param(IS_GPIO_PIN(GPIO_Pin));

  /* Configure the port pins */
  while ((GPIO_Pin >> position) != 0U)
  {
    /* Get current io position */
    iocurrent = (GPIO_Pin) & (1UL << position);

    if (iocurrent != 0x00u)
    {
      /*------------------------- EXTI Mode Configuration --------------------*/
      /* Clear the External Interrupt or Event for the current IO */

      tmp = SYSCFG->EXTICR[position >> 2U];
      tmp &= (0x0FUL << (4U * (position & 0x03U)));
      if (tmp == (GPIO_GET_INDEX(GPIOx) << (4U * (position & 0x03U))))
      {
        /* Clear EXTI line configuration */
        EXTI->IMR1 &= ~(iocurrent);
        EXTI->EMR1 &= ~(iocurrent);

        /* Clear Rising Falling edge configuration */
        EXTI->RTSR1 &= ~(iocurrent);
        EXTI->FTSR1 &= ~(iocurrent);

        tmp = 0x0FUL << (4U * (position & 0x03U));
        SYSCFG->EXTICR[position >> 2U] &= ~tmp;
      }

      /*------------------------- GPIO Mode Configuration --------------------*/
      /* Configure IO in Analog Mode */
      GPIOx->MODER |= (GPIO_MODER_MODE0 << (position * 2u));

      /* Configure the default Alternate Function in current IO */
      GPIOx->AFR[position >> 3u] &= ~(0xFu << ((position & 0x07u) * 4u));

      /* Deactivate the Pull-up and Pull-down resistor for the current IO */
      GPIOx->PUPDR &= ~(GPIO_PUPDR_PUPD0 << (position * 2u));

      /* Configure the default value IO Output Type */
      GPIOx->OTYPER  &= ~(GPIO_OTYPER_OT0 << position);

      /* Configure the default value for IO Speed */
      GPIOx->OSPEEDR &= ~(GPIO_OSPEEDR_OSPEED0 << (position * 2u));
    }

    position++;
  }
}

/**
  * @}
  */

/** @addtogroup GPIO_Exported_Functions_Group2
  *  @brief GPIO Read, Write, Toggle, Lock and EXTI management functions.
  *
@verbatim
 ===============================================================================
                       ##### IO operation functions #####
 ===============================================================================

@endverbatim
  * @{
  */

/**
  * @brief  Read the specified input port pin.
  * @param  GPIOx where x can be (A..G) to select the GPIO peripheral for STM32G4xx family
  * @param  GPIO_Pin specifies the port bit to read.
  *         This parameter can be any combination of GPIO_PIN_x where x can be (0..15).
  * @retval The input port pin value.
  */
GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin)
{
  GPIO_PinState bitstatus;

  /* Check the parameters */
  assert_param(IS_GPIO_PIN(GPIO_Pin));

  if ((GPIOx->IDR & GPIO_Pin) != 0x00U)
  {
    bitstatus = GPIO_PIN_SET;
  }
  else
  {
    bitstatus = GPIO_PIN_RESET;
  }
  return bitstatus;
}

/**
  * @brief  Set or clear the selected data port bit.
  *
  * @note   This function uses GPIOx_BSRR and GPIOx_BRR registers to allow atomic read/modify
  *         accesses. In this way, there is no risk of an IRQ occurring between
  *         the read and the modify access.
  *
  * @param  GPIOx where x can be (A..G) to select the GPIO peripheral for STM32G4xx family
  * @param  GPIO_Pin specifies the port bit to be written.
  *         This parameter can be any combination of GPIO_PIN_x where x can be (0..15).
  * @param  PinState specifies the value to be written to the selected bit.
  *         This parameter can be one of the GPIO_PinState enum values:
  *            @arg GPIO_PIN_RESET: to clear the port pin
  *            @arg GPIO_PIN_SET: to set the port pin
  * @retval None
  */
void HAL_GPIO_WritePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState)
{
  /* Check the parameters */
  assert_param(IS_GPIO_PIN(GPIO_Pin));
  assert_param(IS_GPIO_PIN_ACTION(PinState));

  if (PinState != GPIO_PIN_RESET)
  {
    GPIOx->BSRR = (uint32_t)GPIO_Pin;
  }
  else
  {
    GPIOx->BRR = (uint32_t)GPIO_Pin;
  }
}

/**
  * @brief  Toggle the specified GPIO pin.
  * @param  GPIOx where x can be (A..G) to select the GPIO peripheral for STM32G4xx family
  * @param  GPIO_Pin specifies the pin to be toggled.
  *         This parameter can be any combination of GPIO_PIN_x where x can be (0..15).
  * @retval None
  */
void HAL_GPIO_TogglePin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin)
{
  uint32_t odr;

  /* Check the parameters */
  assert_param(IS_GPIO_PIN(GPIO_Pin));

  /* get current Output Data Register value */
  odr = GPIOx->ODR;

  /* Set selected pins that were at low level, and reset ones that were high */
  GPIOx->BSRR = ((odr & GPIO_Pin) << GPIO_NUMBER) | (~odr & GPIO_Pin);
}

/**
  * @brief  Lock GPIO Pins configuration registers.
  * @note   The locked registers are GPIOx_MODER, GPIOx_OTYPER, GPIOx_OSPEEDR,
  *         GPIOx_PUPDR, GPIOx_AFRL and GPIOx_AFRH.
  * @note   The configuration of the locked GPIO pins can no longer be modified
  *         until the next reset.
  * @param  GPIOx where x can be (A..G) to select the GPIO peripheral for STM32G4xx family
  * @param  GPIO_Pin specifies the port bits to be locked.
  *         This parameter can be any combination of GPIO_Pin_x where x can be (0..15).
  * @retval None
  */
HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef *GPIOx, uint16_t GPIO_Pin)
{
  __IO uint32_t tmp = GPIO_LCKR_LCKK;

  /* Check the parameters */
  assert_param(IS_GPIO_LOCK_INSTANCE(GPIOx));
  assert_param(IS_GPIO_PIN(GPIO_Pin));

  /* Apply lock key write sequence */
  tmp |= GPIO_Pin;
  /* Set LCKx bit(s): LCKK='1' + LCK[15-0] */
  GPIOx->LCKR = tmp;
  /* Reset LCKx bit(s): LCKK='0' + LCK[15-0] */
  GPIOx->LCKR = GPIO_Pin;
  /* Set LCKx bit(s): LCKK='1' + LCK[15-0] */
  GPIOx->LCKR = tmp;
  /* Read LCKK register. This read is mandatory to complete key lock sequence */
  tmp = GPIOx->LCKR;

  /* read again in order to confirm lock is active */
  if ((GPIOx->LCKR & GPIO_LCKR_LCKK) != 0x00u)
  {
    return HAL_OK;
  }
  else
  {
    return HAL_ERROR;
  }
}

/**
  * @brief  Handle EXTI interrupt request.
  * @param  GPIO_Pin Specifies the port pin connected to corresponding EXTI line.
  * @retval None
  */
void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin)
{
  /* EXTI line interrupt detected */
  if (__HAL_GPIO_EXTI_GET_IT(GPIO_Pin) != 0x00u)
  {
    __HAL_GPIO_EXTI_CLEAR_IT(GPIO_Pin);
    HAL_GPIO_EXTI_Callback(GPIO_Pin);
  }
}

/**
  * @brief  EXTI line detection callback.
  * @param  GPIO_Pin: Specifies the port pin connected to corresponding EXTI line.
  * @retval None
  */
__weak void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
  /* Prevent unused argument(s) compilation warning */
  UNUSED(GPIO_Pin);

  /* NOTE: This function should not be modified, when the callback is needed,
           the HAL_GPIO_EXTI_Callback could be implemented in the user file
   */
}

/**
  * @}
  */

/**
  * @}
  */

#endif /* HAL_GPIO_MODULE_ENABLED */
/**
  * @}
  */

/**
  * @}
  */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
package org.kuali.coeus.common.budget.framework.core;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Convert;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.kuali.coeus.common.budget.api.core.CostElementContract;
import org.kuali.coeus.common.budget.framework.core.category.BudgetCategory;
import org.kuali.coeus.common.budget.framework.rate.ValidCeRateType;
import org.kuali.coeus.sys.framework.model.KcPersistableBusinessObjectBase;
import org.kuali.coeus.sys.framework.persistence.BooleanNFConverter;
import org.kuali.rice.core.api.mo.common.active.MutableInactivatable;
import org.kuali.rice.krad.data.jpa.FilterGenerator;
import org.kuali.rice.krad.data.jpa.converters.BooleanYNConverter;

@Entity
@Table(name = "COST_ELEMENT")
public class CostElement extends KcPersistableBusinessObjectBase implements Comparable<CostElement>, MutableInactivatable, CostElementContract {

    @Id
    @Column(name = "COST_ELEMENT")
    private String costElement;

    @Column(name = "BUDGET_CATEGORY_CODE")
    private String budgetCategoryCode;

    @Column(name = "DESCRIPTION")
    private String description;

    @Column(name = "ON_OFF_CAMPUS_FLAG")
    @Convert(converter = BooleanNFConverter.class)
    private Boolean onOffCampusFlag;

    @Column(name = "ACTIVE_FLAG")
    @Convert(converter = BooleanYNConverter.class)
    private boolean active;

    @Column(name = "FIN_OBJECT_CODE")
    private String financialObjectCode;

    @OneToMany(mappedBy = "costElementBo")
    @FilterGenerator(attributeName = "active", attributeValue = "true")
    private List<ValidCeRateType> validCeRateTypes;

    @ManyToOne(fetch = FetchType.LAZY, cascade = { CascadeType.REFRESH })
    @JoinColumn(name = "BUDGET_CATEGORY_CODE", referencedColumnName = "BUDGET_CATEGORY_CODE", insertable = false, updatable = false)
    private BudgetCategory budgetCategory;

    @Transient
    private String budgetCategoryTypeCode;

    public CostElement() {
        validCeRateTypes = new ArrayList<ValidCeRateType>();
    }

    @Override
    public String getFinancialObjectCode() {
        return financialObjectCode;
    }

    public void setFinancialObjectCode(String financialObjectCode) {
        this.financialObjectCode = financialObjectCode;
    }

    @Override
    public String getCostElement() {
        return costElement;
    }

    public void setCostElement(String costElement) {
        this.costElement = costElement;
    }

    @Override
    public String getBudgetCategoryCode() {
        return budgetCategoryCode;
    }

    public void setBudgetCategoryCode(String budgetCategoryCode) {
        this.budgetCategoryCode = budgetCategoryCode;
    }

    @Override
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    @Override
    public Boolean getOnOffCampusFlag() {
        return onOffCampusFlag;
    }

    public void setOnOffCampusFlag(Boolean onOffCampusFlag) {
        this.onOffCampusFlag = onOffCampusFlag;
    }

    @Override
    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    @Override
    public List<ValidCeRateType> getValidCeRateTypes() {
        return validCeRateTypes;
    }

    public void setValidCeRateTypes(List<ValidCeRateType> validCeRateTypes) {
        this.validCeRateTypes = validCeRateTypes;
    }

    @Override
    public int compareTo(CostElement costElement) {
        return this.costElement.compareTo(costElement.costElement);
    }

    @Override
    public BudgetCategory getBudgetCategory() {
        return budgetCategory;
    }

    public void setBudgetCategory(BudgetCategory budgetCategory) {
        this.budgetCategory = budgetCategory;
    }

    public String getBudgetCategoryTypeCode() {
        return budgetCategoryTypeCode;
    }

    public void setBudgetCategoryTypeCode(String budgetCategoryTypeCode) {
        this.budgetCategoryTypeCode = budgetCategoryTypeCode;
    }
}


text:
"""Base-sized Model Hyperparameter configuration."""
from pegasus.flax.configs import pegasus_x_base as pegasus_x_base_config

def get_config():
    """Get large-sized PEGASUS-X hyperparameter configuration."""

    # Load base config
    config = pegasus_x_base_config.get_config()
    config.run_mode = "train"
    config.dataset_name = "scrolls/summ_screen_fd"
    config.per_device_batch_size = 1
    config.overwrite_train_steps = 0
    config.learning_rate = 0.003
    config.max_input_length = 6144

    # Replace this:
    config.eval_load_checkpoint_dir = "path/to/checkpoint_0"

    # Replace this:
    config.tokenizer_path = "path/to/c4.unigram.newline.10pct.96000.model"

    return config


text:
<?php

namespace Package\Requests;

use Pluma\Requests\FormRequest;

class PackageRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        switch ($this->method()) {
            case 'POST':
                if ($this->user()->can('store-package')) {
                    return true;
                }
                break;

            case 'PUT':
                if ($this->user()->can('update-package')) {
                    return true;
                }
                break;

            case 'DELETE':
                if ($this->user()->can('destroy-package')) {
                    return true;
                }
                break;

            default:
                return false;
                break;
        }

        return false;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $isUpdating = $this->method() == "PUT" ? ",id,$this->id" : "";

        return [
            'name' => 'required|max:255',
            'code' => 'required|regex:/^[\pL\s\-\*\#\(0-9)]+$/u|unique:packages'.$isUpdating,
        ];
    }

    /**
     * The array of override messages to use.
     *
     * @return array
     */
    public function messages()
    {
        return [
            'code.regex' => 'Only letters, numbers, spaces, and hypens are allowed.',
        ];
    }
}


text:
use crate::descriptor::field_descriptor_proto;
use crate::error::WireError;

/// Tag occupies three bits.
pub(crate) const TAG_TYPE_BITS: u32 = 3;
/// Apply this mask to varint value to obtain a tag.
pub(crate) const TAG_TYPE_MASK: u32 = (1u32 << TAG_TYPE_BITS as usize) - 1;
/// Max possible field number
pub(crate) const FIELD_NUMBER_MAX: u32 = 0x1fffffff;

pub(crate) const MAX_MESSAGE_SIZE: u64 = i32::MAX as u64;

#[inline]
pub(crate) fn check_message_size(size: u64) -> crate::Result<u32> {
    if size <= MAX_MESSAGE_SIZE {
        Ok(size as u32)
    } else {
        #[cold]
        fn message_too_large(size: u64) -> crate::Error {
            WireError::MessageTooLarge(size).into()
        }

        Err(message_too_large(size))
    }
}

/// All supported "wire types" are listed in this enum.
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
pub enum WireType {
    /// Variable-length integer
    Varint = 0,
    /// 32-bit field (e. g. `fixed64` or `double`)
    Fixed64 = 1,
    /// Length-delimited field
    LengthDelimited = 2,
    /// Groups are not supported in rust-protobuf
    StartGroup = 3,
    /// Groups are not supported in rust-protobuf
    EndGroup = 4,
    /// 32-bit field (e. g. `fixed32` or `float`)
    Fixed32 = 5,
}

impl WireType {
    /// Construct `WireType` from number, or return `None` if type is unknown.
    pub fn new(n: u32) -> Option<WireType> {
        match n {
            0 => Some(WireType::Varint),
            1 => Some(WireType::Fixed64),
            2 => Some(WireType::LengthDelimited),
            3 => Some(WireType::StartGroup),
            4 => Some(WireType::EndGroup),
            5 => Some(WireType::Fixed32),
            _ => None,
        }
    }

    #[doc(hidden)]
    pub fn for_type(field_type: field_descriptor_proto::Type) -> WireType {
        use field_descriptor_proto::Type;
        match field_type {
            Type::TYPE_INT32 => WireType::Varint,
            Type::TYPE_INT64 => WireType::Varint,
            Type::TYPE_UINT32 => WireType::Varint,
            Type::TYPE_UINT64 => WireType::Varint,
            Type::TYPE_SINT32 => WireType::Varint,
            Type::TYPE_SINT64 => WireType::Varint,
            Type::TYPE_BOOL => WireType::Varint,
            Type::TYPE_ENUM => WireType::Varint,
            Type::TYPE_FIXED32 => WireType::Fixed32,
            Type::TYPE_FIXED64 => WireType::Fixed64,
            Type::TYPE_SFIXED32 => WireType::Fixed32,
            Type::TYPE_SFIXED64 => WireType::Fixed64,
            Type::TYPE_FLOAT => WireType::Fixed32,
            Type::TYPE_DOUBLE => WireType::Fixed64,
            Type::TYPE_STRING => WireType::LengthDelimited,
            Type::TYPE_BYTES => WireType::LengthDelimited,
            Type::TYPE_MESSAGE => WireType::LengthDelimited,
            Type::TYPE_GROUP => WireType::LengthDelimited, // not true
        }
    }
}

/// Parsed field tag (a pair of field number and wire type)
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) struct Tag {
    field_number: u32,
    wire_type: WireType,
}

impl Tag {
    /// Fold tag to a number to be serialized.
    pub(crate) fn value(self) -> u32 {
        (self.field_number << TAG_TYPE_BITS) | (self.wire_type as u32)
    }

    /// Extract wire type and field number from integer tag
    pub(crate) fn new(value: u32) -> crate::Result<Tag> {
        let wire_type = WireType::new(value & TAG_TYPE_MASK);
        if wire_type.is_none() {
            return Err(WireError::IncorrectTag(value).into());
        }
        let field_number = value >> TAG_TYPE_BITS;
        if field_number == 0 {
            return Err(WireError::IncorrectTag(value).into());
        }
        Ok(Tag {
            field_number,
            wire_type: wire_type.unwrap(),
        })
    }

    /// Construct a tag from a field number and wire type.
    ///
    /// # Panics
    ///
    /// If field number is outside of valid range.
    pub(crate) fn make(field_number: u32, wire_type: WireType) -> Tag {
        assert!(field_number > 0 && field_number <= FIELD_NUMBER_MAX);
        Tag {
            field_number,
            wire_type,
        }
    }

    /// Get field number and wire type
    pub(crate) fn unpack(self) -> (u32, WireType) {
        (self.field_number(), self.wire_type())
    }

    /// Get wire type
    fn wire_type(self) -> WireType {
        self.wire_type
    }

    /// Get field number
    pub(crate) fn field_number(self) -> u32 {
        self.field_number
    }
}