问:
Jquery Sortable move the parent item along with its child
Guys i have an requirement in which i have items in jquery sortable. but i also want the child item of the parent to be moved along with the parent.for example when i drag the item1 in the browser , the sub item1,2,3 should be moved along with them  and dropped .
kindly let me know ,if there is any possibility through UI.</p>

```<code><ul>
<li>
<p> item 1</p>
<ul>
  <li>
     Sub item 1
  </li>
  <li>
     Sub item 2
  </li>
  <li>
     Sub item 3
  </li>
</ul>
</li>
<li>
<p> item 2</p>
</li>
</ul>
</code>```

答:
You could apply a class or id to the first ul and only apply sortable to that unordered list:

HTML:

```<code><ul id="sortable">
    <li>
        <p> item 1</p>
        <ul>
            <li>
                Sub item 1
            </li>
            <li>
                Sub item 2
            </li>
            <li>
                Sub item 3
            </li>
        </ul>
    </li>
    <li>
        <p> item 2</p>
    </li>
</ul>
</code>```

JavaScript:

```<code>$("#sortable").sortable();
</code>```

This way, the inner uls are not sortable.

Working example: http://jsfiddle.net/andrewwhitaker/Ds7ds/

Body:
Guys i have an requirement in which i have items in jquery sortable. but i also want the child item of the parent to be moved along with the parent.for example when i drag the item1 in the browser , the sub item1,2,3 should be moved along with them  and dropped .
kindly let me know ,if there is any possibility through UI.

 item 1

     Sub item 1

     Sub item 2

     Sub item 3

 item 2

Body:
You could apply a class or id to the first ul and only apply sortable to that unordered list:

HTML:

<ul id="sortable">
    <li>
        <p> item 1</p>
        <ul>
            <li>
                Sub item 1
            </li>
            <li>
                Sub item 2
            </li>
            <li>
                Sub item 3
            </li>
        </ul>
    </li>
    <li>
        <p> item 2</p>
    </li>
</ul>

JavaScript:

$("#sortable").sortable();

This way, the inner uls are not sortable.

Working example: http://jsfiddle.net/andrewwhitaker/Ds7ds/


来源: stackexchange

问:
PHP : check if num rows is zero
I am trying to check if result returned by database is zero but it always falls to zero following is my code </p>

```<code>if(isset($_POST['cust_id'])){
    $cust_id = $_POST['cust_id'];
    $stmt = $connect->prepare("SELECT DISTINCT send_stamp, message, time, status FROM `chat` WHERE cust_id=?");
    $stmt->bind_param('i', $cust_id);

}
else if(isset($_POST['receiverid'])) {
    $receiverid = $_POST['receiverid'];
    $stmt = $connect->prepare("SELECT DISTINCT send_stamp, message, time, status FROM `chat` WHERE receiverid=?");
    $stmt->bind_param('i', $receiverid);

}

if($stmt->execute()){
    $data  = array();
    if($stmt->num_rows ==0){
        $data[] = array(
           'message'=> 'No messages found',
           'status'=>0,
        );
    }
    else{
        $result = $stmt->get_result();
        while ($row =mysqli_fetch_array($result)) {
            $data[] = array(
                'message'=> $row['message'],
                'time'=> $row['time'],
                'status'=> $row['status'],
            );
        }
    }
}
echo json_encode( $data);
</code>```

<p>Please help me to figure out this situation . Thanks </p>

答:
try with this one

execute query and get data into result like  $result=$stmt->execute() and that
result compare in if() condition like if($result) and inside if($result == 0) so it give an result

```<code>$result=$stmt->execute();
if($result)
{
    $data  = array();
    if($result ==0){
        $data[] = array(
               'message'=> 'No messages found',
               'status'=>0,
            );
    }
    else{

    $result = $stmt->get_result();
        while ($row =mysqli_fetch_array($result)) {
            $data[] = array(
               'message'=> $row['message'],
               'time'=> $row['time'],
               'status'=> $row['status'],
            );
        }
    }
}
</code>```

OR

also write $result = $stmt->get_result(); after if($stmt->execute()) and compare if($result->num_rows ==0) like this way

ContentLicense: CC BY-SA 3.0

Title: PHP : check if num rows is zero

Body:
I am trying to check if result returned by database is zero but it always falls to zero following is my code

if(isset($_POST['cust_id'])){
    $cust_id = $_POST['cust_id'];
    $stmt = $connect->prepare("SELECT DISTINCT send_stamp, message, time, status FROM `chat` WHERE cust_id=?");
    $stmt->bind_param('i', $cust_id);

}
else if(isset($_POST['receiverid'])) {
    $receiverid = $_POST['receiverid'];
    $stmt = $connect->prepare("SELECT DISTINCT send_stamp, message, time, status FROM `chat` WHERE receiverid=?");
    $stmt->bind_param('i', $receiverid);

}

if($stmt->execute()){
    $data  = array();
    if($stmt->num_rows ==0){
        $data[] = array(
           'message'=> 'No messages found',
           'status'=>0,
        );
    }
    else{
        $result = $stmt->get_result();
        while ($row =mysqli_fetch_array($result)) {
            $data[] = array(
                'message'=> $row['message'],
                'time'=> $row['time'],
                'status'=> $row['status'],
            );
        }
    }
}
echo json_encode( $data);

Please help me to figure out this situation . Thanks

Body:
try with this one

execute query and get data into result like  $result=$stmt->execute() and that
result compare in if() condition like if($result) and inside if($result == 0) so it give an result

$result=$stmt->execute();
if($result)
{
    $data  = array();
    if($result ==0){
        $data[] = array(
               'message'=> 'No messages found',
               'status'=>0,
            );
    }
    else{

    $result = $stmt->get_result();
        while ($row =mysqli_fetch_array($result)) {
            $data[] = array(
               'message'=> $row['message'],
               'time'=> $row['time'],
               'status'=> $row['status'],
            );
        }
    }
}

OR

also write $result = $stmt->get_result(); after if($stmt->execute()) and compare if($result->num_rows ==0) like this way


问:
NodeJS Express Function not defined
All I'm trying to do is execute geoAutocomplete in browser console so I can console log values from form. I'm getting ReferenceError: geoAutocomplete is not defined error.

```<code>const GooglePlaces = require('google-places');
const places = new GooglePlaces("myapikey");

function geoAutocomplete(input, lat, long) {
    console.log(input, lat, long);

    //const dropdown = places.autocomplete(input);
}

export default geoAutocomplete;
</code>```

myApp.js

```<code>import '../sass/style.scss'
import geoAutocomplete from './modules/geoAutocomplete'

geoAutocomplete( document.querySelector('#address'), document.querySelector('#lat'), document.querySelector('#long') );
</code>```

layout.pug

```<code>    script(src='/javascript/vcaApp.js' type='module')
form(method='POST' action='/addGeofence')
                    h3 Add a Geofence
                    div.input-field
                        label(for='address') Address
                        input(type='text' id='address', placeholder='Address',
                        required='true', autofocus='true' name='address')
                    div.input-field(style="display: none;")
                        input(type='number' id='lat', placeholder='Address',
                        autofocus='true' name='lat')
                    div.input-field(style="display: none;")
                        input(type='number' id='long', autofocus='true' name='long')
</code>```

答:
Just use module.exports / require. It's hard to tell where the error gets produced as you don't know how you're making the code runable in a browser (neither require nor import are supported there).

The easiest will be to just use

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

and to import the function in the other file

```<code>const geoAutocomplete = require('./modules/geoAutocomplete');
</code>```

Your pre es6 compiler/transpiler/whatever will be able to handle this.

Title: NodeJS Express Function not defined

Body:
All I'm trying to do is execute geoAutocomplete in browser console so I can console log values from form. I'm getting ReferenceError: geoAutocomplete is not defined error.

const GooglePlaces = require('google-places');
const places = new GooglePlaces("myapikey");

function geoAutocomplete(input, lat, long) {
    console.log(input, lat, long);

    //const dropdown = places.autocomplete(input);
}

export default geoAutocomplete;

myApp.js

import '../sass/style.scss'
import geoAutocomplete from './modules/geoAutocomplete'

geoAutocomplete( document.querySelector('#address'), document.querySelector('#lat'), document.querySelector('#long') );

layout.pug

    script(src='/javascript/vcaApp.js' type='module')
form(method='POST' action='/addGeofence')
                    h3 Add a Geofence
                    div.input-field
                        label(for='address') Address
                        input(type='text' id='address', placeholder='Address',
                        required='true', autofocus='true' name='address')
                    div.input-field(style="display: none;")
                        input(type='number' id='lat', placeholder='Address',
                        autofocus='true' name='lat')
                    div.input-field(style="display: none;")
                        input(type='number' id='long', autofocus='true' name='long')

Body:
Just use module.exports / require. It's hard to tell where the error gets produced as you don't know how you're making the code runable in a browser (neither require nor import are supported there).

The easiest will be to just use

module.exports = getAutocomplete;

and to import the function in the other file

const geoAutocomplete = require('./modules/geoAutocomplete');

Your pre es6 compiler/transpiler/whatever will be able to handle this.


问:
Populating a TreeView from a query
I'm trying to populate a C# tree view from a database query.

The database is structured something like this:

```<code>-----------------------------------------------
| PARENT_NODE | CHILD_NODE | LEVEL | NAME     |
-----------------------------------------------
|     1       |     2      |   1   | name1    |
-----------------------------------------------
|     1       |     4      |   1   | name2    |
-----------------------------------------------
|     2       |     6      |   1   | name4    |
-----------------------------------------------
|     2       |     3      |   2   | name3    |
-----------------------------------------------
|     3       |   null     |   3   | name5    |
-----------------------------------------------
</code>```

Note the databse query cannot be changed.

And as a representation of the tree view it would look something like this.

```<code>name1
  |---- name3
  |       |---- name5
name2
  |
  |
name4
</code>```

I have tried to look for others having similar problems as I do. However, the examples have been tricky to follow and usually doesn't work for me. Either I implemented it wrong or it just doesn't work for my situation.

My latest try was to make a loop within a loop to iterate through the children and try to associate them with the parents. But it didn't show anything instead.

```<code>// Nodes
            TreeNode rootNode = new TreeNode("root_NAME");
            TreeNode parent = new TreeNode();
            TreeNode child = new TreeNode();

            foreach (DataRow dr in dt.Rows)
            {
                if (dr["LEVEL"].ToString() == "1")
                {
                    parent = new TreeNode(dr["NAME"].ToString());
                    rootNode.Nodes.Add(parent);
                    //TreeView.traceTreeView.Nodes.Add(node);
                }
                else
                {
                    // Search for where child_node == parent_node and add that node

                    List<TreeNode> childList = new List<TreeNode>();

                    foreach (DataRow cr in dt.Rows)
                    {
                        if (cr["PARENT_NODE"].ToString() == dr["CHILD_NODE"].ToString())
                        {
                            childList.Add(child = new TreeNode(cr["NAME"].ToString()));
                        }
                    }
                    TreeNode[] childArray = childList.ToArray();

                    TreeNode node = new TreeNode(dr["NAME"].ToString(), childArray);
                    parent.Nodes.Add(node);

                }

            }
</code>```

Would someone tell/show me how I can iterate through a table and associate parent and child nodes and then add them to the treeview?

答:
Below I'll present how I solved this.

```<code>foreach (DataRow dr in dt.Rows)
        {
            if (!UserFunctions.IsNullOrEmpty(traceWindow.traceTreeView.Nodes.Find(dr["PARENT_NODE"].ToString(), true)))
            {
                // add child to parent
                // if child_node == null -> cNode.Name(Text) = "INDATA"
                TreeNode cNode;
                // "JOB_NAME_IN" is a column name in the database
                if (!string.IsNullOrEmpty(dr["JOB_NAME_IN"].ToString()))
                {
                    cNode = new TreeNode(dr["JOB_NAME_IN"].ToString());
                }
                else
                {
                    cNode = new TreeNode(dr["INDATA"].ToString());
                }
                // .Name is the key of that node.
                // Setting it to child node allows me to search for which node is the parent of the current datarow i'm reading.
                cNode.Name = dr["CHILD_NODE"].ToString();
                TreeNode[] pNode = traceWindow.traceTreeView.Nodes.Find(dr["PARENT_NODE"].ToString(), true);

                pNode[0].Nodes.Add(cNode);

            }
            else
            {
                // There is no child, create new parent
                // if child_node == null -> cNode.Name(Text) = "INDATA"
                TreeNode pNode;
                if (!string.IsNullOrEmpty(dr["JOB_NAME_IN"].ToString()))
                {
                    pNode = new TreeNode(dr["JOB_NAME_IN"].ToString());
                }
                else
                {
                    pNode = new TreeNode(dr["INDATA"].ToString());
                }
                pNode.Name = dr["CHILD_NODE"].ToString(); // Key
                traceWindow.traceTreeView.Nodes.Add(pNode);
            }

        }
</code>```

Note that I have created an extended method of IsNullOrEmpty It looks like follows:

```<code>public static bool IsNullOrEmpty(this Array array)
    {
        // This is an extension of an existing function
        // to make it work with arrays.

        return (array == null || array.Length == 0);
    }
</code>```

Title: Populating a TreeView from a query

Body:
I'm trying to populate a C# tree view from a database query.

The database is structured something like this:

-----------------------------------------------
| PARENT_NODE | CHILD_NODE | LEVEL | NAME     |
-----------------------------------------------
|     1       |     2      |   1   | name1    |
-----------------------------------------------
|     1       |     4      |   1   | name2    |
-----------------------------------------------
|     2       |     6      |   1   | name4    |
-----------------------------------------------
|     2       |     3      |   2   | name3    |
-----------------------------------------------
|     3       |   null     |   3   | name5    |
-----------------------------------------------

Note the databse query cannot be changed.

And as a representation of the tree view it would look something like this.

name1
  |---- name3
  |       |---- name5
name2
  |
  |
name4

I have tried to look for others having similar problems as I do. However, the examples have been tricky to follow and usually doesn't work for me. Either I implemented it wrong or it just doesn't work for my situation.

My latest try was to make a loop within a loop to iterate through the children and try to associate them with the parents. But it didn't show anything instead.

// Nodes
            TreeNode rootNode = new TreeNode("root_NAME");
            TreeNode parent = new TreeNode();
            TreeNode child = new TreeNode();

            foreach (DataRow dr in dt.Rows)
            {
                if (dr["LEVEL"].ToString() == "1")
                {
                    parent = new TreeNode(dr["NAME"].ToString());
                    rootNode.Nodes.Add(parent);
                    //TreeView.traceTreeView.Nodes.Add(node);
                }
                else
                {
                    // Search for where child_node == parent_node and add that node

                    List<TreeNode> childList = new List<TreeNode>();

                    foreach (DataRow cr in dt.Rows)
                    {
                        if (cr["PARENT_NODE"].ToString() == dr["CHILD_NODE"].ToString())
                        {
                            childList.Add(child = new TreeNode(cr["NAME"].ToString()));
                        }
                    }
                    TreeNode[] childArray = childList.ToArray();

                    TreeNode node = new TreeNode(dr["NAME"].ToString(), childArray);
                    parent.Nodes.Add(node);

                }

            }

Would someone tell/show me how I can iterate through a table and associate parent and child nodes and then add them to the treeview?

Body:
Below I'll present how I solved this.

foreach (DataRow dr in dt.Rows)
        {
            if (!UserFunctions.IsNullOrEmpty(traceWindow.traceTreeView.Nodes.Find(dr["PARENT_NODE"].ToString(), true)))
            {
                // add child to parent
                // if child_node == null -> cNode.Name(Text) = "INDATA"
                TreeNode cNode;
                // "JOB_NAME_IN" is a column name in the database
                if (!string.IsNullOrEmpty(dr["JOB_NAME_IN"].ToString()))
                {
                    cNode = new TreeNode(dr["JOB_NAME_IN"].ToString());
                }
                else
                {
                    cNode = new TreeNode(dr["INDATA"].ToString());
                }
                // .Name is the key of that node.
                // Setting it to child node allows me to search for which node is the parent of the current datarow i'm reading.
                cNode.Name = dr["CHILD_NODE"].ToString();
                TreeNode[] pNode = traceWindow.traceTreeView.Nodes.Find(dr["PARENT_NODE"].ToString(), true);

                pNode[0].Nodes.Add(cNode);

            }
            else
            {
                // There is no child, create new parent
                // if child_node == null -> cNode.Name(Text) = "INDATA"
                TreeNode pNode;
                if (!string.IsNullOrEmpty(dr["JOB_NAME_IN"].ToString()))
                {
                    pNode = new TreeNode(dr["JOB_NAME_IN"].ToString());
                }
                else
                {
                    pNode = new TreeNode(dr["INDATA"].ToString());
                }
                pNode.Name = dr["CHILD_NODE"].ToString(); // Key
                traceWindow.traceTreeView.Nodes.Add(pNode);
            }

        }

Note that I have created an extended method of IsNullOrEmpty It looks like follows:

public static bool IsNullOrEmpty(this Array array)
    {
        // This is an extension of an existing function
        // to make it work with arrays.

        return (array == null || array.Length == 0);
    }


问:
Could not write JSON: Infinite recursion (StackOverflowError); nested exception spring boot
This is my District Controller, when I try to fetch data after saving I get the error, even when I try get object form getDistrict(Long id) the same strikes please suggest some way, am very new at spring environment:

```<code>    package com.gad.services;

    import java.util.List;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import com.gad.repositories.DistrictMasterRepositories;
    import com.gad.rmodels.Districtmaster;
    import com.gad.rmodels.Statemaster;

    @Service
    public class DistricMasterServices {

        @Autowired
        DistrictMasterRepositories districtMasterRepositories;
        @Autowired
        StateMasterServices stateMasterServices;
        List<Districtmaster> districtmaster;

        public Iterable<Districtmaster> savenewdistrict(Long id,Districtmaster districtmaster_rec){
             System.out.println(id);
             Statemaster statemaster=null;
             statemaster = stateMasterServices.getStateById(id);
             System.out.println("savenewdistrict");

                districtmaster_rec.setStatemaster(statemaster);
                districtMasterRepositories.save(districtmaster_rec);
                    Iterable<Districtmaster>districtmaster2 = districtMasterRepositories.findAll();
                    return  districtmaster2;

        }

        public Districtmaster  getDistrict(Long id){
            Districtmaster districtmaster =  districtMasterRepositories.findOne(id);
            return districtmaster;

        }
    }
</code>```

The model class for state:

```<code> package com.gad.rmodels;
    import static javax.persistence.GenerationType.SEQUENCE;
    import java.util.HashSet;
    import java.util.Set;
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.OneToMany;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;

    /**
     * Statemaster generated by hbm2java
     */
    @Entity
    @Table(name="statemaster"
        ,schema="aop_gad_v1"
    )
    public class Statemaster  implements java.io.Serializable {

         private long id;
         private String stateName;
         private Set<Districtmaster> districtmasters = new HashSet<Districtmaster>(0);

        public Statemaster() {
        }

        public Statemaster(long id) {
            this.id = id;
        }
        public Statemaster(long id, String stateName, Set<Districtmaster> districtmasters) {
           this.id = id;
           this.stateName = stateName;
           this.districtmasters = districtmasters;
        }

        @SequenceGenerator(name="generator_statemasterid", sequenceName="aop_gad_v1.gad_statemaster_seq")
        @Id
        @GeneratedValue(strategy=SEQUENCE, generator="generator_statemasterid")
        @Column(name="id", unique=true, nullable=false)
        public long getId() {
            return this.id;
        }

        public void setId(long id) {
            this.id = id;
        }

        @Column(name="state_name", length=20)
        public String getStateName() {
            return this.stateName;
        }

        public void setStateName(String stateName) {
            this.stateName = stateName;
        }

    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="statemaster")
        public Set<Districtmaster> getDistrictmasters() {
            return this.districtmasters;
        }

        public void setDistrictmasters(Set<Districtmaster> districtmasters) {
            this.districtmasters = districtmasters;
        }

    }
</code>```

Distric model:

```<code>package com.gad.rmodels;

import static javax.persistence.GenerationType.SEQUENCE;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

/**
 * Districtmaster generated by hbm2java
 */
@SuppressWarnings("serial")
@Entity
@Table(name="districtmaster",schema="aop_gad_v1")
public class Districtmaster  implements java.io.Serializable {

     private long id;
     private Statemaster statemaster;
     private String districtName;
     private Set<GadGuestHouseMaster> gadGuestHouseMasters = new HashSet<GadGuestHouseMaster>(0);

    public Districtmaster() {
    }

    public Districtmaster(long id) {
        this.id = id;
    }
    public Districtmaster(long id, Statemaster statemaster, String districtName, Set<GadGuestHouseMaster> gadGuestHouseMasters) {
       this.id = id;
       this.statemaster = statemaster;
       this.districtName = districtName;
       this.gadGuestHouseMasters = gadGuestHouseMasters;
    }

     @SequenceGenerator(name="generator_districtmasterid", sequenceName="aop_gad_v1.gad_districtmasterid_seq")
     @Id
     @GeneratedValue(strategy=SEQUENCE, generator="generator_districtmasterid")
     @Column(name="id", unique=true, nullable=false)
    public long getId() {
        return this.id;
    }

    public void setId(long id) {
        this.id = id;
    }
@ManyToOne(fetch=FetchType.LAZY)

    @JoinColumn(name="district_of_state")
    public Statemaster getStatemaster() {
        return this.statemaster;
    }

    public void setStatemaster(Statemaster statemaster) {
        this.statemaster = statemaster;
    }

    @Column(name="district_name", length=20)
    public String getDistrictName() {
        return this.districtName;
    }

    public void setDistrictName(String districtName) {
        this.districtName = districtName;
    }
    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="districtmaster")
    public Set<GadGuestHouseMaster> getGadGuestHouseMasters() {
        return this.gadGuestHouseMasters;
    }

    public void setGadGuestHouseMasters(Set<GadGuestHouseMaster> gadGuestHouseMasters) {
        this.gadGuestHouseMasters = gadGuestHouseMasters;
    }

}
</code>```

The Error I get:

[{"timestamp":1512641978311,"status":200,"error":"OK","exception":"org.springframework.http.converter.HttpMessageNotWritableException","message":"Could
  not write JSON: Infinite recursion (StackOverflowError); nested
  exception is com.fasterxml.jackson.databind.JsonMappingException:
  Infinite recursion (StackOverflowError) (through reference chain:
  com.gad.rmodels.Statemaster[\"districtmasters\"]->org.hibernate.collection.internal.PersistentSet[0]-

答:
Looks like your problem is Hibernate relations. When you try to serialize the entity Statemaster the serializer calls serialization of the Districtmaster set which in turn somehow reference the Statemaster again.

There are two possible ways to solve:

Unproxy object

Create DTO (Data Transfer Object) - kind of copy of your entity
where all necessary fields should be assigned and return the DTO.

ContentLicense: CC BY-SA 4.0

Body:
This is my District Controller, when I try to fetch data after saving I get the error, even when I try get object form getDistrict(Long id) the same strikes please suggest some way, am very new at spring environment:

    package com.gad.services;

    import java.util.List;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;

    import com.gad.repositories.DistrictMasterRepositories;
    import com.gad.rmodels.Districtmaster;
    import com.gad.rmodels.Statemaster;

    @Service
    public class DistricMasterServices {

        @Autowired
        DistrictMasterRepositories districtMasterRepositories;
        @Autowired
        StateMasterServices stateMasterServices;
        List<Districtmaster> districtmaster;

        public Iterable<Districtmaster> savenewdistrict(Long id,Districtmaster districtmaster_rec){
             System.out.println(id);
             Statemaster statemaster=null;
             statemaster = stateMasterServices.getStateById(id);
             System.out.println("savenewdistrict");

                districtmaster_rec.setStatemaster(statemaster);
                districtMasterRepositories.save(districtmaster_rec);
                    Iterable<Districtmaster>districtmaster2 = districtMasterRepositories.findAll();
                    return  districtmaster2;

        }

        public Districtmaster  getDistrict(Long id){
            Districtmaster districtmaster =  districtMasterRepositories.findOne(id);
            return districtmaster;

        }
    }

The model class for state:

 package com.gad.rmodels;
    import static javax.persistence.GenerationType.SEQUENCE;
    import java.util.HashSet;
    import java.util.Set;
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.OneToMany;
    import javax.persistence.SequenceGenerator;
    import javax.persistence.Table;

    /**
     * Statemaster generated by hbm2java
     */
    @Entity
    @Table(name="statemaster"
        ,schema="aop_gad_v1"
    )
    public class Statemaster  implements java.io.Serializable {

         private long id;
         private String stateName;
         private Set<Districtmaster> districtmasters = new HashSet<Districtmaster>(0);

        public Statemaster() {
        }

        public Statemaster(long id) {
            this.id = id;
        }
        public Statemaster(long id, String stateName, Set<Districtmaster> districtmasters) {
           this.id = id;
           this.stateName = stateName;
           this.districtmasters = districtmasters;
        }

        @SequenceGenerator(name="generator_statemasterid", sequenceName="aop_gad_v1.gad_statemaster_seq")
        @Id
        @GeneratedValue(strategy=SEQUENCE, generator="generator_statemasterid")
        @Column(name="id", unique=true, nullable=false)
        public long getId() {
            return this.id;
        }

        public void setId(long id) {
            this.id = id;
        }

        @Column(name="state_name", length=20)
        public String getStateName() {
            return this.stateName;
        }

        public void setStateName(String stateName) {
            this.stateName = stateName;
        }

    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="statemaster")
        public Set<Districtmaster> getDistrictmasters() {
            return this.districtmasters;
        }

        public void setDistrictmasters(Set<Districtmaster> districtmasters) {
            this.districtmasters = districtmasters;
        }

    }

Distric model:

package com.gad.rmodels;

import static javax.persistence.GenerationType.SEQUENCE;

import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;

/**
 * Districtmaster generated by hbm2java
 */
@SuppressWarnings("serial")
@Entity
@Table(name="districtmaster",schema="aop_gad_v1")
public class Districtmaster  implements java.io.Serializable {

     private long id;
     private Statemaster statemaster;
     private String districtName;
     private Set<GadGuestHouseMaster> gadGuestHouseMasters = new HashSet<GadGuestHouseMaster>(0);

    public Districtmaster() {
    }

    public Districtmaster(long id) {
        this.id = id;
    }
    public Districtmaster(long id, Statemaster statemaster, String districtName, Set<GadGuestHouseMaster> gadGuestHouseMasters) {
       this.id = id;
       this.statemaster = statemaster;
       this.districtName = districtName;
       this.gadGuestHouseMasters = gadGuestHouseMasters;
    }

     @SequenceGenerator(name="generator_districtmasterid", sequenceName="aop_gad_v1.gad_districtmasterid_seq")
     @Id
     @GeneratedValue(strategy=SEQUENCE, generator="generator_districtmasterid")
     @Column(name="id", unique=true, nullable=false)
    public long getId() {
        return this.id;
    }

    public void setId(long id) {
        this.id = id;
    }
@ManyToOne(fetch=FetchType.LAZY)

    @JoinColumn(name="district_of_state")
    public Statemaster getStatemaster() {
        return this.statemaster;
    }

    public void setStatemaster(Statemaster statemaster) {
        this.statemaster = statemaster;
    }

    @Column(name="district_name", length=20)
    public String getDistrictName() {
        return this.districtName;
    }

    public void setDistrictName(String districtName) {
        this.districtName = districtName;
    }
    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="districtmaster")
    public Set<GadGuestHouseMaster> getGadGuestHouseMasters() {
        return this.gadGuestHouseMasters;
    }

    public void setGadGuestHouseMasters(Set<GadGuestHouseMaster> gadGuestHouseMasters) {
        this.gadGuestHouseMasters = gadGuestHouseMasters;
    }

}

The Error I get:

[{"timestamp":1512641978311,"status":200,"error":"OK","exception":"org.springframework.http.converter.HttpMessageNotWritableException","message":"Could
  not write JSON: Infinite recursion (StackOverflowError); nested
  exception is com.fasterxml.jackson.databind.JsonMappingException:
  Infinite recursion (StackOverflowError) (through reference chain:
  com.gad.rmodels.Statemaster[\"districtmasters\"]->org.hibernate.collection.internal.PersistentSet[0]-


问:
give a color to not a number
I have a matrix of integers, padded with nans

```<code>M=

 1     2     2     3     4     4
 2     2     2     3     4   NaN
 2     2     2     3     4   NaN
 2     2     2     3     4   NaN
 2     2     2     3     4   NaN
 2     2     2     3     4   NaN
</code>```

I am plotting it using imagesc

```<code>imagesc(M)
</code>```

However, if I plot it this way, NaN and 1 are shown with the same color, which is confusing.

How to have different colors for NaNs in imagesc?

答:
One way to do it is to set the NaN to be transparent:</p>

```<code>figure; imagesc ( M, 'alphadata', ~isnan(M) )
</code>```

Title: give a color to not a number

Body:
I have a matrix of integers, padded with nans

M=

 1     2     2     3     4     4
 2     2     2     3     4   NaN
 2     2     2     3     4   NaN
 2     2     2     3     4   NaN
 2     2     2     3     4   NaN
 2     2     2     3     4   NaN

I am plotting it using imagesc

imagesc(M)

However, if I plot it this way, NaN and 1 are shown with the same color, which is confusing.

How to have different colors for NaNs in imagesc?

Body:
One way to do it is to set the NaN to be transparent:

figure; imagesc ( M, 'alphadata', ~isnan(M) )


问:
Join first table with latest record of second table
I have table Product and table Sales

I Product table I have list of product with primary key prodId and in Sales table I have total sales for that product.

I want to get data from table Product by joining it with Sales table's latest record (using SalesDate column).

Sales table may contain 0 to n number of records for particular product.

I know I can do it using sub-query but I need to avoid one due to performance overhead. I also don't want to use max function as it will require me to mentions lots f column in group by.

Can I do this with simple join?

答:
Use ROW_NUMBER feature. like this</p>

```<code>;with cte
as
(
    select
        SeqNo = ROW_NUMBER() OVER(PARTITION BY ProductId ORDER BY SalesDate DESC),
        *
        FROM Sales
)
SELECT
    *
    FROM Product p
        LEFT JOIN cte
         ON p.ProducId = cte.ProductId AND cte.SeqNo = 1
</code>```

Body:
Use ROW_NUMBER feature. like this

;with cte
as
(
    select
        SeqNo = ROW_NUMBER() OVER(PARTITION BY ProductId ORDER BY SalesDate DESC),
        *
        FROM Sales
)
SELECT
    *
    FROM Product p
        LEFT JOIN cte
         ON p.ProducId = cte.ProductId AND cte.SeqNo = 1


问:
Send email without password using nodemailer over a zimbra smtp
im using nodemailer to send emails in a web app using keystonejs as cms. The web app is stored in a server and the email server in other, but SMTP communications between servers does not require password. Now, i need to send emails to other peoples when required using a generic account without the password field because is not neccesary.
This is my nodemailer config:

```<code>var selfSignedConfig = {
            host: 'smtp.abc.cu',
            port: 25,
            secure: false, // use TLS
            auth: {
                user: email.email,
                pass: email.password //NOT REQUIRED
            },
            tls: {
                // do not fail on invalid certs
                rejectUnauthorized: false
            }
        };

        var transporter = nodemailer.createTransport(selfSignedConfig);
        // verify connection configuration
</code>```

and:

```<code>"email": {
    "email": "abcde@abc.cu",
    "password": ""
  }
</code>```

I'm stuck on this, I have tried with "password": "" and "password": " " and nothing works. The email server is Zimbra.
This gave me the following error:

```<code>*-------------------------*
The server IS NOT READY to take the messages: Error: Invalid login: 535 5.7.8 Error: authentication failed: authentication failure
*-------------------------*
</code>```

Greetings...

答:
In our case we removed tls, auth and secure fields and it worked on our SMTP server.

The from, to options were set from mail options separately.

You might give the following a try:

```<code>    var nodemailer = require ('nodemailer'),
    _ = require ('lodash')

    var selfSignedConfig = {
        host: 'smtp.abc.cu',
        port: 25
    };

    var transporter = nodemailer.createTransport(selfSignedConfig);

    var attachFiles = attachments?attachments:[];
    var attachObjArray = [];
    _.forEach(
            attachFiles,
            filePath=>attachObjArray.push({path:filePath})
    );

    var mailOptions = {
            from: fromEmail, // sender address (who sends)
            to: toEmail, // list of receivers (who receives)
            subject: subject, // Subject line
            html: body, // html body
            attachments:attachObjArray   //attachment path with file name
    };

    // send mail with defined transport object
   transporter.sendMail(mailOptions, function(error, info) {
          if(error){
                 return console.log(error);
          } else {
                 console.log('Message sent: ' + info.response);
          }
          done();
   });
</code>```

Body:
im using nodemailer to send emails in a web app using keystonejs as cms. The web app is stored in a server and the email server in other, but SMTP communications between servers does not require password. Now, i need to send emails to other peoples when required using a generic account without the password field because is not neccesary.
This is my nodemailer config:

var selfSignedConfig = {
            host: 'smtp.abc.cu',
            port: 25,
            secure: false, // use TLS
            auth: {
                user: email.email,
                pass: email.password //NOT REQUIRED
            },
            tls: {
                // do not fail on invalid certs
                rejectUnauthorized: false
            }
        };

        var transporter = nodemailer.createTransport(selfSignedConfig);
        // verify connection configuration

and:

"email": {
    "email": "abcde@abc.cu",
    "password": ""
  }

I'm stuck on this, I have tried with "password": "" and "password": " " and nothing works. The email server is Zimbra.
This gave me the following error:

*-------------------------*
The server IS NOT READY to take the messages: Error: Invalid login: 535 5.7.8 Error: authentication failed: authentication failure
*-------------------------*

Greetings...

Body:
In our case we removed tls, auth and secure fields and it worked on our SMTP server.

The from, to options were set from mail options separately.

You might give the following a try:

    var nodemailer = require ('nodemailer'),
    _ = require ('lodash')

    var selfSignedConfig = {
        host: 'smtp.abc.cu',
        port: 25
    };

    var transporter = nodemailer.createTransport(selfSignedConfig);

    var attachFiles = attachments?attachments:[];
    var attachObjArray = [];
    _.forEach(
            attachFiles,
            filePath=>attachObjArray.push({path:filePath})
    );

    var mailOptions = {
            from: fromEmail, // sender address (who sends)
            to: toEmail, // list of receivers (who receives)
            subject: subject, // Subject line
            html: body, // html body
            attachments:attachObjArray   //attachment path with file name
    };

    // send mail with defined transport object
   transporter.sendMail(mailOptions, function(error, info) {
          if(error){
                 return console.log(error);
          } else {
                 console.log('Message sent: ' + info.response);
          }
          done();
   });


问:
Moving Bootstrap modal on page
I have a bootstrap modal on the screen. When the modal is showed, it is positioned on the center of the screen.

```<code><div class="modal fade" id="ua_dialog">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
        <div class="modal-body">
        ....
        </div>
      </div>
</code>```

I need to move the modal on my screen, because cover some information from my screen. The user should be able to move on the right, on the left...etc. Can I do that? there is some settings that I can use? or with js? what is the best way? Thanks!

答:
I think You Need This :)

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>

        <button type="button" class="close" data-dismiss="modal">×Close</button>

Modal title

One fine body…

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

  ```

Title: Moving Bootstrap modal on page

Body:
I have a bootstrap modal on the screen. When the modal is showed, it is positioned on the center of the screen.

        ....

I need to move the modal on my screen, because cover some information from my screen. The user should be able to move on the right, on the left...etc. Can I do that? there is some settings that I can use? or with js? what is the best way? Thanks!

Body:
I think You Need This :)

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>

<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<div>
<div class="modal fade">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>One fine body&hellip;</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</div>

<script>
        $('.modal').modal({ keyboard: false,
                           show: true
        });
        // Jquery draggable
        $('.modal-dialog').draggable({
            handle: ".modal-header"
        });
</script>


问:
Pandas: convert all columns in dataframe to string
I have dataframe

```<code> 0     1     2
12     34   23
10     12    0
</code>```

Desire output

```<code>upd_string
12, 34, 23
10, 12, 0
</code>```

I try

```<code>df_upd = pd.DataFrame()
df_upd['upd_string'] = df[df.columns.values.tolist()].apply(str)
</code>```

But it returns

```<code>ValueError: no results
</code>```

答:
First cast to strings if numeric and then apply join:

```<code>df.astype(str).apply(', '.join, axis=1)
</code>```

for new DataFrame:

```<code>df_upd = pd.DataFrame({'upd_string': df.astype(str).apply(', '.join, axis=1)})
print (df_upd)
   upd_string
0  12, 34, 23
1   10, 12, 0
</code>```

Body:
I have dataframe

 0     1     2
12     34   23
10     12    0

Desire output

upd_string
12, 34, 23
10, 12, 0

I try

df_upd = pd.DataFrame()
df_upd['upd_string'] = df[df.columns.values.tolist()].apply(str)

But it returns

ValueError: no results

Body:
First cast to strings if numeric and then apply join:

df.astype(str).apply(', '.join, axis=1)

for new DataFrame:

df_upd = pd.DataFrame({'upd_string': df.astype(str).apply(', '.join, axis=1)})
print (df_upd)
   upd_string
0  12, 34, 23
1   10, 12, 0


问:
Failure installing pcapy on os x
I'm trying to install pcapy on os x. Here's what happened:

```<code>Joannas-MacBook-Pro:~ joannaburke$ python/Users/joannaburke/Downloads/pcapy-0.10.8/setup.py install my_init_posix: changing LDSHARED = 'gcc-4.2 -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -isysroot /Developer/SDKs/MacOSX10.6.sdk -isysroot /Developer/SDKs/MacOSX10.6.sdk -g' to 'g++-4.2 -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -isysroot /Developer/SDKs/MacOSX10.6.sdk -isysroot /Developer/SDKs/MacOSX10.6.sdk -g'
running install
running build
running build_ext
building 'pcapy' extension
/usr/bin/clang -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch x86_64 -g -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c pcapdumper.cc -o build/temp.macosx-10.6-intel-2.7/pcapdumper.o
clang: error: no such file or directory: 'pcapdumper.cc'
clang: error: no input files
error: command '/usr/bin/clang' failed with exit status 1
Joannas-MacBook-Pro:~ joannaburke$
</code>```

I have no idea how to fix this. Google has given me nothing. All help is appreciated. Thanks!

edit: pcapdumper.cc DOES exist, in the pcapy directory.

答: Go to the pcapy directory and try the command "python setup.py install."  That worked for me.</p>

Title: Failure installing pcapy on os x

Body:
I'm trying to install pcapy on os x. Here's what happened:

Joannas-MacBook-Pro:~ joannaburke$ python/Users/joannaburke/Downloads/pcapy-0.10.8/setup.py install my_init_posix: changing LDSHARED = 'gcc-4.2 -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -isysroot /Developer/SDKs/MacOSX10.6.sdk -isysroot /Developer/SDKs/MacOSX10.6.sdk -g' to 'g++-4.2 -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -isysroot /Developer/SDKs/MacOSX10.6.sdk -isysroot /Developer/SDKs/MacOSX10.6.sdk -g'
running install
running build
running build_ext
building 'pcapy' extension
/usr/bin/clang -fno-strict-aliasing -fno-common -dynamic -arch i386 -arch x86_64 -g -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c pcapdumper.cc -o build/temp.macosx-10.6-intel-2.7/pcapdumper.o
clang: error: no such file or directory: 'pcapdumper.cc'
clang: error: no input files
error: command '/usr/bin/clang' failed with exit status 1
Joannas-MacBook-Pro:~ joannaburke$

I have no idea how to fix this. Google has given me nothing. All help is appreciated. Thanks!

edit: pcapdumper.cc DOES exist, in the pcapy directory.


问:
Convert JS object to JS array
I have a javascript object like {"1":true,"2":false,"3":true}

I want to create a javascript array like [1,3] by taking the keys whose value is true.

How can I do that?

答:
You can do that Out of the box from ES5 using Object.keys(yourobject) and using the filter on top of it

```<code>var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
</code>```

Check it out here MDN article

Title: Convert JS object to JS array

Body:
You can do that Out of the box from ES5 using Object.keys(yourobject) and using the filter on top of it

var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']

Check it out here MDN article


问:
How to test for String = Enum.Value?
How do I do a simple compare of an enum value and a string that should match the enums name?

How do I parse the string into it's appropriate enum value.

For example,

```<code>Enum A
     B=0
     C=1
     D=2
End Enum
</code>```

How do I check if String = A.C and how do I convert string into its corresponding A value without comparing it to a string representation?

OwnerDisplayName: Middletone

ContentLicense: CC BY-SA 2.5

Title: How to test for String = Enum.Value?

Body:
How do I do a simple compare of an enum value and a string that should match the enums name?

How do I parse the string into it's appropriate enum value.

For example,

Enum A
     B=0
     C=1
     D=2
End Enum

How do I check if String = A.C and how do I convert string into its corresponding A value without comparing it to a string representation?

Body: Enum.GetName(typeof(A),enumValue)==stringValue

OwnerDisplayName: Josh


问:
PHP : Error While Using String Separator inside a Class
Why I can't use separators (.) in variables inside a class?

```<code>class Object(){
    public $var  = "Hello"."World";
    # Or
    public $test = "Hello";
    public $var2 = $this->test."World";
}
</code>```

This code gives me this error:

Parse error: syntax error, unexpected '.', expecting ',' or ';' in test.php on line 2

And how should I do it?

答:
Because you cannot declare class properties with variable expressions. That means you cannot use any arithmetic operators + - * / or the concatenation operator ., and you can't call functions. Out of your three lines, only $test should work; the other two will give you errors.

If you need to build your strings dynamically, do it in the constructor.

```<code>class Object {
    public $test = "Hello";
    public $var2;

    public function __construct() {
        $this->var2 = $this->test . "World";
    }
}
</code>```

By the way, . is not a "string separator". It's the concatenation operator. You use it to join strings, not separate them.

Body:
Why I can't use separators (.) in variables inside a class?

class Object(){
    public $var  = "Hello"."World";
    # Or
    public $test = "Hello";
    public $var2 = $this->test."World";
}

This code gives me this error:

Parse error: syntax error, unexpected '.', expecting ',' or ';' in test.php on line 2

And how should I do it?

Body:
Because you cannot declare class properties with variable expressions. That means you cannot use any arithmetic operators + - * / or the concatenation operator ., and you can't call functions. Out of your three lines, only $test should work; the other two will give you errors.

If you need to build your strings dynamically, do it in the constructor.

class Object {
    public $test = "Hello";
    public $var2;

    public function __construct() {
        $this->var2 = $this->test . "World";
    }
}

By the way, . is not a "string separator". It's the concatenation operator. You use it to join strings, not separate them.


问:
Dialog between Android and iPhone
Good day, everyone.

I have some problem with tokbox, when trying make connection between iphone (ios11) and android (7.1.2, chrome 63)

i get Video format not supported with any andorid device (galaxy s7, lenovo, xiaomi redmi 4x, any android studio emulators)

i have no idea what the problem is.
according tokbox site, problem in h264 support on my devices.
https://support.tokbox.com/hc/en-us/articles/115001579624-Chrome-on-Android-does-not-work-with-Safari-projects

but my procs is qualcomm and samsung, and chrome version is 63.

is there anybody, who have same problems? what i'm doing wrong? can be the problem in my code? i guess no, cause this is tokbox system message.

please, i'm waiting for some opinions!

答:
This is a known issue with Android devices that we've reported to the WebRTC bug tracker: https://bugs.chromium.org/p/webrtc/issues/detail?id=8584

We're working on a solution but unfortunately I cannot give a time estimate.

Regards,
Aiham

Title: Dialog between Android and iPhone


问:
JSselect keys with variable of array
Lets say I have an array:

```<code>var array = [
  {
   key1: {
     underkey1: {
       "somekey":"someValue"
     }
   },
  }
];
</code>```

I know I can reach for key1 like this:

```<code>var theVar = "key1";
array[theVar];
</code>```

But I want to reach underkey1 with one variable, like:

```<code>var theVar = "key1.underkey1";
</code>```

From what I have tried I get undefined.

How can it be done?

答:
You can split that string into array of keys and then use reduce() to reach nested value.

var array = [{key1: {underkey1: "somevalue"},}];

var val = 'key1.underkey1'
  .split('.')
  .reduce((r, e, i, arr) => {
    return r[e] || (arr[i+1] ? {} : undefined)
  }, array[0])

console.log(val)```

Title: JSselect keys with variable of array

Body:
Lets say I have an array:

var array = [
  {
   key1: {
     underkey1: {
       "somekey":"someValue"
     }
   },
  }
];

I know I can reach for key1 like this:

var theVar = "key1";
array[theVar];

But I want to reach underkey1 with one variable, like:

var theVar = "key1.underkey1";

From what I have tried I get undefined.

How can it be done?


问:
Types, expressions and arrays dimensions
I red the answers to a similar question where the matter is extensively and straighforwardly discussed. I would like to be sure of the correct interpretation i gave them.

For example, my textbook states, at exercise 6.24, that "The sizeof operator can be used to find the number of bytes needed to store a type or an expression. When applied to arrays, it does not yield the size of the array."

```<code>#include<stdio.h>

void f(int *a);

int main(){
    char s[] = "deep in the heart of texas";
    char *p  = "deep in the heart of texas";
    int a[3];
    double d[5];

    printf("%s%d\n%s%d\n%s%d\n%s%d\n",
        "sizeof(s) = ", sizeof(s),
        "sizeof(p) = ", sizeof(p),
        "sizeof(a) = ", sizeof(a),
        "sizeof(d) = ", sizeof(d));

    f(a);
    return 0;
}

void f(int *a){
    printf("In f(): sizeof(a) = %d\n", sizeof(a));
}
</code>```

Even so, it does not appear that obvious to me. Hence, I would like to briefly discuss the output with you:

```<code>sizeof(s) = 27
sizeof(p) = 8
sizeof(a) = 12
sizeof(d) = 40
In f(): sizeof(a) = 8
</code>```

Then:

```<code>sizeof(s) = 27
</code>```

In this case, 27 is the number of bytes of that s is composed of, being each char composed of one byte. This appear in contrast to the definition of sizeof because it returns what appear to be the _size_of an array. At this point, am I correct thinking that char s[] = "deep in the heart of texas" is considered as an expression?

```<code>sizeof(p) = 8
</code>```

Here, we have a pointer char *. Since sizeof "finds the number of bytes needed to store a type", I assume that a pointer char * is stored in 8 bytes of memory. Am I correct?

```<code>sizeof(a) = 12 and In f(): sizeof(a) = 8
</code>```

This case make me particularly unsure. The only relevant difference I found is that in f() the array a is passed as a parameter : a pointer to its base. As before, a pointer is stored in 8 bytes of memory. Am I correct? If so, 12 has to be considered to be the amount of memory needed to store the expression int a[3]?

```<code>sizeof(d) = 40
</code>```

Again, it appears to return the dimension of the array d, that is, five sections of 8 bytes each. But, again, we are not talking about an array, rather we are considering an expression double d[5]. Is it correct?

Thanks for sharing with me your knowledge and experience!

答:
Lots of text, which I didn't all read, but here is my answer:

```<code>char s[] = "deep in the heart of texas";   // sizeof = length of string + 1
char *p  = "deep in the heart of texas";   // sizeof is size of pointer = 8
int a[3];                                  // size of 3 ints
double d[5];                               // size of 5 doubles
</code>```

and in f, you correctly declare it as getting a pointer, so its size is the size of the pointer.

That's all...

Body:
I red the answers to a similar question where the matter is extensively and straighforwardly discussed. I would like to be sure of the correct interpretation i gave them.

For example, my textbook states, at exercise 6.24, that "The sizeof operator can be used to find the number of bytes needed to store a type or an expression. When applied to arrays, it does not yield the size of the array."

#include<stdio.h>

void f(int *a);

int main(){
    char s[] = "deep in the heart of texas";
    char *p  = "deep in the heart of texas";
    int a[3];
    double d[5];

    printf("%s%d\n%s%d\n%s%d\n%s%d\n",
        "sizeof(s) = ", sizeof(s),
        "sizeof(p) = ", sizeof(p),
        "sizeof(a) = ", sizeof(a),
        "sizeof(d) = ", sizeof(d));

    f(a);
    return 0;
}

void f(int *a){
    printf("In f(): sizeof(a) = %d\n", sizeof(a));
}

Even so, it does not appear that obvious to me. Hence, I would like to briefly discuss the output with you:

sizeof(s) = 27
sizeof(p) = 8
sizeof(a) = 12
sizeof(d) = 40
In f(): sizeof(a) = 8

Then:

sizeof(s) = 27

In this case, 27 is the number of bytes of that s is composed of, being each char composed of one byte. This appear in contrast to the definition of sizeof because it returns what appear to be the _size_of an array. At this point, am I correct thinking that char s[] = "deep in the heart of texas" is considered as an expression?

sizeof(p) = 8

Here, we have a pointer char *. Since sizeof "finds the number of bytes needed to store a type", I assume that a pointer char * is stored in 8 bytes of memory. Am I correct?

sizeof(a) = 12 and In f(): sizeof(a) = 8

This case make me particularly unsure. The only relevant difference I found is that in f() the array a is passed as a parameter : a pointer to its base. As before, a pointer is stored in 8 bytes of memory. Am I correct? If so, 12 has to be considered to be the amount of memory needed to store the expression int a[3]?

sizeof(d) = 40

Again, it appears to return the dimension of the array d, that is, five sections of 8 bytes each. But, again, we are not talking about an array, rather we are considering an expression double d[5]. Is it correct?

Thanks for sharing with me your knowledge and experience!

Body:
Lots of text, which I didn't all read, but here is my answer:

char s[] = "deep in the heart of texas";   // sizeof = length of string + 1
char *p  = "deep in the heart of texas";   // sizeof is size of pointer = 8
int a[3];                                  // size of 3 ints
double d[5];                               // size of 5 doubles

and in f, you correctly declare it as getting a pointer, so its size is the size of the pointer.

That's all...


答:
const o = {
    "1": true,
    "2": false,
    "3": true
};
const result = Object.entries(o).reduce((p, [k, v]) => v ? [...p, +k] : p, []);
console.log(result);```

Title: Convert JS object to JS array

Body:
I have a javascript object like {"1":true,"2":false,"3":true}

I want to create a javascript array like [1,3] by taking the keys whose value is true.

How can I do that?


问:
How to sort inbound props in a ReactJS component?
I have a ReactJS component that has a prop that is a collection.

I want to ensure this collection is always sorted for the component.

Where should I place the sorting logic?

Putting it inside the JSX will mean it is run on every render, which is inefficient.

```<code>class MyComponent {
    render() {
        const { collection } = this.props; // I want collection to stay sorted
        return <div>collection.map(i => <div>i</div>)</div>
    }
}
</code>```

答:
If for some reason you can't sort it before sending it to the component, componentWillReceiveProps would be good for this:

```<code>class MyComponent {
    this.sorted = [];

    componentWillReceiveProps(nextProps) {
        // Here you can check if the collection has changed
        // and skip the sort if it hasn't.
        this.sorted = sort(nextProps.collection);
    }

    render() {...}
}
</code>```

Body:
I have a ReactJS component that has a prop that is a collection.

I want to ensure this collection is always sorted for the component.

Where should I place the sorting logic?

Putting it inside the JSX will mean it is run on every render, which is inefficient.

class MyComponent {
    render() {
        const { collection } = this.props; // I want collection to stay sorted
        return
collection.map(i =>
i
)

    }
}

Body:
If for some reason you can't sort it before sending it to the component, componentWillReceiveProps would be good for this:

class MyComponent {
    this.sorted = [];

    componentWillReceiveProps(nextProps) {
        // Here you can check if the collection has changed
        // and skip the sort if it hasn't.
        this.sorted = sort(nextProps.collection);
    }

    render() {...}
}


答:
Please find the solution below. First you need to filter and then map to Numbers.

var obj = {
  "1": true,
  "2": false,
  "3": true
}

var keys = Object.keys(obj).filter(key => obj[key]).map(key => Number(key))

console.log(keys);```

Title: Convert JS object to JS array


答:
Briefly:

1) sizeof(s) = 27: The length of the string including NUL-terminator. Note that sizeof(char) is 1 by the standard.

2) sizeof(p) = 8: The size of a char* on your system.

3) sizeof(a) = 12: in main, yes that's the number of elements in the array multiplied by the size of each element. From this we can infer that sizeof(int) is 4.

4) sizeof(d) = 40: sizeof(double) multiplied by the number of elements.

In the function f, the array passed has decayed to a pointer type. Most likely sizeof(a) will be 8. The standard does not insist that sizeof(char*) is the same as sizeof(int*) but I've never come across a desktop PC where that is not the case.

Title: Types, expressions and arrays dimensions


问:
Is it possible to use code from a Web project in C# Interactive?
I would like to use C# Interactive on Visual Studio 2017 to run some methods on classes in an .NET Framework 4.6.1 project I have created which uses ASP.NET Core.  In a traditional class library project, I am able to right-click on the project and choose Initialize Interactive with Project to use classes from my project in the C# Interactive window.

Right-clicking on my ASP.NET Core project, I do not have this option. Is there any way to use classes from this project in C# Interactive?

If it matters, the classes I would like to use in C# Interactive do not directly interact with ASP.NET Core; they are simply data containers with methods. It would probably be possible to move them to a separate class library project in the solution, but I'd like to know if it's possible to keep them in the ASP.NET Core project first.

My .csproj:

```<code><Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="EntityFramework" Version="6.1.3" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNet.Mvc" Version="5.2.3" />
    <PackageReference Include="Microsoft.AspNet.Razor" Version="3.2.3" />
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.0.0" />
    <PackageReference Include="RazorEngine" Version="3.10.0" />
  </ItemGroup>

</Project>
</code>```

答:
Just open C# interactive window and type

```<code>#r "full path to dll\exe with your asp.net core project"
</code>```

Then you can use your classes as usual.

Note that if your project targets .NET Core - it might not work as expected (or at all), because as far as I know - C# interactive currently runs under full .NET Framework. However, in your case your project is also under full .NET (<TargetFramework>net461</TargetFramework>) so you should be fine.

Body:
I would like to use C# Interactive on Visual Studio 2017 to run some methods on classes in an .NET Framework 4.6.1 project I have created which uses ASP.NET Core.  In a traditional class library project, I am able to right-click on the project and choose Initialize Interactive with Project to use classes from my project in the C# Interactive window.

Right-clicking on my ASP.NET Core project, I do not have this option. Is there any way to use classes from this project in C# Interactive?

If it matters, the classes I would like to use in C# Interactive do not directly interact with ASP.NET Core; they are simply data containers with methods. It would probably be possible to move them to a separate class library project in the solution, but I'd like to know if it's possible to keep them in the ASP.NET Core project first.

My .csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="EntityFramework" Version="6.1.3" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNet.Mvc" Version="5.2.3" />
    <PackageReference Include="Microsoft.AspNet.Razor" Version="3.2.3" />
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.0.0" />
    <PackageReference Include="RazorEngine" Version="3.10.0" />
  </ItemGroup>

</Project>

Body:
Just open C# interactive window and type

#r "full path to dll\exe with your asp.net core project"

Then you can use your classes as usual.

Note that if your project targets .NET Core - it might not work as expected (or at all), because as far as I know - C# interactive currently runs under full .NET Framework. However, in your case your project is also under full .NET (<TargetFramework>net461</TargetFramework>) so you should be fine.


问:
Algorithm to get indexes in order
I want to assign indexes, in order, starting from 0, to objects. When an object is destroyed, the index should be freed for another use, eg.:

```<code>allocate_index() returns 0
allocate_index() returns 1
allocate_index() returns 2
allocate_index() returns 3
allocate_index() returns 4
release_index(1)
release_index(3)
allocate_index() returns 1
allocate_index() returns 3
allocate_index() returns 5
</code>```

This is similar to allocating file descriptor in a unix with open() and releasing with close().

But there is no bound fixed in advance.

Is there an efficient algorithm/data structure for allocating/freeing those indices?

答:
Adding to @Deimos's answer.

Only the released indices need to be stored in a heap data structure as opposed to all available indexes and use an additional variable to keep track of the currentIndex. That way if the next_index is the consecutive next and not from one of the released index it can be accessed in O(1) time as opposed to having the next_index pull from an heap of available indices and inserting back again the next available index. Both of which are O(log N) operations.

A sample code could look like this

```<code>#include <bits/stdc++.h>
class MaintainIndex
{
    private:
    int currentIndex;
    set<int> releasedIndex;
    public:
    MaintainIndex()
    {
        currentIndex = 1;
    }
    MaintainIndex(int start)
    {
        currentIndex = start;
    }
    int get_index()
    {
        int nextIndex;
        // No released indices available. Return the next consecutive one
        if(releasedIndex.size() == 0)
        {
            nextIndex = currentIndex;
            currentIndex += 1;
        }
        else //Return the smallest released index
        {
            nextIndex = *releasedIndex.begin();
            releasedIndex.erase(releasedIndex.begin());
        }
        return nextIndex;
    }
    void release_index(int index)
    {
        releasedIndex.insert(index);
    }
};
</code>```

Title: Algorithm to get indexes in order

Body:
I want to assign indexes, in order, starting from 0, to objects. When an object is destroyed, the index should be freed for another use, eg.:

allocate_index() returns 0
allocate_index() returns 1
allocate_index() returns 2
allocate_index() returns 3
allocate_index() returns 4
release_index(1)
release_index(3)
allocate_index() returns 1
allocate_index() returns 3
allocate_index() returns 5

This is similar to allocating file descriptor in a unix with open() and releasing with close().

But there is no bound fixed in advance.

Is there an efficient algorithm/data structure for allocating/freeing those indices?

Body:
Adding to @Deimos's answer.

Only the released indices need to be stored in a heap data structure as opposed to all available indexes and use an additional variable to keep track of the currentIndex. That way if the next_index is the consecutive next and not from one of the released index it can be accessed in O(1) time as opposed to having the next_index pull from an heap of available indices and inserting back again the next available index. Both of which are O(log N) operations.

A sample code could look like this

#include <bits/stdc++.h>
class MaintainIndex
{
    private:
    int currentIndex;
    set<int> releasedIndex;
    public:
    MaintainIndex()
    {
        currentIndex = 1;
    }
    MaintainIndex(int start)
    {
        currentIndex = start;
    }
    int get_index()
    {
        int nextIndex;
        // No released indices available. Return the next consecutive one
        if(releasedIndex.size() == 0)
        {
            nextIndex = currentIndex;
            currentIndex += 1;
        }
        else //Return the smallest released index
        {
            nextIndex = *releasedIndex.begin();
            releasedIndex.erase(releasedIndex.begin());
        }
        return nextIndex;
    }
    void release_index(int index)
    {
        releasedIndex.insert(index);
    }
};


问:
if else condition of css in jQuery not working
I wrote below code to get my output.

```<code>$(document).ready(function(){
  if ($('.figure').css("left","702px")) {
    $('.level1').css("display", "inline-block");
  } else {
    $('.level1').css("display", "none");
  }
});
</code>```

What I want when my .figure is reach to left 702px. I want to show level1 icon. But now display none is not applying before 702px. That is level1 icon showing before reaching to 702px. Anything wrong ? please help. Even i want to add more conditions that is after some for example left 1500px of .figure then show level2 icon. Thanks.

答:
It looks like your if statement is incorrect. This won't work;

```<code>if ($('.figure').css("left","702px"))
</code>```

You can't check against CSS values the same way that you set them. The if statement above will be evaluating "set left to 702px and check if successful...", which will almost always be true. Try changing it to the following;

```<code>if ($('.figure').css("left") == "702px")
</code>```

Update

Your comment just made me realise - this probably isn't going to work for you anyway. This will apply at exactly 702px only. Anything under or over will evaluate false. In that case, try comparing against the offset (this way, you can use < and > which won't work when the value contains 'px' as it does with .css);

```<code>if ($('.figure').offset().left > 702)
</code>```

Body:
I wrote below code to get my output.

$(document).ready(function(){
  if ($('.figure').css("left","702px")) {
    $('.level1').css("display", "inline-block");
  } else {
    $('.level1').css("display", "none");
  }
});

What I want when my .figure is reach to left 702px. I want to show level1 icon. But now display none is not applying before 702px. That is level1 icon showing before reaching to 702px. Anything wrong ? please help. Even i want to add more conditions that is after some for example left 1500px of .figure then show level2 icon. Thanks.

Body:
It looks like your if statement is incorrect. This won't work;

if ($('.figure').css("left","702px"))

You can't check against CSS values the same way that you set them. The if statement above will be evaluating "set left to 702px and check if successful...", which will almost always be true. Try changing it to the following;

if ($('.figure').css("left") == "702px")

Update

Your comment just made me realise - this probably isn't going to work for you anyway. This will apply at exactly 702px only. Anything under or over will evaluate false. In that case, try comparing against the offset (this way, you can use < and > which won't work when the value contains 'px' as it does with .css);

if ($('.figure').offset().left > 702)


问:
How to generate all the permutations of two elements in an array?
I would like, from a given array, to generate all the arrays obtained by swapping every possible couple of elements in an array, basically $\frac{n \cdot (n-1)} {2} $. What is the simplest way to make it ?

[EDIT] :For example, if I have [1 2 3 4] array, I would to generate [1 3 2 4],[1 2 4 3], [1 4 3 2],[2 1 3 4],[3 2 1 4]and [4 2 3 1]

答:
You can use this:

```<code>x = [10 20 30 40]; % example input array
t = nchoosek(1:numel(x),2); % each row defines a swapping of two elements
ind = bsxfun(@plus, (1:size(t,1)).', (t-1)*size(t,1)); % convert to linear index
result = repmat(x, size(t,1), 1); % initiallize result as copies of the input
result(ind) = result(fliplr(ind)); % do the swapping in each row
</code>```

In this example,

```<code>result =
    20    10    30    40
    30    20    10    40
    40    20    30    10
    10    30    20    40
    10    40    30    20
    10    20    40    30
</code>```

Each row of the result contains the input with 2 elements swapped. The swappings are done in lexicographical order. So in the first row elements 1 and 2 are swapped; in the second row elements 1 and 3 are swapped; ... ; in the last row elements 3 and 4 are swapped.

Body:
You can use this:

x = [10 20 30 40]; % example input array
t = nchoosek(1:numel(x),2); % each row defines a swapping of two elements
ind = bsxfun(@plus, (1:size(t,1)).', (t-1)*size(t,1)); % convert to linear index
result = repmat(x, size(t,1), 1); % initiallize result as copies of the input
result(ind) = result(fliplr(ind)); % do the swapping in each row

In this example,

result =
    20    10    30    40
    30    20    10    40
    40    20    30    10
    10    30    20    40
    10    40    30    20
    10    20    40    30

Each row of the result contains the input with 2 elements swapped. The swappings are done in lexicographical order. So in the first row elements 1 and 2 are swapped; in the second row elements 1 and 3 are swapped; ... ; in the last row elements 3 and 4 are swapped.


问:
Waiting for system to delete file
I had a problem with refreshing file list after deleting a file. When I gave command to delete file, the exception was thrown because the refresh method tried to access a file that was supposed to be deleted.

After some thought and debuging I came to conclusion that problem was in a fact that system needs some time to delete a file. And I solve it like this:

```<code>//Deleting file
System.Threading.Thread.Sleep(2000);
//Refreshing list
</code>```

and it worked fine.

My question is

Is there a more elegant way to wait for system do delete file and then continue with code...?

答:
I always used this:

```<code>System.GC.Collect();
System.GC.WaitForPendingFinalizers();
</code>```

See here and here

Title: Waiting for system to delete file

Body:
I had a problem with refreshing file list after deleting a file. When I gave command to delete file, the exception was thrown because the refresh method tried to access a file that was supposed to be deleted.

After some thought and debuging I came to conclusion that problem was in a fact that system needs some time to delete a file. And I solve it like this:

//Deleting file
System.Threading.Thread.Sleep(2000);
//Refreshing list

and it worked fine.

My question is

Is there a more elegant way to wait for system do delete file and then continue with code...?

Body:
I always used this:

System.GC.Collect();
System.GC.WaitForPendingFinalizers();

See here and here


问:
How to maintain cucumber test results for each Jenkins job
I am executing cucumber tests using Jenkins pipeline job(Jenkinsfile). But for every job it is overwriting the existing test results in the target/surefire-reports folder.

I would like to display all the cucumber test results for each and every job.

答:
You should add a timestamp in the reports folder name. Try the following code.

```<code>  <properties>
     <timestamp>${maven.build.timestamp}</timestamp>
     <maven.build.timestamp.format>yyyy_MM_dd_HH_mm</maven.build.timestamp.format>
  <properties>

    <plugin>
        <groupId>net.masterthought</groupId>
        <artifactId>maven-cucumber-reporting</artifactId>
        <version>${masterThougth.version}</version>
        <executions>
            <execution>
                <id>execution</id>
                <phase>verify</phase>
                <goals>
                    <goal>generate</goal>
                </goals>
                <configuration>
                    <checkBuildResult>false</checkBuildResult>
                    <projectName>${project.artifactId}</projectName>
                    <buildNumber>${project.build}</buildNumber>
                    <parallelTesting>true</parallelTesting>
                    <outputDirectory>target/cucumber-report/${timestamp}</outputDirectory>
                    <cucumberOutput>target/cucumber-report/</cucumberOutput>
                </configuration>
            </execution>
        </executions>
    </plugin>
</code>```

Body:
You should add a timestamp in the reports folder name. Try the following code.

  <properties>
     <timestamp>${maven.build.timestamp}</timestamp>
     <maven.build.timestamp.format>yyyy_MM_dd_HH_mm</maven.build.timestamp.format>
  <properties>

    <plugin>
        <groupId>net.masterthought</groupId>
        <artifactId>maven-cucumber-reporting</artifactId>
        <version>${masterThougth.version}</version>
        <executions>
            <execution>
                <id>execution</id>
                <phase>verify</phase>
                <goals>
                    <goal>generate</goal>
                </goals>
                <configuration>
                    <checkBuildResult>false</checkBuildResult>
                    <projectName>${project.artifactId}</projectName>
                    <buildNumber>${project.build}</buildNumber>
                    <parallelTesting>true</parallelTesting>
                    <outputDirectory>target/cucumber-report/${timestamp}</outputDirectory>
                    <cucumberOutput>target/cucumber-report/</cucumberOutput>
                </configuration>
            </execution>
        </executions>
    </plugin>


答:
.modal-content{
    margin-top:50px !important;
}```

Title: Moving Bootstrap modal on page

Body:
I have a bootstrap modal on the screen. When the modal is showed, it is positioned on the center of the screen.

        ....

I need to move the modal on my screen, because cover some information from my screen. The user should be able to move on the right, on the left...etc. Can I do that? there is some settings that I can use? or with js? what is the best way? Thanks!


问:
iOS 11 & iPhone X: UINavigationBar's toolbar spacing incorrect when embedded in UITabBarController
I am experiencing an annoying problem testing the newest iOS 11 on the iPhone X simulator.

I have an UITabBarController and inside each tab there is a UINavigationController, each UINavigationBar has defined also a bottom toolBar (setToolbarHidden:), and by default they show up at the bottom, just over the tabBar.

It has been working fine so far and seems to work fine also in the upcomming iPhone 8 and 8 Plus models, but on the iPhone X there is a gap between the toolBar and the tabBar. My guess is that the toolBar doesn't realize that is displayed inside a tabBar and then leaves the accommodating space at the bottom.

I guess the only way to fix it would be using a custom toolbar and display/animate it myself instead of using the defaults UINavigationBar, but I would like to hear other options :)

This is how it looks on iPhone 8.

And here is the problem on iPhone X.

答:
Apple still has not yet fixed this bug in iOS 11.2. Derived from Mousavian's solution, here is a simpler approach that I took.

I took this approach because I have just one UITableViewController where this bug happens. So in my case, I just added the following code listed below to my ViewController (which is UITableViewController) where this bug happens.

Advantages are:

This fix just takes over in case of an iPhone X. No side effects to expect on other devices

Works with any transition

Works regardless of other parent/child controllers having Toolbars or not

Simple

And here is the code:

1.Add startFixIPhoneXToolbarBug to your viewWillAppear like this:

```<code>override func viewWillAppear(_ animated: Bool)
{
    super.viewWillAppear(animated)

    startFixIPhoneXToolbarBug()
}
</code>```

2.Add endFixIPhoneXToolbarBug to your viewWillDisappear like this:

```<code>override func viewWillDisappear(_ animated: Bool)
{
    super.viewWillDisappear(animated)

    endFixIPhoneXToolbarBug()
}
</code>```

3.Implement start/endFixIPhoneXToolbarBug in your viewController like this:

```<code>private var alterToolbarHeightConstraint: NSLayoutConstraint? = nil
private var alterToolbar: UIToolbar? = nil

func startFixIPhoneXToolbarBug()
{
    // Check if we are running on an iPhone X
    if UIScreen.main.nativeBounds.height != 2436
    {
        return  // No
    }
    // See if we have a Toolbar
    if let tb:UIToolbar = self.navigationController?.toolbar
    {
        // See if we already added our own
        if alterToolbar == nil
        {
            // Should always be the case
            if let tbView = tb.superview
            {
                // Create a new Toolbar and apply correct constraints
                alterToolbar = UIToolbar()
                alterToolbar!.isTranslucent = true
                alterToolbar!.translatesAutoresizingMaskIntoConstraints = false
                tb.isHidden = true
                tbView.addSubview(alterToolbar!)
                if tbView.traitCollection.verticalSizeClass == .compact
                {
                    alterToolbarHeightConstraint = alterToolbar!.heightAnchor.constraint(equalToConstant: 32.0)
                }
                else
                {
                    alterToolbarHeightConstraint = alterToolbar!.heightAnchor.constraint(equalToConstant: 44.0)
                }
                let bottomAnchor: NSLayoutConstraint
                if #available(iOS 11.0, *)
                {
                    bottomAnchor = alterToolbar!.bottomAnchor.constraint(equalTo: tbView.safeAreaLayoutGuide.bottomAnchor)
                }
                else
                {
                    bottomAnchor = alterToolbar!.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor)
                }
                NSLayoutConstraint.activate([
                    alterToolbar!.leadingAnchor.constraint(equalTo: tbView.leadingAnchor),
                    alterToolbar!.trailingAnchor.constraint(equalTo: tbView.trailingAnchor),
                    bottomAnchor,
                    alterToolbarHeightConstraint!
                    ])
                tbView.updateFocusIfNeeded()
                tbView.layoutIfNeeded()
            }
        }
        // Add the original items to the new toolbox
        alterToolbar!.setItems(tb.items, animated: false)
    }
}

func endFixIPhoneXToolbarBug()
{
    if alterToolbar != nil
    {
        alterToolbar!.removeFromSuperview()
        alterToolbar = nil
        alterToolbarHeightConstraint = nil

        if let tb:UIToolbar = self.navigationController?.toolbar
        {
            tb.isHidden = false
        }
    }
}
</code>```

Body:
Apple still has not yet fixed this bug in iOS 11.2. Derived from Mousavian's solution, here is a simpler approach that I took.

I took this approach because I have just one UITableViewController where this bug happens. So in my case, I just added the following code listed below to my ViewController (which is UITableViewController) where this bug happens.

Advantages are:

This fix just takes over in case of an iPhone X. No side effects to expect on other devices

Works with any transition

Works regardless of other parent/child controllers having Toolbars or not

Simple

And here is the code:

1.Add startFixIPhoneXToolbarBug to your viewWillAppear like this:

override func viewWillAppear(_ animated: Bool)
{
    super.viewWillAppear(animated)

    startFixIPhoneXToolbarBug()
}

2.Add endFixIPhoneXToolbarBug to your viewWillDisappear like this:

override func viewWillDisappear(_ animated: Bool)
{
    super.viewWillDisappear(animated)

    endFixIPhoneXToolbarBug()
}

3.Implement start/endFixIPhoneXToolbarBug in your viewController like this:

private var alterToolbarHeightConstraint: NSLayoutConstraint? = nil
private var alterToolbar: UIToolbar? = nil

func startFixIPhoneXToolbarBug()
{
    // Check if we are running on an iPhone X
    if UIScreen.main.nativeBounds.height != 2436
    {
        return  // No
    }
    // See if we have a Toolbar
    if let tb:UIToolbar = self.navigationController?.toolbar
    {
        // See if we already added our own
        if alterToolbar == nil
        {
            // Should always be the case
            if let tbView = tb.superview
            {
                // Create a new Toolbar and apply correct constraints
                alterToolbar = UIToolbar()
                alterToolbar!.isTranslucent = true
                alterToolbar!.translatesAutoresizingMaskIntoConstraints = false
                tb.isHidden = true
                tbView.addSubview(alterToolbar!)
                if tbView.traitCollection.verticalSizeClass == .compact
                {
                    alterToolbarHeightConstraint = alterToolbar!.heightAnchor.constraint(equalToConstant: 32.0)
                }
                else
                {
                    alterToolbarHeightConstraint = alterToolbar!.heightAnchor.constraint(equalToConstant: 44.0)
                }
                let bottomAnchor: NSLayoutConstraint
                if #available(iOS 11.0, *)
                {
                    bottomAnchor = alterToolbar!.bottomAnchor.constraint(equalTo: tbView.safeAreaLayoutGuide.bottomAnchor)
                }
                else
                {
                    bottomAnchor = alterToolbar!.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor)
                }
                NSLayoutConstraint.activate([
                    alterToolbar!.leadingAnchor.constraint(equalTo: tbView.leadingAnchor),
                    alterToolbar!.trailingAnchor.constraint(equalTo: tbView.trailingAnchor),
                    bottomAnchor,
                    alterToolbarHeightConstraint!
                    ])
                tbView.updateFocusIfNeeded()
                tbView.layoutIfNeeded()
            }
        }
        // Add the original items to the new toolbox
        alterToolbar!.setItems(tb.items, animated: false)
    }
}

func endFixIPhoneXToolbarBug()
{
    if alterToolbar != nil
    {
        alterToolbar!.removeFromSuperview()
        alterToolbar = nil
        alterToolbarHeightConstraint = nil

        if let tb:UIToolbar = self.navigationController?.toolbar
        {
            tb.isHidden = false
        }
    }
}


问:
binding a angular reactive form FormControl to a dynamic value
I have a reactive form instantiated using FormBuilder.  I would like to use this form for updating or adding a new employee.  I am trying to add an expression to the formBuilder constructor that checks to see whether there is a currently selected employee and if there is use one of that employee's interface fields as the value on the form and if there's no current selected employee have a empty string as the value of the specific FormControl.

what i've tried:

```<code>'EMP_NM': [this.selectedEmp ? this.selectedEmp.EMP_NM : '',  Validators.required],
</code>```

and then in my editEmployee function:

```<code>editCashier(employee: IEmployee) {
    this.selectedEmp = employee;
    this.empForm.reset();
    console.log(this.selectedEmp.EMP_NM);
}
</code>```

When I do this the value shown on the EMP_NM input field in the HTML doesn't get updated.  i've tried setting a setTimeout() in my editEmployee function but that didn't work either.  Any idea what might be going wrong here?

I initialize the empForm in my conponent's constructor using formBuilder's group function.  Would it help if I moved that to a different function and then call that function everytime the editEmployee function is called to re-initialize the form?

答:
You can update it with patchValue or setValue:

```<code>this.empForm['controls']['employee'].patchValue(employee);
</code>```

Have no clue if it's a nested control but you can go more layers down.

Body:
I have a reactive form instantiated using FormBuilder.  I would like to use this form for updating or adding a new employee.  I am trying to add an expression to the formBuilder constructor that checks to see whether there is a currently selected employee and if there is use one of that employee's interface fields as the value on the form and if there's no current selected employee have a empty string as the value of the specific FormControl.

what i've tried:

'EMP_NM': [this.selectedEmp ? this.selectedEmp.EMP_NM : '',  Validators.required],

and then in my editEmployee function:

editCashier(employee: IEmployee) {
    this.selectedEmp = employee;
    this.empForm.reset();
    console.log(this.selectedEmp.EMP_NM);
}

When I do this the value shown on the EMP_NM input field in the HTML doesn't get updated.  i've tried setting a setTimeout() in my editEmployee function but that didn't work either.  Any idea what might be going wrong here?

I initialize the empForm in my conponent's constructor using formBuilder's group function.  Would it help if I moved that to a different function and then call that function everytime the editEmployee function is called to re-initialize the form?

Body:
You can update it with patchValue or setValue:

this.empForm['controls']['employee'].patchValue(employee);

Have no clue if it's a nested control but you can go more layers down.