问:
Angular JS reloading whole body when clicked on Other Tabs
My web page has 3 bootstrap tabs with data some data being populated run time. After page loads, tab1 looks fine and when I click on other tabs, whole body reloads and tab1 displays. I do not see any errors in Console.

HTML:

```<code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-animate.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular-sanitize.js"></script>
<script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-2.5.0.js"></script>

<div class="container" -ng-controller="incidentSummaryCtrl" >
    <div class="panel panel-primary">
        <div class="panel-heading"><h3>Incident  {{c.data.incidentData[0].incidentId}} </h3> </div>
        <div class="panel-body" style="padding:0px">
            <div class="panel-group">

                <div class="container">
                    <div class="row text-center">
                        <h1 class="white"></h1>
                    </div>

                    <div class="row">
                        <div class="col-md-10">
                            <div class="tab" role="tabpanel">
                                <!-- Nav tabs -->
                                <ul class="nav nav-tabs" role="tablist">
                                    <li role="presentation" class="active"><a href="#Section1" aria-controls="home" role="tab" data-toggle="tab" aria-expanded="true">Incident Information</a></li>
                                    <li role="presentation" class=""><a href="#Section2" aria-controls="profile" role="tab" data-toggle="tab" aria-expanded="false">Potential Indicators</a></li>
                                    <li role="presentation" class=""><a href="#Section3" aria-controls="messages" role="tab" data-toggle="tab" aria-expanded="false">Course of Action</a></li>
                                </ul>
                                <!-- Tab panes -->
                                <div class="tab-content">
                                    <div role="tabpanel" class="tab-pane fade active in" id="Section1">
                                                                            <div class="col-md-3 col-xs-3">
                                       <p><label>First Name: </label> {{c.data.incidentData[0].firstName}}    </p>
                                        <p><label>Last Name: </label> {{c.data.incidentData[0].lastName}}      </p>
                                        <p><label>Email: </label> {{c.data.incidentData[0].email}}      </p>
                                        <p><label>Telephone Number: </label> {{c.data.incidentData[0].telephoneNumber}}      </p>
                                        <p><label>Reported Date:  </label> {{c.data.incidentData[0].createdDate}}   </p>
                                        <p><label>Last Updated:  </label> {{c.data.incidentData[0].lastUpdated}}   </p>
                                      </div>

                                        <div class="col-md-3 col-xs-3">
                                        <p><label>Incident #: </label> {{c.data.incidentData[0].incidentId}}    </p>
                                        <p><label>Status: </label> {{c.data.incidentData[0].incidentStatus}}      </p>
                                        <p><label>Category: </label> {{c.data.incidentData[0].incidentType}}      </p>
                                        <p><label>Organization:  </label> {{c.data.incidentData[0].organization}}   </p>
                                        <p><label>Department:  </label> {{c.data.incidentData[0].department}}   </p>
                                        <p><label>Assigned To:  </label> {{c.data.incidentData[0].assignedTo}} </p>
                                      </div>

                                        <div class="col-md-12 col-xs-12">
                                        <p><label for="notes">Notes:</label>   </p>
                                        <textarea class="form-control" rows="5" id="notes" ng-readonly="true">{{c.data.incidentData[0].note}}</textarea>
                                      </div>

                                    </div> <!-- End of Section1 -->

                                    <div role="tabpanel" class="tab-pane fade" id="Section2">
                                        <label>Extracted Potential Indicators</label>
                                        <table class="table table-condensed table-hover table-bordered">
                                            <thead>
                                            <tr>
                                                <th>No</th>
                                                <th>Ranking</th>
                                                <th>Indicator</th>
                                                <th>Status</th>
                                            </tr>
                                            </thead>
                                            <tbody>
                                            <tr ng-repeat="indicator in c.data.indicatorsData track by $index" >
                                                <td>{{indicator.number}}</td>
                                                <td>{{indicator.urgencyRanking}}</td>
                                                <td>{{indicator.indicatorText}}</td>
                                                <td class="{{indicator.cssClass}}"><a href="https://dev21310.service-now.com/haloportal/?id=potential_indicator_summary&indicator_id={{indicator.sysId}}" data-toggle="tooltip" data-placement="top" title="Click here to see more information">{{indicator.indicatorStatus}}</a></td>
                                            </tr>
                                            </tbody>
                                        </table>
                                    </div> <!-- End of Section2 -->

                                    <div role="tabpanel" class="tab-pane fade" id="Section3">
                                        <p><label>Recommendation: </label> {{c.data.courseOfActionsData[0].recommendedName}}   </p>
                                        <p><label>Reasoning: </label> {{c.data.courseOfActionsData[0].reasoning}}  </p>

                                        <p><label>Select Course of Action: </label>
                                            <select class="form-control" id="sel1" ng-model="selectedValue"  style="max-width:700px">
                                                <option ng-repeat="coa in c.data.ListOfCourseOfActionsData track by $index" value="{{coa.name}}" ng-selected="{{defaultvalue == c.data.courseOfActionsData[0].recommendedName}}">{{coa.name}}</option>
                                            </select> </p>

                                        <p><label>Additional Actions: </label>   </p>
                                        <div id="actions">
                                            <label class="checkbox-inline"><input type="checkbox" value="" id="sendEmailUpdateToReporter">Send Email Update to Reporter</label>
                                            <label class="checkbox-inline"><input type="checkbox" value="" id="notifyIsp" ng-model="notifyIsp">Notify ISP</label>
                                            <label class="checkbox-inline"><input type="checkbox" value="" id="notifyDomainRegistrar" ng-model="notifyDomainRegistrar">Notify Domain Registrar</label> <br/>
                                            <label class="checkbox-inline"><input type="checkbox" value="" id="sendEmailReceipt">Send Email Receipt to Reporter</label>
                                            <label class="checkbox-inline"><input type="checkbox" value="" id="setStatusOfTicketToResolved">Set Status of Ticket Resolved
                                            </label>
                                            <label class="checkbox-inline"><input type="checkbox" value="" id="notifyProduction">Notify Production</label><br/>
                                            <label class="checkbox-inline"><input type="checkbox" value="" id="resolveAndCloseTicket">Resolve and Close Ticket</label>
                                            <label class="checkbox-inline"><input type="checkbox" value="" ng-model="checked" id="assignToGroup">Assign to Group</label>
                                            <br/>
                                        </div> <br/>

                                        <div class="row">

                                            <div id="assignment" class="col-md-4">
                                                <b>Group Name:</b>
                                                <select  id="groupSelectedValue" ng-model="groupSelectedValue"  style="max-width:700px"    class="form-control">
                                                    <option value="Tier1">Tier1</option>
                                                    <option value="Tier2">Tier2</option>
                                                    <option value="Tier3">Tier3</option>
                                                    <option value="Tier4">Tier4</option>
                                                    <option value="Tier5">Tier5</option>
                                                    <option value="Halo Administrator">Halo Administrator</option>
                                                </select>
                                            </div>

                                            <div class="col-md-4">
                                                <b>Assign To:</b>
                                                <select  id="assignTo" ng-model="assignTo"    style="max-width:700px"  class="form-control" >
                                                    <option  ng-repeat="user in (c.data.groupUsers | filter: {'groupName':groupSelectedValue}) track by $index" value="user.name">{{user.name}}</option>
                                                </select>
                                            </div>

                                        </div>
                                        <br/>

                                    <div id="commentsSection" >
                                        <div class="">
                                         <span ng-hide="c.data.incidentData[0].incidentStatus == 'Closed'">
                                           <b>Comments:</b>  <textarea id="comments"  class="form-control"  ng-model="comments"> </textarea> <br/>
                                         </span>
                                        </div>
                                        <br/>

                                        <div class="">
                                            <b>Comments History: </b>
                                            <table class="table table-responsive">
                                                <thead>
                                                <tr>
                                                    <th>Comment </th>
                                                    <th>Entered Date </th>
                                                    <th>Entered By </th>
                                                </tr>
                                                </thead>
                                                <tbody>
                                                <tr ng-repeat="text in c.data.commentshistory track by $index">
                                                    <td>{{text.comment}}</td>
                                                    <td>{{text.enteredDate}}</td>
                                                    <td>{{text.enteredBy}}</td>
                                                </tr>
                                                </tbody>

                                            </table>
                                            <button type="button" class="btn btn-primary" ng-click="execute()">Execute</button>
                                            <input type="hidden" id="sysId" value="{{sysId}}">
                                        </div>
                                    </div>
                                </div> <!-- End of Section3 -->
                        </div>
                    </div>
                </div>
            </div>
        </div> <!-- End of Container -->

        </div> <!--End of Panel Group -->
    </div>
</div>
</div>
</code>```

Angular JS Code:

```<code>(function()
{
    "use strict";
    var app=angular.module('indicatorModal',[]);
    app.controller('incidentSummaryCtrl',['$scope',function($scope)
    {

        $scope.updateSelectedCoa=function()
        {
            //get Values from Form
            var selectedCoa=jQuery("#sel1 option:selected").text();
            var sendEmailUpdateToReporter=jQuery("#sendEmailUpdateToReporter").is(":checked");
            var notifyIsp=jQuery("#notifyIsp").is(":checked");
            var notifyDomainRegistrar=jQuery("#notifyDomainRegistrar").is(":checked");
            var sendEmailReceipt=jQuery("#sendEmailReceipt").is(":checked");
            var setStatusOfTicketToResolved=jQuery("#setStatusOfTicketToResolved").is(":checked");
            var notifyProduction=jQuery("#notifyProduction").is(":checked");
            var assignToNextTier=jQuery("#assignToNextTier").is(":checked");
            var assignToGroup=jQuery("#assignToGroup").is(":checked");
            var resolveAndCloseTicket=jQuery("#resolveAndCloseTicket").is(":checked");
            var sysId=jQuery("#sysId").val();

            var gr=new GlideRecord('x_19668_halo_incident');
            gr.addQuery('sys_id',sysId);
            gr.query(callbackFunction);
            function callbackFunction(gr)
            {
                if(gr.next())
                    {
                    $scope.updateSelectedSysIdOfCoa(selectedCoa,sysId);
                    gr.send_email_update_to_reporter=sendEmailUpdateToReporter;
                    gr.notify_isp=notifyIsp;
                    gr.send_email_receipt_to_reporter=sendEmailReceipt;
                    gr.set_status_to_resolved=setStatusOfTicketToResolved;
                    gr.notify_production=notifyProduction;
                    gr.notify_domain_registrar=notifyDomainRegistrar;
                    gr.assign_to_tier=assignToNextTier;
                    gr.assign_to_group=assignToGroup;
                    gr.resolve_and_close_the_ticket=resolveAndCloseTicket;
                    gr.update();
                }
            }

        };

        $scope.updateSelectedSysIdOfCoa=function(selectedCoa,sysId)
        {
            var selectedCoaSysId='';
            var gr1=new GlideRecord('x_19668_halo_selcted_ticket_course_of_action');
            gr1.addQuery('incident_id',sysId);
            gr1.query(callbackFunction2);
            function callbackFunction2(gr1)
            {
                if(gr1.next())
                    {
                    var gr2=new GlideRecord('x_19668_halo_courseofactions');
                    gr2.addQuery('ticket_coa_name',selectedCoa);
                    gr2.query();
                    if(gr2.next())
                        {
                        selectedCoaSysId=gr2.sys_id+'';
                    }
                    gr1.ticket_coa_selected_id=selectedCoaSysId;
                    gr1.update();

                }
            }

        };

        $scope.passSysId=function(indicatorSysId,indicatorType)
        {
            var ipIndicatorsData = JSON.parse(sessionStorage.getItem('ipIndicatorsData'));
            var domainIndicatorsData = JSON.parse(sessionStorage.getItem('domainIndicatorsData'));
            var hashCodeIndicatorsData = JSON.parse(sessionStorage.getItem('hashCodeIndicatorsData'));
            if(indicatorType == 'IP Address')
                {
                for(var indicator in ipIndicatorsData )
                    {
                    if(ipIndicatorsData[indicator].sysId == indicatorSysId)
                        {
                        jQuery("#indicatorId").text(ipIndicatorsData[indicator].indicatorId);
                        jQuery("#indicatorStatus").text(ipIndicatorsData[indicator].indicatorStatus);
                        jQuery("#indicatorType").text(ipIndicatorsData[indicator].indicatorType);
                        jQuery("#urgencyRanking").text(ipIndicatorsData[indicator].urgencyRanking);
                        jQuery("#completedEnrichCount").text(ipIndicatorsData[indicator].completedEnrichCount);
                        jQuery("#enrichStartTimestamp").text(ipIndicatorsData[indicator].enrichStartTimestamp);
                        jQuery("#enrichEndTimestamp").text(ipIndicatorsData[indicator].enrichEndTimestamp);
                        jQuery("#indicatorText").text(ipIndicatorsData[indicator].indicatorText);
                        $("#indicatorLink").attr("href", "https://dev21310.service-now.com/haloportal/?id=potential_indicator_summary&indicator_id="+indicatorSysId);
                    }
                }
            }
            else if(indicatorType == 'Full Qualified Domain Name (FQDN)')
                {
                for(var indicator in domainIndicatorsData )
                    {
                    if(domainIndicatorsData[indicator].sysId == indicatorSysId)
                        {
                        jQuery("#indicatorId").text(domainIndicatorsData[indicator].indicatorId);
                        jQuery("#indicatorStatus").text(domainIndicatorsData[indicator].indicatorStatus);
                        jQuery("#indicatorType").text(domainIndicatorsData[indicator].indicatorType);
                        jQuery("#urgencyRanking").text(domainIndicatorsData[indicator].urgencyRanking);
                        jQuery("#completedEnrichCount").text(domainIndicatorsData[indicator].completedEnrichCount);
                        jQuery("#enrichStartTimestamp").text(domainIndicatorsData[indicator].enrichStartTimestamp);
                        jQuery("#enrichEndTimestamp").text(domainIndicatorsData[indicator].enrichEndTimestamp);
                        jQuery("#indicatorText").text(domainIndicatorsData[indicator].indicatorText);
                        jQuery("#indicatorLink").attr("href", "https://dev21310.service-now.com/haloportal/?id=potential_indicator_summary&indicator_id="+indicatorSysId);

                    }
                }
            }
            else if(indicatorType == 'Hash Code')
                {
                for(var indicator in hashCodeIndicatorsData )
                    {
                    if(hashCodeIndicatorsData[indicator].sysId == indicatorSysId)
                        {
                        jQuery("#indicatorId").text(hashCodeIndicatorsData[indicator].indicatorId);
                        jQuery("#indicatorStatus").text(hashCodeIndicatorsData[indicator].indicatorStatus);
                        jQuery("#indicatorType").text(hashCodeIndicatorsData[indicator].indicatorType);
                        jQuery("#urgencyRanking").text(hashCodeIndicatorsData[indicator].urgencyRanking);
                        jQuery("#completedEnrichCount").text(hashCodeIndicatorsData[indicator].completedEnrichCount);
                        jQuery("#enrichStartTimestamp").text(hashCodeIndicatorsData[indicator].enrichStartTimestamp);
                        jQuery("#enrichEndTimestamp").text(hashCodeIndicatorsData[indicator].enrichEndTimestamp);
                        jQuery("#indicatorText").text(hashCodeIndicatorsData[indicator].indicatorText);
                        $("#indicatorLink").attr("href", "https://dev21310.service-now.com/haloportal/?id=potential_indicator_summary&indicator_id="+indicatorSysId);
                    }
                }

            }

        };

    }]);

})();
</code>```

答:
I would suggest you to use Angular UI instead of bootstrap

https://angular-ui.github.io/bootstrap/

Body:
My web page has 3 bootstrap tabs with data some data being populated run time. After page loads, tab1 looks fine and when I click on other tabs, whole body reloads and tab1 displays. I do not see any errors in Console.

HTML:

Incident  {{c.data.incidentData[0].incidentId}}

Incident Information

Potential Indicators

Course of Action

First Name:  {{c.data.incidentData[0].firstName}}

Last Name:  {{c.data.incidentData[0].lastName}}

Email:  {{c.data.incidentData[0].email}}

Telephone Number:  {{c.data.incidentData[0].telephoneNumber}}

Reported Date:   {{c.data.incidentData[0].createdDate}}

Last Updated:   {{c.data.incidentData[0].lastUpdated}}

Incident #:  {{c.data.incidentData[0].incidentId}}

Status:  {{c.data.incidentData[0].incidentStatus}}

Category:  {{c.data.incidentData[0].incidentType}}

Organization:   {{c.data.incidentData[0].organization}}

Department:   {{c.data.incidentData[0].department}}

Assigned To:   {{c.data.incidentData[0].assignedTo}}

Notes:

                                        <textarea class="form-control" rows="5" id="notes" ng-readonly="true">{{c.data.incidentData[0].note}}</textarea>

                                        Extracted Potential Indicators

                                                No
                                                Ranking
                                                Indicator
                                                Status

                                                {{indicator.number}}
                                                {{indicator.urgencyRanking}}
                                                {{indicator.indicatorText}}
                                                {{indicator.indicatorStatus}}

Recommendation:  {{c.data.courseOfActionsData[0].recommendedName}}

Reasoning:  {{c.data.courseOfActionsData[0].reasoning}}

Select Course of Action:
                                            <select class="form-control" id="sel1" ng-model="selectedValue"  style="max-width:700px">
                                                <option ng-repeat="coa in c.data.ListOfCourseOfActionsData track by $index" value="{{coa.name}}" ng-selected="{{defaultvalue == c.data.courseOfActionsData[0].recommendedName}}">{{coa.name}}</option>
                                            </select>

Additional Actions:

                                            <input type="checkbox" value="" id="sendEmailUpdateToReporter">Send Email Update to Reporter
                                            <input type="checkbox" value="" id="notifyIsp" ng-model="notifyIsp">Notify ISP
                                            <input type="checkbox" value="" id="notifyDomainRegistrar" ng-model="notifyDomainRegistrar">Notify Domain Registrar

                                            <input type="checkbox" value="" id="sendEmailReceipt">Send Email Receipt to Reporter
                                            <input type="checkbox" value="" id="setStatusOfTicketToResolved">Set Status of Ticket Resolved

                                            <input type="checkbox" value="" id="notifyProduction">Notify Production

                                            <input type="checkbox" value="" id="resolveAndCloseTicket">Resolve and Close Ticket
                                            <input type="checkbox" value="" ng-model="checked" id="assignToGroup">Assign to Group

                                                Group Name:
                                                <select  id="groupSelectedValue" ng-model="groupSelectedValue"  style="max-width:700px"    class="form-control">
                                                    <option value="Tier1">Tier1</option>
                                                    <option value="Tier2">Tier2</option>
                                                    <option value="Tier3">Tier3</option>
                                                    <option value="Tier4">Tier4</option>
                                                    <option value="Tier5">Tier5</option>
                                                    <option value="Halo Administrator">Halo Administrator</option>
                                                </select>

                                                Assign To:
                                                <select  id="assignTo" ng-model="assignTo"    style="max-width:700px"  class="form-control" >
                                                    <option  ng-repeat="user in (c.data.groupUsers | filter: {'groupName':groupSelectedValue}) track by $index" value="user.name">{{user.name}}</option>
                                                </select>

                                           Comments:  <textarea id="comments"  class="form-control"  ng-model="comments"> </textarea>

                                            Comments History:

                                                    Comment
                                                    Entered Date
                                                    Entered By

                                                    {{text.comment}}
                                                    {{text.enteredDate}}
                                                    {{text.enteredBy}}

                                            <button type="button" class="btn btn-primary" ng-click="execute()">Execute</button>
                                            <input type="hidden" id="sysId" value="{{sysId}}">

Angular JS Code:

(function()
{
    "use strict";
    var app=angular.module('indicatorModal',[]);
    app.controller('incidentSummaryCtrl',['$scope',function($scope)
    {

        $scope.updateSelectedCoa=function()
        {
            //get Values from Form
            var selectedCoa=jQuery("#sel1 option:selected").text();
            var sendEmailUpdateToReporter=jQuery("#sendEmailUpdateToReporter").is(":checked");
            var notifyIsp=jQuery("#notifyIsp").is(":checked");
            var notifyDomainRegistrar=jQuery("#notifyDomainRegistrar").is(":checked");
            var sendEmailReceipt=jQuery("#sendEmailReceipt").is(":checked");
            var setStatusOfTicketToResolved=jQuery("#setStatusOfTicketToResolved").is(":checked");
            var notifyProduction=jQuery("#notifyProduction").is(":checked");
            var assignToNextTier=jQuery("#assignToNextTier").is(":checked");
            var assignToGroup=jQuery("#assignToGroup").is(":checked");
            var resolveAndCloseTicket=jQuery("#resolveAndCloseTicket").is(":checked");
            var sysId=jQuery("#sysId").val();

            var gr=new GlideRecord('x_19668_halo_incident');
            gr.addQuery('sys_id',sysId);
            gr.query(callbackFunction);
            function callbackFunction(gr)
            {
                if(gr.next())
                    {
                    $scope.updateSelectedSysIdOfCoa(selectedCoa,sysId);
                    gr.send_email_update_to_reporter=sendEmailUpdateToReporter;
                    gr.notify_isp=notifyIsp;
                    gr.send_email_receipt_to_reporter=sendEmailReceipt;
                    gr.set_status_to_resolved=setStatusOfTicketToResolved;
                    gr.notify_production=notifyProduction;
                    gr.notify_domain_registrar=notifyDomainRegistrar;
                    gr.assign_to_tier=assignToNextTier;
                    gr.assign_to_group=assignToGroup;
                    gr.resolve_and_close_the_ticket=resolveAndCloseTicket;
                    gr.update();
                }
            }

        };

        $scope.updateSelectedSysIdOfCoa=function(selectedCoa,sysId)
        {
            var selectedCoaSysId='';
            var gr1=new GlideRecord('x_19668_halo_selcted_ticket_course_of_action');
            gr1.addQuery('incident_id',sysId);
            gr1.query(callbackFunction2);
            function callbackFunction2(gr1)
            {
                if(gr1.next())
                    {
                    var gr2=new GlideRecord('x_19668_halo_courseofactions');
                    gr2.addQuery('ticket_coa_name',selectedCoa);
                    gr2.query();
                    if(gr2.next())
                        {
                        selectedCoaSysId=gr2.sys_id+'';
                    }
                    gr1.ticket_coa_selected_id=selectedCoaSysId;
                    gr1.update();

                }
            }

        };

        $scope.passSysId=function(indicatorSysId,indicatorType)
        {
            var ipIndicatorsData = JSON.parse(sessionStorage.getItem('ipIndicatorsData'));
            var domainIndicatorsData = JSON.parse(sessionStorage.getItem('domainIndicatorsData'));
            var hashCodeIndicatorsData = JSON.parse(sessionStorage.getItem('hashCodeIndicatorsData'));
            if(indicatorType == 'IP Address')
                {
                for(var indicator in ipIndicatorsData )
                    {
                    if(ipIndicatorsData[indicator].sysId == indicatorSysId)
                        {
                        jQuery("#indicatorId").text(ipIndicatorsData[indicator].indicatorId);
                        jQuery("#indicatorStatus").text(ipIndicatorsData[indicator].indicatorStatus);
                        jQuery("#indicatorType").text(ipIndicatorsData[indicator].indicatorType);
                        jQuery("#urgencyRanking").text(ipIndicatorsData[indicator].urgencyRanking);
                        jQuery("#completedEnrichCount").text(ipIndicatorsData[indicator].completedEnrichCount);
                        jQuery("#enrichStartTimestamp").text(ipIndicatorsData[indicator].enrichStartTimestamp);
                        jQuery("#enrichEndTimestamp").text(ipIndicatorsData[indicator].enrichEndTimestamp);
                        jQuery("#indicatorText").text(ipIndicatorsData[indicator].indicatorText);
                        $("#indicatorLink").attr("href", "https://dev21310.service-now.com/haloportal/?id=potential_indicator_summary&indicator_id="+indicatorSysId);
                    }
                }
            }
            else if(indicatorType == 'Full Qualified Domain Name (FQDN)')
                {
                for(var indicator in domainIndicatorsData )
                    {
                    if(domainIndicatorsData[indicator].sysId == indicatorSysId)
                        {
                        jQuery("#indicatorId").text(domainIndicatorsData[indicator].indicatorId);
                        jQuery("#indicatorStatus").text(domainIndicatorsData[indicator].indicatorStatus);
                        jQuery("#indicatorType").text(domainIndicatorsData[indicator].indicatorType);
                        jQuery("#urgencyRanking").text(domainIndicatorsData[indicator].urgencyRanking);
                        jQuery("#completedEnrichCount").text(domainIndicatorsData[indicator].completedEnrichCount);
                        jQuery("#enrichStartTimestamp").text(domainIndicatorsData[indicator].enrichStartTimestamp);
                        jQuery("#enrichEndTimestamp").text(domainIndicatorsData[indicator].enrichEndTimestamp);
                        jQuery("#indicatorText").text(domainIndicatorsData[indicator].indicatorText);
                        jQuery("#indicatorLink").attr("href", "https://dev21310.service-now.com/haloportal/?id=potential_indicator_summary&indicator_id="+indicatorSysId);

                    }
                }
            }
            else if(indicatorType == 'Hash Code')
                {
                for(var indicator in hashCodeIndicatorsData )
                    {
                    if(hashCodeIndicatorsData[indicator].sysId == indicatorSysId)
                        {
                        jQuery("#indicatorId").text(hashCodeIndicatorsData[indicator].indicatorId);
                        jQuery("#indicatorStatus").text(hashCodeIndicatorsData[indicator].indicatorStatus);
                        jQuery("#indicatorType").text(hashCodeIndicatorsData[indicator].indicatorType);
                        jQuery("#urgencyRanking").text(hashCodeIndicatorsData[indicator].urgencyRanking);
                        jQuery("#completedEnrichCount").text(hashCodeIndicatorsData[indicator].completedEnrichCount);
                        jQuery("#enrichStartTimestamp").text(hashCodeIndicatorsData[indicator].enrichStartTimestamp);
                        jQuery("#enrichEndTimestamp").text(hashCodeIndicatorsData[indicator].enrichEndTimestamp);
                        jQuery("#indicatorText").text(hashCodeIndicatorsData[indicator].indicatorText);
                        $("#indicatorLink").attr("href", "https://dev21310.service-now.com/haloportal/?id=potential_indicator_summary&indicator_id="+indicatorSysId);
                    }
                }

            }

        };

    }]);

})();


来源: stackexchange

问:
Kubernetes exec throw the WebSocket API
I'm trying to connect on a container throw the Kubernetes WebSocket API, from a container running within Kubernetes, without any success.

Install wscat:

```<code>apt-get update
apt-get install -y npm
ln -s /usr/bin/nodejs /usr/bin/node
npm install -g n
n stable
npm install -g wscat
</code>```

Exec on Kubernetes API:

```<code>wscat -c "wss://kubernetes.default.svc.cluster.local/api/v1/namespaces/default/pods/my-pod-1623018646-kvc4b/exec?container=aws&stdin=1&stdout=1&stderr=1&tty=1&command=bash" \
  --ca /var/run/secrets/kubernetes.io/serviceaccount/ca.crt \
  -H "Authorization: Bearer $(</var/run/secrets/kubernetes.io/serviceaccount/token)"
error: Error: unexpected server response (400)
</code>```

Do you know what I'm doing wrong?

Note that the following works:

```<code>curl https://kubernetes.default.svc.cluster.local/api/v1/namespaces/default/pods/my-pod-1623018646-kvc4b \
  --cacert /var/run/secrets/kubernetes.io/serviceaccount/ca.crt \
  -H "Authorization: Bearer $(</var/run/secrets/kubernetes.io/serviceaccount/token)"
</code>```

Apparently some people are able to connect: https://stackoverflow.com/a/43841572/599728

Cheers

答:
I just found out that the container name was wrong:

?container=aws Aws was not on this pod.

ContentLicense: CC BY-SA 3.0

Title: Kubernetes exec throw the WebSocket API

Body:
I'm trying to connect on a container throw the Kubernetes WebSocket API, from a container running within Kubernetes, without any success.

Install wscat:

apt-get update
apt-get install -y npm
ln -s /usr/bin/nodejs /usr/bin/node
npm install -g n
n stable
npm install -g wscat

Exec on Kubernetes API:

wscat -c "wss://kubernetes.default.svc.cluster.local/api/v1/namespaces/default/pods/my-pod-1623018646-kvc4b/exec?container=aws&stdin=1&stdout=1&stderr=1&tty=1&command=bash" \
  --ca /var/run/secrets/kubernetes.io/serviceaccount/ca.crt \
  -H "Authorization: Bearer $(</var/run/secrets/kubernetes.io/serviceaccount/token)"
error: Error: unexpected server response (400)

Do you know what I'm doing wrong?

Note that the following works:

curl https://kubernetes.default.svc.cluster.local/api/v1/namespaces/default/pods/my-pod-1623018646-kvc4b \
  --cacert /var/run/secrets/kubernetes.io/serviceaccount/ca.crt \
  -H "Authorization: Bearer $(</var/run/secrets/kubernetes.io/serviceaccount/token)"

Apparently some people are able to connect: https://stackoverflow.com/a/43841572/599728

Cheers


问:
ruby-on-rails - Problem with Nested Resources
I have a Problem with Nested Resources.

2 Models

```<code>User => has_many :stuffs

Stuff => belongs_to :user
</code>```

routes.rb

```<code>map.resources :stuffs

map.resources :users, :has_many => [:stuffs]
</code>```

When i call /users/1/stuffs it presents me the Stuff for the corresponding User. but i got this also when i call /users/2/stuffs. It should return 0 "Stuffs" but it dont work.

```<code>MySQL Query from Server
SELECT * FROM `stuffs`
</code>```

rake routes

```<code>stuffs GET    /stuffs(.:format)                         {:action=>"index", :controller=>"stuffs"}
                POST   /stuffs(.:format)                         {:action=>"create", :controller=>"stuffs"}
      new_stuff GET    /stuffs/new(.:format)                     {:action=>"new", :controller=>"stuffs"}
     edit_stuff GET    /stuffs/:id/edit(.:format)                {:action=>"edit", :controller=>"stuffs"}
          stuff GET    /stuffs/:id(.:format)                     {:action=>"show", :controller=>"stuffs"}
                PUT    /stuffs/:id(.:format)                     {:action=>"update", :controller=>"stuffs"}
                DELETE /stuffs/:id(.:format)                     {:action=>"destroy", :controller=>"stuffs"}
    user_stuffs GET    /users/:user_id/stuffs(.:format)          {:action=>"index", :controller=>"stuffs"}
                POST   /users/:user_id/stuffs(.:format)          {:action=>"create", :controller=>"stuffs"}
 new_user_stuff GET    /users/:user_id/stuffs/new(.:format)      {:action=>"new", :controller=>"stuffs"}
edit_user_stuff GET    /users/:user_id/stuffs/:id/edit(.:format) {:action=>"edit", :controller=>"stuffs"}
     user_stuff GET    /users/:user_id/stuffs/:id(.:format)      {:action=>"show", :controller=>"stuffs"}
                PUT    /users/:user_id/stuffs/:id(.:format)      {:action=>"update", :controller=>"stuffs"}
                DELETE /users/:user_id/stuffs/:id(.:format)      {:action=>"destroy", :controller=>"stuffs"}
          users GET    /users(.:format)                          {:action=>"index", :controller=>"users"}
                POST   /users(.:format)                          {:action=>"create", :controller=>"users"}
       new_user GET    /users/new(.:format)                      {:action=>"new", :controller=>"users"}
      edit_user GET    /users/:id/edit(.:format)                 {:action=>"edit", :controller=>"users"}
           user GET    /users/:id(.:format)                      {:action=>"show", :controller=>"users"}
                PUT    /users/:id(.:format)                      {:action=>"update", :controller=>"users"}
                DELETE /users/:id(.:format)                      {:action=>"destroy", :controller=>"users"}
           root        /                                         {:action=>"index", :controller=>"users"}
</code>```

gem list

```<code>actionmailer (2.3.8)
actionpack (2.3.8)
activerecord (2.3.8)
activeresource (2.3.8)
activesupport (2.3.8)
arel (2.0.6)
authlogic (2.1.6)
builder (2.1.2)
cgi_multipart_eof_fix (2.5.0)
gem_plugin (0.2.3)
i18n (0.5.0)
mongrel (1.1.5 x86-mingw32)
mysql (2.8.1 x86-mingw32)
paperclip (2.3.7)
rack (1.1.0)
rails (2.3.8)
rake (0.8.7)
tzinfo (0.3.23)
</code>```

There is no where clause for the corresponding user_id. But how to fix it?

Rails Version 2.3.8

Should work like this => http://guides.rubyonrails.org/routing.html 2.7 Nested Resources

Hope somebody can help

答:
Routes alone don't affect the model.  Since the user id is passed in, though, you can do:</p>

```<code>User.find(params[:user_id]).stuffs
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a Problem with Nested Resources.

2 Models

User => has_many :stuffs

Stuff => belongs_to :user

routes.rb

map.resources :stuffs

map.resources :users, :has_many => [:stuffs]

When i call /users/1/stuffs it presents me the Stuff for the corresponding User. but i got this also when i call /users/2/stuffs. It should return 0 "Stuffs" but it dont work.

MySQL Query from Server
SELECT * FROM `stuffs`

rake routes

stuffs GET    /stuffs(.:format)                         {:action=>"index", :controller=>"stuffs"}
                POST   /stuffs(.:format)                         {:action=>"create", :controller=>"stuffs"}
      new_stuff GET    /stuffs/new(.:format)                     {:action=>"new", :controller=>"stuffs"}
     edit_stuff GET    /stuffs/:id/edit(.:format)                {:action=>"edit", :controller=>"stuffs"}
          stuff GET    /stuffs/:id(.:format)                     {:action=>"show", :controller=>"stuffs"}
                PUT    /stuffs/:id(.:format)                     {:action=>"update", :controller=>"stuffs"}
                DELETE /stuffs/:id(.:format)                     {:action=>"destroy", :controller=>"stuffs"}
    user_stuffs GET    /users/:user_id/stuffs(.:format)          {:action=>"index", :controller=>"stuffs"}
                POST   /users/:user_id/stuffs(.:format)          {:action=>"create", :controller=>"stuffs"}
 new_user_stuff GET    /users/:user_id/stuffs/new(.:format)      {:action=>"new", :controller=>"stuffs"}
edit_user_stuff GET    /users/:user_id/stuffs/:id/edit(.:format) {:action=>"edit", :controller=>"stuffs"}
     user_stuff GET    /users/:user_id/stuffs/:id(.:format)      {:action=>"show", :controller=>"stuffs"}
                PUT    /users/:user_id/stuffs/:id(.:format)      {:action=>"update", :controller=>"stuffs"}
                DELETE /users/:user_id/stuffs/:id(.:format)      {:action=>"destroy", :controller=>"stuffs"}
          users GET    /users(.:format)                          {:action=>"index", :controller=>"users"}
                POST   /users(.:format)                          {:action=>"create", :controller=>"users"}
       new_user GET    /users/new(.:format)                      {:action=>"new", :controller=>"users"}
      edit_user GET    /users/:id/edit(.:format)                 {:action=>"edit", :controller=>"users"}
           user GET    /users/:id(.:format)                      {:action=>"show", :controller=>"users"}
                PUT    /users/:id(.:format)                      {:action=>"update", :controller=>"users"}
                DELETE /users/:id(.:format)                      {:action=>"destroy", :controller=>"users"}
           root        /                                         {:action=>"index", :controller=>"users"}

gem list

actionmailer (2.3.8)
actionpack (2.3.8)
activerecord (2.3.8)
activeresource (2.3.8)
activesupport (2.3.8)
arel (2.0.6)
authlogic (2.1.6)
builder (2.1.2)
cgi_multipart_eof_fix (2.5.0)
gem_plugin (0.2.3)
i18n (0.5.0)
mongrel (1.1.5 x86-mingw32)
mysql (2.8.1 x86-mingw32)
paperclip (2.3.7)
rack (1.1.0)
rails (2.3.8)
rake (0.8.7)
tzinfo (0.3.23)

There is no where clause for the corresponding user_id. But how to fix it?

Rails Version 2.3.8

Should work like this => http://guides.rubyonrails.org/routing.html 2.7 Nested Resources

Hope somebody can help

Body:
Routes alone don't affect the model.  Since the user id is passed in, though, you can do:

User.find(params[:user_id]).stuffs


问:
under gluon project how to get the Android assets folder
I had creat a gluon project ,then I put some folders and files under assets folder(Android)  and I want to read the files in application,now how do I can read the assets folder ? or how do I get the android Context or AssetManager ? under gluon project there is no Activity class or any class extends Activity.I had read all of the gluonMobile API, javaFXports API and developer docs, there is no help!
Dose anyone can help me? I nearly got crazy!</p>

答: FXActivity which you obtain via FXActivity.getInstance extends Activity, thus you can call fxActivity.getAssets() to get an instance of AssetManager


问:
how to save a DNN model with tensorflow
I have code that trains a DNN network. I don't want to train this network every time, because it uses too much time. How can I save the model?

```<code>def train_model(filename, validation_ratio=0.):
    # define model to be trained
    columns = [tf.contrib.layers.real_valued_column(str(col),
                                                    dtype=tf.int8)
               for col in FEATURE_COLS]
    classifier = tf.contrib.learn.DNNClassifier(
        feature_columns=columns,
        hidden_units=[100, 100],
        n_classes=N_LABELS,
        dropout=0.3)

    # load and split data
    print( 'Loading training data.')
    data = load_batch(filename)
    overall_size = data.shape[0]
    learn_size = int(overall_size * (1 - validation_ratio))
    learn, validation = np.array_split(data, [learn_size])
    print( 'Finished loading data. Samples count = {}'.format(overall_size))

    # learning
    print( 'Training using batch of size {}'.format(learn_size))
    classifier.fit(input_fn=lambda: pipeline(learn),
                   steps=learn_size)

    if validation_ratio > 0:
        validate_model(classifier, learn, validation)

    return classifier
</code>```

After running this function, I get a DNNClassifier which I want to save.

答:
I believe this has already been answered here: Tensorflow: how to save/restore a model?

```<code>saver = tf.train.Saver()
saver.save(sess, 'my_test_model',global_step=1000)
</code>```

(code copied from that question's answer)

Title: how to save a DNN model with tensorflow

Body:
I have code that trains a DNN network. I don't want to train this network every time, because it uses too much time. How can I save the model?

def train_model(filename, validation_ratio=0.):
    # define model to be trained
    columns = [tf.contrib.layers.real_valued_column(str(col),
                                                    dtype=tf.int8)
               for col in FEATURE_COLS]
    classifier = tf.contrib.learn.DNNClassifier(
        feature_columns=columns,
        hidden_units=[100, 100],
        n_classes=N_LABELS,
        dropout=0.3)

    # load and split data
    print( 'Loading training data.')
    data = load_batch(filename)
    overall_size = data.shape[0]
    learn_size = int(overall_size * (1 - validation_ratio))
    learn, validation = np.array_split(data, [learn_size])
    print( 'Finished loading data. Samples count = {}'.format(overall_size))

    # learning
    print( 'Training using batch of size {}'.format(learn_size))
    classifier.fit(input_fn=lambda: pipeline(learn),
                   steps=learn_size)

    if validation_ratio > 0:
        validate_model(classifier, learn, validation)

    return classifier

After running this function, I get a DNNClassifier which I want to save.

Body:
I believe this has already been answered here: Tensorflow: how to save/restore a model?

saver = tf.train.Saver()
saver.save(sess, 'my_test_model',global_step=1000)

(code copied from that question's answer)


问:
Laravel 5.4 npm run dev error: Error: Cannot find module 'lodash._baseclone'
I am trying to run following command: npm run dev. However, it is giving an error as

```<code>> cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

module.js:471
throw err;
^

Error: Cannot find module 'lodash._baseclone'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/var/www/html/korsall-clean/node_modules/node-
notifier/node_modules/lodash.clonedeep/index.js:9:17)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ development: `cross-env NODE_ENV=development
node_modules/webpack/bin/webpack.js --progress --hide-modules --
config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely
additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/ubuntu/.npm/_logs/2017-06-07T10_34_11_411Z-
debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ dev: `npm run development`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm. There is likely
additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/ubuntu/.npm/_logs/2017-06-07T10_34_11_426Z-
debug.log
</code>```

I have removed node_modules folder and re-installed it, but still it is giving same error.

Please guide me wher

答: Try this npm i --save lodash._baseclone</p>

Body:
I am trying to run following command: npm run dev. However, it is giving an error as

> cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js

module.js:471
throw err;
^

Error: Cannot find module 'lodash._baseclone'
at Function.Module._resolveFilename (module.js:469:15)
at Function.Module._load (module.js:417:25)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/var/www/html/korsall-clean/node_modules/node-
notifier/node_modules/lodash.clonedeep/index.js:9:17)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ development: `cross-env NODE_ENV=development
node_modules/webpack/bin/webpack.js --progress --hide-modules --
config=node_modules/laravel-mix/setup/webpack.config.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ development script.
npm ERR! This is probably not a problem with npm. There is likely
additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/ubuntu/.npm/_logs/2017-06-07T10_34_11_411Z-
debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ dev: `npm run development`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm. There is likely
additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/ubuntu/.npm/_logs/2017-06-07T10_34_11_426Z-
debug.log

I have removed node_modules folder and re-installed it, but still it is giving same error.

Please guide me wher

Body: Try this npm i --save lodash._baseclone


问:
Where is SYSTEM_INFORMATION_CLASS defined?
I came across a short C++ code designed to prevent applications from stealing focus using DLL injection. As usual with C++, I have problems with things being undefined and libraries being missing.

Specifically, this constant is undefined: SYSTEM_INFORMATION_CLASS. In this code:

```<code>typedef NTSTATUS( WINAPI* PNT_QUERY_SYSTEM_INFORMATION ) (
  __in       SYSTEM_INFORMATION_CLASS SystemInformationClass,
  __inout    PVOID SystemInformation,
  __in       ULONG SystemInformationLength,
  __out_opt  PULONG ReturnLength
);
</code>```

The windows.h is already included so it must be something else missing. When googling that, I got lot of results about getting the CPU temperature, but I can't see what should I include in them...

答:
Have a look to this: http://www.geoffchappell.com/studies/windows/km/ntoskrnl/api/ex/sysinfo/query.htm.

There is a good description for [Nt]|[Zw]QuerySystemInformation and input arguments.

Body:
I came across a short C++ code designed to prevent applications from stealing focus using DLL injection. As usual with C++, I have problems with things being undefined and libraries being missing.

Specifically, this constant is undefined: SYSTEM_INFORMATION_CLASS. In this code:

typedef NTSTATUS( WINAPI* PNT_QUERY_SYSTEM_INFORMATION ) (
  __in       SYSTEM_INFORMATION_CLASS SystemInformationClass,
  __inout    PVOID SystemInformation,
  __in       ULONG SystemInformationLength,
  __out_opt  PULONG ReturnLength
);

The windows.h is already included so it must be something else missing. When googling that, I got lot of results about getting the CPU temperature, but I can't see what should I include in them...


问:
How to archive and unarchive custom objects in Swift? Or how to save custom object to NSUserDefaults in Swift?
I have a class

```<code>class Player {

    var name = ""

    func encodeWithCoder(encoder: NSCoder) {
        encoder.encodeObject(name)
    }

    func initWithCoder(decoder: NSCoder) -> Player {
        self.name = decoder.decodeObjectForKey("name") as String
        return self
    }

    init(coder aDecoder: NSCoder!) {
        self.name = aDecoder.decodeObjectForKey("name") as String
    }

    init(name: String) {
        self.name = name
    }
}
</code>```

and i want to serialise it and save to user defaults.

First of all I'm not sure how to correctly write encoder and decoder. So for init i wrote two methods.

When i try to execute this code:

```<code>func saveUserData() {
    let player1 = Player(name: "player1")
    let myEncodedObject = NSKeyedArchiver.archivedDataWithRootObject(player1)
    NSUserDefaults.standardUserDefaults().setObject(myEncodedObject, forKey: "player")
}
</code>```

app crashes and i get this message:

```<code>*** NSForwarding: warning: object 0xebf0000 of class '_TtC6GameOn6Player' does not implement methodSignatureForSelector: -- trouble ahead
</code>```

What do i do wrong?

答:
In Swift 4 you don't need NSCoding anymore! There is a new protocol called Codable!

```<code>class Player: Codable {

    var name = ""

    init(name: String) {
        self.name = name
    }
}
</code>```

And Codable also supports Enums and Structs so you can rewrite your player class to a struct if you want!

```<code>struct Player: Codable {
    let name: String
}
</code>```

To save your player in Userdefaults:

```<code>let player = Player(name: "PlayerOne")
try? UserDefaults.standard.set(PropertyListEncoder().encode(player), forKey: "player")
</code>```

Note: PropertyListEncoder() is a class from the framework Foundation

To Retrieve:

```<code>let encoded = UserDefault.standard.object(forKey: "player") as! Data
let storedPlayer = try! PropertyListDecoder().decode(Player.self, from: encoded)
</code>```

For more information, read https://developer.apple.com/documentation/swift/codable

Body:
I have a class

class Player {

    var name = ""

    func encodeWithCoder(encoder: NSCoder) {
        encoder.encodeObject(name)
    }

    func initWithCoder(decoder: NSCoder) -> Player {
        self.name = decoder.decodeObjectForKey("name") as String
        return self
    }

    init(coder aDecoder: NSCoder!) {
        self.name = aDecoder.decodeObjectForKey("name") as String
    }

    init(name: String) {
        self.name = name
    }
}

and i want to serialise it and save to user defaults.

First of all I'm not sure how to correctly write encoder and decoder. So for init i wrote two methods.

When i try to execute this code:

func saveUserData() {
    let player1 = Player(name: "player1")
    let myEncodedObject = NSKeyedArchiver.archivedDataWithRootObject(player1)
    NSUserDefaults.standardUserDefaults().setObject(myEncodedObject, forKey: "player")
}

app crashes and i get this message:

*** NSForwarding: warning: object 0xebf0000 of class '_TtC6GameOn6Player' does not implement methodSignatureForSelector: -- trouble ahead

What do i do wrong?

Body:
In Swift 4 you don't need NSCoding anymore! There is a new protocol called Codable!

class Player: Codable {

    var name = ""

    init(name: String) {
        self.name = name
    }
}

And Codable also supports Enums and Structs so you can rewrite your player class to a struct if you want!

struct Player: Codable {
    let name: String
}

To save your player in Userdefaults:

let player = Player(name: "PlayerOne")
try? UserDefaults.standard.set(PropertyListEncoder().encode(player), forKey: "player")

Note: PropertyListEncoder() is a class from the framework Foundation

To Retrieve:

let encoded = UserDefault.standard.object(forKey: "player") as! Data
let storedPlayer = try! PropertyListDecoder().decode(Player.self, from: encoded)

For more information, read https://developer.apple.com/documentation/swift/codable


问:
How do I join an unknown number of rows to another row?
I have this scenario:

Table A:

```<code>---------------
ID| SOME_VALUE|
---------------
1 | 123223    |
2 | 1232ff    |
---------------
</code>```

Table B:

```<code>------------------
ID | KEY | VALUE |
------------------
23 | 1   | 435   |
24 | 1   | 436   |
------------------
</code>```

KEY is a reference to to Table A's ID. Can I somehow join these tables so that I get the following result:

Table C

```<code>-------------------------
ID| SOME_VALUE|    |    |
-------------------------
1 | 123223    |435 |436 |
2 | 1232ff    |    |    |
-------------------------
</code>```

Table C should be able to have any given number of columns depending on how many matching values that are found in Table B.

I hope this enough to explain what I'm after here.

Thanks.

答:
You need to use a Dynamic PIVOT clause in order to do this.

EDIT:

Ok so I've done some playing around and based on the following sample data:

```<code>Create Table TableA
(
IDCol int,
SomeValue varchar(50)
)
Create Table TableB
(
IDCol int,
KEYCol int,
Value varchar(50)
)

Insert into TableA
Values (1, '123223')
Insert Into TableA
Values (2,'1232ff')
Insert into TableA
Values (3, '222222')

Insert Into TableB
Values( 23, 1, 435)
Insert Into TableB
Values( 24, 1, 436)

Insert Into TableB
Values( 25, 3, 45)
Insert Into TableB
Values( 26, 3, 46)

Insert Into TableB
Values( 27, 3, 435)
Insert Into TableB
Values( 28, 3, 437)
</code>```

You can execute the following Dynamic SQL.

```<code>declare @sql varchar(max)
declare @pivot_list varchar(max)
declare @pivot_select varchar(max)

Select
        @pivot_list = Coalesce(@Pivot_List + ', ','') + '[' + Value +']',
        @Pivot_select = Coalesce(@pivot_Select, ', ','') +'IsNull([' + Value +'],'''') as [' + Value + '],'
From
(
Select distinct Value From dbo.TableB
)PivotCodes

Set @Sql = '
;With p as (

Select a.IdCol,
        a.SomeValue,
        b.Value
From dbo.TableA a
Left Join dbo.TableB b on a.IdCol = b.KeyCol
)
Select IdCol, SomeValue ' + Left(@pivot_select, Len(@Pivot_Select)-1) + '
From p
Pivot ( Max(Value) for Value in (' + @pivot_list + '
        )
    )as pvt
'

exec (@sql)
</code>```

This gives you the following output:

Although this works at the moment it would be a nightmare to maintain.  I'd recommend trying to achieve these results somewhere else. i.e not in SQL!

Good luck!

Body:
I have this scenario:

Table A:

---------------
ID| SOME_VALUE|
---------------
1 | 123223    |
2 | 1232ff    |
---------------

Table B:

------------------
ID | KEY | VALUE |
------------------
23 | 1   | 435   |
24 | 1   | 436   |
------------------

KEY is a reference to to Table A's ID. Can I somehow join these tables so that I get the following result:

Table C

-------------------------
ID| SOME_VALUE|    |    |
-------------------------
1 | 123223    |435 |436 |
2 | 1232ff    |    |    |
-------------------------

Table C should be able to have any given number of columns depending on how many matching values that are found in Table B.

I hope this enough to explain what I'm after here.

Thanks.

Body:
You need to use a Dynamic PIVOT clause in order to do this.

EDIT:

Ok so I've done some playing around and based on the following sample data:

Create Table TableA
(
IDCol int,
SomeValue varchar(50)
)
Create Table TableB
(
IDCol int,
KEYCol int,
Value varchar(50)
)

Insert into TableA
Values (1, '123223')
Insert Into TableA
Values (2,'1232ff')
Insert into TableA
Values (3, '222222')

Insert Into TableB
Values( 23, 1, 435)
Insert Into TableB
Values( 24, 1, 436)

Insert Into TableB
Values( 25, 3, 45)
Insert Into TableB
Values( 26, 3, 46)

Insert Into TableB
Values( 27, 3, 435)
Insert Into TableB
Values( 28, 3, 437)

You can execute the following Dynamic SQL.

declare @sql varchar(max)
declare @pivot_list varchar(max)
declare @pivot_select varchar(max)

Select
        @pivot_list = Coalesce(@Pivot_List + ', ','') + '[' + Value +']',
        @Pivot_select = Coalesce(@pivot_Select, ', ','') +'IsNull([' + Value +'],'''') as [' + Value + '],'
From
(
Select distinct Value From dbo.TableB
)PivotCodes

Set @Sql = '
;With p as (

Select a.IdCol,
        a.SomeValue,
        b.Value
From dbo.TableA a
Left Join dbo.TableB b on a.IdCol = b.KeyCol
)
Select IdCol, SomeValue ' + Left(@pivot_select, Len(@Pivot_Select)-1) + '
From p
Pivot ( Max(Value) for Value in (' + @pivot_list + '
        )
    )as pvt
'

exec (@sql)

This gives you the following output:

Although this works at the moment it would be a nightmare to maintain.  I'd recommend trying to achieve these results somewhere else. i.e not in SQL!

Good luck!


问:
Kafka Consumer Re-reading Messages
I've seen an issue where all my messages in my topic gets re-read by my consumer.  I only have 1 consumer, and I turn it on/off while I'm developing/testing.  I notice that sometimes after days of not running the consumer, when I turn it on again suddenly it re-reads all my messages.

The clientid and groupid stays the same throughout.  I explicitly call commitSync, since my enable.auto.commit=false.  I do set auto.offset.reset=earliest, but to my understanding that should only kick in if the offset is deleted on the server.  I'm using IBM Bluemix's MessageHub service, so maybe that's automatically deleting an offset?

Does anyone have any clues/ideas?

Thanks.

答:
Yes offsets are automatically deleted if you don't commit for 24hours.
This is the default setting with Kafka and we've not changed it.</p>

Title: Kafka Consumer Re-reading Messages


问:
Python Script runs fine manually but errors out when I run with Cronjob
I have a Python Script below that will just run hostname on 4 different hosts and then it will save it to a file. It then will open that file and save these each line or output into a variable which the program will use later. It works fine when I run it manually although everytime I use cronjob I am getting an error.

Note: the whole script is obviously not here if you wondering how I can SSH into these hosts just by the below lines. But the script is failing at the part that I have put below.

Python Script:

```<code>#! /usr/bin/python

import os

hostname=['a','b','c','d']

for i in hostname:

    os.system('hostname >> hostlist.txt')

data = open('hostlist.txt')
hosta, hostb, hostc, hostd = data.read().splitlines()
</code>```

Error:

```<code>ValueError: too many values to unpack
</code>```

Cronjob looks like:

```<code>00 14 * * * python /tmp/hostname.py &> /tmp/hostnamerror.log
</code>```

Update:::

Ok I am pretty sure I know the problem after more troubleshooting. It seems that when I run it with Cronjob that it is not creating the file hostlist.txt, although if I ran it manually then it does create this file. So in the Cronjob it opens hostlist.txt as a new file with no variables hence giving me the error message. Does anyone have any idea why running the Python Script as a Cronjob would cause the redirect in the first os.system command not to create a append and create a file?

答: Ok I figured it out. For some reason when I run it as a cronjob the double direct was not creating a file so I created the file first then ran the command and it seems to be working now. Thanks everyone for your inputs!!</p>

Body:
I have a Python Script below that will just run hostname on 4 different hosts and then it will save it to a file. It then will open that file and save these each line or output into a variable which the program will use later. It works fine when I run it manually although everytime I use cronjob I am getting an error.

Note: the whole script is obviously not here if you wondering how I can SSH into these hosts just by the below lines. But the script is failing at the part that I have put below.

Python Script:

#! /usr/bin/python

import os

hostname=['a','b','c','d']

for i in hostname:

    os.system('hostname >> hostlist.txt')

data = open('hostlist.txt')
hosta, hostb, hostc, hostd = data.read().splitlines()

Error:

ValueError: too many values to unpack

Cronjob looks like:

00 14 * * * python /tmp/hostname.py &> /tmp/hostnamerror.log

Update:::

Ok I am pretty sure I know the problem after more troubleshooting. It seems that when I run it with Cronjob that it is not creating the file hostlist.txt, although if I ran it manually then it does create this file. So in the Cronjob it opens hostlist.txt as a new file with no variables hence giving me the error message. Does anyone have any idea why running the Python Script as a Cronjob would cause the redirect in the first os.system command not to create a append and create a file?


问:
ModelState.IsValid threw an exception of type System.IO.FileLoadException
I have an .NET MVC application and I'm writing some unit test for it using NUnit.

This is the function I'm currently testing:

```<code>[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Add(AddInstrumentViewModel model)
{
    if (ModelState.IsValid)
    {
        var group = new FtpServerGroup
        {
            Disabled = true,
            FtpLastPullTime = DateTime.Now,
            FtpPullInterval = TimeSpan.Zero,
        };

        await db.CreateAsync(group, model.Address, model.Username, model.Password);

        // go back to card view
        var res = await db.GetAll();
        return RedirectToAction("Index", res);
    }

    return View(model);
}
</code>```

this is the actual test:

```<code>[Test]
public async Task Test()
{
    var controller = new AutomaticTransferController(mockService.Object);

    var model = new AddInstrumentViewModel
    {
        Address = "124.124.124.124",
        Password = "123456",
        Username = "John Foo"
    };

    var res = await controller.Add(model);
}
</code>```

Stepping with the debugger I noticed that as soon as I enter the .Add() method the line  if (ModelState.IsValid) throw an exception

ModelState.IsValid threw an exception of type
  System.IO.FileLoadException

In fact, it threw an exception without telling me when nor where

EDIT

This is the code for my InstrumentViewModel

```<code>    using System.ComponentModel.DataAnnotations;

    public class AddInstrumentViewModel
    {
        [Display(Name = "IP Address or Domain Name")]
        [Required]
        [RegularExpression(@"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$")]
        public string Address { get; set; }

        [Display(Name = "FTP Username")]
        [Required]
        public string Username { get; set; }

        [Display(Name = "FTP Password")]
        [Required]
        public string Password { get; set; }
    }
</code>```

答: I had the same problem. Just update & consolidate nuget packages. I'm not sure which exactly:)</p>

Body:
I have an .NET MVC application and I'm writing some unit test for it using NUnit.

This is the function I'm currently testing:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Add(AddInstrumentViewModel model)
{
    if (ModelState.IsValid)
    {
        var group = new FtpServerGroup
        {
            Disabled = true,
            FtpLastPullTime = DateTime.Now,
            FtpPullInterval = TimeSpan.Zero,
        };

        await db.CreateAsync(group, model.Address, model.Username, model.Password);

        // go back to card view
        var res = await db.GetAll();
        return RedirectToAction("Index", res);
    }

    return View(model);
}

this is the actual test:

[Test]
public async Task Test()
{
    var controller = new AutomaticTransferController(mockService.Object);

    var model = new AddInstrumentViewModel
    {
        Address = "124.124.124.124",
        Password = "123456",
        Username = "John Foo"
    };

    var res = await controller.Add(model);
}

Stepping with the debugger I noticed that as soon as I enter the .Add() method the line  if (ModelState.IsValid) throw an exception

ModelState.IsValid threw an exception of type
  System.IO.FileLoadException

In fact, it threw an exception without telling me when nor where

EDIT

This is the code for my InstrumentViewModel

    using System.ComponentModel.DataAnnotations;

    public class AddInstrumentViewModel
    {
        [Display(Name = "IP Address or Domain Name")]
        [Required]
        [RegularExpression(@"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$")]
        public string Address { get; set; }

        [Display(Name = "FTP Username")]
        [Required]
        public string Username { get; set; }

        [Display(Name = "FTP Password")]
        [Required]
        public string Password { get; set; }
    }

ContentLicense: CC BY-SA 4.0


问:
SQL Server: (implicit?) date conversion failure from text
I have the something akin to the following code:

```<code>DECLARE @EvalDate VARCHAR(254)
SET @Evaldate = '''4/30/2017'',''12/31/2016'',''12/31/2015'',''12/31/2014'',''12/31/2013'''

SELECT field1, field2, YEAR(datefield1) AS YR, datefield2
FROM table
WHERE datefield2 IN (@EvalDate)
</code>```

When I run this code, I get the following error:

Msg 241, Level 16, State 1, Line 4

  Conversion failed when converting date and/or time from character string.

I'm pretty sure that the error comes from my SET @Evaldate statement since this used to run when I just entered the dates directly into the WHERE/IN clause. How can I correct this?

I am using SQL Server 2008 btw.

答:
The error isn't from your SET command, it's from your WHERE statement.  It's trying to convert the literal value '4/30/2017','12/31/2016','12/31/2015','12/31/2014','12/31/2013' into a date, and obviously failing.

You can't use a variable to insert multiple values into an IN like that.  What this is doing is attempting to convert the entire string into a single date, and failing.

This should give you the results you want using a TABLE variable and doing a  JOIN to it:

```<code>Declare @Dates Table
(
    EvalDate Date
)

Insert  @Dates (EvalDate)
Values  ('2017-04-30'),
        ('2016-12-31'),
        ('2015-12-31'),
        ('2014-12-31'),
        ('2013-12-31');

SELECT  field1, field2, YEAR(datefield1) AS YR, datefield2
FROM    table   T
Join    @Dates  D   On  D.EvalDate = T.DateField2
</code>```

Additionally, you should always use the ISO standard date format (yyyy-MM-dd).

Body:
I have the something akin to the following code:

DECLARE @EvalDate VARCHAR(254)
SET @Evaldate = '''4/30/2017'',''12/31/2016'',''12/31/2015'',''12/31/2014'',''12/31/2013'''

SELECT field1, field2, YEAR(datefield1) AS YR, datefield2
FROM table
WHERE datefield2 IN (@EvalDate)

When I run this code, I get the following error:

Msg 241, Level 16, State 1, Line 4

  Conversion failed when converting date and/or time from character string.

I'm pretty sure that the error comes from my SET @Evaldate statement since this used to run when I just entered the dates directly into the WHERE/IN clause. How can I correct this?

I am using SQL Server 2008 btw.

Body:
The error isn't from your SET command, it's from your WHERE statement.  It's trying to convert the literal value '4/30/2017','12/31/2016','12/31/2015','12/31/2014','12/31/2013' into a date, and obviously failing.

You can't use a variable to insert multiple values into an IN like that.  What this is doing is attempting to convert the entire string into a single date, and failing.

This should give you the results you want using a TABLE variable and doing a  JOIN to it:

Declare @Dates Table
(
    EvalDate Date
)

Insert  @Dates (EvalDate)
Values  ('2017-04-30'),
        ('2016-12-31'),
        ('2015-12-31'),
        ('2014-12-31'),
        ('2013-12-31');

SELECT  field1, field2, YEAR(datefield1) AS YR, datefield2
FROM    table   T
Join    @Dates  D   On  D.EvalDate = T.DateField2

Additionally, you should always use the ISO standard date format (yyyy-MM-dd).


问:
Merge all columns into one without keeping colnames
I have this format of dataframe:

```<code>df <- structure(list(col1 = structure(1:2, .Label = c("text1", "text3"
), class = "factor"), col2 = structure(c(2L, 1L), .Label = c("text1",
"text2"), class = "factor"), col3 = structure(c(1L, 1L), .Label = "text1", class = "factor"),
    col4 = structure(1:2, .Label = c("text2", "text4"), class = "factor")), .Names = c("col1",
"col2", "col3", "col4"), class = "data.frame", row.names = c(NA,
-2L))
</code>```

And I would like to merge/combine all columns into one without keeping the column names.

Example output:

```<code>text1
text2
text1
text2
text3
text1
text1
text4
</code>```

I found this example but it merges the rows.

答:
We transpose the dataset, concatenate it to a vector and create a data.frame based on that

```<code>data.frame(newcol = c(t(df)), stringsAsFactors=FALSE)
</code>```

Body:
I have this format of dataframe:

df <- structure(list(col1 = structure(1:2, .Label = c("text1", "text3"
), class = "factor"), col2 = structure(c(2L, 1L), .Label = c("text1",
"text2"), class = "factor"), col3 = structure(c(1L, 1L), .Label = "text1", class = "factor"),
    col4 = structure(1:2, .Label = c("text2", "text4"), class = "factor")), .Names = c("col1",
"col2", "col3", "col4"), class = "data.frame", row.names = c(NA,
-2L))

And I would like to merge/combine all columns into one without keeping the column names.

Example output:

text1
text2
text1
text2
text3
text1
text1
text4

I found this example but it merges the rows.

Body:
We transpose the dataset, concatenate it to a vector and create a data.frame based on that

data.frame(newcol = c(t(df)), stringsAsFactors=FALSE)


问:
Method is not applicable for arguments when adding wildcard
I have following two classes:

```<code>class ProblematicConverter implements Converter<List<?>> {};
class NonProblematicConverter implements Converter<List> {};
</code>```

And method of class Utils:

```<code><T> void addConverter(Class<? extends T> cls, Converter<T> converter);
</code>```

Now, first function invocation is ok but second produces error:

```<code>addConverter(List.class, new ProblematicConverter());
addConverter(List.class, new NonProblematicConverter());
</code>```

Error says:

"The method addConverter(Class, Converter) in the type Utils is not applicable for the arguments (Class, ProblematicConverter)"

I do not understand why it's like that.

答:
Based on your comment, I think the right thing to do here might be to use an unchecked cast on List.class, but first, the reason the code in the question doesn't compile is roughly:

T of addConverter is inferred to be List<?>.

The bounded wildcard in cls requires that its type argument be T or a subtype of T, but the raw type List is a supertype of List<?> (specified here).

Therefore, Class<List> is incompatible with the inferred type of cls which is Class<? extends List<?>>.

So, for example, either of the following two declarations would compile with the invocations in the question:

```<code><T> void m(Class<T> cls, Converter<? extends T> converter) {}
<T> void m(Class<? super T> cls, Converter<T> converter) {}
</code>```

That of course doesn't help you out, but it illustrates the relationship between List and List<?>.

You might see also these two answers of mine which discuss similar situations.

So anyway, based on your comment saying that you're trying to eliminate raw types and can't change the declaration of addConverter, what could be appropriate is to use an unchecked cast from Class<List> to Class<List<?>>:

```<code>@SuppressWarnings("unchecked")
static final Class<List<?>> WILD_LIST =
    (Class<List<?>>) (Class<? super List<?>>) List.class;
</code>```

This will let you call e.g.:

```<code>addConverter(WILD_LIST, new ProblematicConverter());
</code>```

However, I'd like to point out that unchecked casting is not a general solution. It's a solution to this specific problem of converting e.g. a Class<GenericType> to a Class<GenericType<?>>. It's safe to do because GenericType<?> is a more restrictive type than the raw type GenericType and because Class has a very limited range of things it can do with its type argument.

If you could change the declaration of addConverter, I think I would recommend using something like Guava TypeToken instead of Class, because then you don't have this sort of problem.

Body:
I have following two classes:

class ProblematicConverter implements Converter<List<?>> {};
class NonProblematicConverter implements Converter<List> {};

And method of class Utils:

<T> void addConverter(Class<? extends T> cls, Converter<T> converter);

Now, first function invocation is ok but second produces error:

addConverter(List.class, new ProblematicConverter());
addConverter(List.class, new NonProblematicConverter());

Error says:

"The method addConverter(Class, Converter) in the type Utils is not applicable for the arguments (Class, ProblematicConverter)"

I do not understand why it's like that.

Body:
Based on your comment, I think the right thing to do here might be to use an unchecked cast on List.class, but first, the reason the code in the question doesn't compile is roughly:

T of addConverter is inferred to be List<?>.

The bounded wildcard in cls requires that its type argument be T or a subtype of T, but the raw type List is a supertype of List<?> (specified here).

Therefore, Class<List> is incompatible with the inferred type of cls which is Class<? extends List<?>>.

So, for example, either of the following two declarations would compile with the invocations in the question:

<T> void m(Class<T> cls, Converter<? extends T> converter) {}
<T> void m(Class<? super T> cls, Converter<T> converter) {}

That of course doesn't help you out, but it illustrates the relationship between List and List<?>.

You might see also these two answers of mine which discuss similar situations.

So anyway, based on your comment saying that you're trying to eliminate raw types and can't change the declaration of addConverter, what could be appropriate is to use an unchecked cast from Class<List> to Class<List<?>>:

@SuppressWarnings("unchecked")
static final Class<List<?>> WILD_LIST =
    (Class<List<?>>) (Class<? super List<?>>) List.class;

This will let you call e.g.:

addConverter(WILD_LIST, new ProblematicConverter());

However, I'd like to point out that unchecked casting is not a general solution. It's a solution to this specific problem of converting e.g. a Class<GenericType> to a Class<GenericType<?>>. It's safe to do because GenericType<?> is a more restrictive type than the raw type GenericType and because Class has a very limited range of things it can do with its type argument.

If you could change the declaration of addConverter, I think I would recommend using something like Guava TypeToken instead of Class, because then you don't have this sort of problem.


问:
How to repeat earlier parts of code • Luau
Now, I'm not amazing with words, so bear with me.

So I am creating a program within Lua, but I've run into a problem. I am making a bank sorta program, and I what it does is it asks for a PIN number, and then you are able to withdrawal or deposit. But, I want it to go back to asking for the PIN number after you deposit or withdrawal.

I am able to do that in Python:

```<code>while True:
    pin = input("PIN: ")
    if pin == 21171:
        -- code
    elif pin == 21172:
        -- code
</code>```

So that asks for pin, runs code in one of the if statements, then when all code is run in if statement it goes back to asking for PIN. This is what I wanna do in Lua, but how?

答:
I recommend Programming in Lua. https://www.lua.org/pil/21.1.html

```<code>while true do
  io.write("PIN: ")
  local pin = tonumber(io.read("*line"))
  if pin == 21171 then
      -- code
  elseif pin == 21172 then
      -- code
  end -- if
end -- while
</code>```

Body:
Now, I'm not amazing with words, so bear with me.

So I am creating a program within Lua, but I've run into a problem. I am making a bank sorta program, and I what it does is it asks for a PIN number, and then you are able to withdrawal or deposit. But, I want it to go back to asking for the PIN number after you deposit or withdrawal.

I am able to do that in Python:

while True:
    pin = input("PIN: ")
    if pin == 21171:
        -- code
    elif pin == 21172:
        -- code

So that asks for pin, runs code in one of the if statements, then when all code is run in if statement it goes back to asking for PIN. This is what I wanna do in Lua, but how?

Body:
I recommend Programming in Lua. https://www.lua.org/pil/21.1.html

while true do
  io.write("PIN: ")
  local pin = tonumber(io.read("*line"))
  if pin == 21171 then
      -- code
  elseif pin == 21172 then
      -- code
  end -- if
end -- while


问:
How to get value of 2 different radio box and set it to specific place using loop/each?

$(document).ready(function() {

  $('.allrb').change(function() {
    valueE();
  });

});

function valueE()
{
  for(j=0; j<=2 ; j++)
  {
    var nofr1=[];
    row=document.getElementsByName("Fr"+j);
      for (i=0; i<row.length; i++)
      {
        if(row[i].checked)
          nofr1[i]= parseInt(row.value);
      }
    $("#numFr"+(j+1)).val(nofr1[j]);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-hover table-responsive" id="tab">
<tr id="alertr1" name="v">
  <td width="200px" id="text">content 1</td>
  <td width="40px"><label><input type="radio" name="Fr1" class="allrb" value="0"></label></td>
  <td width="40px"><label><input type="radio" name="Fr1" class="allrb" value="1"></label></td>
  <td width="40px"><label><input type="radio" name="Fr1" class="allrb" value="2"></label></td>
  <td width="40px"><label><input type="radio" name="Fr1" class="allrb" value="3"></label></td>
  <td width="30px"><label><input type="radio" name="Fr1" class="allrb" value="4"></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb" value="0" ></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb" value="1" ></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb" value="2" ></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb" value="3" ></label></td>
  <td width="120px" bgcolor="Gainsboro"><label><input type="radio" name="Ir1" class="allrb" value="4" ></label></td>
  <td width="30px"><input type="number" name="numFr1" id="numFr1" disabled></td>
  <td width="30px" bgcolor="Gainsboro"><input type="number" name="numIr1" id="numIr1" disabled></td>
</tr>

<tr id="alertr2" name="v">
  <td width="200px" id="text">content 2</td>
  <td width="40px"><label><input type="radio" name="Fr2" class="allrb" value="0"></label></td>
  <td width="40px"><label><input type="radio" name="Fr2" class="allrb" value="1"></label></td>
  <td width="40px"><label><input type="radio" name="Fr2" class="allrb" value="2"></label></td>
  <td width="40px"><label><input type="radio" name="Fr2" class="allrb" value="3"></label></td>
  <td width="30px"><label><input type="radio" name="Fr2" class="allrb" value="4"></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb" value="0" ></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb" value="1" ></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb" value="2" ></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb" value="3" ></label></td>
  <td width="120px" bgcolor="Gainsboro"><label><input type="radio" name="Ir2" class="allrb" value="4" ></label></td>
  <td width="30px"><input type="number" name="numFr2" id="numFr2" disabled></td>
  <td width="30px" bgcolor="Gainsboro"><input type="number" name="numIr2" id="numIr2" disabled></td>
</tr>

<tr id="alertr3" name="v">
  <td width="200px" id="text">content 3</td>
  <td width="40px"><label><input type="radio" name="Fr3" class="allrb" value="0"></label></td>
  <td width="40px"><label><input type="radio" name="Fr3" class="allrb" value="1"></label></td>
  <td width="40px"><label><input type="radio" name="Fr3" class="allrb" value="2"></label></td>
  <td width="40px"><label><input type="radio" name="Fr3" class="allrb" value="3"></label></td>
  <td width="30px"><label><input type="radio" name="Fr3" class="allrb" value="4"></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3" class="allrb" value="0" ></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3" class="allrb" value="1" ></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3" class="allrb" value="2" ></label></td>
  <td width="50px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3" class="allrb" value="3" ></label></td>
  <td width="120px" bgcolor="Gainsboro"><label><input type="radio" name="Ir3" class="allrb" value="4" ></label></td>
  <td width="30px"><input type="number" name="numFr3" id="numFr3" disabled></td>
  <td width="30px" bgcolor="Gainsboro"><input type="number" name="numIr3" id="numIr3" disabled></td>
</tr>

</tbody>
</table></code>```

In a row, I have 2 different radio box, how to I get the value of all of the radio box and set the value in the specific input[type=number] there? Since I had 16 row and each row had 2 different value box, I would like to use loop to loop all the value into specific place, else there will be many redundant code. I had try to do it, but my jquery won't work. Thanks.

答:
This should work for you without changing the HTML:

```<code>$(document).ready(function() {
  $('.allrb').change(valueE);
});

function valueE(e) {
    var index = $(this).closest("tr").index();
  var newValue = e.target.value;
  if ($(this).closest("td").attr("bgcolor") == "Gainsboro"){
     $("#numIr" + (index + 1)).val(newValue);
  }else $("#numFr" + (index + 1)).val(newValue);
}
</code>```

However, this won't work for your first radio group of the last row since your input has an id="numFr2", which I believe you meant to label as id="numFr3" Once you correct the name it will work for that one as well.

Body:
$(document).ready(function() {

  $('.allrb').change(function() {
    valueE();
  });

});

function valueE()
{
  for(j=0; j<=2 ; j++)
  {
    var nofr1=[];
    row=document.getElementsByName("Fr"+j);
      for (i=0; i<row.length; i++)
      {
        if(row[i].checked)
          nofr1[i]= parseInt(row.value);
      }
    $("#numFr"+(j+1)).val(nofr1[j]);
  }
}

  content 1
  <input type="radio" name="Fr1" class="allrb" value="0">
  <input type="radio" name="Fr1" class="allrb" value="1">
  <input type="radio" name="Fr1" class="allrb" value="2">
  <input type="radio" name="Fr1" class="allrb" value="3">
  <input type="radio" name="Fr1" class="allrb" value="4">
  <input type="radio" name="Ir1" class="allrb" value="0" >
  <input type="radio" name="Ir1" class="allrb" value="1" >
  <input type="radio" name="Ir1" class="allrb" value="2" >
  <input type="radio" name="Ir1" class="allrb" value="3" >
  <input type="radio" name="Ir1" class="allrb" value="4" >
  <input type="number" name="numFr1" id="numFr1" disabled>
  <input type="number" name="numIr1" id="numIr1" disabled>

  content 2
  <input type="radio" name="Fr2" class="allrb" value="0">
  <input type="radio" name="Fr2" class="allrb" value="1">
  <input type="radio" name="Fr2" class="allrb" value="2">
  <input type="radio" name="Fr2" class="allrb" value="3">
  <input type="radio" name="Fr2" class="allrb" value="4">
  <input type="radio" name="Ir2" class="allrb" value="0" >
  <input type="radio" name="Ir2" class="allrb" value="1" >
  <input type="radio" name="Ir2" class="allrb" value="2" >
  <input type="radio" name="Ir2" class="allrb" value="3" >
  <input type="radio" name="Ir2" class="allrb" value="4" >
  <input type="number" name="numFr2" id="numFr2" disabled>
  <input type="number" name="numIr2" id="numIr2" disabled>

  content 3
  <input type="radio" name="Fr3" class="allrb" value="0">
  <input type="radio" name="Fr3" class="allrb" value="1">
  <input type="radio" name="Fr3" class="allrb" value="2">
  <input type="radio" name="Fr3" class="allrb" value="3">
  <input type="radio" name="Fr3" class="allrb" value="4">
  <input type="radio" name="Ir3" class="allrb" value="0" >
  <input type="radio" name="Ir3" class="allrb" value="1" >
  <input type="radio" name="Ir3" class="allrb" value="2" >
  <input type="radio" name="Ir3" class="allrb" value="3" >
  <input type="radio" name="Ir3" class="allrb" value="4" >
  <input type="number" name="numFr3" id="numFr3" disabled>
  <input type="number" name="numIr3" id="numIr3" disabled>

In a row, I have 2 different radio box, how to I get the value of all of the radio box and set the value in the specific input[type=number] there? Since I had 16 row and each row had 2 different value box, I would like to use loop to loop all the value into specific place, else there will be many redundant code. I had try to do it, but my jquery won't work. Thanks.

Body:
This should work for you without changing the HTML:

$(document).ready(function() {
  $('.allrb').change(valueE);
});

function valueE(e) {
    var index = $(this).closest("tr").index();
  var newValue = e.target.value;
  if ($(this).closest("td").attr("bgcolor") == "Gainsboro"){
     $("#numIr" + (index + 1)).val(newValue);
  }else $("#numFr" + (index + 1)).val(newValue);
}

However, this won't work for your first radio group of the last row since your input has an id="numFr2", which I believe you meant to label as id="numFr3" Once you correct the name it will work for that one as well.


问:
How could i add a binary which need another document to command line?
My environment is Ubuntu16.04.

The structure of my binary's floder is that:

```<code>copy
├── creat
├── creat.cpp
├── makeup.sh
├── MODEL.cpp
└── README.md
</code>```

And the creat is the binary which i want to add to command line.

The MODEL.cpp is the doc that creat need.

In creat.cpp i should open the MODEL.cpp like this:

in.open("MODEL.cpp");

but i want anyother who cloned this repo could use it easily.
So i write a shell script makeup.sh:

```<code>#!/bin/bash
g++ creat.cpp -o creat
sudo cp creat /usr/local/bin
sudo cp MODEL.cpp /usr/local/bin
echo "Now you can try it"
</code>```

But when I use the command creat, the terminal told me:

```<code>Can not find MODEL.cpp
</code>```

But the MODEL.cpp exits in /usr/local/bin.

I don't know what's wrong with that, What should I do?

答:
This is because the MODEL.cpp is not present in the current location from where you are executing creat even though both creat and MODEL.cpp are in same folder.

best option is to keep the depend MODEL.cpp file in /etc folder.

change this line in.open("MODEL.cpp");  to in.open("/etc/MODEL.cpp");

so it doesn't matter from where you execute the creat binary it will work.

Body:
My environment is Ubuntu16.04.

The structure of my binary's floder is that:

copy
├── creat
├── creat.cpp
├── makeup.sh
├── MODEL.cpp
└── README.md

And the creat is the binary which i want to add to command line.

The MODEL.cpp is the doc that creat need.

In creat.cpp i should open the MODEL.cpp like this:

in.open("MODEL.cpp");

but i want anyother who cloned this repo could use it easily.
So i write a shell script makeup.sh:

#!/bin/bash
g++ creat.cpp -o creat
sudo cp creat /usr/local/bin
sudo cp MODEL.cpp /usr/local/bin
echo "Now you can try it"

But when I use the command creat, the terminal told me:

Can not find MODEL.cpp

But the MODEL.cpp exits in /usr/local/bin.

I don't know what's wrong with that, What should I do?


问:
iOS Firebase push notifications not appearing
I've set up push notifications according to this walkthrough: https://www.appcoda.com/firebase-push-notifications/

But when I send a test message from Firebase, it doesn't show up. I followed all the steps, I have valid certificates:

Provisioning Profile set up for push notifications:

Under my App ID it shows that notifications are enabled:

And I have the certificate uploaded to Firebase:

And in my AppDelegate didFinishLaunchingWithOptions:

```<code>    if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
        // For iOS 10 data message (sent via FCM
        FIRMessaging.messaging().remoteMessageDelegate = self
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()
</code>```

Along with the Firebase callback method in AppDelegate:

```<code>func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
    print(remoteMessage.appData)
}
</code>```

And obviously I have imported:

```<code>import UserNotifications
import FirebaseInstanceID
import FirebaseMessaging
</code>```

I'm not sure why the push notifications are not working, it seems like everything is in place. The only thing out of the ordinary I did was remove the entitlements from Target -> Code Signing, as it was giving me an invalid entitlements error when I tried to run the app. Now that it's removed, the app is running fine. I do have an open question about that separate issue but for now I'll assume that's not the cause of my problems here.

And just to confirm, I don't have to re-download the Google plist after adding notifications? I was using Firebase in my project before adding notifications, so I already have one.

Thanks for any help getting the notifications working!

答: Can you check in the capabilities tab if push notifications are enabled. Also, since Xcode 8 you need to add the entitlements file with aps-environment set. If you disable and enable the push notifications from capabilities you will get this file.</p>

Body:
I've set up push notifications according to this walkthrough: https://www.appcoda.com/firebase-push-notifications/

But when I send a test message from Firebase, it doesn't show up. I followed all the steps, I have valid certificates:

Provisioning Profile set up for push notifications:

Under my App ID it shows that notifications are enabled:

And I have the certificate uploaded to Firebase:

And in my AppDelegate didFinishLaunchingWithOptions:

    if #available(iOS 10.0, *) {
        // For iOS 10 display notification (sent via APNS)
        UNUserNotificationCenter.current().delegate = self
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })
        // For iOS 10 data message (sent via FCM
        FIRMessaging.messaging().remoteMessageDelegate = self
    } else {
        let settings: UIUserNotificationSettings =
            UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil)
        application.registerUserNotificationSettings(settings)
    }

    application.registerForRemoteNotifications()

Along with the Firebase callback method in AppDelegate:

func applicationReceivedRemoteMessage(_ remoteMessage: FIRMessagingRemoteMessage) {
    print(remoteMessage.appData)
}

And obviously I have imported:

import UserNotifications
import FirebaseInstanceID
import FirebaseMessaging

I'm not sure why the push notifications are not working, it seems like everything is in place. The only thing out of the ordinary I did was remove the entitlements from Target -> Code Signing, as it was giving me an invalid entitlements error when I tried to run the app. Now that it's removed, the app is running fine. I do have an open question about that separate issue but for now I'll assume that's not the cause of my problems here.

And just to confirm, I don't have to re-download the Google plist after adding notifications? I was using Firebase in my project before adding notifications, so I already have one.

Thanks for any help getting the notifications working!