问:
Generating PDF from HTML giving unwanted space due table inside table

     column1
     column2
     column3
     column4
     column5
     column6
     column7
     column8

          column thead 1
          column thead 2
          column thead 3
          column thead 4
          column thead 5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

```

Here I have HTML code which is not coming proper when I generate PDF.
What I want table should start from first page not from second page while generating PDF in landscape mode also thead having class "t2" should repeat in every page as data increase in table inside "table-block" div.

答:
                 column1
                 column2
                 column3
                 column4
                 column5
                 column6
                 column7
                 column8

                                     column thead 1
                                     column thead 2
                                     column thead 3
                                     column thead 4
                                     column thead 5

                                 column td1
                                 column td2
                                 column td3
                                 column td4
                                 column td5

                                 column td1
                                 column td2
                                 column td3
                                 column td4
                                 column td5

                                 column td1
                                 column td2
                                 column td3
                                 column td4
                                 column td5

                                 column td1
                                 column td2
                                 column td3
                                 column td4
                                 column td5

                                 column td1
                                 column td2
                                 column td3
                                 column td4
                                 column td5

                                 column td1
                                 column td2
                                 column td3
                                 column td4
                                 column td5

                                 column td1
                                 column td2
                                 column td3
                                 column td4
                                 column td5

```

I have used mm instead of px and the table is display in the first page.

Body:
     column1
     column2
     column3
     column4
     column5
     column6
     column7
     column8

          column thead 1
          column thead 2
          column thead 3
          column thead 4
          column thead 5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

         column td1
         column td2
         column td3
         column td4
         column td5

Here I have HTML code which is not coming proper when I generate PDF.
What I want table should start from first page not from second page while generating PDF in landscape mode also thead having class "t2" should repeat in every page as data increase in table inside "table-block" div.

Body:
<html>
    <head>

      <style>
      body {
        margin: 0;
    }
      table{
        width: 100%;
        border-spacing: 0;
        border-collapse: collapse;
        text-align: center;
      }
      thead.t1{
      background: #dac8c8;
      }
      table td , table th{
      padding:1mm;
      }
      table{
      margin-top:1mm;
      }
      thead.t2{
      background: #dcdcdc;
      }
    @media print{
    @page {
        size: A4 landscape;
    }
  }

    table { page-break-inside:auto }
    tr    { page-break-inside:avoid; page-break-after:auto }
    thead { display:table-header-group }
    @media print{
        table {page-break-after:always}
    }

      </style>

     </head>

    <body class="" style="width:1070px; margin:0 auto;">

<div style="height:300px; width:100%; background:#ccc; border-bottom:2px solid #000;">
    </div>
        <table class="splitForPrint table-rc1 ">
            <thead class="t1">
            <tr>
                <th> column1 </th>
                <th> column2 </th>
                <th> column3 </th>
                <th> column4 </th>
                <th> column5 </th>
                <th> column6 </th>
                <th> column7 </th>
                <th> column8 </th>
            </tr>
        </thead>

                <tbody>
                <tr>
                <td colspan="8" class="">
                    <div class=" table-block">

                        <table>
                            <thead class="t2">
                                <tr>
                                    <td> column thead 1 </td>
                                    <td> column thead 2 </td>
                                    <td> column thead 3 </td>
                                    <td> column thead 4 </td>
                                    <td> column thead 5 </td>
                                </tr>
                            </thead>

                            <tbody>

                                <tr>
                                <td> column td1 </td>
                                <td> column td2 </td>
                                <td> column td3 </td>
                                <td> column td4 </td>
                                <td> column td5 </td>
                            </tr>
                            <tr>
                                <td> column td1 </td>
                                <td> column td2 </td>
                                <td> column td3 </td>
                                <td> column td4 </td>
                                <td> column td5 </td>
                            </tr>
                            <tr>
                                <td> column td1 </td>
                                <td> column td2 </td>
                                <td> column td3 </td>
                                <td> column td4 </td>
                                <td> column td5 </td>
                            </tr>
                            <tr>
                                <td> column td1 </td>
                                <td> column td2 </td>
                                <td> column td3 </td>
                                <td> column td4 </td>
                                <td> column td5 </td>
                            </tr>
                            <tr>
                                <td> column td1 </td>
                                <td> column td2 </td>
                                <td> column td3 </td>
                                <td> column td4 </td>
                                <td> column td5 </td>
                            </tr>
                            <tr>
                                <td> column td1 </td>
                                <td> column td2 </td>
                                <td> column td3 </td>
                                <td> column td4 </td>
                                <td> column td5 </td>
                            </tr>

                                <td> column td1 </td>
                                <td> column td2 </td>
                                <td> column td3 </td>
                                <td> column td4 </td>
                                <td> column td5 </td>
                            </tr>

                            </tbody>

                        </table>

                    </div>
                </td>
                </tr>
                </tbody>

        </table>
    </body>

</html>

I have used mm instead of px and the table is display in the first page.


来源: stackexchange

问:
Validate email without dot(.) at starting in HTML pattern
I have validated email with proper @ and .com availbale in the email address by using  but its not validating whether the email address has dot(.) at starting point (For example: .john@gmail.com).

Actually while creating account in gmail it will check whether the choosed address has dot at starting point of the address i want same as like that.

I have tried like below but its not working

```<code><input type="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" title="Enter valid email address" name="email" required class="form-control" placeholder="Enter email is here...">
</code>```

Can anyone give me an idea to achieve this....?

ContentLicense: CC BY-SA 3.0

Body:
I have validated email with proper @ and .com availbale in the email address by using  but its not validating whether the email address has dot(.) at starting point (For example: .john@gmail.com).

Actually while creating account in gmail it will check whether the choosed address has dot at starting point of the address i want same as like that.

I have tried like below but its not working

<input type="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" title="Enter valid email address" name="email" required class="form-control" placeholder="Enter email is here...">

Can anyone give me an idea to achieve this....?

Body:
You can use not operator (^) .

Here is your regxr: ^[^(\.)][a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}


问:
How to specify multiple conditions on left join using JPA Criteria API?
I'd like to convert the following SQL query:

```<code>select * from region_tree country left outer join region_tree region
on country.REG_CODE_PAR=region.REG_CODE
and region.LFT < country.LFT
and region.RGT > country.RGT
and region.REG_CODE_PAR = 'ALL'
and COUNTRY.STATUS_CODE = 'A'
and REGION.STATUS_CODE = 'A
</code>```

into JPA Crtieria based query.

I created an entity to represent the self join:

```<code>@Entity
@Table(name = "REGION_TREE")
public class RegionTree implements Serializable {
    ... some other attributes

    @ManyToOne
    @JoinColumn(name = "REG_CODE_PAR")
    private RegionTree region;

    ... getters and setters
}
</code>```

I used the following code to create the JPA query

```<code>CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<RegionTree> cq = cb.createQuery(RegionTree.class);
Root<RegionTree> e = cq.from(RegionTree.class);
Join<RegionTree, RegionTree> r = e.join("region", JoinType.LEFT);
Predicate p1 = cb.greaterThan(e.get("lft").as(Integer.class), r.get("lft").as(Integer.class));
Predicate p2 = cb.lessThan(e.get("rgt").as(Integer.class), r.get("rgt").as(Integer.class));
Predicate p3 = cb.equal(e.get("statusCode"), "A");
Predicate p4 = cb.equal(r.get("statusCode"), "A");
Predicate p5 = cb.equal(r.get("regCodePar"), "ALL");
cq.where(p1,p2,p3,p4,p5);
TypedQuery<RegionTree> tq = em.createQuery(cq);
l = tq.getResultList();`
</code>```

This is the query automatically generated by Hibernate when I run this piece of code.

```<code>select
regiontree0_.REG_CODE as REG1_7_,
regiontree0_.LFT as LFT7_,
regiontree0_.NAME as NAME7_,
regiontree0_.REG_CODE_PAR as REG4_7_,
regiontree0_.RGT as RGT7_,
regiontree0_.STATUS_CODE as STATUS6_7_
from
REGION_TREE regiontree0_
left outer join
REGION_TREE regiontree1_
on regiontree0_.REG_CODE_PAR=regiontree1_.REG_CODE
where
cast(regiontree0_.LFT as integer)>cast(regiontree1_.LFT as integer)
and cast(regiontree0_.RGT as integer)<cast(regiontree1_.RGT as integer)
and regiontree0_.STATUS_CODE=?
and regiontree1_.STATUS_CODE=?
and regiontree1_.REG_CODE_PAR=?
</code>```

I've tried a number of ways including removing the cq.where line of code but the generated query can't match my original one. Have I configured anything wrong?

答: Try invoking cq.select(r); after creating a join. Without cq.select() the result of the last cq.from() call is used as a selection root.

ContentLicense: CC BY-SA 2.5

Body:
I'd like to convert the following SQL query:

select * from region_tree country left outer join region_tree region
on country.REG_CODE_PAR=region.REG_CODE
and region.LFT < country.LFT
and region.RGT > country.RGT
and region.REG_CODE_PAR = 'ALL'
and COUNTRY.STATUS_CODE = 'A'
and REGION.STATUS_CODE = 'A

into JPA Crtieria based query.

I created an entity to represent the self join:

@Entity
@Table(name = "REGION_TREE")
public class RegionTree implements Serializable {
    ... some other attributes

    @ManyToOne
    @JoinColumn(name = "REG_CODE_PAR")
    private RegionTree region;

    ... getters and setters
}

I used the following code to create the JPA query

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<RegionTree> cq = cb.createQuery(RegionTree.class);
Root<RegionTree> e = cq.from(RegionTree.class);
Join<RegionTree, RegionTree> r = e.join("region", JoinType.LEFT);
Predicate p1 = cb.greaterThan(e.get("lft").as(Integer.class), r.get("lft").as(Integer.class));
Predicate p2 = cb.lessThan(e.get("rgt").as(Integer.class), r.get("rgt").as(Integer.class));
Predicate p3 = cb.equal(e.get("statusCode"), "A");
Predicate p4 = cb.equal(r.get("statusCode"), "A");
Predicate p5 = cb.equal(r.get("regCodePar"), "ALL");
cq.where(p1,p2,p3,p4,p5);
TypedQuery<RegionTree> tq = em.createQuery(cq);
l = tq.getResultList();`

This is the query automatically generated by Hibernate when I run this piece of code.

select
regiontree0_.REG_CODE as REG1_7_,
regiontree0_.LFT as LFT7_,
regiontree0_.NAME as NAME7_,
regiontree0_.REG_CODE_PAR as REG4_7_,
regiontree0_.RGT as RGT7_,
regiontree0_.STATUS_CODE as STATUS6_7_
from
REGION_TREE regiontree0_
left outer join
REGION_TREE regiontree1_
on regiontree0_.REG_CODE_PAR=regiontree1_.REG_CODE
where
cast(regiontree0_.LFT as integer)>cast(regiontree1_.LFT as integer)
and cast(regiontree0_.RGT as integer)<cast(regiontree1_.RGT as integer)
and regiontree0_.STATUS_CODE=?
and regiontree1_.STATUS_CODE=?
and regiontree1_.REG_CODE_PAR=?

I've tried a number of ways including removing the cq.where line of code but the generated query can't match my original one. Have I configured anything wrong?


问:
Choose Browser while clicking url in UITextView
I have a URL link in my UITextView. And in my iPhone, there are both safari & chrome apps. Whenever I click on the URL link, I want to list both safari & Chrome (and all other browsers in the phone) in a pop up view so that the user can choose which browser they want to open the url. Now it is always opening safari as it is the default browser in my phone. Is there any way I can choose the browser to open the URL? I know there is this delegate

```<code>func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        // Got the url here. how can i force this url to open in chrome
        return true
    }
</code>```

but how can i force this url to open in chrome or any other browser? And how can I list all available browsers in a view?

答:
i didn't tried but just check it out.Return false to shouldInteractWith  delagte method.You this delegate method for your stuffs

```<code>func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        // Got the url here. how can i force this url to open in chrome

        //here do your stuffs to show popup or something & based on selection launch url with specific browsers

        return false //to restrict open automatically
 }
</code>```

Body:
I have a URL link in my UITextView. And in my iPhone, there are both safari & chrome apps. Whenever I click on the URL link, I want to list both safari & Chrome (and all other browsers in the phone) in a pop up view so that the user can choose which browser they want to open the url. Now it is always opening safari as it is the default browser in my phone. Is there any way I can choose the browser to open the URL? I know there is this delegate

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        // Got the url here. how can i force this url to open in chrome
        return true
    }

but how can i force this url to open in chrome or any other browser? And how can I list all available browsers in a view?

Body:
i didn't tried but just check it out.Return false to shouldInteractWith  delagte method.You this delegate method for your stuffs

func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        // Got the url here. how can i force this url to open in chrome

        //here do your stuffs to show popup or something & based on selection launch url with specific browsers

        return false //to restrict open automatically
 }


问:
Unable retrieving data from server side using custom columns DataTable Plugin
i am trying to retrieving data by custom searching. my code work properly, but when i try to filter some data from the input box. the process, get stuck. Please can anyone tell me what I m   forgotting ?

My JQuery

```<code> //this work fine retrieving data by only if i search using "Search box"
 var dataTableInstance = $("#dataTable").DataTable({
            bServerSide: true,
            sAjaxSource: 'AccountingMovementsService.asmx/GetAccountingMovements',
            "processing": true,
            sServerMethod: 'POST',
            columns: [
                {
                    'data': 'Payment'
                },
                {
                    'data': 'Account',
                },
                {
                    'data': 'customer',
                }
            ]
        });

//here I make all input box under footer columns (work fine)
$('#dataTable tfoot th').each(function () {
            var title = $(this).text();

            $(this).html("<input type='text' placeholder='" + title + "' />");

        });

  //And here i get stuck processing ... and data not come
  dataTableInstance.columns().every(function() {
                    var dataTableColumn = this;
                    $(this.footer()).find('input').on('keyup change', function () {
                        dataTableColumn.search(this.value).draw();
                    });
                });
</code>```

If i use NOT SERVER-SIDE all work fine

My c# code is

```<code> [WebMethod]
    public void GetAccountingMovements(int iDisplayLength, int iDisplayStart, int iSortCol_0, string sSortDir_0, string sSearch)
    {

        int displayLength = iDisplayLength;
        int displayStart = iDisplayStart;
        int sortCol = iSortCol_0;
        string sortDir = sSortDir_0;
        string search = sSearch;
        int filteredCount = 0;
        var accountingTransactions = new List<AccountMovement>();
        string cs = ConfigurationManager.ConnectionStrings["Sg4DevMaster"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand("spGetAccountingTransactions", conn);
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add(new SqlParameter
            {
                ParameterName = "DisplayLength",
                Value = displayLength
            });
            cmd.Parameters.Add(new SqlParameter
            {
                ParameterName = "DisplayStart",
                Value = displayStart
            });
            cmd.Parameters.Add(new SqlParameter
            {
                ParameterName = "SortCol",
                Value = sortCol
            });
            cmd.Parameters.Add(new SqlParameter
            {
                ParameterName = "SortDir",
                Value = sortDir
            });
            cmd.Parameters.Add(new SqlParameter
            {
                ParameterName = "Search",
                Value = search
            });

            conn.Open();
            SqlDataReader rdr = cmd.ExecuteReader();

            while (rdr.Read())
            {
                AccountMovement am = new AccountMovement();

                filteredCount = Convert.ToInt32(rdr["totalCount"]);
                am.payment = Convert.ToDouble(rdr["payment"]);
                am.Account = Convert.ToDouble(rdr["account"]);
                am.Customer = rdr["Customer"].ToString();

                accountingTransactions.Add(am);

            }

        }

        var result = new
        {
            iTotalRecords = GetAccountingMovementsTotalCount(),
            iTotalDisplayRecords = filteredCount,
            aaData = accountingTransactions
        };

        JavaScriptSerializer js = new JavaScriptSerializer();
        Context.Response.Write(js.Serialize(result));

    }
</code>```

All work fine using "the main search input box" in the DataTable Plugin, but it get stuck when put some data in one of custom input box placed in the footer

Thank for you time!

答:
If you go to my GitHub https://github.com/bindrid/DataTablesServerSide take a look at the c# classes. That is how I take the parameters provided by DataTable and turn it into a usable c# object.

Also listed there is my web method that uses those classes.

Below is the DataTables logic, including your search stuff and it all works.

```<code>        var table = $('#example').DataTable({
            "processing": true,
            "serverSide": true,
            "rowCallback": function (row, data) {
                if ($.inArray(data.employeeId, selected) !== -1) {
                    table.row(row).select();
                }
            },
            "infoCallback": function (settings, start, end, max, total, pre) {
                  var api = this.api();
                var pageInfo = api.page.info();
                return 'Page '+ (pageInfo.page+1) +' of '+ pageInfo.pages + "  ";
            },
            rowId:"employeeId",
            "createdRow": function (row, data, dataIndex) {},
            "columns":  [
                { "data": "name" },
                { "data": "position" },
                { "data": "office" },
                { "data": "extn" },
                { "data": "start_date" },
                { "data": "salary" }
            ],
            "select":"multi",
            "lengthMenu": [5, [10, 15, 25, 50, -1], [5, 10, 15, 25, 50, "All"]],
            "pageLength": 5,
            "ajax": {
                contentType: "application/json; charset=utf-8",
                url: "wsSample.asmx/GetDTDataUnserializedObject",
                type: "Post",
                data: function (dtParms) {
                    // notice dtParameters exactly matches the web service

                    return JSON.stringify({ dtParameters: dtParms });
                },
                // Data filter is a part of ajax and lets you look at the raw
                dataFilter: function (res) {
                    // You probably know by know that WebServices
                    // puts your data in an object call d. these two lines puts it
                    // in the form that DataTable expects
                    var parsed = JSON.parse(res);

                    return  JSON.stringify(parsed.d);
                },
                error: function (x, y) {
                    debugger;
                    console.log(x);
                }
            },
            order: [[0, 'asc']]
        });

        // add search boxes to footer
        $('#example tfoot th').each(function () {
            var title = $(this).text();
            $(this).html("<input type='search' placeholder='" + title + "' />");
        });
        //And here i get stuck processing ... and data not come
        table.columns().every(function () {
            var dataTableColumn = this;
            $(this.footer()).find('input').on('keyup change', function () {
                dataTableColumn.search(this.value).draw();
            });
        });
</code>```

Body:
i am trying to retrieving data by custom searching. my code work properly, but when i try to filter some data from the input box. the process, get stuck. Please can anyone tell me what I m   forgotting ?

My JQuery

 //this work fine retrieving data by only if i search using "Search box"
 var dataTableInstance = $("#dataTable").DataTable({
            bServerSide: true,
            sAjaxSource: 'AccountingMovementsService.asmx/GetAccountingMovements',
            "processing": true,
            sServerMethod: 'POST',
            columns: [
                {
                    'data': 'Payment'
                },
                {
                    'data': 'Account',
                },
                {
                    'data': 'customer',
                }
            ]
        });

//here I make all input box under footer columns (work fine)
$('#dataTable tfoot th').each(function () {
            var title = $(this).text();

            $(this).html("<input type='text' placeholder='" + title + "' />");

        });

  //And here i get stuck processing ... and data not come
  dataTableInstance.columns().every(function() {
                    var dataTableColumn = this;
                    $(this.footer()).find('input').on('keyup change', function () {
                        dataTableColumn.search(this.value).draw();
                    });
                });

If i use NOT SERVER-SIDE all work fine

My c# code is

 [WebMethod]
    public void GetAccountingMovements(int iDisplayLength, int iDisplayStart, int iSortCol_0, string sSortDir_0, string sSearch)
    {

        int displayLength = iDisplayLength;
        int displayStart = iDisplayStart;
        int sortCol = iSortCol_0;
        string sortDir = sSortDir_0;
        string search = sSearch;
        int filteredCount = 0;
        var accountingTransactions = new List<AccountMovement>();
        string cs = ConfigurationManager.ConnectionStrings["Sg4DevMaster"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand("spGetAccountingTransactions", conn);
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add(new SqlParameter
            {
                ParameterName = "DisplayLength",
                Value = displayLength
            });
            cmd.Parameters.Add(new SqlParameter
            {
                ParameterName = "DisplayStart",
                Value = displayStart
            });
            cmd.Parameters.Add(new SqlParameter
            {
                ParameterName = "SortCol",
                Value = sortCol
            });
            cmd.Parameters.Add(new SqlParameter
            {
                ParameterName = "SortDir",
                Value = sortDir
            });
            cmd.Parameters.Add(new SqlParameter
            {
                ParameterName = "Search",
                Value = search
            });

            conn.Open();
            SqlDataReader rdr = cmd.ExecuteReader();

            while (rdr.Read())
            {
                AccountMovement am = new AccountMovement();

                filteredCount = Convert.ToInt32(rdr["totalCount"]);
                am.payment = Convert.ToDouble(rdr["payment"]);
                am.Account = Convert.ToDouble(rdr["account"]);
                am.Customer = rdr["Customer"].ToString();

                accountingTransactions.Add(am);

            }

        }

        var result = new
        {
            iTotalRecords = GetAccountingMovementsTotalCount(),
            iTotalDisplayRecords = filteredCount,
            aaData = accountingTransactions
        };

        JavaScriptSerializer js = new JavaScriptSerializer();
        Context.Response.Write(js.Serialize(result));

    }

All work fine using "the main search input box" in the DataTable Plugin, but it get stuck when put some data in one of custom input box placed in the footer

Thank for you time!

Body:
If you go to my GitHub https://github.com/bindrid/DataTablesServerSide take a look at the c# classes. That is how I take the parameters provided by DataTable and turn it into a usable c# object.

Also listed there is my web method that uses those classes.

Below is the DataTables logic, including your search stuff and it all works.

        var table = $('#example').DataTable({
            "processing": true,
            "serverSide": true,
            "rowCallback": function (row, data) {
                if ($.inArray(data.employeeId, selected) !== -1) {
                    table.row(row).select();
                }
            },
            "infoCallback": function (settings, start, end, max, total, pre) {
                  var api = this.api();
                var pageInfo = api.page.info();
                return 'Page '+ (pageInfo.page+1) +' of '+ pageInfo.pages + "&nbsp;&nbsp;";
            },
            rowId:"employeeId",
            "createdRow": function (row, data, dataIndex) {},
            "columns":  [
                { "data": "name" },
                { "data": "position" },
                { "data": "office" },
                { "data": "extn" },
                { "data": "start_date" },
                { "data": "salary" }
            ],
            "select":"multi",
            "lengthMenu": [5, [10, 15, 25, 50, -1], [5, 10, 15, 25, 50, "All"]],
            "pageLength": 5,
            "ajax": {
                contentType: "application/json; charset=utf-8",
                url: "wsSample.asmx/GetDTDataUnserializedObject",
                type: "Post",
                data: function (dtParms) {
                    // notice dtParameters exactly matches the web service

                    return JSON.stringify({ dtParameters: dtParms });
                },
                // Data filter is a part of ajax and lets you look at the raw
                dataFilter: function (res) {
                    // You probably know by know that WebServices
                    // puts your data in an object call d. these two lines puts it
                    // in the form that DataTable expects
                    var parsed = JSON.parse(res);

                    return  JSON.stringify(parsed.d);
                },
                error: function (x, y) {
                    debugger;
                    console.log(x);
                }
            },
            order: [[0, 'asc']]
        });

        // add search boxes to footer
        $('#example tfoot th').each(function () {
            var title = $(this).text();
            $(this).html("<input type='search' placeholder='" + title + "' />");
        });
        //And here i get stuck processing ... and data not come
        table.columns().every(function () {
            var dataTableColumn = this;
            $(this.footer()).find('input').on('keyup change', function () {
                dataTableColumn.search(this.value).draw();
            });
        });


问:
Segue values nil in new ViewController (Xcode 8, Swift 3)
I know this type of question has been posed before. I have read many answers. Most had 0 or 1 votes, and none solved my problem. I am new to coding, so some of the answers were a little beyond me. To keep it short, my values (billAmount) are turning to nil when the segue is performed. The segue works, and print gives the correct value:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let segueController = segue.destination as! ResultsViewController
        segueController.transferBill = "Bill: $\(billAmount)"
    print(billAmount)
}
</code>```

In ResultsViewController, transferBill displays the following:

```<code> Bill: $
</code>```

This is expected, except the billAmount does not carry over.

Any help is greatly appreciated.

答: Have you tried to use it as raw billamount value & format it with strings whenever it is required ?</p>

Body:
I know this type of question has been posed before. I have read many answers. Most had 0 or 1 votes, and none solved my problem. I am new to coding, so some of the answers were a little beyond me. To keep it short, my values (billAmount) are turning to nil when the segue is performed. The segue works, and print gives the correct value:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let segueController = segue.destination as! ResultsViewController
        segueController.transferBill = "Bill: $\(billAmount)"
    print(billAmount)
}

In ResultsViewController, transferBill displays the following:

 Bill: $

This is expected, except the billAmount does not carry over.

Any help is greatly appreciated.


问:
How to post same names for file and parameter name by php curl CURLOPT_POSTFIELDS?
I post file and parameter by curl command to t.php:

t.php:

```<code><?php

print_r( $_FILES );
print_r( $_POST );
?>
</code>```

it's need the same names for file and parameter "name":

```<code>curl http://localhost/t.php -X POST -F "name=@D:\file.zip" -F "name=test"
</code>```

result is:

```<code>Array
(
    [name] => Array
        (
            [name] => file.zip
            [type] => application/octet-stream
            [tmp_name] => D:\www\tmp\php653B.tmp
            [error] => 0
            [size] => 150
        )

)
Array
(
    [name] => test
)
</code>```

it is ok!

But,
How to post same names for file and parameter name by php curl CURLOPT_POSTFIELDS?

```<code>//
$data = [
    'name' => curl_file_create('D:\file.zip'),
    //'name' => 'test', // <--- ?????????????
];

$curl = curl_init('http://localhost/t.php');
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data );
$out = curl_exec($curl);
curl_close($curl);
</code>```

Help me, please

答:
Prepare the array of data something like below:

```<code>$data = array('name' => 'Foo', 'file' => '@/home/user/test.png');
</code>```

Notice: @ is appended before the file path.

The following example taken from php.net.

```<code><?php

$ch = curl_init();

$data = array('name' => 'Foo', 'file' => '@/home/user/test.png');

curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
?>
</code>```

Body:
I post file and parameter by curl command to t.php:

t.php:

<?php

print_r( $_FILES );
print_r( $_POST );
?>

it's need the same names for file and parameter "name":

curl http://localhost/t.php -X POST -F "name=@D:\file.zip" -F "name=test"

result is:

Array
(
    [name] => Array
        (
            [name] => file.zip
            [type] => application/octet-stream
            [tmp_name] => D:\www\tmp\php653B.tmp
            [error] => 0
            [size] => 150
        )

)
Array
(
    [name] => test
)

it is ok!

But,
How to post same names for file and parameter name by php curl CURLOPT_POSTFIELDS?

//
$data = [
    'name' => curl_file_create('D:\file.zip'),
    //'name' => 'test', // <--- ?????????????
];

$curl = curl_init('http://localhost/t.php');
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data );
$out = curl_exec($curl);
curl_close($curl);

Help me, please

Body:
Prepare the array of data something like below:

$data = array('name' => 'Foo', 'file' => '@/home/user/test.png');

Notice: @ is appended before the file path.

The following example taken from php.net.

<?php

$ch = curl_init();

$data = array('name' => 'Foo', 'file' => '@/home/user/test.png');

curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
?>


问:
Angular2: How to change selected file name to 'No file chosen'?
I am using html file upload.

```<code><input type="file" name="filedata" class="form-control" #file/>
</code>```

After selection of file, file name showing in screen/UI.

```<code><button pButton type="button" icon="fa-check" class="form-control"
(click)="uploadFileByRest();" label="Upload"></button>
</code>```

I am using upload button for uploading that file to Alfresco. On clicking on upload button I need to empty the file selected. Need to change file name showing to "No file chosen", which is showing before selecting file. How to do this?

答:
Setting the value to an empty string should do that according to how to reset <input type = "file"></p>

```<code><button pButton type="button" icon="fa-check" class="form-control"
    (click)="uploadFileByRest();file.value = ''"
    [disabled]="!isFileSelected" label="Upload"></button>
</code>```

Body:
I am using html file upload.

<input type="file" name="filedata" class="form-control" #file/>

After selection of file, file name showing in screen/UI.

<button pButton type="button" icon="fa-check" class="form-control"
(click)="uploadFileByRest();" label="Upload"></button>

I am using upload button for uploading that file to Alfresco. On clicking on upload button I need to empty the file selected. Need to change file name showing to "No file chosen", which is showing before selecting file. How to do this?

Body:
Setting the value to an empty string should do that according to how to reset <input type = "file">

<button pButton type="button" icon="fa-check" class="form-control"
    (click)="uploadFileByRest();file.value = ''"
    [disabled]="!isFileSelected" label="Upload"></button>


问:
Duplicating a file attachment for another model in October CMS
I have model User with relationships like this:

```<code>public $attachMany = [
    'logos' => ['System\Models\File', 'delete' => true]
];

public $hasMany = [
    'jobs' => ['Acme\Plugin\Models\Job']
];
</code>```

I also have the following relationship in the Job model:

```<code>public $attachOne = [
    'logo' => ['System\Models\File', 'delete' => true]
];
</code>```

So, a User can attach lots of logos and when a user creates a Job they can attach one logo to it.

When a User creates a Job and attaches a logo to it, I need them to be able to choose to attach one of the logos that is already attached to User but I don't want it to be the actual relation (ie: not a many-to-many type of relationship) but rather a complete duplication of the File so that if the user later decided to delete some of their logos at a later date, it wouldn't affect the logo attached to the job.

I have theoretically solved this and answered my own question, but it's quite messy and I can't help but think there may be a simpler way.

```<code>    // Get the File model
    $chosenLogo = \System\Models\File::find(1);

    // Save the contents of the file to local storage
    Storage::disk('local')->put('tempLogos/' . $chosenLogo->disk_name, $chosenLogo->getContents());

    // Get the job
    $job = \Acme\Plugin\Models\Job::find(34);

    // Create a new File and specify path for data
    $file = new \System\Models\File;
    $file->data = base_path('storage/app/tempLogos/' . $chosenLogo->disk_name);

    // Save file then attach logo to job
    $file->save();
    $job->logo()->add($file);
</code>```

It works, but it's a lot of messing about. Is there an easier way?

答:
Try use MorphTo relations: https://octobercms.com/docs/database/relations#polymorphic-relations
You can create Logo model and morph it to User and to Job models.</p>

Body:
I have model User with relationships like this:

public $attachMany = [
    'logos' => ['System\Models\File', 'delete' => true]
];

public $hasMany = [
    'jobs' => ['Acme\Plugin\Models\Job']
];

I also have the following relationship in the Job model:

public $attachOne = [
    'logo' => ['System\Models\File', 'delete' => true]
];

So, a User can attach lots of logos and when a user creates a Job they can attach one logo to it.

When a User creates a Job and attaches a logo to it, I need them to be able to choose to attach one of the logos that is already attached to User but I don't want it to be the actual relation (ie: not a many-to-many type of relationship) but rather a complete duplication of the File so that if the user later decided to delete some of their logos at a later date, it wouldn't affect the logo attached to the job.

I have theoretically solved this and answered my own question, but it's quite messy and I can't help but think there may be a simpler way.

    // Get the File model
    $chosenLogo = \System\Models\File::find(1);

    // Save the contents of the file to local storage
    Storage::disk('local')->put('tempLogos/' . $chosenLogo->disk_name, $chosenLogo->getContents());

    // Get the job
    $job = \Acme\Plugin\Models\Job::find(34);

    // Create a new File and specify path for data
    $file = new \System\Models\File;
    $file->data = base_path('storage/app/tempLogos/' . $chosenLogo->disk_name);

    // Save file then attach logo to job
    $file->save();
    $job->logo()->add($file);

It works, but it's a lot of messing about. Is there an easier way?


问:
Refresh page after bootstrap modal close
I am trying to refresh my current page after I close bootstrap modal.

```<code>$('#modal1').on('hide', function() {
window.location.href = 'current-page.php';
})
</code>```

Is there a way for refresh current page after closing modal.

答:
Refresh page using location.reload();

```<code>$('#myModal').on('hidden.bs.modal', function () {
    location.reload();
});
</code>```

Body:
I am trying to refresh my current page after I close bootstrap modal.

$('#modal1').on('hide', function() {
window.location.href = 'current-page.php';
})

Is there a way for refresh current page after closing modal.

Body:
Refresh page using location.reload();

$('#myModal').on('hidden.bs.modal', function () {
    location.reload();
});


问:
Htaccess Manually inserted links not working
I have edited my htaccess file for https redirection. But when we manually write https://domainname.com/fashion it is redirecting to https://domainname.com/index.php?route=fashion.

My htaccess file looks like

```<code>RewriteEngine On
RewriteBase /
RewriteRule ^sitemap.xml$ index.php?route=feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=feed/google_base [L]
RewriteRule ^download/(.*) /index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [R=301, L]
RewriteCond %{HTTPS} off
RewriteCond %{HTTPS} ^www\. [NC]
RewriteRule (.*) https://domainname.com%{REQUEST_URI} [R=301, L]
</code>```

Please help.

答:
Remove R flag from index rule

```<code>RewriteRule ^([^?]*) index.php?_route_=$1 [L]
</code>```

And move the https redirection to the top

```<code>RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} off
RewriteCond %{HTTPS} ^www\. [NC]
RewriteRule (.*) https://domainname.com%{REQUEST_URI} [R=301, L]
...
</code>```

Body:
I have edited my htaccess file for https redirection. But when we manually write https://domainname.com/fashion it is redirecting to https://domainname.com/index.php?route=fashion.

My htaccess file looks like

RewriteEngine On
RewriteBase /
RewriteRule ^sitemap.xml$ index.php?route=feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=feed/google_base [L]
RewriteRule ^download/(.*) /index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [R=301, L]
RewriteCond %{HTTPS} off
RewriteCond %{HTTPS} ^www\. [NC]
RewriteRule (.*) https://domainname.com%{REQUEST_URI} [R=301, L]

Please help.

Body:
Remove R flag from index rule

RewriteRule ^([^?]*) index.php?_route_=$1 [L]

And move the https redirection to the top

RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} off
RewriteCond %{HTTPS} ^www\. [NC]
RewriteRule (.*) https://domainname.com%{REQUEST_URI} [R=301, L]
...


问:
unable to find mojo sonar (or one of its component) in the plugin org.sonarsource.scanner.maven:sonar-maven-plugin
I am implementing sonar in my existing maven project.I am getting this error :

unable to find mojo sonar (or one of its component) in the plugin org.sonarsource.scanner.maven:sonar-maven-plugin

Following are my configs:

Maven version:2.2.1

Java version:1.6

sonar-maven-plugin version:3.0.2

sonarcube version:6.4

sonar java version: 4.10.0.10260

I have updated:

pom.xml

settings.xml

sonar-project.properties

to mentioned my intended java version in it.

答: Upgrade to Java 7 and Maven 3, and this should work.</p>


问:
SSL cert on ELB or EC2?
I have some questions on setting up SSL certs on AWS setup (ELB + EC2)..

Where do I put the SSL cert, on the ELB or EC2 or both?

Depending on the answer to question #1, how do I configure the port forwarding on the ELB, do I do it this way? HTTP Port 80 -> HTTP Port 80 and HTTPS Port 443 -> HTTPS Port 443

Thanks!

答:
You can use ELB in one of two ways:

SSL un-encrytpion at the ELB

In this mode, you'll give the ELB the cert and key. It will un-encrypt the request and pass it to your servers unencrypted. The benefit of this is that you can reduce the CPU load of your servers.

The ELB just acts as a passthrough.

The ELB can act as a dumb passthrough. It won't need the cert or key. In order to set it up this way, instead of using the HTTPS option, set it as TCP port.

Title: SSL cert on ELB or EC2?


问:
MySQL LEFT JOIN with SUM before a date and SUM before and at that date
I have three tables (pagu, realisasi and perencanaan). I'm using left join. I want to sum one field before a certain date while for another field sum before and at that date.

My pagu table:

```<code>idpagu  kode    komponen    pagu    target_kinerja  tahun   keterangan
1   2217.057.056    Pengembangan Sistem Manajemen Mutu UPTP     52740000    1   2017    tes123
2   2220.051.051    Pelatihan Peningkatan Produktivitas     4732755000  120     2017    tes123
3   2220.052.051    Calon Wirausaha Baru yang Dilatih (RM)  12464938000     240     2017    TES123
</code>```

My realisasi table:

```<code>idrealisasi     idpagu  kode    komponen    realisasi   target_kinerja  tgl     keterangan
5   1   2217.057.056    Pengembangan Sistem Manajemen Mutu UPTP     52740000    1   1/14/2017   tes
6   2   2220.051.051    Pelatihan Peningkatan Produktivitas     10000000    10  1/14/2017   tes
7   2   2220.051.051    Pelatihan Peningkatan Produktivitas     20000000    20  2/14/2017   tes2
8   2   2220.051.051    Pelatihan Peningkatan Produktivitas     10000000    10  3/14/2017   tes3
9   2   2220.051.051    Pelatihan Peningkatan Produktivitas     10000000    10  6/14/2017   tes4
10  2   2220.051.051    Pelatihan Peningkatan Produktivitas     10000000    10  1/15/2017   tes
</code>```

My perencanaan table (no records):

```<code>idperencanaan   idpagu  kode    komponen    penarikan   target_kinerja  tgl     keterangan
</code>```

My query:

```<code>select p.idpagu,p.kode,p.komponen,p.pagu,p.target_kinerja,
if(pr.penarikan is null,0,sum(pr.penarikan)) as perenuang,
if(pr.target_kinerja is null,0,sum(pr.target_kinerja)) as perenfis,
if(r.realisasi is null,0,sum(r.realisasi)) as realuang,
if(r.target_kinerja is null,0,sum(r.target_kinerja)) as realfis,
p.pagu-if(r.realisasi is null,0,sum(r.realisasi)) as sisauang,
p.target_kinerja-if(r.target_kinerja is null,0,sum(r.target_kinerja)) as sisafis,
if(sum(rr.realisasi) is null,0,sum(rr.realisasi)) as tes
from pagu p
left join realisasi r on p.idpagu=r.idpagu and r.tgl BETWEEN "2017-01-01" and "2017-01-15"
left join perencanaan pr on p.idpagu=pr.idpagu and r.tgl BETWEEN "2017-01-01" and "2017-01-15"
left join realisasi rr on p.idpagu=rr.idpagu and rr.tgl < "2017-01-15"
group by p.idpagu,r.idpagu,rr.idpagu
</code>```

My result:

```<code>idpagu  kode    komponen    pagu    target_kinerja  perenuang   perenfis    realuang    realfis     sisauang    sisafis     tes
1   2217.057.056    Pengembangan Sistem Manajemen Mutu UPTP     52740000    1   0   0   52740000    1   0   0   52740000
2   2220.051.051    Pelatihan Peningkatan Produktivitas     4732755000  120     0   0   20000000    20  4712755000  100     20000000
3   2220.052.051    Calon Wirausaha Baru yang Dilatih (RM)  12464938000     240     0   0   0   0   12464938000     240     0
</code>```

My question:

The tes column is pagu - realuang before the current date "2017-01-15", and the second row should be 10.000.000, but my query gives 20.000.000.
How do I write my query so that in the second record the tes column is 10.000.000?

My schema:

```<code>SET FOREIGN_KEY_CHECKS=0;

DROP TABLE IF EXISTS `pagu`;
CREATE TABLE `pagu` (
  `idpagu` int(11) NOT NULL AUTO_INCREMENT,
  `kode` varchar(45) NOT NULL,
  `komponen` varchar(250) NOT NULL,
  `pagu` bigint(20) NOT NULL,
  `target_kinerja` int(11) NOT NULL,
  `tahun` varchar(4) NOT NULL,
  `keterangan` varchar(250) DEFAULT NULL,
  PRIMARY KEY (`idpagu`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

INSERT INTO `pagu` VALUES ('1', '2217.057.056', 'Pengembangan Sistem Manajemen Mutu UPTP', '52740000', '1', '2017', 'tes123');
INSERT INTO `pagu` VALUES ('2', '2220.051.051', 'Pelatihan Peningkatan Produktivitas', '4732755000', '120', '2017', 'tes123');
INSERT INTO `pagu` VALUES ('3', '2220.052.051', 'Calon Wirausaha Baru yang Dilatih (RM)', '12464938000', '240', '2017', 'TES123');

DROP TABLE IF EXISTS `perencanaan`;
CREATE TABLE `perencanaan` (
  `idperencanaan` int(11) NOT NULL AUTO_INCREMENT,
  `idpagu` int(11) NOT NULL,
  `kode` varchar(45) NOT NULL,
  `komponen` varchar(250) NOT NULL,
  `penarikan` bigint(20) NOT NULL,
  `target_kinerja` int(11) NOT NULL,
  `tgl` date NOT NULL,
  `keterangan` varchar(250) DEFAULT NULL,
  PRIMARY KEY (`idperencanaan`),
  KEY `fk_perencanaan_pagu1_idx` (`idpagu`),
  CONSTRAINT `fk_perencanaan_pagu1` FOREIGN KEY (`idpagu`) REFERENCES `pagu` (`idpagu`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `realisasi`;
CREATE TABLE `realisasi` (
  `idrealisasi` int(11) NOT NULL AUTO_INCREMENT,
  `idpagu` int(11) NOT NULL,
  `kode` varchar(45) NOT NULL,
  `komponen` varchar(250) NOT NULL,
  `realisasi` bigint(20) NOT NULL,
  `target_kinerja` int(11) NOT NULL,
  `tgl` date NOT NULL,
  `keterangan` varchar(250) DEFAULT NULL,
  PRIMARY KEY (`idrealisasi`),
  KEY `fk_perencanaan_pagu1_idx` (`idpagu`),
  CONSTRAINT `fk_perencanaan_pagu10` FOREIGN KEY (`idpagu`) REFERENCES `pagu` (`idpagu`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

INSERT INTO `realisasi` VALUES ('5', '1', '2217.057.056', 'Pengembangan Sistem Manajemen Mutu UPTP', '52740000', '1', '2017-01-14', 'tes');
INSERT INTO `realisasi` VALUES ('6', '2', '2220.051.051', 'Pelatihan Peningkatan Produktivitas', '10000000', '10', '2017-01-14', 'tes');
INSERT INTO `realisasi` VALUES ('7', '2', '2220.051.051', 'Pelatihan Peningkatan Produktivitas', '20000000', '20', '2017-02-14', 'tes2');
INSERT INTO `realisasi` VALUES ('8', '2', '2220.051.051', 'Pelatihan Peningkatan Produktivitas', '10000000', '10', '2017-03-14', 'tes3');
INSERT INTO `realisasi` VALUES ('9', '2', '2220.051.051', 'Pelatihan Peningkatan Produktivitas', '10000000', '10', '2017-06-14', 'tes4');
INSERT INTO `realisasi` VALUES ('10', '2', '2220.051.051', 'Pelatihan Peningkatan Produktivitas', '10000000', '10', '2017-01-15', 'tes');
</code>```

答:
Guessing from your query and table & column names (pagu = ceiling, realisasi = actual, perencanaan = planned), for each ceiling you are summing its actual values on days in a certain range, its planned values on those days, its actual values on some of those days, and some related target values, treating NULL values as 0.

I assume that if a ceiling has an actual value on a date then it has a planned value on that date. Otherwise, your query would involve FULL JOIN, and a LEFT JOIN would wrongly sometimes form rows with different dates, etc. So I suspect you are missing a FK (foreign key).

Your first LEFT JOIN gets the actual value for each ceiling for some dates. Then you want any planned value for a ceiling & date. So you are missing and r.tgl = pr.tgl. Then you want any actual value for a ceiling & date for some of those dates. So your third LEFT JOIN is missing and r.tgl = rr.tgl.

You are grouping & summing incorrectly. If a SELECT uses a column outside an aggregate call then it should be single-valued for each subrow of GROUPed columns. (GROUP BY returns one row per subrow of GROUPed columns.) (SET sql_mode = 'ONLY_FULL_GROUP_BY' disallows MySQL's non-standard behaviour.)

```<code>select p.idpagu, count(*), p.pagu, p.target_kinerja,
    sum(coalesce(pr.penarikan,0)) as pr_penarikan,
    sum(coalesce(pr.target_kinerja,0)) as pr_target_kinerja,
    sum(coalesce(r.realisasi,0)) as r_realisasi,
    sum(coalesce(r.target_kinerja,0)) as r_target_kinerja,
    p.pagu-sum(coalesce(r.realisasi,0)) as d_realisasi,
    p.target_kinerja-sum(coalesce(r.target_kinerja,0)) as d_target_kinerja,
    sum(coalesce(rr.realisasi,0)) as rr_realisasi
from pagu p
left join realisasi r on p.idpagu=r.idpagu and r.tgl BETWEEN "2017-01-01" and "2017-01-15"
left join perencanaan pr on p.idpagu=pr.idpagu and r.tgl = pr.tgl and r.tgl BETWEEN "2017-01-01" and "2017-01-15"
left join realisasi rr on p.idpagu=rr.idpagu and r.tgl = rr.tgl and r.tgl < "2017-01-15"
group by p.idpagu, p.pagu, p.target_kinerja;
</code>```

```<code>idpagu  pagu                    pr_penarikan    r_realisasi     d_realisasi             rr_target_kinerja
    count(*)        target_kinerja  pr_target_kinerja       r_target_kinerja    d_target_kinerja
1   1   52740000    1           0   0           52740000    1   0               0       52740000
2   2   4732755000  120         0   0           20000000    20  4712755000      100     10000000
3   1   12464938000 240         0   0           0           0   12464938000     240     0
</code>```

Body:
I have three tables (pagu, realisasi and perencanaan). I'm using left join. I want to sum one field before a certain date while for another field sum before and at that date.

My pagu table:

idpagu  kode    komponen    pagu    target_kinerja  tahun   keterangan
1   2217.057.056    Pengembangan Sistem Manajemen Mutu UPTP     52740000    1   2017    tes123
2   2220.051.051    Pelatihan Peningkatan Produktivitas     4732755000  120     2017    tes123
3   2220.052.051    Calon Wirausaha Baru yang Dilatih (RM)  12464938000     240     2017    TES123

My realisasi table:

idrealisasi     idpagu  kode    komponen    realisasi   target_kinerja  tgl     keterangan
5   1   2217.057.056    Pengembangan Sistem Manajemen Mutu UPTP     52740000    1   1/14/2017   tes
6   2   2220.051.051    Pelatihan Peningkatan Produktivitas     10000000    10  1/14/2017   tes
7   2   2220.051.051    Pelatihan Peningkatan Produktivitas     20000000    20  2/14/2017   tes2
8   2   2220.051.051    Pelatihan Peningkatan Produktivitas     10000000    10  3/14/2017   tes3
9   2   2220.051.051    Pelatihan Peningkatan Produktivitas     10000000    10  6/14/2017   tes4
10  2   2220.051.051    Pelatihan Peningkatan Produktivitas     10000000    10  1/15/2017   tes

My perencanaan table (no records):

idperencanaan   idpagu  kode    komponen    penarikan   target_kinerja  tgl     keterangan

My query:

select p.idpagu,p.kode,p.komponen,p.pagu,p.target_kinerja,
if(pr.penarikan is null,0,sum(pr.penarikan)) as perenuang,
if(pr.target_kinerja is null,0,sum(pr.target_kinerja)) as perenfis,
if(r.realisasi is null,0,sum(r.realisasi)) as realuang,
if(r.target_kinerja is null,0,sum(r.target_kinerja)) as realfis,
p.pagu-if(r.realisasi is null,0,sum(r.realisasi)) as sisauang,
p.target_kinerja-if(r.target_kinerja is null,0,sum(r.target_kinerja)) as sisafis,
if(sum(rr.realisasi) is null,0,sum(rr.realisasi)) as tes
from pagu p
left join realisasi r on p.idpagu=r.idpagu and r.tgl BETWEEN "2017-01-01" and "2017-01-15"
left join perencanaan pr on p.idpagu=pr.idpagu and r.tgl BETWEEN "2017-01-01" and "2017-01-15"
left join realisasi rr on p.idpagu=rr.idpagu and rr.tgl < "2017-01-15"
group by p.idpagu,r.idpagu,rr.idpagu

My result:

idpagu  kode    komponen    pagu    target_kinerja  perenuang   perenfis    realuang    realfis     sisauang    sisafis     tes
1   2217.057.056    Pengembangan Sistem Manajemen Mutu UPTP     52740000    1   0   0   52740000    1   0   0   52740000
2   2220.051.051    Pelatihan Peningkatan Produktivitas     4732755000  120     0   0   20000000    20  4712755000  100     20000000
3   2220.052.051    Calon Wirausaha Baru yang Dilatih (RM)  12464938000     240     0   0   0   0   12464938000     240     0

My question:

The tes column is pagu - realuang before the current date "2017-01-15", and the second row should be 10.000.000, but my query gives 20.000.000.
How do I write my query so that in the second record the tes column is 10.000.000?

My schema:

SET FOREIGN_KEY_CHECKS=0;

DROP TABLE IF EXISTS `pagu`;
CREATE TABLE `pagu` (
  `idpagu` int(11) NOT NULL AUTO_INCREMENT,
  `kode` varchar(45) NOT NULL,
  `komponen` varchar(250) NOT NULL,
  `pagu` bigint(20) NOT NULL,
  `target_kinerja` int(11) NOT NULL,
  `tahun` varchar(4) NOT NULL,
  `keterangan` varchar(250) DEFAULT NULL,
  PRIMARY KEY (`idpagu`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

INSERT INTO `pagu` VALUES ('1', '2217.057.056', 'Pengembangan Sistem Manajemen Mutu UPTP', '52740000', '1', '2017', 'tes123');
INSERT INTO `pagu` VALUES ('2', '2220.051.051', 'Pelatihan Peningkatan Produktivitas', '4732755000', '120', '2017', 'tes123');
INSERT INTO `pagu` VALUES ('3', '2220.052.051', 'Calon Wirausaha Baru yang Dilatih (RM)', '12464938000', '240', '2017', 'TES123');

DROP TABLE IF EXISTS `perencanaan`;
CREATE TABLE `perencanaan` (
  `idperencanaan` int(11) NOT NULL AUTO_INCREMENT,
  `idpagu` int(11) NOT NULL,
  `kode` varchar(45) NOT NULL,
  `komponen` varchar(250) NOT NULL,
  `penarikan` bigint(20) NOT NULL,
  `target_kinerja` int(11) NOT NULL,
  `tgl` date NOT NULL,
  `keterangan` varchar(250) DEFAULT NULL,
  PRIMARY KEY (`idperencanaan`),
  KEY `fk_perencanaan_pagu1_idx` (`idpagu`),
  CONSTRAINT `fk_perencanaan_pagu1` FOREIGN KEY (`idpagu`) REFERENCES `pagu` (`idpagu`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `realisasi`;
CREATE TABLE `realisasi` (
  `idrealisasi` int(11) NOT NULL AUTO_INCREMENT,
  `idpagu` int(11) NOT NULL,
  `kode` varchar(45) NOT NULL,
  `komponen` varchar(250) NOT NULL,
  `realisasi` bigint(20) NOT NULL,
  `target_kinerja` int(11) NOT NULL,
  `tgl` date NOT NULL,
  `keterangan` varchar(250) DEFAULT NULL,
  PRIMARY KEY (`idrealisasi`),
  KEY `fk_perencanaan_pagu1_idx` (`idpagu`),
  CONSTRAINT `fk_perencanaan_pagu10` FOREIGN KEY (`idpagu`) REFERENCES `pagu` (`idpagu`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

INSERT INTO `realisasi` VALUES ('5', '1', '2217.057.056', 'Pengembangan Sistem Manajemen Mutu UPTP', '52740000', '1', '2017-01-14', 'tes');
INSERT INTO `realisasi` VALUES ('6', '2', '2220.051.051', 'Pelatihan Peningkatan Produktivitas', '10000000', '10', '2017-01-14', 'tes');
INSERT INTO `realisasi` VALUES ('7', '2', '2220.051.051', 'Pelatihan Peningkatan Produktivitas', '20000000', '20', '2017-02-14', 'tes2');
INSERT INTO `realisasi` VALUES ('8', '2', '2220.051.051', 'Pelatihan Peningkatan Produktivitas', '10000000', '10', '2017-03-14', 'tes3');
INSERT INTO `realisasi` VALUES ('9', '2', '2220.051.051', 'Pelatihan Peningkatan Produktivitas', '10000000', '10', '2017-06-14', 'tes4');
INSERT INTO `realisasi` VALUES ('10', '2', '2220.051.051', 'Pelatihan Peningkatan Produktivitas', '10000000', '10', '2017-01-15', 'tes');

Body:
Guessing from your query and table & column names (pagu = ceiling, realisasi = actual, perencanaan = planned), for each ceiling you are summing its actual values on days in a certain range, its planned values on those days, its actual values on some of those days, and some related target values, treating NULL values as 0.

I assume that if a ceiling has an actual value on a date then it has a planned value on that date. Otherwise, your query would involve FULL JOIN, and a LEFT JOIN would wrongly sometimes form rows with different dates, etc. So I suspect you are missing a FK (foreign key).

Your first LEFT JOIN gets the actual value for each ceiling for some dates. Then you want any planned value for a ceiling & date. So you are missing and r.tgl = pr.tgl. Then you want any actual value for a ceiling & date for some of those dates. So your third LEFT JOIN is missing and r.tgl = rr.tgl.

You are grouping & summing incorrectly. If a SELECT uses a column outside an aggregate call then it should be single-valued for each subrow of GROUPed columns. (GROUP BY returns one row per subrow of GROUPed columns.) (SET sql_mode = 'ONLY_FULL_GROUP_BY' disallows MySQL's non-standard behaviour.)

select p.idpagu, count(*), p.pagu, p.target_kinerja,
    sum(coalesce(pr.penarikan,0)) as pr_penarikan,
    sum(coalesce(pr.target_kinerja,0)) as pr_target_kinerja,
    sum(coalesce(r.realisasi,0)) as r_realisasi,
    sum(coalesce(r.target_kinerja,0)) as r_target_kinerja,
    p.pagu-sum(coalesce(r.realisasi,0)) as d_realisasi,
    p.target_kinerja-sum(coalesce(r.target_kinerja,0)) as d_target_kinerja,
    sum(coalesce(rr.realisasi,0)) as rr_realisasi
from pagu p
left join realisasi r on p.idpagu=r.idpagu and r.tgl BETWEEN "2017-01-01" and "2017-01-15"
left join perencanaan pr on p.idpagu=pr.idpagu and r.tgl = pr.tgl and r.tgl BETWEEN "2017-01-01" and "2017-01-15"
left join realisasi rr on p.idpagu=rr.idpagu and r.tgl = rr.tgl and r.tgl < "2017-01-15"
group by p.idpagu, p.pagu, p.target_kinerja;

idpagu  pagu                    pr_penarikan    r_realisasi     d_realisasi             rr_target_kinerja
    count(*)        target_kinerja  pr_target_kinerja       r_target_kinerja    d_target_kinerja
1   1   52740000    1           0   0           52740000    1   0               0       52740000
2   2   4732755000  120         0   0           20000000    20  4712755000      100     10000000
3   1   12464938000 240         0   0           0           0   12464938000     240     0


问:
PHP set date to end at a specific hour
I am currently working at a system for a manufacturing company that monitors a daily output data, but the company follows a 24hours production duration which the date ends at 6:00 AM, but the standard PHP date/time change after 12:00 midnight,is it possible to change the PHP date/timestamp to change the current date after 6am?

Edit

this is what i have so far, so the date must be todays date.

```<code>  <?php

  $dt = new DateTime("2017-07-07 00:00:00",
  new DateTimeZone("Asia/Tokyo"));
  echo "Start: ", $dt->format("Y-m-d H:i:s"), PHP_EOL;
  $dt->add(new DateInterval("PT6H"));
  echo "<br/>";
  echo "End:   ", $dt->format("Y-m-d H:i:s"), PHP_EOL;

  ?>
</code>```

The output is below

```<code>   Start: 2017-07-07 00:00:00
   End: 2017-07-07 06:00:00
</code>```

What i want to achieve is the logic below, the day will start at 6:00 AM in the morning then will end on 5:59 AM on the next day.

```<code>   Start: 2017-07-07 06:00:00 AM
   End: 2017-07-07 05:59:00 AM
</code>```

答:
No, you can't fundamentally change the way the Calendar works.  It seems to me that what you are looking for is a pair of DateTime(s) that represent one shift.  As you described them it's pretty clear.  I'll just use an array to keep them together:

```<code>$shift = array();
$format = 'Y-m-d H:i:s';

$shift['start'] = DateTime::createFromFormat($format, date('Y-m-d') . ' 6:00:00', new DateTimeZone("Asia/Tokyo"));
$shift['end'] = clone $shift['start'];
// Now add 23:59:59 to it
$shift['end']->add(DateInterval::createFromDateString('1 Day - 1 seconds'));

echo "Start: ", $shift['start']->format("Y-m-d H:i:s"), PHP_EOL;
echo "End: ", $shift['end']->format("Y-m-d H:i:s"), PHP_EOL;
echo PHP_EOL;

var_dump($shift);
</code>```

Here's a sample:  https://3v4l.org/m1XgX

Title: PHP set date to end at a specific hour

Body:
I am currently working at a system for a manufacturing company that monitors a daily output data, but the company follows a 24hours production duration which the date ends at 6:00 AM, but the standard PHP date/time change after 12:00 midnight,is it possible to change the PHP date/timestamp to change the current date after 6am?

Edit

this is what i have so far, so the date must be todays date.

  <?php

  $dt = new DateTime("2017-07-07 00:00:00",
  new DateTimeZone("Asia/Tokyo"));
  echo "Start: ", $dt->format("Y-m-d H:i:s"), PHP_EOL;
  $dt->add(new DateInterval("PT6H"));
  echo "
";
  echo "End:   ", $dt->format("Y-m-d H:i:s"), PHP_EOL;

  ?>

The output is below

   Start: 2017-07-07 00:00:00
   End: 2017-07-07 06:00:00

What i want to achieve is the logic below, the day will start at 6:00 AM in the morning then will end on 5:59 AM on the next day.

   Start: 2017-07-07 06:00:00 AM
   End: 2017-07-07 05:59:00 AM

Body:
No, you can't fundamentally change the way the Calendar works.  It seems to me that what you are looking for is a pair of DateTime(s) that represent one shift.  As you described them it's pretty clear.  I'll just use an array to keep them together:

$shift = array();
$format = 'Y-m-d H:i:s';

$shift['start'] = DateTime::createFromFormat($format, date('Y-m-d') . ' 6:00:00', new DateTimeZone("Asia/Tokyo"));
$shift['end'] = clone $shift['start'];
// Now add 23:59:59 to it
$shift['end']->add(DateInterval::createFromDateString('1 Day - 1 seconds'));

echo "Start: ", $shift['start']->format("Y-m-d H:i:s"), PHP_EOL;
echo "End: ", $shift['end']->format("Y-m-d H:i:s"), PHP_EOL;
echo PHP_EOL;

var_dump($shift);

Here's a sample:  https://3v4l.org/m1XgX


问:
Inheritance of models with relationships (hasOne and hasMany)
How to inherit from a model that has hasOne and hasMany relationships? It is necessary to preserve these relationships.

I made an example in the sandbox: https://fiddle.sencha.com/#view/editor&fiddle/22fi

The model Fiddle.model.User2 is inherited fromFiddle.model.User.

In the file app.js User2 I connect to the repository. If you connect User, then everything will work. But when using the User2 model, the links do not work: thegetAddress()method returns empty, and thegetUser()method does not work.

答:
Sencha Technical Support Answer

Unfortunately, this is currently not supported.
But we do have an open feature request to add this functionality.

Please not as it is a feature request and not a bug, there is no guarantee of when or if it will be added to the framework.


问:
How can I show popup fit to the screen size of the mobile device in mapboxgl?
I want to make my mapboxgl popup fit to my mobile device screen size.

```<code>  new mapboxgl.Popup()
      .setLngLat(e.features[0].geometry.coordinates)
      .setHTML("htmlString")
      .addTo(map);
</code>```

I used the above code, but to see the entire content of the popup i need to move right/left.

Also I want to show popup on the center of the marker. Not it appears left/right side

答:
You can staticly position the popup using the anchor option:

A string indicating the popup's location relative to the coordinate set via Popup#setLngLat . Options are  'top' ,  'bottom' ,  'left' ,  'right' ,  'top-left' ,  'top-right' ,  'bottom-left' , and  'bottom-right' . If unset the anchor will be dynamically set to ensure the popup falls within the map container with a preference for  'bottom'.

Reference: https://www.mapbox.com/mapbox-gl-js/api/#popup

As for scaling the popup is supposed to do that automaticly according to the content you provide. But if you really need to you can fiddle with it's styling,

```<code><div class="mapboxgl-popup">
     <div class="mapboxgl-popup-tip"></div>
     <div class="mapboxgl-popup-content">
         <button class="mapboxgl-popup-close-button" type="button" aria-label="Close popup">×</button>
         <h1>Hello World!</h1>
     </div>
</div>
</code>```

But i'de really advise against that. If you need a specific size or so i'de enclose the content in a container element and style that.

Body:
I want to make my mapboxgl popup fit to my mobile device screen size.

  new mapboxgl.Popup()
      .setLngLat(e.features[0].geometry.coordinates)
      .setHTML("htmlString")
      .addTo(map);

I used the above code, but to see the entire content of the popup i need to move right/left.

Also I want to show popup on the center of the marker. Not it appears left/right side

Body:
You can staticly position the popup using the anchor option:

A string indicating the popup's location relative to the coordinate set via Popup#setLngLat . Options are  'top' ,  'bottom' ,  'left' ,  'right' ,  'top-left' ,  'top-right' ,  'bottom-left' , and  'bottom-right' . If unset the anchor will be dynamically set to ensure the popup falls within the map container with a preference for  'bottom'.

Reference: https://www.mapbox.com/mapbox-gl-js/api/#popup

As for scaling the popup is supposed to do that automaticly according to the content you provide. But if you really need to you can fiddle with it's styling,

<div class="mapboxgl-popup">
     <div class="mapboxgl-popup-tip"></div>
     <div class="mapboxgl-popup-content">
         <button class="mapboxgl-popup-close-button" type="button" aria-label="Close popup">×</button>
         <h1>Hello World!</h1>
     </div>
</div>

But i'de really advise against that. If you need a specific size or so i'de enclose the content in a container element and style that.


问:
jQuery UI : How can I know that the div are center on drag event
If I have two or more divs or p tags. I want to know how can I get the center with each elements means in my fiddle example ( that I will provide below ) if I drag the the "I am title H3" ( that is my H3 tag ) to the "I am a Title H1" ( which is my H1 tag ) or to the "I am a parargraph p" ( which is my p tag ) a line that comes that indicate the two elements are center to each other.

```<code>var element = $(".draggable_element");

element.each(function() {
  $(this).draggable({
    zIndex: 999,
    scroll: false,
    refreshPosition: true,
  });
});
</code>```

Here is my fiddle.

答:
The below code will help you to find the center of each element on dragging. https://jsfiddle.net/44ve3syv/4/</p>

```<code>var element = $(".draggable_element");
element.each(function() {
     $(this).draggable({
            zIndex: 999,
            scroll: false,
        refreshPosition: true,
        drag: function() {
         console.log(1);
        },
        stop:function(){
            checkIfCenter($(this));
        }
        });
  });
  checkIfCenter = function(el){
    var cPos;
    var elCenter = findCentre(el);
    var isCenter = true;
    $( ".draggable_element" ).each(function() {
      cPos = findCentre($(this));
      console.log(cPos);
      if(cPos.x == elCenter.x && cPos.y == elCenter.y && isCenter){
        isCenter = true;
      }else{
        isCenter = false;
      }
    });
    if(isCenter){
        alert("All elements came in center");
    }
  }
  findCentre = function(el){
    var offset = el.offset();
    var width = el.width();
    var height = el.height();
    var pos = { x : parseInt(offset.left + width / 2),y : parseInt(offset.top + height / 2)}
    return pos;
  }
</code>```

Body:
If I have two or more divs or p tags. I want to know how can I get the center with each elements means in my fiddle example ( that I will provide below ) if I drag the the "I am title H3" ( that is my H3 tag ) to the "I am a Title H1" ( which is my H1 tag ) or to the "I am a parargraph p" ( which is my p tag ) a line that comes that indicate the two elements are center to each other.

var element = $(".draggable_element");

element.each(function() {
  $(this).draggable({
    zIndex: 999,
    scroll: false,
    refreshPosition: true,
  });
});

Here is my fiddle.

Body:
The below code will help you to find the center of each element on dragging. https://jsfiddle.net/44ve3syv/4/

var element = $(".draggable_element");
element.each(function() {
     $(this).draggable({
            zIndex: 999,
            scroll: false,
        refreshPosition: true,
        drag: function() {
         console.log(1);
        },
        stop:function(){
            checkIfCenter($(this));
        }
        });
  });
  checkIfCenter = function(el){
    var cPos;
    var elCenter = findCentre(el);
    var isCenter = true;
    $( ".draggable_element" ).each(function() {
      cPos = findCentre($(this));
      console.log(cPos);
      if(cPos.x == elCenter.x && cPos.y == elCenter.y && isCenter){
        isCenter = true;
      }else{
        isCenter = false;
      }
    });
    if(isCenter){
        alert("All elements came in center");
    }
  }
  findCentre = function(el){
    var offset = el.offset();
    var width = el.width();
    var height = el.height();
    var pos = { x : parseInt(offset.left + width / 2),y : parseInt(offset.top + height / 2)}
    return pos;
  }


问:
Get value in for loop to outside loop to array?

This is my code.

```<code>          for (int i = 1; i < dataGridView2.RowCount - 1; i++)
                {

                    int valueCellIndex = 3;//assume calculate the 0th column
                    int resultCellIndex = 4;//assume result to put into the 1th column
                    var lastRow = dataGridView2.Rows[i - 1];
                    var curRow = dataGridView2.Rows[i];
                    double last = Convert.ToInt32(lastRow.Cells[valueCellIndex].Value);
                    double cur = Convert.ToInt32(curRow.Cells[valueCellIndex].Value);

                    gain = Convert.ToInt32(curRow.Cells[resultCellIndex].Value = cur - last); //

                }
          JsonArray.Add(new JsonInput(close, gain));
</code>```

How to get 'gain' in for loop into JsonArray  ?

答:
As gain variable is int type, you can create a List object to add gain variable value/s inside the loop. Later convert that int  Listto json array.

```<code>List<int> gainList = new List<int>();
for (int i = 1; i < dataGridView2.RowCount - 1; i++)
{

    int valueCellIndex = 3;//assume calculate the 0th column
    int resultCellIndex = 4;//assume result to put into the 1th column
    var lastRow = dataGridView2.Rows[i - 1];
    var curRow = dataGridView2.Rows[i];
    double last = Convert.ToInt32(lastRow.Cells[valueCellIndex].Value);
    double cur = Convert.ToInt32(curRow.Cells[valueCellIndex].Value);
    gain = Convert.ToInt32(curRow.Cells[resultCellIndex].Value = cur - last);
    gainList.Add(gain);
}
</code>```

To convert the list to json format you can use System.Web.Script.Serialization namespace.

```<code>using System.Web.Script.Serialization;
.....
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(gainList);
</code>```

Body:
This is my code.

          for (int i = 1; i < dataGridView2.RowCount - 1; i++)
                {

                    int valueCellIndex = 3;//assume calculate the 0th column
                    int resultCellIndex = 4;//assume result to put into the 1th column
                    var lastRow = dataGridView2.Rows[i - 1];
                    var curRow = dataGridView2.Rows[i];
                    double last = Convert.ToInt32(lastRow.Cells[valueCellIndex].Value);
                    double cur = Convert.ToInt32(curRow.Cells[valueCellIndex].Value);

                    gain = Convert.ToInt32(curRow.Cells[resultCellIndex].Value = cur - last); //

                }
          JsonArray.Add(new JsonInput(close, gain));

How to get 'gain' in for loop into JsonArray  ?

Body:
As gain variable is int type, you can create a List object to add gain variable value/s inside the loop. Later convert that int  Listto json array.

List<int> gainList = new List<int>();
for (int i = 1; i < dataGridView2.RowCount - 1; i++)
{

    int valueCellIndex = 3;//assume calculate the 0th column
    int resultCellIndex = 4;//assume result to put into the 1th column
    var lastRow = dataGridView2.Rows[i - 1];
    var curRow = dataGridView2.Rows[i];
    double last = Convert.ToInt32(lastRow.Cells[valueCellIndex].Value);
    double cur = Convert.ToInt32(curRow.Cells[valueCellIndex].Value);
    gain = Convert.ToInt32(curRow.Cells[resultCellIndex].Value = cur - last);
    gainList.Add(gain);
}

To convert the list to json format you can use System.Web.Script.Serialization namespace.

using System.Web.Script.Serialization;
.....
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(gainList);

ContentLicense: CC BY-SA 4.0


问:
How to manipulate php time data and get a result in hour:minute format
I am trying to create a program where it calculates start hour and finish hour and gets the time in between to see how many hours have been worked (the start and stop variables are replaced by time values from a database in the real code)

Here is an example:

```<code>$start = "11:15:35"
$stop = "17:30:13"

$start2 = date( 'G:i' ,strtotime($start) );
$stop2 = date( 'G:i' ,strtotime($stop) );

echo $stop2 ."<br>". $start2;
echo "<br><br>";
echo $stop2 - $start2;
</code>```

I need the code to output something like 6.25 or 6h and 15min, currently it is only doing hours and outputting just a 6.

i have tried
$stop2[1] & start2[1]

and changing around the 'G:i' bit with various other letters from http://php.net/manual/en/function.date.php

Sorry if this is a simple question, any answers appreciated!

Edit: misspelt minute

答:
Try this</p>

```<code>$hour_one = "17:30:13";
$hour_two = "11:15:35";

$h =  strtotime($hour_one);
$h2 = strtotime($hour_two);

$minute = date("i", $h2);
$second = date("s", $h2);
$hour = date("H", $h2);

$convert = strtotime("-$minute minutes", $h);
$convert = strtotime("-$second seconds", $convert);
$convert = strtotime("-$hour hours", $convert);
$new_time = date('H:i:s', $convert);

echo $new_time;
</code>```

Body:
I am trying to create a program where it calculates start hour and finish hour and gets the time in between to see how many hours have been worked (the start and stop variables are replaced by time values from a database in the real code)

Here is an example:

$start = "11:15:35"
$stop = "17:30:13"

$start2 = date( 'G:i' ,strtotime($start) );
$stop2 = date( 'G:i' ,strtotime($stop) );

echo $stop2 ."
". $start2;
echo "

";
echo $stop2 - $start2;

I need the code to output something like 6.25 or 6h and 15min, currently it is only doing hours and outputting just a 6.

i have tried
$stop2[1] & start2[1]

and changing around the 'G:i' bit with various other letters from http://php.net/manual/en/function.date.php

Sorry if this is a simple question, any answers appreciated!

Edit: misspelt minute

Body:
Try this

$hour_one = "17:30:13";
$hour_two = "11:15:35";

$h =  strtotime($hour_one);
$h2 = strtotime($hour_two);

$minute = date("i", $h2);
$second = date("s", $h2);
$hour = date("H", $h2);

$convert = strtotime("-$minute minutes", $h);
$convert = strtotime("-$second seconds", $convert);
$convert = strtotime("-$hour hours", $convert);
$new_time = date('H:i:s', $convert);

echo $new_time;


问:
Unity3D Only single if statement being called
I'm having issue with my code.
Only the first if statement is being called.
I know my level is increasing, however after the first statement is called and the level increases the continue button is still shown even if the score is lower than called for.</p>

```<code>private void PlayBuzzer()
{
    GetComponent<AudioSource>().PlayOneShot(buzzer);
    timeRemaining -= 1;
    endPanel.SetActive(true);
    if (PlayerScore.score >= 15 && level == 1) // THIS ONE WORKS
    {
        GameObject.Find("Restart").SetActive(false);
        GameObject.Find("Continue").SetActive(true);
    }
// EVERYTHING BELOW HERE DOES NOT - Score Below 35 still shows 'Continue'
    else if (PlayerScore.score >= 35 && level == 2)
    {
        GameObject.Find("Restart").SetActive(false);
        GameObject.Find("Continue").SetActive(true);
    }
    else if (PlayerScore.score >= 45 && level == 3)
    {
        GameObject.Find("Restart").SetActive(false);
        GameObject.Find("Continue").SetActive(true);
    }
    else if (PlayerScore.score >= 70 && level == 4)
    {
        GameObject.Find("Restart").SetActive(false);
        GameObject.Find("Continue").SetActive(true);
    }
    else if (PlayerScore.score >= 120 && level == 5)
    {
        GameObject.Find("Restart").SetActive(false);
        GameObject.Find("Continue").SetActive(true);
    }
    else if (PlayerScore.score >= 160 && level == 6)
    {
        GameObject.Find("Restart").SetActive(false);
        GameObject.Find("Continue").SetActive(true);
    }
    else if (PlayerScore.score >= 230 && level == 7)
    {
        GameObject.Find("Restart").SetActive(false);
        GameObject.Find("Continue").SetActive(true);
    }
    else if (PlayerScore.score >= 300 && level == 8)
    {
        GameObject.Find("Restart").SetActive(false);
        GameObject.Find("Continue").SetActive(true);
    }
    else
    {
        GameObject.Find("Restart").SetActive(true);
        GameObject.Find("Continue").SetActive(false);
    }
    Time.timeScale = 0;
}
</code>```

答:
Ok without knowing where PlayBuzzer() is called and if level is increased before or after that, finding the problem is really hard. Did you debug the program?

anyway I took the freedom to shorten your function, in order to follow the DRY principle:

```<code>private void PlayBuzzer()
{
    GetComponent<AudioSource>().PlayOneShot(buzzer);
    timeRemaining -= 1;
    endPanel.SetActive(true);
    var scores = new List<int> { 15, 35, 45, 70, 120, 160 };
    var mustRestart = PlayerScore.score < scores[level - 1];
    GameObject.Find("Restart").SetActive(mustRestart);
    GameObject.Find("Continue").SetActive(!mustRestart);
    Time.timeScale = 0;
}
</code>```

you must of cause insure that your level is between 1 and scores.Count.

Body:
I'm having issue with my code.
Only the first if statement is being called.
I know my level is increasing, however after the first statement is called and the level increases the continue button is still shown even if the score is lower than called for.

private void PlayBuzzer()
{
    GetComponent<AudioSource>().PlayOneShot(buzzer);
    timeRemaining -= 1;
    endPanel.SetActive(true);
    if (PlayerScore.score >= 15 && level == 1) // THIS ONE WORKS
    {
        GameObject.Find("Restart").SetActive(false);
        GameObject.Find("Continue").SetActive(true);
    }
// EVERYTHING BELOW HERE DOES NOT - Score Below 35 still shows 'Continue'
    else if (PlayerScore.score >= 35 && level == 2)
    {
        GameObject.Find("Restart").SetActive(false);
        GameObject.Find("Continue").SetActive(true);
    }
    else if (PlayerScore.score >= 45 && level == 3)
    {
        GameObject.Find("Restart").SetActive(false);
        GameObject.Find("Continue").SetActive(true);
    }
    else if (PlayerScore.score >= 70 && level == 4)
    {
        GameObject.Find("Restart").SetActive(false);
        GameObject.Find("Continue").SetActive(true);
    }
    else if (PlayerScore.score >= 120 && level == 5)
    {
        GameObject.Find("Restart").SetActive(false);
        GameObject.Find("Continue").SetActive(true);
    }
    else if (PlayerScore.score >= 160 && level == 6)
    {
        GameObject.Find("Restart").SetActive(false);
        GameObject.Find("Continue").SetActive(true);
    }
    else if (PlayerScore.score >= 230 && level == 7)
    {
        GameObject.Find("Restart").SetActive(false);
        GameObject.Find("Continue").SetActive(true);
    }
    else if (PlayerScore.score >= 300 && level == 8)
    {
        GameObject.Find("Restart").SetActive(false);
        GameObject.Find("Continue").SetActive(true);
    }
    else
    {
        GameObject.Find("Restart").SetActive(true);
        GameObject.Find("Continue").SetActive(false);
    }
    Time.timeScale = 0;
}

Body:
Ok without knowing where PlayBuzzer() is called and if level is increased before or after that, finding the problem is really hard. Did you debug the program?

anyway I took the freedom to shorten your function, in order to follow the DRY principle:

private void PlayBuzzer()
{
    GetComponent<AudioSource>().PlayOneShot(buzzer);
    timeRemaining -= 1;
    endPanel.SetActive(true);
    var scores = new List<int> { 15, 35, 45, 70, 120, 160 };
    var mustRestart = PlayerScore.score < scores[level - 1];
    GameObject.Find("Restart").SetActive(mustRestart);
    GameObject.Find("Continue").SetActive(!mustRestart);
    Time.timeScale = 0;
}

you must of cause insure that your level is between 1 and scores.Count.


问:
Get Azure Active Directory token from an electron app
What would be the best way to obtain an AAD token from an electron app?

Microsoft has 2 javascript authentication libraries: adal.js and msal.js.
Both are designed for browsers and not native Electron apps (For example - AAD won't allow for file:/// scheme as a reply URL).

Sounds like a long term solution would be native AAD packages (like Microsoft built for Apache Cordova), but since that's probably not going to happen any time soon, what is the best short-term option?

答:
Azure Storage Explorer  is a good example of an Electron app that does this. It even allows for being logged into multiple AAD accounts at the same time.

You might be able to check out what's going on in the app's dev tools. I've had a poke around and it looks like it uses adal-node npm package instead of the browser based js libraries.

It also looks like it uses an authorization code flow for obtaining tokens.


问:
authentification angular js with symfony
I have make authentification in application with angular js when I use API rest developed with symfony 2 (fosrestbundle for example),
how to make authentification (login and register) in angular js with api rest symfony
thanks adavanced my friends</p>

答:
setup the server side oauth mechanism using https://github.com/FriendsOfSymfony/FOSOAuthServerBundle

then implement it in angular ..


问:
CPLEX - Error in accessing solution C++
I have a problem in accessing the solution of a LP problem.

This is the output of CPLEX after calling cplex.solve();

```<code> CPXPARAM_MIP_Strategy_CallbackReducedLP          0
 Found incumbent of value 0.000000 after 0.00 sec. (0.70 ticks)
 Tried aggregator 1 time.
 MIP Presolve eliminated 570 rows and 3 columns.
 MIP Presolve modified 88 coefficients.
 Reduced MIP has 390 rows, 29291 columns, and 76482 nonzeros.
 Reduced MIP has 29291 binaries, 0 generals, 0 SOSs, and 0 indicators.
 Presolve time = 0.06 sec. (49.60 ticks)
 Tried aggregator 1 time.
 Reduced MIP has 390 rows, 29291 columns, and 76482 nonzeros.
 Reduced MIP has 29291 binaries, 0 generals, 0 SOSs, and 0 indicators.
 Presolve time = 0.04 sec. (31.47 ticks)
 Probing time = 0.02 sec. (1.36 ticks)
 MIP emphasis: balance optimality and feasibility.
 MIP search method: dynamic search.
 Parallel mode: deterministic, using up to 8 threads.
 Root relaxation solution time = 0.03 sec. (17.59 ticks)

    Nodes                                         Cuts/
Node  Left     Objective  IInf  Best Integer    Best Bound    ItCnt     Gap

*     0+    0                            0.0000     -395.1814              ---
*     0+    0                         -291.2283     -395.1814            35.69%
*     0     0      integral     0     -372.2283     -372.2283      201    0.00%
 Elapsed time = 0.21 sec. (131.64 ticks, tree = 0.00 MB, solutions = 3)

 Root node processing (before b&c):
   Real time             =    0.21 sec. (133.18 ticks)
 Parallel b&c, 8 threads:
   Real time             =    0.00 sec. (0.00 ticks)
   Sync time (average)   =    0.00 sec.
   Wait time (average)   =    0.00 sec.
                      ------------
 Total (root+branch&cut) =    0.21 sec. (133.18 ticks)
</code>```

However when I call cplex.getValues(values, variables); the program gives a SIGABRT signal throwing the following exception:

```<code>libc++abi.dylib: terminating with uncaught exception of type IloAlgorithm::NotExtractedException
</code>```

This is my code. What I'm doing wrong?

```<code>std::vector<links_t> links(pointsA.size()*pointsB.size());

std::unordered_map<int, std::vector<std::size_t> > point2DToLinks;

for(std::size_t i=0; i<pointsA.size(); ++i){

  for(std::size_t j=0; j<pointsB.size(); ++j){

    std::size_t index = (i*pointsA.size()) + j;

    links[index].from = i;
    links[index].to   = j;

    links[index].value = cv::norm(pointsA[i] - pointsB[j]);

    point2DToLinks[pointsA[i].point2D[0]->id].push_back(index);
    point2DToLinks[pointsA[i].point2D[1]->id].push_back(index);
    point2DToLinks[pointsA[i].point2D[2]->id].push_back(index);

    point2DToLinks[pointsB[j].point2D[0]->id].push_back(index);
    point2DToLinks[pointsB[j].point2D[1]->id].push_back(index);
    point2DToLinks[pointsB[j].point2D[2]->id].push_back(index);

  }

}

std::size_t size = links.size() + point2DToLinks.size();

IloEnv environment;

IloNumArray coefficients(environment, size);

for(std::size_t i=0; i<links.size(); ++i)    coefficients[i] = links[i].value;
for(std::size_t i=links.size(); i<size; ++i) coefficients[i] = -lambda;

IloNumVarArray variables(environment, size, 0, 1, IloNumVar::Bool);

IloObjective objective(environment, 0.0, IloObjective::Minimize);

objective.setLinearCoefs(variables, coefficients);

IloRangeArray constrains = IloRangeArray(environment);

std::size_t counter = 0;

for(auto point=point2DToLinks.begin(); point!=point2DToLinks.end(); point++){

  IloExpr expression(environment);

  const std::vector<std::size_t> & inLinks = point->second;

  for(std::size_t j=0; j<inLinks.size(); j++) expression += variables[inLinks[j]];

  expression -= variables[links.size() + counter];

  constrains.add(IloRange(environment, 0, expression));

  expression.end();

  ++counter;

}

IloModel model(environment);

model.add(objective);
model.add(constrains);

IloCplex cplex(model);

cplex.solve();

if(cplex.getStatus() != IloAlgorithm::Optimal){
  fprintf(stderr, "error: cplex terminate with an error.\n");
  abort();
}

IloNumArray values(environment, size);

cplex.getValues(values, variables);

for(std::size_t i=0; i<links.size(); ++i)
  if(values[i] > 0) pairs.push_back(links[i]);

environment.end();
</code>```

答:
This is an error that happens if you ask CPLEX for the value of a variable that CPLEX does not have in its model. When you build the model, it is not enough to just declare and define the variable for it to be included in the model. It also has to be part of one of the constraints or the objective in the model. Any variable that you declare/define that is NOT included in one of the constraints or the objective will therefore not be in the set of variables that gets extracted into the inner workings of CPLEX. There are two obvious things that you can do to resolve this.

First you can try to get the variable values inside a loop over the variables, and test whether each is actually in the cplex model - I think is is something like cplex.isExtracted(var). Do something simple like print a message when you come across a variable that is not extracted, telling you which variable is causing the problem.

Secondly you can export the model from CPLEX as an LP format file and check it manually. This is a very useful way to see what is actually in your model rather than what you think is in your model.

Title: CPLEX - Error in accessing solution C++

Body:
I have a problem in accessing the solution of a LP problem.

This is the output of CPLEX after calling cplex.solve();

 CPXPARAM_MIP_Strategy_CallbackReducedLP          0
 Found incumbent of value 0.000000 after 0.00 sec. (0.70 ticks)
 Tried aggregator 1 time.
 MIP Presolve eliminated 570 rows and 3 columns.
 MIP Presolve modified 88 coefficients.
 Reduced MIP has 390 rows, 29291 columns, and 76482 nonzeros.
 Reduced MIP has 29291 binaries, 0 generals, 0 SOSs, and 0 indicators.
 Presolve time = 0.06 sec. (49.60 ticks)
 Tried aggregator 1 time.
 Reduced MIP has 390 rows, 29291 columns, and 76482 nonzeros.
 Reduced MIP has 29291 binaries, 0 generals, 0 SOSs, and 0 indicators.
 Presolve time = 0.04 sec. (31.47 ticks)
 Probing time = 0.02 sec. (1.36 ticks)
 MIP emphasis: balance optimality and feasibility.
 MIP search method: dynamic search.
 Parallel mode: deterministic, using up to 8 threads.
 Root relaxation solution time = 0.03 sec. (17.59 ticks)

    Nodes                                         Cuts/
Node  Left     Objective  IInf  Best Integer    Best Bound    ItCnt     Gap

*     0+    0                            0.0000     -395.1814              ---
*     0+    0                         -291.2283     -395.1814            35.69%
*     0     0      integral     0     -372.2283     -372.2283      201    0.00%
 Elapsed time = 0.21 sec. (131.64 ticks, tree = 0.00 MB, solutions = 3)

 Root node processing (before b&c):
   Real time             =    0.21 sec. (133.18 ticks)
 Parallel b&c, 8 threads:
   Real time             =    0.00 sec. (0.00 ticks)
   Sync time (average)   =    0.00 sec.
   Wait time (average)   =    0.00 sec.
                      ------------
 Total (root+branch&cut) =    0.21 sec. (133.18 ticks)

However when I call cplex.getValues(values, variables); the program gives a SIGABRT signal throwing the following exception:

libc++abi.dylib: terminating with uncaught exception of type IloAlgorithm::NotExtractedException

This is my code. What I'm doing wrong?

std::vector<links_t> links(pointsA.size()*pointsB.size());

std::unordered_map<int, std::vector<std::size_t> > point2DToLinks;

for(std::size_t i=0; i<pointsA.size(); ++i){

  for(std::size_t j=0; j<pointsB.size(); ++j){

    std::size_t index = (i*pointsA.size()) + j;

    links[index].from = i;
    links[index].to   = j;

    links[index].value = cv::norm(pointsA[i] - pointsB[j]);

    point2DToLinks[pointsA[i].point2D[0]->id].push_back(index);
    point2DToLinks[pointsA[i].point2D[1]->id].push_back(index);
    point2DToLinks[pointsA[i].point2D[2]->id].push_back(index);

    point2DToLinks[pointsB[j].point2D[0]->id].push_back(index);
    point2DToLinks[pointsB[j].point2D[1]->id].push_back(index);
    point2DToLinks[pointsB[j].point2D[2]->id].push_back(index);

  }

}

std::size_t size = links.size() + point2DToLinks.size();

IloEnv environment;

IloNumArray coefficients(environment, size);

for(std::size_t i=0; i<links.size(); ++i)    coefficients[i] = links[i].value;
for(std::size_t i=links.size(); i<size; ++i) coefficients[i] = -lambda;

IloNumVarArray variables(environment, size, 0, 1, IloNumVar::Bool);

IloObjective objective(environment, 0.0, IloObjective::Minimize);

objective.setLinearCoefs(variables, coefficients);

IloRangeArray constrains = IloRangeArray(environment);

std::size_t counter = 0;

for(auto point=point2DToLinks.begin(); point!=point2DToLinks.end(); point++){

  IloExpr expression(environment);

  const std::vector<std::size_t> & inLinks = point->second;

  for(std::size_t j=0; j<inLinks.size(); j++) expression += variables[inLinks[j]];

  expression -= variables[links.size() + counter];

  constrains.add(IloRange(environment, 0, expression));

  expression.end();

  ++counter;

}

IloModel model(environment);

model.add(objective);
model.add(constrains);

IloCplex cplex(model);

cplex.solve();

if(cplex.getStatus() != IloAlgorithm::Optimal){
  fprintf(stderr, "error: cplex terminate with an error.\n");
  abort();
}

IloNumArray values(environment, size);

cplex.getValues(values, variables);

for(std::size_t i=0; i<links.size(); ++i)
  if(values[i] > 0) pairs.push_back(links[i]);

environment.end();