问:
How can I send a variable "getId" to another JFrame "Student_Info"?
I want the value of getId variable in my student_info.java JFrame by the method it gives me only either null or nothing and by the constructor overloading it gives correct value but only when I print the value and when I use that value or when I store that value into a variable still It gives null.

student_login.java:

```<code>    public String getId;
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
    ConnectionProvider con = new ConnectionProvider();
    student_Password = new String(this.student_password.getPassword());
    student_Username= this.student_username.getText();
    String getStudentLoginTableId = "select student_id from Student_Login where student_username='"+student_Username+"' and student_password='"+student_Password+"'";
    Connection con1 = con.getConn();
    try {
        Statement stmt = con1.createStatement();
        ResultSet rs = stmt.executeQuery(getStudentLoginTableId);
        while(rs.next()){
            getId = rs.getString("student_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Student_Login.class.getName()).log(Level.SEVERE, null, ex);   }
}
public String getid(){
if("101".equals(getId)){
    JOptionPane.showMessageDialog(null, "yes");
}
else{
    JOptionPane.showMessageDialog(null, "no");
}
return getId;   }
</code>```

student_info.java:

```<code>String a = new Student_Login().getid();
JOptionPane.showMessageDialog(null, a);
String get = "select student_id , student_name from student_info where student_id='"+a+"'";
ConnectionProvider con = new ConnectionProvider();
Connection con1 = con.getConn();
try{
    Statement stmt = con1.createStatement();
    ResultSet rs = stmt.executeQuery(get);
    while(rs.next()){
        i = rs.getString("student_id");
        n = rs.getString("student_name");
    }
    //JOptionPane.showMessageDialog(null, getId);
    jLabel13.setText(i);
    jLabel14.setText(n);
} catch (SQLException ex) {
    Logger.getLogger(Student_Login.class.getName()).log(Level.SEVERE, null, ex);
}
</code>```

答:
Reason:

That because you have two separate classes, one is student_login and other one is student_info. So to get  value of getId you have created  new object from student_login.

```<code>String a = new Student_Login().getid();
</code>```

Keep remember each and every time when you create a object from a class, that class member variable values are individual to the object. In another word vales are not common to the every object that you are creating.

Solution:

You need to make getId variable to be common for every object. In another word getId values should be share among the all objects.

To do this you can use static keyword(modifier).

```<code>public static String getId;
</code>```

Learn more about static modifier.

Body:
I want the value of getId variable in my student_info.java JFrame by the method it gives me only either null or nothing and by the constructor overloading it gives correct value but only when I print the value and when I use that value or when I store that value into a variable still It gives null.

student_login.java:

    public String getId;
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt){
    ConnectionProvider con = new ConnectionProvider();
    student_Password = new String(this.student_password.getPassword());
    student_Username= this.student_username.getText();
    String getStudentLoginTableId = "select student_id from Student_Login where student_username='"+student_Username+"' and student_password='"+student_Password+"'";
    Connection con1 = con.getConn();
    try {
        Statement stmt = con1.createStatement();
        ResultSet rs = stmt.executeQuery(getStudentLoginTableId);
        while(rs.next()){
            getId = rs.getString("student_id");
        }
    } catch (SQLException ex) {
        Logger.getLogger(Student_Login.class.getName()).log(Level.SEVERE, null, ex);   }
}
public String getid(){
if("101".equals(getId)){
    JOptionPane.showMessageDialog(null, "yes");
}
else{
    JOptionPane.showMessageDialog(null, "no");
}
return getId;   }

student_info.java:

String a = new Student_Login().getid();
JOptionPane.showMessageDialog(null, a);
String get = "select student_id , student_name from student_info where student_id='"+a+"'";
ConnectionProvider con = new ConnectionProvider();
Connection con1 = con.getConn();
try{
    Statement stmt = con1.createStatement();
    ResultSet rs = stmt.executeQuery(get);
    while(rs.next()){
        i = rs.getString("student_id");
        n = rs.getString("student_name");
    }
    //JOptionPane.showMessageDialog(null, getId);
    jLabel13.setText(i);
    jLabel14.setText(n);
} catch (SQLException ex) {
    Logger.getLogger(Student_Login.class.getName()).log(Level.SEVERE, null, ex);
}

Body:
Reason:

That because you have two separate classes, one is student_login and other one is student_info. So to get  value of getId you have created  new object from student_login.

String a = new Student_Login().getid();

Keep remember each and every time when you create a object from a class, that class member variable values are individual to the object. In another word vales are not common to the every object that you are creating.

Solution:

You need to make getId variable to be common for every object. In another word getId values should be share among the all objects.

To do this you can use static keyword(modifier).

public static String getId;

Learn more about static modifier.


来源: stackexchange

问:
How can I make the tabs transparent in Ionic 2?
I'm using Ionic 3 and I need to make the Tabs (https://ionicframework.com/docs/api/components/tabs/Tabs/) transparent or change the opacity level to have a translucent effect while scrolling a list of cards. I've tried modifying via CSS a lot of elements (tabs itself, their parents and children) but no luck at all.</p>

答:
If you want to modify the classes directly you need to add

```<code>.md,.ios,.wp{}
</code>```

in order to override the ionic based styles in the build. So it would be something like

```<code>.md,.ios,.wp{
    ion-tabs{
        opacity:0.4;
    }
}
</code>```

You could also try creating a sass variable in theme/variables.scss file. And then apply that color on the color attribute.

```<code> $colors:{
 ...
  tabs-color :  rgba(255,255,255,0.1);
 }

 ----
 <ion-tabs color="tabs-color">
</code>```

ContentLicense: CC BY-SA 3.0

Body:
If you want to modify the classes directly you need to add

.md,.ios,.wp{}

in order to override the ionic based styles in the build. So it would be something like

.md,.ios,.wp{
    ion-tabs{
        opacity:0.4;
    }
}

You could also try creating a sass variable in theme/variables.scss file. And then apply that color on the color attribute.

 $colors:{
 ...
  tabs-color :  rgba(255,255,255,0.1);
 }

 ----
 <ion-tabs color="tabs-color">


问:
How to populate MVC partial view form fields from JQuery table row click
I have a Jquery DataTable that contains users. Its generated by a JQuery AJAX call to a Json result method in my MVC controller and iterates over the result to generate the rows in the table. Now I need to be able to click on the row, and have it make the MVC partial view form go from hidden to visible and populate the form with the user's data which will be with another Json call. My question is how do I get that ID value passed to another Json method to retrieve the data for that user then make the partial visible upon being populated with the user's data. Currently the partial view is set in a div on the main partial and called using @Html.Partial("TeamMember")

DataTable Code

```<code> $(document).ready(function () {
        $.getJSON("TeamData", {Id: 636},
            function (json) {
                var tr;
                for (var i = 0; i < json.length; i++) {
                    tr = $('<tr/>');
                    tr.append("<td>" + json[i].Id + "</td>")
                    tr.append("<td>" + json[i].FullName + "</td>");
                    tr.append("<td>" + json[i].Lan_Id + "</td>");
                    tr.append("<td>" + json[i].CurrDept + "</td>");
                    tr.append("<td>" + json[i].Email + "</td>");
                    $('#mTeamTable').append(tr);
                }
                $('#mTeamTable').DataTable();
            });
    });
</code>```

答:
Suppose you have HTML view like this:

```<code><table id="mTeamTable">
   ...
</table>

<div id="partialView">
    @Html.Partial("TeamMember")
</div>
</code>```

And a controller method returning JSON data like this:

```<code>public JsonResult TeamData(string Id)
{
    // query team data
    var member = GetTeamData();

    // return JSON string
    return Json(member, JsonRequestBehavior.AllowGet);
}
</code>```

Then, you need to configure 2 actions: when JSON data received & when clicking DataTable row to show partial view. Both of actions illustrated in code below:

$(document).ready(function () {

    // hide partial view div first
    $('#partialView').hide();

    $.getJSON("TeamData", { Id: 636 }, function (json) {
        var tr;
        for (var i = 0; i < json.length; i++) {
           tr = $('
');
           tr.append("" + json[i].Id + "	");
           tr.append("" + json[i].FullName + "	");
           tr.append("" + json[i].Lan_Id + "	");
           tr.append("" + json[i].CurrDept + "	");
           tr.append("" + json[i].Email + "	");
           $('#mTeamTable').append(tr);
        }
        $('#mTeamTable').DataTable();
    });

    // this section just an example to handle row click event
    // if the table contains tbody element, use $('#mTeamTable tbody')
    // see https://datatables.net/examples/advanced_init/events_live.html for row event handling
    $('#mTeamTable').on('click', 'tr', function () {
        var table = $('#mTeamTable').DataTable();
        var data = table.row(this).data();

        // call partial view here
        // use of @Url.Action in url part is recommended
        $.get("TeamMember", { Id: data[0] } , function () {

            // show partial view div
            $('#partialView').show();
        });
    });
});
```

<p>Additionally, you may need to set up a controller action method which returns partial view with viewmodel as given below:</p>

```public PartialViewResult TeamMember(string Id)
{
    // query team member
    var member = GetTeamMember();

    // put query results on a viewmodel, say it Member
    var teamMember = new Member()
    {
        Id = member.Id,
        FullName = member.FullName,
        ...
        Email = member.Email
    };

    // return partial view with viewmodel properties
    return PartialView("TeamMember", model);
}
```

Perhaps this is far from perfect, but at least explain key points which should be consider to handle datatable row clicking event.

Body:
I have a Jquery DataTable that contains users. Its generated by a JQuery AJAX call to a Json result method in my MVC controller and iterates over the result to generate the rows in the table. Now I need to be able to click on the row, and have it make the MVC partial view form go from hidden to visible and populate the form with the user's data which will be with another Json call. My question is how do I get that ID value passed to another Json method to retrieve the data for that user then make the partial visible upon being populated with the user's data. Currently the partial view is set in a div on the main partial and called using @Html.Partial("TeamMember")

DataTable Code

 $(document).ready(function () {
        $.getJSON("TeamData", {Id: 636},
            function (json) {
                var tr;
                for (var i = 0; i < json.length; i++) {
                    tr = $('
');
                    tr.append("" + json[i].Id + "	")
                    tr.append("" + json[i].FullName + "	");
                    tr.append("" + json[i].Lan_Id + "	");
                    tr.append("" + json[i].CurrDept + "	");
                    tr.append("" + json[i].Email + "	");
                    $('#mTeamTable').append(tr);
                }
                $('#mTeamTable').DataTable();
            });
    });

Body:
Suppose you have HTML view like this:

<table id="mTeamTable">
   ...
</table>

<div id="partialView">
    @Html.Partial("TeamMember")
</div>

And a controller method returning JSON data like this:

public JsonResult TeamData(string Id)
{
    // query team data
    var member = GetTeamData();

    // return JSON string
    return Json(member, JsonRequestBehavior.AllowGet);
}

Then, you need to configure 2 actions: when JSON data received & when clicking DataTable row to show partial view. Both of actions illustrated in code below:

$(document).ready(function () {

    // hide partial view div first
    $('#partialView').hide();

    $.getJSON("TeamData", { Id: 636 }, function (json) {
        var tr;
        for (var i = 0; i < json.length; i++) {
           tr = $('<tr data-id="' + json[i].Id + '"/>');
           tr.append("<td>" + json[i].Id + "</td>");
           tr.append("<td>" + json[i].FullName + "</td>");
           tr.append("<td>" + json[i].Lan_Id + "</td>");
           tr.append("<td>" + json[i].CurrDept + "</td>");
           tr.append("<td>" + json[i].Email + "</td>");
           $('#mTeamTable').append(tr);
        }
        $('#mTeamTable').DataTable();
    });

    // this section just an example to handle row click event
    // if the table contains tbody element, use $('#mTeamTable tbody')
    // see https://datatables.net/examples/advanced_init/events_live.html for row event handling
    $('#mTeamTable').on('click', 'tr', function () {
        var table = $('#mTeamTable').DataTable();
        var data = table.row(this).data();

        // call partial view here
        // use of @Url.Action in url part is recommended
        $.get("TeamMember", { Id: data[0] } , function () {

            // show partial view div
            $('#partialView').show();
        });
    });
});

Additionally, you may need to set up a controller action method which returns partial view with viewmodel as given below:

public PartialViewResult TeamMember(string Id)
{
    // query team member
    var member = GetTeamMember();

    // put query results on a viewmodel, say it Member
    var teamMember = new Member()
    {
        Id = member.Id,
        FullName = member.FullName,
        ...
        Email = member.Email
    };

    // return partial view with viewmodel properties
    return PartialView("TeamMember", model);
}

Perhaps this is far from perfect, but at least explain key points which should be consider to handle datatable row clicking event.


问:
css footer always bottom of page
How do I make the footer always stay bottom of the page (no sticky)? My footer is at the bottom of the screen, but not on the page.

Here is an example of my code.

HTML

```<code><!DOCTYPE html>
<html>
<head>
     <meta http-equiv="Content-Type" content="text/html charset=utf-8"/>
     <link href="styles.css" type="text/css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <div class="header">Header</div>
        <div class="body">Body</div>
        <div class="footer">Footer</div>
    </div>
</body>
</html>
</code>```

CSS

```<code>.footer {
    width:100%;
    height:109px;
    position:absolute;
    bottom:0;
    left:0;
    background-color: purple;
}
</code>```

答:
By using position:relative and bottom:0, you can make your footer at the end of the page

Modify your style-sheet like this and you can clearly understand the effect

```<code>.footer {
width:100%;
height:109px;
position:relative;
bottom:0;
left:0;
background-color: purple;
}
.body {               // I've added this
    height: 1000px;  // For better understaing
}
</code>```

This footer will visible at the end of the page while scrolling the page

Title: css footer always bottom of page

Body:
How do I make the footer always stay bottom of the page (no sticky)? My footer is at the bottom of the screen, but not on the page.

Here is an example of my code.

HTML

<!DOCTYPE html>

     <meta http-equiv="Content-Type" content="text/html charset=utf-8"/>
     <link href="styles.css" type="text/css" rel="stylesheet">

Header

Body

Footer

CSS

.footer {
    width:100%;
    height:109px;
    position:absolute;
    bottom:0;
    left:0;
    background-color: purple;
}

Body:
By using position:relative and bottom:0, you can make your footer at the end of the page

Modify your style-sheet like this and you can clearly understand the effect

.footer {
width:100%;
height:109px;
position:relative;
bottom:0;
left:0;
background-color: purple;
}
.body {               // I've added this
    height: 1000px;  // For better understaing
}

This footer will visible at the end of the page while scrolling the page


问:
i want key along with value like Barcode:null like this from below json value
{
    "Barcode": null,
    "Brand": null,
    "Color": "RED",
    "Department": null,
    "Depth": 0,
    "DueDate": null,
    "Height": 0,
    "Innerqty": 1000,
    "IsActive": true,
    "IsBuyOutOfStock": false,
    "IsNew": false,
    "IsOutOfStock": false,
    "IsSpecialOffer": false,
    "IsVatApply": false,
    "Isbestdeal": false,
    "ItemType": 1,
    "MSRP": null,
    "MainBigThumb": null,
    "MainImage": null,
    "MainSmallImages": null,
    "Offerprice": 0,
    "Outerqty": 100,
    "Price": 1000,
    "PriceBand": null,
    "ProductDescription": "
Product Description
\r\n",
    "ProductDescription3": "
Product Description3
\r\n",
    "ProductDescription4": "
Product Description4
\r\n",
    "ProductGroupCode": null,
    "ProductImage1_Large": null,
    "ProductImage2": null,
    "ProductImage2_Large": null,
    "ProductImage2_Thumb": null,
    "ProductImage3": null,
    "ProductImage3_Large": null,
    "ProductImage3_Thumb": null,
    "ProductSummary": "Product Summary",
    "ProductVisiblity": "All",
    "Productcode": "Multi-00007",
    "RRP": 1000,
    "Size": "XL",
    "Sku_Description": "Multi-000072",
    "StockDate": null,
    "StockKeepingunit": "Multi-000072_2",
    "StockQty": 100,
    "Supplier": null,
    "SupplierPartNumber": null,
    "Tax_Code": null,
    "Thumbnail": null,
    "UPC": null,
    "UnitOfSale": null,
    "VatProductPostingGroup": null,
    "Vat_Percentage": 10,
    "Weight": 0,
    "Width": 0,
    "isProductConfigurable": false,
    "IndexNumber": null,
    "Web1_Category": null,
    "Web1_Category_1": null,
    "Web1_Category_2": null,
    "Web2_Category": null,
    "Web2_Category_1": null,
    "Web2_Category_2": null,
    "Web_Category": "",
    "Web_Category_1": "",
    "Web_Category_2": ""
} {
    "Barcode": null,
    "Brand": null,
    "Color": "RED",
    "Department": null,
    "Depth": 0,
    "DueDate": null,
    "Height": 0,
    "Innerqty": 1000,
    "IsActive": true,
    "IsBuyOutOfStock": false,
    "IsNew": false,
    "IsOutOfStock": false,
    "IsSpecialOffer": false,
    "IsVatApply": false,
    "Isbestdeal": false,
    "ItemType": 1,
    "MSRP": null,
    "MainBigThumb": "rsz_390b37be04c34a7099951612b09b0efa.jpg",
    "MainImage": "rsz_e4217163f7eb401b9204c4543110925a.jpg",
    "MainSmallImages": "rsz_275e5e51603c49b2ac21ed023965544c.jpg",
    "Offerprice": 0,
    "Outerqty": 100,
    "Price": 1000,
    "PriceBand": null,
    "ProductDescription": "
Product Description
\r\n",
    "ProductDescription3": "
Product Description3
\r\n",
    "ProductDescription4": "
Product Description4
\r\n",
    "ProductGroupCode": null,
    "ProductImage1_Large": "rsz_60f8111b3605457d9f971cf0f60b15f1.jpg",
    "ProductImage2": "rsz_d88eb3ba241a4e60b9b77a46b9165551.jpg",
    "ProductImage2_Large": "rsz_1617bb90f96e41a4925bac2a483d32d1.jpg",
    "ProductImage2_Thumb": "rsz_e57028cc675d4ccdb63640b685447390.jpg",
    "ProductImage3": "rsz_c5d14b3239e348d7a970fa3be583647c.jpg",
    "ProductImage3_Large": "rsz_b9021dde26c6455a95e7849ee795ca1a.jpg",
    "ProductImage3_Thumb": "rsz_b8cd1eb8c9e84593b9e69feb6ce6c8dd.jpg",
    "ProductSummary": "Product Summary",
    "ProductVisiblity": "All",
    "Productcode": "Multi-00007",
    "RRP": 1000,
    "Size": "XL",
    "Sku_Description": "Multi-000072",
    "StockDate": null,
    "StockKeepingunit": "Multi-000072",
    "StockQty": 100,
    "Supplier": null,
    "SupplierPartNumber": null,
    "Tax_Code": null,
    "Thumbnail": "rsz_6a67f865f3e44fdea309cd672145193e.jpg",
    "UPC": null,
    "UnitOfSale": null,
    "VatProductPostingGroup": null,
    "Vat_Percentage": 10,
    "Weight": 0,
    "Width": 0,
    "isProductConfigurable": false,
    "IndexNumber": null,
    "Web1_Category": null,
    "Web1_Category_1": null,
    "Web1_Category_2": null,
    "Web2_Category": null,
    "Web2_Category_1": null,
    "Web2_Category_2": null,
    "Web_Category": "",
    "Web_Category_1": "",
    "Web_Category_2": ""
} {
    "Barcode": null,
    "Brand": null,
    "Color": "RED",
    "Department": null,
    "Depth": 0,
    "DueDate": null,
    "Height": 0,
    "Innerqty": 1000,
    "IsActive": true,
    "IsBuyOutOfStock": false,
    "IsNew": false,
    "IsOutOfStock": false,
    "IsSpecialOffer": false,
    "IsVatApply": false,
    "Isbestdeal": false,
    "ItemType": 1,
    "MSRP": null,
    "MainBigThumb": null,
    "MainImage": null,
    "MainSmallImages": null,
    "Offerprice": 0,
    "Outerqty": 100,
    "Price": 1000,
    "PriceBand": null,
    "ProductDescription": "
Product Description
\r\n",
    "ProductDescription3": "
Product Description3
\r\n",
    "ProductDescription4": "
Product Description4
\r\n",
    "ProductGroupCode": null,
    "ProductImage1_Large": null,
    "ProductImage2": null,
    "ProductImage2_Large": null,
    "ProductImage2_Thumb": null,
    "ProductImage3": null,
    "ProductImage3_Large": null,
    "ProductImage3_Thumb": null,
    "ProductSummary": "Product Summary",
    "ProductVisiblity": "All",
    "Productcode": "Multi-00007",
    "RRP": 1000,
    "Size": "XL",
    "Sku_Description": "Multi-000072",
    "StockDate": null,
    "StockKeepingunit": "Multi-000072_2",
    "StockQty": 100,
    "Supplier": null,
    "SupplierPartNumber": null,
    "Tax_Code": null,
    "Thumbnail": null,
    "UPC": null,
    "UnitOfSale": null,
    "VatProductPostingGroup": null,
    "Vat_Percentage": 10,
    "Weight": 0,
    "Width": 0,
    "isProductConfigurable": false,
    "IndexNumber": null,
    "Web1_Category": null,
    "Web1_Category_1": null,
    "Web1_Category_2": null,
    "Web2_Category": null,
    "Web2_Category_1": null,
    "Web2_Category_2": null,
    "Web_Category": "",
    "Web_Category_1": "",
    "Web_Category_2": ""
}

答:
Try this. </p>

```<code>String json = "[{ Barcode: 5022481129341, Brand: new, Color: null, }] ";
    try {
        JSONArray jsonArray = new JSONArray(json);
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        ArrayList<String> keyArray = new ArrayList<>();
        for(int i = 0; i<jsonObject.names().length(); i++){
            Log.v("", "key = " + jsonObject.names().getString(i) + " value = " + jsonObject.get(jsonObject.names().getString(i)));
            keyArray.add(jsonObject.names().getString(i) + " : " + jsonObject.get(jsonObject.names().getString(i)));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
</code>```

Body:
Try this.

String json = "[{ Barcode: 5022481129341, Brand: new, Color: null, }] ";
    try {
        JSONArray jsonArray = new JSONArray(json);
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        ArrayList<String> keyArray = new ArrayList<>();
        for(int i = 0; i<jsonObject.names().length(); i++){
            Log.v("", "key = " + jsonObject.names().getString(i) + " value = " + jsonObject.get(jsonObject.names().getString(i)));
            keyArray.add(jsonObject.names().getString(i) + " : " + jsonObject.get(jsonObject.names().getString(i)));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }


问:
How to solve: Use of unresolved identifier 'indexPath' in Swift
```<code>func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    return interests.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt cellForItemAtindexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Storyboard.CellIdentifier, forIndexPath:indexPath) as! InterestCollectionViewCell

    cell.interest = self.interest[indexPath.item]

    return cell
}
</code>```

答:
```<code>//MARK:- extension of collection view

extension CreateTapUpFirstVC :  UICollectionViewDelegate, UICollectionViewDataSource , UICollectionViewDelegateFlowLayout{

    // MARK: - Collection View delegate & datasource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

            return arrCategory.count

    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TappUpCell", for: indexPath as IndexPath) as! TappUpCell

        return cell

    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath){

    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        let bounds = UIScreen.main.bounds
        let height = bounds.size.height

        if(height == 736) {
            // return UIEdgeInsetsMake(top, left, bottom, right);
            return UIEdgeInsetsMake(20, 40, 20, 40)
        } else if(height == 667){
            return UIEdgeInsetsMake(20, 40, 20, 40)
        } else if(height == 568) {
            return UIEdgeInsetsMake(20, 20, 10, 20)
        } else if(height == 480) {
            return UIEdgeInsetsMake(20, 20, 10, 20)
        } else {
            return UIEdgeInsetsMake(20, 40, 20, 40)
        }
    }

    func collectionView(_ collectionView: UICollectionView,layout collectionViewLayout: UICollectionViewLayout,minimumLineSpacingForSectionAt section: Int) -> CGFloat {

        let bounds = UIScreen.main.bounds
        // let width = bounds.size.width
        let height = bounds.size.height
        if(height == 736) {
            return 10//20
        } else if(height == 667){
           return 5//15
        } else {
            return 5//10
        }
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

         return CGSize(width: 100.0, height: 100.0);

    }
}
</code>```


问:
Submit an ng-form if focus is not in the textarea

 <ng-form name="ctrl.scaleItemForm" ng-submit="ctrl.submit()">
      <input type="text"
      ng-model="ctrl.scaleItemPF.tareValue"
      name="tare-val-si">

      <textarea name="sectionLayouts"
      ng-trim="false"
      autocomplete="off"
      autocorrect="off"
      autocapitalize="off"
      spellcheck="false">
      </textarea>

      <button type="submit"
      class="button-save">
      Save
      </button>
 </ng-form>```

I am using Angular 1.5.8, In my view, I have a ng-form with ng-submit attached to it so as to trigger submit function on entering key press. I have a textarea inside the ng-form, default behavior when pressing an enter key inside a textarea is a newline, which is happening alongside the submit of the form and I don't want to submit the form if the focus is on texture, instead I need a new line. If replaced with form tag instead of ng-form its working as expected. Is this a bug associated with ng-form or am I doing something wrong

To wrap the question. Don't want to submit the form on entering key press if the focus is on textarea, otherwise, the form should be submitted.

答:
Yes, This is an issue with ng-forms and ng-sumbit.

They are not built to work together. ng-submit is a directive that triggers the submit event of a form tag.
But ng-form is not an HTML5 form its an instance of angular FormController.
This means ng-form with ng-submit does not trigger submit as ng-form does not create an HTML5 form tag. you can see that if you check the HTML in your Application.
So, to round up, you need to use  instead of  directive.

Body:
 <ng-form name="ctrl.scaleItemForm" ng-submit="ctrl.submit()">
      <input type="text"
      ng-model="ctrl.scaleItemPF.tareValue"
      name="tare-val-si">

      <textarea name="sectionLayouts"
      ng-trim="false"
      autocomplete="off"
      autocorrect="off"
      autocapitalize="off"
      spellcheck="false">
      </textarea>

      <button type="submit"
      class="button-save">
      Save
      </button>
 </ng-form>

I am using Angular 1.5.8, In my view, I have a ng-form with ng-submit attached to it so as to trigger submit function on entering key press. I have a textarea inside the ng-form, default behavior when pressing an enter key inside a textarea is a newline, which is happening alongside the submit of the form and I don't want to submit the form if the focus is on texture, instead I need a new line. If replaced with form tag instead of ng-form its working as expected. Is this a bug associated with ng-form or am I doing something wrong

To wrap the question. Don't want to submit the form on entering key press if the focus is on textarea, otherwise, the form should be submitted.


问:
Sending ASCII character to server using Java
I am trying to connect my computer with a device using Socket.

Using my code, I managed to connect to another device using socket.

The connection worked but the problem now is that the device that I am connected to have it's own SDK and it's in ASCII characters.

When I try to send in a command (from the SDK) using String, the code does not work, please advice.

```<code>String Address = txtAddress.getText();
    Socket MyClient;
    try {
        MyClient = new Socket(Address,9993);
        os = new DataOutputStream(MyClient.getOutputStream());
        is = new DataInputStream(MyClient.getInputStream());
        this.main.showUserView();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
         lble.setText("Don't know about host: hostname");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        lble.setText("Couldn't get I/O for the connection to: hostname");
    }
</code>```

答:
Maybe you can try to send data using DatagramPacket?</p>

```<code>int PORT = ## (port we are using for communication)

byte[] strBytes = myString.getBytes();

InetAddress address = InetAddress.getByName(ipAddressString);
DatagramPacket packet = new DatagramPacket(strBytes, strBytes.length, address, PORT);
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
socket.close();
</code>```

Body:
I am trying to connect my computer with a device using Socket.

Using my code, I managed to connect to another device using socket.

The connection worked but the problem now is that the device that I am connected to have it's own SDK and it's in ASCII characters.

When I try to send in a command (from the SDK) using String, the code does not work, please advice.

String Address = txtAddress.getText();
    Socket MyClient;
    try {
        MyClient = new Socket(Address,9993);
        os = new DataOutputStream(MyClient.getOutputStream());
        is = new DataInputStream(MyClient.getInputStream());
        this.main.showUserView();
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
         lble.setText("Don't know about host: hostname");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        lble.setText("Couldn't get I/O for the connection to: hostname");
    }

Body:
Maybe you can try to send data using DatagramPacket?

int PORT = ## (port we are using for communication)

byte[] strBytes = myString.getBytes();

InetAddress address = InetAddress.getByName(ipAddressString);
DatagramPacket packet = new DatagramPacket(strBytes, strBytes.length, address, PORT);
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
socket.close();


问:
Fast (< n^2) clustering algorithm
I have 1 million 5-dimensional points that I need to group into k clusters with k << 1 million. In each cluster, no two points should be too far apart (e.g. they could be bounding spheres with a specified radius). That means that there probably has to be many clusters of size 1.

But! I need the running time to be well below n^2. n log n or so should be fine. The reason I'm doing this clustering is to avoid computing a distance matrix of all n points (which takes n^2 time or many hours), instead I want to just compute distances between clusters.

I tried the pycluster k-means algorithm but quickly realized it's way too slow. I've also tried the following greedy approach:

Slice space into 20 pieces in each dimension. (so there are 20^5 total pieces). I will store clusters in these gridboxes, according to their centroids.

For each point, retrieve the gridboxes that are within r (maximum bounding sphere radius). If there is a near enough cluster, add it to that cluster, otherwise make a new cluster.

However, this seems to give me more clusters than I want. I also implemented approaches similar to this twice, and they give very different answers.

Are there any standard approaches to clustering in faster than n^2 time? Probabilistic algorithms are ok.

答:
Below is a little test bench to see how fast
scipy.spatial.cKDTree
is on your data,
and to get a rough idea of how the distances between nearby points scatter.

A nice way to run K-cluster for various K
is to build an MST of nearest pairs, and remove the K-1 longest; see
Wayne, Greedy Algorithms .

Visualizing the clusters would be fun -- project to 2d with PCA ?

(Just curious, is your K 10, 100, 1000 ?)

Added 17 Dec: real runtimes: 100000 x 5 10 sec, 500000 x 5 60sec

```<code>#!/usr/bin/env python
# time scipy.spatial.cKDTree build, query

from __future__ import division
import random
import sys
import time
import numpy as np
from scipy.spatial import cKDTree as KDTree
    # http://docs.scipy.org/doc/scipy/reference/spatial.html
    # $scipy/spatial/kdtree.py is slow but clean, 0.9 has cython
__date__ = "2010-12-17 dec denis"

def clumpiness( X, nbin=10 ):
    """ how clumpy is X ? histogramdd av, max """
        # effect on kdtree time ? not much
    N, dim = X.shape
    histo = np.histogramdd( X, nbin )[0] .astype(int)  # 10^dim
    n0 = histo.size - histo.astype(bool).sum()  # uniform: 1/e^lambda
    print "clumpiness: %d of %d^%d data bins are empty  av %.2g  max %d" % (
        n0, nbin, dim, histo.mean(), histo.max())

#...............................................................................
N = 100000
nask = 0  # 0: ask all N
dim = 5
rnormal = .9
    # KDtree params --
nnear = 2  # k=nnear+1, self
leafsize = 10
eps = 1  # approximate nearest, dist <= (1 + eps) * true nearest
seed = 1

exec "\n".join( sys.argv[1:] )  # run this.py N= ...
np.random.seed(seed)
np.set_printoptions( 2, threshold=200, suppress=True )  # .2f
nask = nask or N
print "\nkdtree:  dim=%d  N=%d  nask=%d  nnear=%d  rnormal=%.2g  leafsize=%d  eps=%.2g" % (
    dim, N, nask, nnear, rnormal, leafsize, eps)

if rnormal > 0:  # normal point cloud, .9 => many near 1 1 1 axis
    cov = rnormal * np.ones((dim,dim)) + (1 - rnormal) * np.eye(dim)
    data = np.abs( np.random.multivariate_normal( np.zeros(dim), cov, N )) % 1
        # % 1: wrap to unit cube
else:
    data = np.random.uniform( size=(N,dim) )
clumpiness(data)
ask = data if nask == N  else random.sample( data, sample )
t = time.time()

#...............................................................................
datatree = KDTree( data, leafsize=leafsize )  # build the tree
print "%.1f sec to build KDtree of %d points" % (time.time() - t, N)

t = time.time()
distances, ix = datatree.query( ask, k=nnear+1, eps=eps )
print "%.1f sec to query %d points" % (time.time() - t, nask)

distances = distances[:,1:]  # [:,0] is all 0, point to itself
avdist = distances.mean( axis=0 )
maxdist = distances.max( axis=0 )
print "distances to %d nearest: av" % nnear, avdist, "max", maxdist

# kdtree:  dim=5  N=100000  nask=100000  nnear=2  rnormal=0.9  leafsize=10  eps=1
# clumpiness: 42847 of 10^5 data bins are empty  av 1  max 21
# 0.4 sec to build KDtree of 100000 points
# 10.1 sec to query 100000 points
# distances to 2 nearest: av [ 0.07  0.08] max [ 0.15  0.18]

# kdtree:  dim=5  N=500000  nask=500000  nnear=2  rnormal=0.9  leafsize=10  eps=1
# clumpiness: 2562 of 10^5 data bins are empty  av 5  max 80
# 2.5 sec to build KDtree of 500000 points
# 60.1 sec to query 500000 points
# distances to 2 nearest: av [ 0.05  0.06] max [ 0.13  0.13]
# run: 17 Dec 2010 15:23  mac 10.4.11 ppc
</code>```

ContentLicense: CC BY-SA 2.5

Title: Fast (< n^2) clustering algorithm

Body:
Below is a little test bench to see how fast
scipy.spatial.cKDTree
is on your data,
and to get a rough idea of how the distances between nearby points scatter.

A nice way to run K-cluster for various K
is to build an MST of nearest pairs, and remove the K-1 longest; see
Wayne, Greedy Algorithms .

Visualizing the clusters would be fun -- project to 2d with PCA ?

(Just curious, is your K 10, 100, 1000 ?)

Added 17 Dec: real runtimes: 100000 x 5 10 sec, 500000 x 5 60sec

#!/usr/bin/env python
# time scipy.spatial.cKDTree build, query

from __future__ import division
import random
import sys
import time
import numpy as np
from scipy.spatial import cKDTree as KDTree
    # http://docs.scipy.org/doc/scipy/reference/spatial.html
    # $scipy/spatial/kdtree.py is slow but clean, 0.9 has cython
__date__ = "2010-12-17 dec denis"

def clumpiness( X, nbin=10 ):
    """ how clumpy is X ? histogramdd av, max """
        # effect on kdtree time ? not much
    N, dim = X.shape
    histo = np.histogramdd( X, nbin )[0] .astype(int)  # 10^dim
    n0 = histo.size - histo.astype(bool).sum()  # uniform: 1/e^lambda
    print "clumpiness: %d of %d^%d data bins are empty  av %.2g  max %d" % (
        n0, nbin, dim, histo.mean(), histo.max())

#...............................................................................
N = 100000
nask = 0  # 0: ask all N
dim = 5
rnormal = .9
    # KDtree params --
nnear = 2  # k=nnear+1, self
leafsize = 10
eps = 1  # approximate nearest, dist <= (1 + eps) * true nearest
seed = 1

exec "\n".join( sys.argv[1:] )  # run this.py N= ...
np.random.seed(seed)
np.set_printoptions( 2, threshold=200, suppress=True )  # .2f
nask = nask or N
print "\nkdtree:  dim=%d  N=%d  nask=%d  nnear=%d  rnormal=%.2g  leafsize=%d  eps=%.2g" % (
    dim, N, nask, nnear, rnormal, leafsize, eps)

if rnormal > 0:  # normal point cloud, .9 => many near 1 1 1 axis
    cov = rnormal * np.ones((dim,dim)) + (1 - rnormal) * np.eye(dim)
    data = np.abs( np.random.multivariate_normal( np.zeros(dim), cov, N )) % 1
        # % 1: wrap to unit cube
else:
    data = np.random.uniform( size=(N,dim) )
clumpiness(data)
ask = data if nask == N  else random.sample( data, sample )
t = time.time()

#...............................................................................
datatree = KDTree( data, leafsize=leafsize )  # build the tree
print "%.1f sec to build KDtree of %d points" % (time.time() - t, N)

t = time.time()
distances, ix = datatree.query( ask, k=nnear+1, eps=eps )
print "%.1f sec to query %d points" % (time.time() - t, nask)

distances = distances[:,1:]  # [:,0] is all 0, point to itself
avdist = distances.mean( axis=0 )
maxdist = distances.max( axis=0 )
print "distances to %d nearest: av" % nnear, avdist, "max", maxdist

# kdtree:  dim=5  N=100000  nask=100000  nnear=2  rnormal=0.9  leafsize=10  eps=1
# clumpiness: 42847 of 10^5 data bins are empty  av 1  max 21
# 0.4 sec to build KDtree of 100000 points
# 10.1 sec to query 100000 points
# distances to 2 nearest: av [ 0.07  0.08] max [ 0.15  0.18]

# kdtree:  dim=5  N=500000  nask=500000  nnear=2  rnormal=0.9  leafsize=10  eps=1
# clumpiness: 2562 of 10^5 data bins are empty  av 5  max 80
# 2.5 sec to build KDtree of 500000 points
# 60.1 sec to query 500000 points
# distances to 2 nearest: av [ 0.05  0.06] max [ 0.13  0.13]
# run: 17 Dec 2010 15:23  mac 10.4.11 ppc


问:
JPA very strange error when change query parameter
I'm having an strange issue in this query.
Code:

```<code>em2=getNewEntityManager();
(...)
Query query2 = em2.createNativeQuery("SELECT DISTINCT ID_ZONA FROM VWG_REL_USUARIOS_ZONAS WHERE DNI like '"+dni+"'") ;
                List <Long> permisos = query2.getResultList();
(...)
</code>```

If "dni" equals to: "%" the query goes normal, but if "dni" is "%123456789" gives this error

javax.persistence.PersistenceException: Exception [EclipseLink-4002]
  (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b):
  org.eclipse.persistence.exceptions.DatabaseException
          Internal Exception: java.sql.SQLException: sql string is not a dml statement
          Error Code: 17129
          Call: SELECT DISTINCT ID_ZONA FROM VWG_REL_USUARIOS_ZONAS WHERE DNI like '%XX828747B'
          Query: DataReadQuery(sql="SELECT DISTINCT ID_ZONA FROM VWG_REL_USUARIOS_ZONAS WHERE DNI like '%XX828747B'")

And if I copy the exact query above in my SQL developer, it works as magic.
I've tried with the "createQuery" with the entities and all the stuff, same error.

Thanks a lot

答:
Finally I got it, it is working now.

I was changing DNI value in debugging mode in eclipse, to fit the test I want to do. So a session validator invalidated my the user as some of the data "by magic" changed in an strange way. To do the test without compiling every time, I have to change DNI value BEFORE session is created.

What I don't know is why is it giving so specific SQL exception when the error originated validating the session. Something like "session is invalid" would have saved me a couple of hours...

Thanks all for your time

Body:
I'm having an strange issue in this query.
Code:

em2=getNewEntityManager();
(...)
Query query2 = em2.createNativeQuery("SELECT DISTINCT ID_ZONA FROM VWG_REL_USUARIOS_ZONAS WHERE DNI like '"+dni+"'") ;
                List <Long> permisos = query2.getResultList();
(...)

If "dni" equals to: "%" the query goes normal, but if "dni" is "%123456789" gives this error

javax.persistence.PersistenceException: Exception [EclipseLink-4002]
  (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b):
  org.eclipse.persistence.exceptions.DatabaseException
          Internal Exception: java.sql.SQLException: sql string is not a dml statement
          Error Code: 17129
          Call: SELECT DISTINCT ID_ZONA FROM VWG_REL_USUARIOS_ZONAS WHERE DNI like '%XX828747B'
          Query: DataReadQuery(sql="SELECT DISTINCT ID_ZONA FROM VWG_REL_USUARIOS_ZONAS WHERE DNI like '%XX828747B'")

And if I copy the exact query above in my SQL developer, it works as magic.
I've tried with the "createQuery" with the entities and all the stuff, same error.

Thanks a lot


问:
Mongoose inserts document without properties
MongoDB inserts document without properties(look at the bottom of the post to see how my collection looks like).I'm using postman to test my db when I try to insert the following:

```<code>{
    "username":"JohnDoe",
    "password" : "123456"
}
</code>```

I'm building a MEAN stack application.Also, I noticed if I set the properties to be required, postman tells me that it Failed to register user. That's why I comment it out, but even without it and getting a postive response I still get empty documents in my collection.

Postman tells me:

```<code>{
  "success": true,
  "msg": "User registered"
}
</code>```

My user.js file

```<code> const bcrypt = require ('bcryptjs');
    const config = require ('../config/database');

    //UserSchema

    const UserSchema = mongoose.Schema({
        username: {
            type: String,
            //required: true
        },
        password: {
            type: String,
            //required: true
        }

    });

    const User = module.exports = mongoose.model("User", UserSchema);

    //To user function outside
    module.exports.getUserById = function(id, callback){
        User.findById(id,callback);
    }

    module.exports.getUserByUsername= function(username, callback){
        const query = {username: username}
        User.findOne (query,callback);
    }

    User.addUser = function (newUser, callback) {
        bcrypt.genSalt(10, (err, salt) =>{
            bcrypt.hash(newUser.password, salt, (err, hash) => {

                newUser.password = hash;
                newUser.save(callback);
            });
        });
    }
</code>```

My users.js file:

```<code>const express = require('express');
const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
const User = require('../modules/user');

// Register
router.post('/register', (req, res, next) => {
  let newUser = new User({
    username: req.body.username,
    password: req.body.password
  });

  User.addUser(newUser, (err, user) => {
    if(err){
      res.json({success: false, msg:'Failed to register user'});
    } else {
      res.json({success: true, msg:'User registered'});
    }
  });
});

module.exports = router;
</code>```

What I see in my collection:

```<code>{
    "_id": {
        "$oid": "5937b36bafdd733088cb27d0"
    },
    "__v": 0
}
</code>```

答:
You should learn about what is mongoose statics and methods.

In User model you should be declaring the functions as methods and statics based on the way you want it.

```<code>const bcrypt = require ('bcryptjs');
const config = require ('../config/database');

//UserSchema

const UserSchema = mongoose.Schema({
    username: {
        type: String,
        //required: true
    },
    password: {
        type: String,
        //required: true
    }

});

//To user function outside
UserSchema.statics.getUserById = function(id, callback){
    User.findById(id,callback);
}

UserSchema.statics.getUserByUsername= function(username, callback){
    const query = {username: username}
    User.findOne (query,callback);
}

UserSchema.methods.addUser = function (callback) {
    bcrypt.genSalt(10, (err, salt) =>{
        bcrypt.hash(newUser.password, salt, (err, hash) => {

            this.password = hash;
            this.save(callback);
        });
    });
}

exports.User = mongoose.model("User", UserSchema);
</code>```

In your controller user file, you should use addUser with your instance of the User model not on the Model you exporting. Check below..

```<code>const express = require('express');
const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
const User = require('../modules/user');

// Register
router.post('/register', (req, res, next) => {
  let newUser = new User({
    username: req.body.username,
    password: req.body.password
  });

  newUser.addUser(function(err, user) => {
    if(err){
      res.json({success: false, msg:'Failed to register user'});
    } else {
      res.json({success: true, msg:'User registered'});
    }
  });
});

module.exports = router;
</code>```

Body:
MongoDB inserts document without properties(look at the bottom of the post to see how my collection looks like).I'm using postman to test my db when I try to insert the following:

{
    "username":"JohnDoe",
    "password" : "123456"
}

I'm building a MEAN stack application.Also, I noticed if I set the properties to be required, postman tells me that it Failed to register user. That's why I comment it out, but even without it and getting a postive response I still get empty documents in my collection.

Postman tells me:

{
  "success": true,
  "msg": "User registered"
}

My user.js file

 const bcrypt = require ('bcryptjs');
    const config = require ('../config/database');

    //UserSchema

    const UserSchema = mongoose.Schema({
        username: {
            type: String,
            //required: true
        },
        password: {
            type: String,
            //required: true
        }

    });

    const User = module.exports = mongoose.model("User", UserSchema);

    //To user function outside
    module.exports.getUserById = function(id, callback){
        User.findById(id,callback);
    }

    module.exports.getUserByUsername= function(username, callback){
        const query = {username: username}
        User.findOne (query,callback);
    }

    User.addUser = function (newUser, callback) {
        bcrypt.genSalt(10, (err, salt) =>{
            bcrypt.hash(newUser.password, salt, (err, hash) => {

                newUser.password = hash;
                newUser.save(callback);
            });
        });
    }

My users.js file:

const express = require('express');
const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
const User = require('../modules/user');

// Register
router.post('/register', (req, res, next) => {
  let newUser = new User({
    username: req.body.username,
    password: req.body.password
  });

  User.addUser(newUser, (err, user) => {
    if(err){
      res.json({success: false, msg:'Failed to register user'});
    } else {
      res.json({success: true, msg:'User registered'});
    }
  });
});

module.exports = router;

What I see in my collection:

{
    "_id": {
        "$oid": "5937b36bafdd733088cb27d0"
    },
    "__v": 0
}

Body:
You should learn about what is mongoose statics and methods.

In User model you should be declaring the functions as methods and statics based on the way you want it.

const bcrypt = require ('bcryptjs');
const config = require ('../config/database');

//UserSchema

const UserSchema = mongoose.Schema({
    username: {
        type: String,
        //required: true
    },
    password: {
        type: String,
        //required: true
    }

});

//To user function outside
UserSchema.statics.getUserById = function(id, callback){
    User.findById(id,callback);
}

UserSchema.statics.getUserByUsername= function(username, callback){
    const query = {username: username}
    User.findOne (query,callback);
}

UserSchema.methods.addUser = function (callback) {
    bcrypt.genSalt(10, (err, salt) =>{
        bcrypt.hash(newUser.password, salt, (err, hash) => {

            this.password = hash;
            this.save(callback);
        });
    });
}

exports.User = mongoose.model("User", UserSchema);

In your controller user file, you should use addUser with your instance of the User model not on the Model you exporting. Check below..

const express = require('express');
const router = express.Router();
const passport = require('passport');
const jwt = require('jsonwebtoken');
const User = require('../modules/user');

// Register
router.post('/register', (req, res, next) => {
  let newUser = new User({
    username: req.body.username,
    password: req.body.password
  });

  newUser.addUser(function(err, user) => {
    if(err){
      res.json({success: false, msg:'Failed to register user'});
    } else {
      res.json({success: true, msg:'User registered'});
    }
  });
});

module.exports = router;


问:
Not able to get contents of JSON / Array in PHP
new to php.... can't seem to get the contents of this array... ie. trying to do: $key = var0  and  $value = string0

This is what I am trying the following, with no success:

```<code>$getJSON = [
    {
        "item0": [
            {"var0":"string0"},
            {"var1":"string1"},
            {"var2":"string2"},
            {"var3":"string3"}
        ]
    }
]

$arr = json_decode( $getJSON, true );

$test1 = $arr[0]['item0']['var0'];
$test2 = $arr['item0']['var0'];
</code>```

答:
```<code>First change Desing of json pattern

$getJSON = '{"item0":[
                        {"var0":"string0"},
                        {"var1":"string1"},
                        {"var2":"string2"},
                        {"var3":"string3"}
                     ]
            }';

use json_decode function for get json data

$arr = json_decode( $getJSON);

echo $arr->item0[0]->var0.'</br>';
echo $arr->item0[1]->var1.'</br>';
echo $arr->item0[2]->var2.'</br>';
echo $arr->item0[3]->var3.'</br>';
</code>```

Body:
new to php.... can't seem to get the contents of this array... ie. trying to do: $key = var0  and  $value = string0

This is what I am trying the following, with no success:

$getJSON = [
    {
        "item0": [
            {"var0":"string0"},
            {"var1":"string1"},
            {"var2":"string2"},
            {"var3":"string3"}
        ]
    }
]

$arr = json_decode( $getJSON, true );

$test1 = $arr[0]['item0']['var0'];
$test2 = $arr['item0']['var0'];


问:
Reporting Services Custom Assembly
I created a custom assembly to convert RTF to plain text and it works nice with the following configuration:  SSRS 2008, Win 2003 Server, rssrvpolicy.config changes, an Excecution Account, and IIS 6.0.

We created a new server running SSRS 2008R2, Win 2008, and IIS 7.  It does not work on this new environment and I do not get any error, but instead the SSRS Service reboots itself.  This only happens when I reference System.Windows.Forms.RichTextBox().  See code below.

Can anyone give me an idea of what I may need to do or test to get this working?  I've checked the log files and the Event Viewer, but not seeing any errors.  It does call my assembly and works if I just output some text to the report and not call the RichTextControl.  It fails when I try to reference System.Windows.Forms.RichTextBox.  I also installed to the GAC with no luck, but shouldn't need to(?) and didn't with the old version.

I also tried to put a try/catch block around the code to see if I could get the error.  If I just throw an error, I get the message.  If I call the RichTextBox control, it causes the SSRS service to reboot.

My code:

```<code>using System;
using System.Windows.Forms;
using System.Diagnostics;
namespace ConversionUtility
{
    public class ConversionUtility
    {
        [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Assert, Unrestricted = true)]
        public static string ConvertRTFToText(string richText)
        {
            string sText = "";

            try
            {
                // if I comment out these 3 lines, this will work
                RichTextBox richTextBox = new System.Windows.Forms.RichTextBox();
                richTextBox.Rtf = richText;
                sText = richTextBox.Text;
                //throw new Exception("Log this error");
            }
            catch (Exception e)
            {
                sText = "Error Caught: " + e.Message;
            }

            return sText;
        }
    }
}
</code>```

I have these permissions defined.  I add the CodeGroup below and it works if I don't reference the RichTextBox.  The service reboots as soon as I try to reference System.Forms.Windows.RichTextBox()

```<code><CodeGroup
class="UnionCodeGroup"
version="1"
Name="SecurityExtensionCodeGroup"
Description="Code group Conversion Utility"
PermissionSetName="FullTrust">
<IMembershipCondition
    class="UrlMembershipCondition"
    version="1"
    Url="C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportServer\bin        \ConversionUtility.dll"
/>
</code>```

I'm thinking it's having an issue with permissions to System.Windows.Forms, but haven't been able to figure out what I need to do.

Thanks in advance,

Randy

答:
I ended up contacting Microsoft because this should have worked.  When I gave them a sample application in worked in their environment.  It turned out that they had a hotfix installed for Reporting Services that I did not.  After I installed the hotfix, everything worked.

build 10.50.1720 - applied CU2 for SSRS 2008 R2 RTM (http://support.microsoft.com/kb/2072493).

Title: Reporting Services Custom Assembly

Body:
I created a custom assembly to convert RTF to plain text and it works nice with the following configuration:  SSRS 2008, Win 2003 Server, rssrvpolicy.config changes, an Excecution Account, and IIS 6.0.

We created a new server running SSRS 2008R2, Win 2008, and IIS 7.  It does not work on this new environment and I do not get any error, but instead the SSRS Service reboots itself.  This only happens when I reference System.Windows.Forms.RichTextBox().  See code below.

Can anyone give me an idea of what I may need to do or test to get this working?  I've checked the log files and the Event Viewer, but not seeing any errors.  It does call my assembly and works if I just output some text to the report and not call the RichTextControl.  It fails when I try to reference System.Windows.Forms.RichTextBox.  I also installed to the GAC with no luck, but shouldn't need to(?) and didn't with the old version.

I also tried to put a try/catch block around the code to see if I could get the error.  If I just throw an error, I get the message.  If I call the RichTextBox control, it causes the SSRS service to reboot.

My code:

using System;
using System.Windows.Forms;
using System.Diagnostics;
namespace ConversionUtility
{
    public class ConversionUtility
    {
        [System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Assert, Unrestricted = true)]
        public static string ConvertRTFToText(string richText)
        {
            string sText = "";

            try
            {
                // if I comment out these 3 lines, this will work
                RichTextBox richTextBox = new System.Windows.Forms.RichTextBox();
                richTextBox.Rtf = richText;
                sText = richTextBox.Text;
                //throw new Exception("Log this error");
            }
            catch (Exception e)
            {
                sText = "Error Caught: " + e.Message;
            }

            return sText;
        }
    }
}

I have these permissions defined.  I add the CodeGroup below and it works if I don't reference the RichTextBox.  The service reboots as soon as I try to reference System.Forms.Windows.RichTextBox()

<CodeGroup
class="UnionCodeGroup"
version="1"
Name="SecurityExtensionCodeGroup"
Description="Code group Conversion Utility"
PermissionSetName="FullTrust">
<IMembershipCondition
    class="UrlMembershipCondition"
    version="1"
    Url="C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportServer\bin        \ConversionUtility.dll"
/>

I'm thinking it's having an issue with permissions to System.Windows.Forms, but haven't been able to figure out what I need to do.

Thanks in advance,

Randy


问:
JQuery how to submit only changed fields when the form has some data array
I have a database structure with an one to many relationship. In the html form, there are similar inputs with a name 'item[]' or 'file[]' to make the data to be an array

```<code><form action="submit.php" method="get">
  Name:<input type="text" name="name"/><br/>
  Item:<input type="text" name="item[]"/><br/>
  File:<input type="file" name="file[]" multiple/>
  Item:<input type="text" name="item[]"/><br/>
  File:<input type="file" name="file[]" multiple/>
  Select:<select name="select" value="1" original="1">
  <option value="1">One</option>
  <option value="2">Two</option>
  </select>

</form>
</code>```

how can i submit only the changed field, and in the server side i can recongize which item is changed? I tried disable the inputs, but it seems not working.

another problem is that if i submit the form with ajax, how can i submit the files

答:
You could solve this with jQuery and add a class on every changed input

Than you can disable all inputs without the class and submit the form

$(document).ready(function() {
  $('input, select, textarea').on('change', function() {
    $(this).addClass('changed');
  });

  $('form').on('submit', function() {
    $('input:not(.changed), textarea:not(.changed)').prop('disabled', true);

    // alert and return just for showing
    alert($(this).serialize().replace('%5B', '[').replace('%5D', ']'));
    return false;
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="submit.php" method="get">
  Name:<input type="text" name="name" /><br/><br/>
  Item:<input type="text" name="item[]" /><br/><br/>
  File:<input type="file" name="file[]" multiple /><br/><br/>
  Item:<input type="text" name="item[]" /><br/><br/>
  File:<input type="file" name="file[]" multiple /><br/><br/>
  Select:<select name="select" value="1" original="1">
  <option value="" selected="selected" disabled="disabled"></option>
  <option value="1">One</option>
  <option value="2">Two</option>
  </select><br/><br/>
  <button type="submit">send</button>
</form></code>```

You could use indexes in the name attribute like this <input type="text" name="item[1]" />

Body:
I have a database structure with an one to many relationship. In the html form, there are similar inputs with a name 'item[]' or 'file[]' to make the data to be an array

<form action="submit.php" method="get">
  Name:<input type="text" name="name"/>

  Item:<input type="text" name="item[]"/>

  File:<input type="file" name="file[]" multiple/>
  Item:<input type="text" name="item[]"/>

  File:<input type="file" name="file[]" multiple/>
  Select:<select name="select" value="1" original="1">
  <option value="1">One</option>
  <option value="2">Two</option>
  </select>

</form>

how can i submit only the changed field, and in the server side i can recongize which item is changed? I tried disable the inputs, but it seems not working.

another problem is that if i submit the form with ajax, how can i submit the files

Body:
You could solve this with jQuery and add a class on every changed input

Than you can disable all inputs without the class and submit the form

$(document).ready(function() {
  $('input, select, textarea').on('change', function() {
    $(this).addClass('changed');
  });

  $('form').on('submit', function() {
    $('input:not(.changed), textarea:not(.changed)').prop('disabled', true);

    // alert and return just for showing
    alert($(this).serialize().replace('%5B', '[').replace('%5D', ']'));
    return false;
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="submit.php" method="get">
  Name:<input type="text" name="name" /><br/><br/>
  Item:<input type="text" name="item[]" /><br/><br/>
  File:<input type="file" name="file[]" multiple /><br/><br/>
  Item:<input type="text" name="item[]" /><br/><br/>
  File:<input type="file" name="file[]" multiple /><br/><br/>
  Select:<select name="select" value="1" original="1">
  <option value="" selected="selected" disabled="disabled"></option>
  <option value="1">One</option>
  <option value="2">Two</option>
  </select><br/><br/>
  <button type="submit">send</button>
</form>

You could use indexes in the name attribute like this <input type="text" name="item[1]" />


问:
What's the purpose to use Viewstate in asp. net
It is being said that Viewstate is used to retain state between request, but let's have a scenario like this:
I have a textbox starts with 0,  and a button to increment +1. Below are steps:

Initially it was a get request to get the page, so the text in the textbox is 0.

I clicked the button, the value 0 was being postback to the server.

The method in the event handler on the server  increment the value by 1, then value one is sent to my browser.

Now the 1 was  being displayed in the textbox on my browser, and I clicked the button again, 1 is sent to the server again

Same as step 3, and then  I will have 2 displayed in the textbox.

As you can see, I don't need to use Viewstate to "remember" values in previous request, I know textbox in asp.net will use Viewstate by default even though enableviewstate is set to be false, so just ignore that, whatz the purpose of using viewstate in my example?

答:
Digression:

Note that you're asking about ASP.NET WebForms, which is now effectively deprecated. It's an abstraction layer in ASP.NET which was meant to make designing stateful data entry web-pages ("web forms") easy by mimicking how VB6 and WinForms works (with "server-side events" and "controls"), however it is a very leaky abstraction which falls apart whenever you need precise control of the web-application which is why WebForms is not popular today and why ASP.NET MVC has taken its place (and WebForms isn't even supported by ASP.NET Core (formerly known as ASP.NET 5)).

Back on-topic:

As you've observed, values which are directly POSTed back to the server (because they're inside <input /> elements) do not benefit from ViewState at all - however ASP.NET WebForms' Controls have many properties and values which will not be contained within their own <input /> element, such as (for example) <asp:Label>'s Text="" property:

I'll illustrate:

MyPage.aspx:

```<code><form runat="server">
    <p>Name: <input runat="server" id="name" type="text" /></p>
    <p>Special message: <asp:Label runat="server" id="message" /></p>
    <asp:Button runat="server" id="submit" text="Set name" />
    <asp:Button runat="server" id="somethingElse" text="Submit form" />
</form>
</code>```

MyPage.aspx.cs ("code-behind" page):

```<code>protected override void submit_ServerClick(Object sender, EventArgs e) {

    this.message.Text = "Congratulations to " + this.name + ", our 1,000,000th customer!"; // https://www.youtube.com/watch?v=suyQ44rRL5M
    this.name.Text = "";
}
</code>```

If the user enters their name in the <input id="name" /> textbox

then clicks the "Set name" button

then their name will appear in the <asp:Label id="message" />

(the code also clears the name input)

then if the user clicks the "Submit form" button without entering their name again, the <asp:Label /> will retain the displayed message - even though their name was never in any of the <input /> elements!

This works because the text of the label was actually resubmitted inside the hidden __VIEWSTATE value, and the page was reconstructed (behind the scenes, inside ASP.NET) for it to be rendered again.

Here's another way of looking at it:

```<code>C > S : client-to-server (web-browser to web-server)
S > C : server-to-client (web-server response to user's browser)

C > S - GET /MyPage.aspx (no form data)
S < C - OK                name="", __VIEWSTATE=""
C > S - POST /MyPage.aspx name="Foo", __VIEWSTATE=""
S < C - OK                name="", __VIEWSTATE="message.Text:\"Congratulations to foo, our 1,000,000th customer!\""
C > S - POST /MyPage.aspx name="", __VIEWSTATE="message.Text:\"Congratulations to foo, our 1,000,000th customer!\""
S < C - OK                name="", __VIEWSTATE="message.Text:\"Congratulations to foo, our 1,000,000th customer!\""
</code>```

Even though the name="" field is cleared after it's set, the original supplied value ("foo") is retained in the __VIEWSTATE field.

Remember that __VIEWSTATE is an opaque blob as far as the client web-browser is concerned: it's a HMAC-signed Base64-encoded string that is not decoded or read by consumers, only by the server. Developers can also enable encryption of the __VIEWSTATE value (though this should have been enabled by default, IMO). It works similarly to a HTTP cookie that contains a security token. (ViewState is not compatible with cookies because it's specific to a single page, not a HTTP session, and it can often reach sizes in the megabytes which is too big for a cookie anyway).

I feel WebForms was an interesting experiment for the web - but it added a lot of complexity which was arguably unnecessary, and WebForms applications were inherently non-RESTful, which broke many assumptions about the web that we can now take for granted - for example, it made it almost impossible to automate web-applications through simple requests (e.g. you would need to replay every intermediate viewstate-mutating request) and if a resource was only accessible via a WebForms postback (e.g. because of a "server-side event handler") then it would break bookmarks. One particularly egregious sin was the use of <asp:Hyperlink> that wasn't an href=""> at all, but would instead cause a POST followed by a HTTP Redirection (via Response.Redirect in the link's "server-side click" event handler).

Body:
Digression:

Note that you're asking about ASP.NET WebForms, which is now effectively deprecated. It's an abstraction layer in ASP.NET which was meant to make designing stateful data entry web-pages ("web forms") easy by mimicking how VB6 and WinForms works (with "server-side events" and "controls"), however it is a very leaky abstraction which falls apart whenever you need precise control of the web-application which is why WebForms is not popular today and why ASP.NET MVC has taken its place (and WebForms isn't even supported by ASP.NET Core (formerly known as ASP.NET 5)).

Back on-topic:

As you've observed, values which are directly POSTed back to the server (because they're inside <input /> elements) do not benefit from ViewState at all - however ASP.NET WebForms' Controls have many properties and values which will not be contained within their own <input /> element, such as (for example) <asp:Label>'s Text="" property:

I'll illustrate:

MyPage.aspx:

<form runat="server">
    <p>Name: <input runat="server" id="name" type="text" /></p>
    <p>Special message: <asp:Label runat="server" id="message" /></p>
    <asp:Button runat="server" id="submit" text="Set name" />
    <asp:Button runat="server" id="somethingElse" text="Submit form" />
</form>

MyPage.aspx.cs ("code-behind" page):

protected override void submit_ServerClick(Object sender, EventArgs e) {

    this.message.Text = "Congratulations to " + this.name + ", our 1,000,000th customer!"; // https://www.youtube.com/watch?v=suyQ44rRL5M
    this.name.Text = "";
}

If the user enters their name in the <input id="name" /> textbox

then clicks the "Set name" button

then their name will appear in the <asp:Label id="message" />

(the code also clears the name input)

then if the user clicks the "Submit form" button without entering their name again, the <asp:Label /> will retain the displayed message - even though their name was never in any of the <input /> elements!

This works because the text of the label was actually resubmitted inside the hidden __VIEWSTATE value, and the page was reconstructed (behind the scenes, inside ASP.NET) for it to be rendered again.

Here's another way of looking at it:

C > S : client-to-server (web-browser to web-server)
S > C : server-to-client (web-server response to user's browser)

C > S - GET /MyPage.aspx (no form data)
S < C - OK                name="", __VIEWSTATE=""
C > S - POST /MyPage.aspx name="Foo", __VIEWSTATE=""
S < C - OK                name="", __VIEWSTATE="message.Text:\"Congratulations to foo, our 1,000,000th customer!\""
C > S - POST /MyPage.aspx name="", __VIEWSTATE="message.Text:\"Congratulations to foo, our 1,000,000th customer!\""
S < C - OK                name="", __VIEWSTATE="message.Text:\"Congratulations to foo, our 1,000,000th customer!\""

Even though the name="" field is cleared after it's set, the original supplied value ("foo") is retained in the __VIEWSTATE field.

Remember that __VIEWSTATE is an opaque blob as far as the client web-browser is concerned: it's a HMAC-signed Base64-encoded string that is not decoded or read by consumers, only by the server. Developers can also enable encryption of the __VIEWSTATE value (though this should have been enabled by default, IMO). It works similarly to a HTTP cookie that contains a security token. (ViewState is not compatible with cookies because it's specific to a single page, not a HTTP session, and it can often reach sizes in the megabytes which is too big for a cookie anyway).

I feel WebForms was an interesting experiment for the web - but it added a lot of complexity which was arguably unnecessary, and WebForms applications were inherently non-RESTful, which broke many assumptions about the web that we can now take for granted - for example, it made it almost impossible to automate web-applications through simple requests (e.g. you would need to replay every intermediate viewstate-mutating request) and if a resource was only accessible via a WebForms postback (e.g. because of a "server-side event handler") then it would break bookmarks. One particularly egregious sin was the use of <asp:Hyperlink> that wasn't an <a href=""> at all, but would instead cause a POST followed by a HTTP Redirection (via Response.Redirect in the link's "server-side click" event handler).


问:
Optimized mysql queries in mysql database
I want to fetch 3 rows data from class table who is belongs to class 5,6 and 7 last row only.

Right now I'm using 3 sql queries to fetch data:

```<code> 1. SELECT * from class where class_name = '5';

 2. SELECT * from class where class_name = '6';

 3. SELECT * from class where class_name = '7';
</code>```

How can I use single sql query to retrieve 3 row data instead of 3 sql queries ?

```<code>**class table structure:**

|id | class_name | student  |
|---| -----------| ---------|
|1  |      5     | Student A|
|2  |      6     | Student B|
|3  |      4     | Student C|
|4  |      6     | Student D|
|5  |      7     | Student E|
|6  |      5     | Student F|
|7  |      4     | Student G|
|8  |      6     | Student H|
|9  |      5     | Student I|
|10 |      6     | Student J|
|11 |      7     | Student K|
|12 |      6     | Student L|
|13 |      8     | Student M|
|14 |      6     | Student N|
|15 |      8     | Student O|
</code>```

Result required:
Student I,Student N and Student K

答:
```<code>SELECT * from (SELECT * from class ORDER BY id  DESC) t WHERE class_name in (5,6,7) GROUP BY class_name ORDER BY id DESC
</code>```

Body:
I want to fetch 3 rows data from class table who is belongs to class 5,6 and 7 last row only.

Right now I'm using 3 sql queries to fetch data:

 1. SELECT * from class where class_name = '5';

 2. SELECT * from class where class_name = '6';

 3. SELECT * from class where class_name = '7';

How can I use single sql query to retrieve 3 row data instead of 3 sql queries ?

**class table structure:**

|id | class_name | student  |
|---| -----------| ---------|
|1  |      5     | Student A|
|2  |      6     | Student B|
|3  |      4     | Student C|
|4  |      6     | Student D|
|5  |      7     | Student E|
|6  |      5     | Student F|
|7  |      4     | Student G|
|8  |      6     | Student H|
|9  |      5     | Student I|
|10 |      6     | Student J|
|11 |      7     | Student K|
|12 |      6     | Student L|
|13 |      8     | Student M|
|14 |      6     | Student N|
|15 |      8     | Student O|

Result required:
Student I,Student N and Student K


问:
Call to undefined method CI_DB_mysqli_driver::and()
```<code>$q_cat_beauty = $this->db->select('*')->from('ms_categories')->where('source_id', 1)->and('category_name', 'Oral Care')->get();
</code>```

i am trying to fetch the category name from my table.

答:
There is no   and keyword or method in CI. If you want where with and condition you again have to write where

```<code>$q_cat_beauty = $this->db->select('*')->from('ms_categories')
->where('source_id', 1)->where('category_name', 'Oral Care')->get();
</code>```

or use array in where

```<code>$q_cat_beauty = $this->db->select('*')->from('ms_categories')
->where(array('source_id'=> 1,'category_name' => 'Oral Care'))->get();
</code>```

Body:
$q_cat_beauty = $this->db->select('*')->from('ms_categories')->where('source_id', 1)->and('category_name', 'Oral Care')->get();

i am trying to fetch the category name from my table.

Body:
There is no   and keyword or method in CI. If you want where with and condition you again have to write where

$q_cat_beauty = $this->db->select('*')->from('ms_categories')
->where('source_id', 1)->where('category_name', 'Oral Care')->get();

or use array in where

$q_cat_beauty = $this->db->select('*')->from('ms_categories')
->where(array('source_id'=> 1,'category_name' => 'Oral Care'))->get();


问:
Why do you need to import React multiple times in parent and child components?
If you have a parent component file that already imports React, why does any of its rendered children files also need to import React? Is it just a safety measure in case those children are ever rendered somewhere else where React has not been imported yet?

答:
In nodejs each file is a module, that has its own scope of variables. When you import variable into file (React for example) you add this variable to the module scope, but not to the global scope.

In case of webpack you can use providePlugin to easily make React variable global:

```<code>new webpack.ProvidePlugin({
  React: 'react' // ReactJS module name in node_modules folder
})
</code>```

After that you are able to skip importing React variable in all of your modules. Webpack will do it itself where needed.

Body:
In nodejs each file is a module, that has its own scope of variables. When you import variable into file (React for example) you add this variable to the module scope, but not to the global scope.

In case of webpack you can use providePlugin to easily make React variable global:

new webpack.ProvidePlugin({
  React: 'react' // ReactJS module name in node_modules folder
})

After that you are able to skip importing React variable in all of your modules. Webpack will do it itself where needed.


问:
images not staying in place, dragging with adjustment of window
When I put some images on the page they will move across the screen when I try
and adjust the size of the window on my browser. The images I'm talking about in css are coded as .ex { position: absolute; top: 200px; right 200px; } and they move across the screen but some do not. why does this happen and how can I prevent it.

#logo {
  text-align: center;
  position: absolute;
  top: 0;
  right: 750px;
}

#logoleft {
  float: left;
  position: absolute;
  top: 0;
  left: 500px;
}

#logoright {
  float: right;
  position: absolute;
  top: 0;
  right: 420px;
}

#leftleft {
  position: absolute;
  left: 270px;
}

#rightright {
  position: absolute;
  right: 180px;
}

#bdlogo {
  position: absolute;
  top: 500px;
  left: 220px;
}

#logobelow {
  position: absolute;
  top: 150px;
  right: 750px;
}

#logoprayer {
  position: absolute;
  right: 200px;
  top: 500px;
}

#gc {
  position: fixed;
  top: 10px;
  right: 20px;
}

#ib {
  position: fixed;
  top: 10px;
  left: 70px;
}

#fc {
  position: fixed;
  top: 350px;
  right: 1040px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="rightright"><img src="data/pics/mr.png" width="140px;" height="140px;">
  <!--randomness-->
</div>
<div id="leftleft"><img src="data/pics/lr.png" width="140px;" height="140px;">
  <!--randomness-->
</div>
<div id="logoleft"><img src="data/pics/wom.png" width="145px" height="340px">
  <!--randomness-->
</div>
<div id="logo">
  <img src="data/pics/rslogo.png" width="450px;" height="170px;">
    <!--randomness-->

</div>
<div id="logoright"><img src="data/pics/emt.png" width="245px;" height="340px;">
  <!--randomness-->
</div>
<div id="bdlogo"><img src="data/pics/bd.gif">
  <!--randomness-->
</div>
<div id="logobelow">
  <img src="data/pics/fs.png">
    <!--randomness-->

</div>
<div id="logoprayer"><img src="data/pics/rc.gif" width="195px;" height="300px;">
  <!--randomness-->
</div>
<div id="gc"><img src="data/pics/gc.png" width="95px;" height="95px;">
  <!--randomness-->
</div>
<div id="ib"><img src="data/pics/ib.png" width="65px;" height="65px;">
  <!--randomness-->
</div>
<div id="fc"><img src="data/pics/fc.png" width="90" ; height="90" ;>
  <!--randomness-->
</div></code>```

答:
A jsfiddle example would be much nicer.
Absolute positioning is relative to the images parent.
The parent of these images changes so the images move.
What you could do is determine the width of the parent which has position relative.If the parent won't move the images won't move.

If you add a jsfiddle or plunker example, it will be easy to fix.


问:
Error in docker-compose build. version issue
i have docker-compose installed with version 1.13

```<code> docker-compose --version
 docker-compose version 1.13.0, build 1719ceb
</code>```

but when i run docker-compose build it says

ERROR: The Docker Engine version is less than the minimum required by
  Compose. Your current project requires a Docker Engine of version
  1.13.0 or greater.

i have tried to upgrade it to version 1.14 using
https://github.com/docker/compose/releases

but i gives same response.

答: What version of Docker engine are you using? You need to upgrade Docker engine version as Docker compose format needs later version of Docker engine. </p>

Body:
i have docker-compose installed with version 1.13

 docker-compose --version
 docker-compose version 1.13.0, build 1719ceb

but when i run docker-compose build it says

ERROR: The Docker Engine version is less than the minimum required by
  Compose. Your current project requires a Docker Engine of version
  1.13.0 or greater.

i have tried to upgrade it to version 1.14 using
https://github.com/docker/compose/releases

but i gives same response.


问:
CentOS: delete line contain string in txt files
The title look familiar but it's different requirement.

I have 2 txt file:
 first one :

```<code>./aaa/bbb/ccc.txt
./hhh/fff.txt
./abc.txt
./gh/gh/jj.txt
</code>```

second :

```<code> fff
 abc
</code>```

Expected result:

```<code>./aaa/bbb/ccc.txt
./gh/gh/jj.txt
</code>```

Second file contain only file name (with out extension).
I want to remove all lines in first file with have file name in second file.

Please help thanks

答:
```<code>grep -Fvf second_file first_file
</code>```

Explanation:

```<code>-F: use literal strings instead of the default BRE
-v: print non-matching
-f file: take patterns from the given file
</code>```

Body:
The title look familiar but it's different requirement.

I have 2 txt file:
 first one :

./aaa/bbb/ccc.txt
./hhh/fff.txt
./abc.txt
./gh/gh/jj.txt

second :

 fff
 abc

Expected result:

./aaa/bbb/ccc.txt
./gh/gh/jj.txt

Second file contain only file name (with out extension).
I want to remove all lines in first file with have file name in second file.

Please help thanks

Body:
grep -Fvf second_file first_file

Explanation:

-F: use literal strings instead of the default BRE
-v: print non-matching
-f file: take patterns from the given file


答:
You can add the "changed" class to desired elements on change and send data of elements  those have not the class "changed":

```<code><form action="submit.php" method="get" id="myform">
  Name:<input type="text" name="name"/><br/>
  Item:<input type="text" name="item[]"/><br/>
  File:<input type="file" name="file[]" multiple/>
  Item:<input type="text" name="item[]"/><br/>
  File:<input type="file" name="file[]" multiple/>
  Select:<select name="select" value="1" original="1">
  <option value="1">One</option>
  <option value="2">Two</option>
  </select>
<input type="submit" id="submit">
</form>
</code>```

listening for changes:

```<code>$("input,select").on("change",function(){
   $(this).addClass("changed");
})
</code>```

handle data by ajax call and prevent form submission by return false and reset the changed class to nothing:

```<code>$("#myform").on("submit",function(){

//Collecting data from changed class:
var data;
$(".changed").each(function(){
data=data+$(this).attr("name")+":"+$(this).val()+",";
});

//just removing last comma:
data=data.substring(0, data.length - 1);

//Submit data:
$.ajax({
    ...
    data : { data },
    ...
    success: function(){
    //Removing changed class from all elements
    $(".changed").removeClass("changed");
    }
});

return false;
});
</code>```

Title: JQuery how to submit only changed fields when the form has some data array

Body:
You can add the "changed" class to desired elements on change and send data of elements  those have not the class "changed":

<form action="submit.php" method="get" id="myform">
  Name:<input type="text" name="name"/><br/>
  Item:<input type="text" name="item[]"/><br/>
  File:<input type="file" name="file[]" multiple/>
  Item:<input type="text" name="item[]"/><br/>
  File:<input type="file" name="file[]" multiple/>
  Select:<select name="select" value="1" original="1">
  <option value="1">One</option>
  <option value="2">Two</option>
  </select>
<input type="submit" id="submit">
</form>

listening for changes:

$("input,select").on("change",function(){
   $(this).addClass("changed");
})

handle data by ajax call and prevent form submission by return false and reset the changed class to nothing:

$("#myform").on("submit",function(){

//Collecting data from changed class:
var data;
$(".changed").each(function(){
data=data+$(this).attr("name")+":"+$(this).val()+",";
});

//just removing last comma:
data=data.substring(0, data.length - 1);

//Submit data:
$.ajax({
    ...
    data : { data },
    ...
    success: function(){
    //Removing changed class from all elements
    $(".changed").removeClass("changed");
    }
});

return false;
});


问:
working with codeigniter using bootsrap and jQuery
I am new to CodeIgniter and I displayed table from DB using Boostrap, jQuery and DataTable.

However jQuery and DataTable don't work and showing error like this

here is my source code from View header where I liked

答: Use the site_url(); in image src

Body: Use the site_url(); in image src


答:
Try This

```<code> $q_cat_beauty =
 $this->db->where('source_id', 1)
->where('category_name', 'Oral Care')
->get('ms_categories')
->result_array();
</code>```

The Query builder class dosnt support and()   so if you chain 2 where together like above it will represent the and you can keep chaining

https://www.codeigniter.com/userguide3/database/query_builder.html

Title: Call to undefined method CI_DB_mysqli_driver::and()

Body:
Try This

 $q_cat_beauty =
 $this->db->where('source_id', 1)
->where('category_name', 'Oral Care')
->get('ms_categories')
->result_array();

The Query builder class dosnt support and()   so if you chain 2 where together like above it will represent the and you can keep chaining

https://www.codeigniter.com/userguide3/database/query_builder.html


问:
How do I detect the number of keyboards in OSX through command line using bash?
I am trying to write a bash script which can detect they number of keyboards currently connected to my MacBook Pro. The keyboards can be the

default one

any USB keyboards or

Bluetooth keyboard

Please give me any suggestions or areas I should be looking for. I am currently using a 2015 MacBook Pro running OSX 10.12.5. I am using the default terminal running bash 4.

答:
The ioreg command can be used to get a tree of all connected USB devices:

```<code>ioreg -p IOUSB
</code>```

You can use sed to extract just the device names and grep to filter out the root nodes from the tree.

```<code>ioreg -p IOUSB -w0 | sed 's/[^o]*o //; s/@.*$//' | grep -v '^Root.*'
</code>```

Body:
The ioreg command can be used to get a tree of all connected USB devices:

ioreg -p IOUSB

You can use sed to extract just the device names and grep to filter out the root nodes from the tree.

ioreg -p IOUSB -w0 | sed 's/[^o]*o //; s/@.*$//' | grep -v '^Root.*'

ContentLicense: CC BY-SA 4.0


问:
Customize "export users" result
In Liferay there is a "Export Users" button that exports a CSV file of all users. Is there a way that you can extend the fields that are fetched from multiple database tables? Default values are only full name and email.</p>

答: Yes sure there is in your portal-ext.properties check for users.export.csv.fields=fullName,emailAddress. You can add columns from User_ table here.

Title: Customize "export users" result


问:
How to return this result using linq in entity framework( 2 foreign key mapping table)
I have a table that contains 2 foreign key that reference separately to 2 different table.
I would like to return the result of all person that has course of "Science".

How to retrieve the record back using LINQ?
This is what i gotten so far:

```<code>       return
        _ctx.Person
            .Include(u => u.Course
            .Where(ug=>ug.CourseName== "Science"));
</code>```

This is not working as it shows the error.

The Include path expression must refer to a navigation property
  defined on the type

```<code>public class Course
{
    public int CourseID {get; set;}
    public string CourseName {get; set;}

    public virtual ICollection<Person> Persons { get; set; }
}

public class Person
{
   public int PersonID {get; set;}
   public virtual ICollection<Course> Courses { get; set; }
}
</code>```

This is the mapping table. Only contains 2 foreign key from 2 different table.
I could not use this table inside the solution.As the code first won't generate this table as it doesn't contain it's own PK.

```<code>//This is not shown in the EntityFramework when generating Code First.
    public class PersonCouseMap
    {
      public int PersonID {get; set;}
      public int CourseID {get; set;}
    }
</code>```

Update : this works after I switched the entity.

```<code>return _ctx.Course
       .Include(u=>u.Person)
       .Where(ug=>ug.CourseName == "Sciene");
</code>```

Anyone can explain why it won't work the another way round.
I need to display a List of Person who have course of "Science",
not Course Science that has a list of user.

答:
It looks like there is no relations between these two entites, you can establish a relationship by making the following changes to your code:

Here I am assuming that you want to establish Many-to-Many relationship between these two tables by having a third entity PersonCourseMap

```<code>public class Course
{
    public int CourseID {get; set;}
    public string CourseName {get; set;}

   public virtual ICollection<CoursePersons> Courses { get; set; }
}

public class Person
{
   public int PersonID {get; set;}
   public virtual ICollection<PersonCourse> Courses { get; set; }
}

public class PersonCourseMap
{
  public int PersonID {get; set;}
  public int CourseID {get; set;}

  public virtual ICollection<Person> Persons { get; set; }
  public virtual ICollection<Course> Courses { get; set; }
}
</code>```

After making above changes you can simply navigate through properties.

Body:
I have a table that contains 2 foreign key that reference separately to 2 different table.
I would like to return the result of all person that has course of "Science".

How to retrieve the record back using LINQ?
This is what i gotten so far:

       return
        _ctx.Person
            .Include(u => u.Course
            .Where(ug=>ug.CourseName== "Science"));

This is not working as it shows the error.

The Include path expression must refer to a navigation property
  defined on the type

public class Course
{
    public int CourseID {get; set;}
    public string CourseName {get; set;}

    public virtual ICollection<Person> Persons { get; set; }
}

public class Person
{
   public int PersonID {get; set;}
   public virtual ICollection<Course> Courses { get; set; }
}

This is the mapping table. Only contains 2 foreign key from 2 different table.
I could not use this table inside the solution.As the code first won't generate this table as it doesn't contain it's own PK.

//This is not shown in the EntityFramework when generating Code First.
    public class PersonCouseMap
    {
      public int PersonID {get; set;}
      public int CourseID {get; set;}
    }

Update : this works after I switched the entity.

return _ctx.Course
       .Include(u=>u.Person)
       .Where(ug=>ug.CourseName == "Sciene");

Anyone can explain why it won't work the another way round.
I need to display a List of Person who have course of "Science",
not Course Science that has a list of user.

Body:
It looks like there is no relations between these two entites, you can establish a relationship by making the following changes to your code:

Here I am assuming that you want to establish Many-to-Many relationship between these two tables by having a third entity PersonCourseMap

public class Course
{
    public int CourseID {get; set;}
    public string CourseName {get; set;}

   public virtual ICollection<CoursePersons> Courses { get; set; }
}

public class Person
{
   public int PersonID {get; set;}
   public virtual ICollection<PersonCourse> Courses { get; set; }
}

public class PersonCourseMap
{
  public int PersonID {get; set;}
  public int CourseID {get; set;}

  public virtual ICollection<Person> Persons { get; set; }
  public virtual ICollection<Course> Courses { get; set; }
}

After making above changes you can simply navigate through properties.


问:
How to make filters case insensitive in Vuejs/Javascript
I'm trying to build an application in Vuejs 2 where I'm having a filter to find out the specific data from an array of elements. This filter is case sensitive but I want to have case insensitive, following is my code:

```<code>tableFilter: function () {
    if( this.model ) {
        return this.model.filter(
            item =>
                item.clients_association.includes( this.search_by_name ) &&
                item.event_type.includes( this.search_by_event_type )
            )
            .map(
                d => (
                    {
                        id: d.id,
                        client_names: d.clients_association,
                        stellar_participants: d.stellar_participants,
                        contact_participants: d.contacts_association,
                    }
                )
            );
    }
}
</code>```

Please guide me how can I achieve it.

答:
Since Array#includes is case sensitive you can convert everything to lower case:

```<code>const searchTerm = this.search_by_name.toLowerCase();
const searchEvent = this.search_by_event_type.toLowerCase();

this.model.filter((item) =>
  item.clients_association.toLowerCase().includes(searchTerm) &&
  item.event_type.toLowerCase().includes(searchEvent)
);
</code>```

You can also use String#test, which accepts a regex with the insensitive (i) flag, and returns true if the string matches the expression, or false if not:

```<code>const searchTerm = new RegExp(this.search_by_name, 'i');
const searchEvent = new RegExp(this.search_by_event_type, 'i');

this.model.filter((item) =>
  searchTerm.test(item.clients_association) &&
  searchEvent.test(item.event_type)
);
</code>```

Body:
I'm trying to build an application in Vuejs 2 where I'm having a filter to find out the specific data from an array of elements. This filter is case sensitive but I want to have case insensitive, following is my code:

tableFilter: function () {
    if( this.model ) {
        return this.model.filter(
            item =>
                item.clients_association.includes( this.search_by_name ) &&
                item.event_type.includes( this.search_by_event_type )
            )
            .map(
                d => (
                    {
                        id: d.id,
                        client_names: d.clients_association,
                        stellar_participants: d.stellar_participants,
                        contact_participants: d.contacts_association,
                    }
                )
            );
    }
}

Please guide me how can I achieve it.

Body:
Since Array#includes is case sensitive you can convert everything to lower case:

const searchTerm = this.search_by_name.toLowerCase();
const searchEvent = this.search_by_event_type.toLowerCase();

this.model.filter((item) =>
  item.clients_association.toLowerCase().includes(searchTerm) &&
  item.event_type.toLowerCase().includes(searchEvent)
);

You can also use String#test, which accepts a regex with the insensitive (i) flag, and returns true if the string matches the expression, or false if not:

const searchTerm = new RegExp(this.search_by_name, 'i');
const searchEvent = new RegExp(this.search_by_event_type, 'i');

this.model.filter((item) =>
  searchTerm.test(item.clients_association) &&
  searchEvent.test(item.event_type)
);