问:
jQuery can't catch the parent element
I am trying to access the parent element up to the button element to modify its css. I can access the span element via id. But when I try to go to the parent img it says undefined

Here is my html code

```<code><button type="button" class="buttonLike">\
    <img src = "../Image/thumbsUp.png" clas="test">\
            <span class="postID" id=' + idPost + '>' + likesPost + '</span>\
    </img>\
 </button>\
</code>```

and here is my jquery code that access the span element

```<code>$.each(result, function (index,data) {
                var liked = data.liked;
                if (liked == true) {
                    console.log($("#" + postId).parent("img").attr("src"));
                }
   });
</code>```

How can i do this right.

答:
img element is self-closing. try this:

```<code><button type="button" class="buttonLike">\
    <img src = "../Image/thumbsUp.png" clas="test">
    <span class="postID" id=' + idPost + '>' + likesPost + '</span>\
 </button>
</code>```

and get it with jquery:

```<code>  console.log($("#" + postId).parent().find("img").attr("src"));
</code>```

Title: jQuery can't catch the parent element

Body:
I am trying to access the parent element up to the button element to modify its css. I can access the span element via id. But when I try to go to the parent img it says undefined

Here is my html code

<button type="button" class="buttonLike">\
    \
            ' + likesPost + '\
    \
 </button>\

and here is my jquery code that access the span element

$.each(result, function (index,data) {
                var liked = data.liked;
                if (liked == true) {
                    console.log($("#" + postId).parent("img").attr("src"));
                }
   });

How can i do this right.

Body:
img element is self-closing. try this:

<button type="button" class="buttonLike">\
    <img src = "../Image/thumbsUp.png" clas="test">
    <span class="postID" id=' + idPost + '>' + likesPost + '</span>\
 </button>

and get it with jquery:

  console.log($("#" + postId).parent().find("img").attr("src"));


来源: stackexchange

问:
ASP.Net MVC returning values from List of Checkboxes
I have a model with a property that is a List. MyObjects simply has an id, a description and a selected boolean property.

I have managed to display the items as checkboxes on my view. I did this via:

```<code> <%foreach (var cat in Model.DefaultCategories)
      {%>
    <tr>
        <td>
        <%=cat.Category %>

        </td>
        <td>
           <%=Html.CheckBoxFor(x=>cat.Selected) %>
        </td>
    </tr>
    <%
        }%>
</table>
</code>```

However, there is a problem. They all end up, when rendered, with the same names. Here's a portion of my list:

```<code>        <tr>
        <td>
        Medical

        </td>
        <td>
           <input id="cat_Selected" name="cat.Selected" type="checkbox" value="true" /><input name="cat.Selected" type="hidden" value="false" />
        </td>

    </tr>

    <tr>
        <td>
        Salary

        </td>
        <td>
           <input checked="checked" id="cat_Selected" name="cat.Selected" type="checkbox" value="true" /><input name="cat.Selected" type="hidden" value="false" />
        </td>
    </tr>
</code>```

They have all been named "cat.Selected".

How can I resolve this?

And then, when I submit, I need to iterate through them. With different names, I assume I can get them in my HttpPost method:

```<code>        [HttpPost]
    public ActionResult Modify(int id, FormCollection formValues)
    {
        PayeeDto p = new PayeeDto { Name = Request.Form["name"], PayeeId = id };

        Services.PayeeServices.Save(p);
        return RedirectToAction("Index");
    }
</code>```

The FormCollection will have the different names? At the moment, it just has the single 'cat.selected' item.

答:
This may not be the best answer but I try not to use generated checkboxes in MVC.

I would change

```<code><td>
   <%=Html.CheckBoxFor(x=>cat.Selected) %>
</td>
</code>```

To

```<code><td>
   <input type="checkbox" name="<%: cat.value %>" id="<%: cat.value %>" <% cat.Selected ? " checked=\"checked\" " : ""; %> />
</td>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a model with a property that is a List. MyObjects simply has an id, a description and a selected boolean property.

I have managed to display the items as checkboxes on my view. I did this via:

 <%foreach (var cat in Model.DefaultCategories)
      {%>

        <%=cat.Category %>

           <%=Html.CheckBoxFor(x=>cat.Selected) %>

    <%
        }%>

However, there is a problem. They all end up, when rendered, with the same names. Here's a portion of my list:

        Medical

           <input id="cat_Selected" name="cat.Selected" type="checkbox" value="true" /><input name="cat.Selected" type="hidden" value="false" />

        Salary

           <input checked="checked" id="cat_Selected" name="cat.Selected" type="checkbox" value="true" /><input name="cat.Selected" type="hidden" value="false" />

They have all been named "cat.Selected".

How can I resolve this?

And then, when I submit, I need to iterate through them. With different names, I assume I can get them in my HttpPost method:

        [HttpPost]
    public ActionResult Modify(int id, FormCollection formValues)
    {
        PayeeDto p = new PayeeDto { Name = Request.Form["name"], PayeeId = id };

        Services.PayeeServices.Save(p);
        return RedirectToAction("Index");
    }

The FormCollection will have the different names? At the moment, it just has the single 'cat.selected' item.

Body:
This may not be the best answer but I try not to use generated checkboxes in MVC.

I would change

<td>
   <%=Html.CheckBoxFor(x=>cat.Selected) %>
</td>

To

<td>
   <input type="checkbox" name="<%: cat.value %>" id="<%: cat.value %>" <% cat.Selected ? " checked=\"checked\" " : ""; %> />
</td>


问:
retuning null value on getActivity() after Firebase updates the database and gets back to the fragment
I am using Firebase in my project. I have a navigation drawer to navigate through different fragments. everything was working until I added onItemLongClick on my listView. at the bigining, when the app starts, I can go to my listview and add and remove items without problems. But when I go to another fragment, and come back to that listview, the listview is working fine but once I do the onItemLongClick to remove, the Firebase removes the element in the database instantly, but the  getActivity() on onCreate function returns null and crashes the app. I am doing the same mistake in adding method, because I get the same error on adding. Herein is my code:

```<code>public class dressListActivity extends Fragment {

    ListView dressListView;
    DatabaseReference databaseDresss;
    myDressAdapter dressAdapter;
    Query queryMyDresss;
    ArrayList<DressDataModel> dressList= new ArrayList<DressDataModel>();;

    @Override
    public void onStart() {
        super.onStart();

        String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
        queryMyDresss = FirebaseDatabase.getInstance().getReference("dresses").orderByChild("dressCreatorId").equalTo(userID);

        queryMyDresss.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                dressList.clear();
                for (DataSnapshot postSnapshot: dataSnapshot.getChildren())
                {
                    DressDataModel dress = postSnapshot.getValue(DressDataModel.class);
                    dressList.add(dress);
                }
                //getActivity() returns null in the below line:
                dressAdapter = new myDressAdapter(getActivity(),dressList);
                dressListView.setAdapter(dressAdapter);
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
dressListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l)

        DressDataModel dress = dressList.get(i);
        deleteDress(dress);
        return true;

    }
});
});
        dressListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        closetListActivity pla=new closetListActivity();
        Bundle args =new Bundle();
        DressDataModel dress = dressList.get(i);
        args.putString("DRESS_ID",dress.getDressId());
        args.putString("DRESS_NAME",dress.getDressName());
        args.putString("DRESS_CREATOR_ID",dress.getDressCreatorId());
        pla.setArguments(args);
        FragmentManager fm=getFragmentManager();
        FragmentTransaction ft=fm.beginTransaction();
        ft.replace(R.id.content_dress_main,pla);
        ft.commit();

    }
});
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    getActivity().setTitle("Dress List");
    databaseDresss = FirebaseDatabase.getInstance().getReference("dresses");
    dressListView = (ListView) view.findViewById(R.id.dressListview);
    //-------------------------------------------
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.dress_list,container,false);
    dressListView = (ListView) view.findViewById(R.id.dressListview);

    return  view;
}
private void deleteDress(DressDataModel dress) {
    DatabaseReference eventContactsRef = FirebaseDatabase.getInstance().getReference("dresses");
    eventContactsRef.child(dress.getDressId()).removeValue();
    dressList.remove(dress);
}
}
</code>```

and here is my main activity having navigation code

```<code>private void navigationSelectedScreen(int i)
{
    Fragment fragment = null;
    switch (i)
    {
        case R.id.nav_Search:
        fragment = new ActivedressActivity();
        break;
    case R.id.nav_myJukebox:

        fragment = new dressListActivity();
        break;
    case R.id.nav_favorite:
        fragment=new favoriteListActivity();
        break;
    case R.id.nav_message:
    fragment = new MessageActivity();
        break;
    case R.id.nav_friends:
        fragment = new MessageActivity();
        break;
}
if (fragment!=null)
{
    FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.content_dress_main,fragment);
    ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
</code>```

Error message:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.dress.pooya.dressy, PID: 933
                  java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
                      at android.view.LayoutInflater.from(LayoutInflater.java:233)
                      at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:181)
                      at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:166)
                      at com.dress.myDressAdapter.<init>(myDressAdapter.java:37)
                      at com.dress.dressListActivity$1.onDataChange(dressListActivity.java:75)
                      at com.google.android.gms.internal.zzaie.zza(Unknown Source)
                      at com.google.android.gms.internal.zzaje.zzcta(Unknown Source)
                      at com.google.android.gms.internal.zzajh$1.run(Unknown Source)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6776)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
</code>```

答:
Your post includes this code containing a comment indicating getActivity() returns null.

```<code>    queryMyDresss.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            dressList.clear();
            for (DataSnapshot postSnapshot: dataSnapshot.getChildren())
            {
                DressDataModel dress = postSnapshot.getValue(DressDataModel.class);
                dressList.add(dress);
            }
            //getActivity() returns null in the below line:
            dressAdapter = new myDressAdapter(getActivity(),dressList);
            dressListView.setAdapter(dressAdapter);
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
</code>```

In this code, when adding a listener, you should use addListenerForSingleValueEvent(), not addValueEventListener(), which  leaves the listener attached.  When the user navigates away from dressListActivity (which despite the name is actually a fragment), the fragment is detached from the host activity, so getActivity() returns null. But the fragment still exists in memory with the active listener, so when the data at the query location changes, onDataChange() fires and the NPE occurs.

ContentLicense: CC BY-SA 3.0

Body:
I am using Firebase in my project. I have a navigation drawer to navigate through different fragments. everything was working until I added onItemLongClick on my listView. at the bigining, when the app starts, I can go to my listview and add and remove items without problems. But when I go to another fragment, and come back to that listview, the listview is working fine but once I do the onItemLongClick to remove, the Firebase removes the element in the database instantly, but the  getActivity() on onCreate function returns null and crashes the app. I am doing the same mistake in adding method, because I get the same error on adding. Herein is my code:

public class dressListActivity extends Fragment {

    ListView dressListView;
    DatabaseReference databaseDresss;
    myDressAdapter dressAdapter;
    Query queryMyDresss;
    ArrayList<DressDataModel> dressList= new ArrayList<DressDataModel>();;

    @Override
    public void onStart() {
        super.onStart();

        String userID = FirebaseAuth.getInstance().getCurrentUser().getUid();
        queryMyDresss = FirebaseDatabase.getInstance().getReference("dresses").orderByChild("dressCreatorId").equalTo(userID);

        queryMyDresss.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                dressList.clear();
                for (DataSnapshot postSnapshot: dataSnapshot.getChildren())
                {
                    DressDataModel dress = postSnapshot.getValue(DressDataModel.class);
                    dressList.add(dress);
                }
                //getActivity() returns null in the below line:
                dressAdapter = new myDressAdapter(getActivity(),dressList);
                dressListView.setAdapter(dressAdapter);
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
dressListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l)

        DressDataModel dress = dressList.get(i);
        deleteDress(dress);
        return true;

    }
});
});
        dressListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

        closetListActivity pla=new closetListActivity();
        Bundle args =new Bundle();
        DressDataModel dress = dressList.get(i);
        args.putString("DRESS_ID",dress.getDressId());
        args.putString("DRESS_NAME",dress.getDressName());
        args.putString("DRESS_CREATOR_ID",dress.getDressCreatorId());
        pla.setArguments(args);
        FragmentManager fm=getFragmentManager();
        FragmentTransaction ft=fm.beginTransaction();
        ft.replace(R.id.content_dress_main,pla);
        ft.commit();

    }
});
@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    getActivity().setTitle("Dress List");
    databaseDresss = FirebaseDatabase.getInstance().getReference("dresses");
    dressListView = (ListView) view.findViewById(R.id.dressListview);
    //-------------------------------------------
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.dress_list,container,false);
    dressListView = (ListView) view.findViewById(R.id.dressListview);

    return  view;
}
private void deleteDress(DressDataModel dress) {
    DatabaseReference eventContactsRef = FirebaseDatabase.getInstance().getReference("dresses");
    eventContactsRef.child(dress.getDressId()).removeValue();
    dressList.remove(dress);
}
}

and here is my main activity having navigation code

private void navigationSelectedScreen(int i)
{
    Fragment fragment = null;
    switch (i)
    {
        case R.id.nav_Search:
        fragment = new ActivedressActivity();
        break;
    case R.id.nav_myJukebox:

        fragment = new dressListActivity();
        break;
    case R.id.nav_favorite:
        fragment=new favoriteListActivity();
        break;
    case R.id.nav_message:
    fragment = new MessageActivity();
        break;
    case R.id.nav_friends:
        fragment = new MessageActivity();
        break;
}
if (fragment!=null)
{
    FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
    ft.replace(R.id.content_dress_main,fragment);
    ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}

Error message:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.dress.pooya.dressy, PID: 933
                  java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
                      at android.view.LayoutInflater.from(LayoutInflater.java:233)
                      at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:181)
                      at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:166)
                      at com.dress.myDressAdapter.<init>(myDressAdapter.java:37)
                      at com.dress.dressListActivity$1.onDataChange(dressListActivity.java:75)
                      at com.google.android.gms.internal.zzaie.zza(Unknown Source)
                      at com.google.android.gms.internal.zzaje.zzcta(Unknown Source)
                      at com.google.android.gms.internal.zzajh$1.run(Unknown Source)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6776)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

Body:
Your post includes this code containing a comment indicating getActivity() returns null.

    queryMyDresss.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            dressList.clear();
            for (DataSnapshot postSnapshot: dataSnapshot.getChildren())
            {
                DressDataModel dress = postSnapshot.getValue(DressDataModel.class);
                dressList.add(dress);
            }
            //getActivity() returns null in the below line:
            dressAdapter = new myDressAdapter(getActivity(),dressList);
            dressListView.setAdapter(dressAdapter);
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

In this code, when adding a listener, you should use addListenerForSingleValueEvent(), not addValueEventListener(), which  leaves the listener attached.  When the user navigates away from dressListActivity (which despite the name is actually a fragment), the fragment is detached from the host activity, so getActivity() returns null. But the fragment still exists in memory with the active listener, so when the data at the query location changes, onDataChange() fires and the NPE occurs.


问:
How to marge two arrays data and save one SQL table
I have two array. I want merge and insert to the database using php. here i put some array data. but my array is very big one.

Array1

```<code>Array
(
    [1] => Array
        (
            [ALT_ID] => 2003211
            [STUDENT_ID] => 2235
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [2] => Array
        (
            [ALT_ID] => 2003458
            [STUDENT_ID] => 2495
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [3] => Array
        (
            [ALT_ID] => 2003211
            [STUDENT_ID] => 2235
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [4] => Array
        (
            [ALT_ID] => 2003587
            [STUDENT_ID] => 2624
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [5] => Array
        (
            [ALT_ID] => 2003614
            [STUDENT_ID] => 2651
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [6] => Array
        (
            [ALT_ID] => 2003682
            [STUDENT_ID] => 2721
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [7] => Array
        (
            [ALT_ID] => 2003685
            [STUDENT_ID] => 2724
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [8] => Array
        (
            [ALT_ID] => 2003777
            [STUDENT_ID] => 2814
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )
)
</code>```

Array2

```<code>Array
(
    [1] => Array
        (
            [COURSE_ID] => 1
            [TITLE] => Programming Methodology
            [SHORT_NAME] => ECSI402
            [MODULE_STATUS] => Core
        )

    [2] => Array
        (
            [COURSE_ID] => 2
            [TITLE] => Communication and Learning Skills in Computer Science  (SE)
            [SHORT_NAME] => ECSI400
            [MODULE_STATUS] => Core
        )

    [3] => Array
        (
            [COURSE_ID] => 3
            [TITLE] => Computer Systems Fundamentals
            [SHORT_NAME] => ECSI404
            [MODULE_STATUS] => Core
        )

    [4] => Array
        (
            [COURSE_ID] => 4
            [TITLE] => Information and Data Modeling  (SE)
            [SHORT_NAME] => EBSI401
            [MODULE_STATUS] => Core
        )

    [5] => Array
        (
            [COURSE_ID] => 5
            [TITLE] => Software Development Principles
            [SHORT_NAME] => ECSI406
            [MODULE_STATUS] => Core
        )
)
</code>```

I want these two data submit to the one table. this is the SQL query for that.

```<code>INSERT INTO MODULE_REG (STUDENT_ID, COURSE_ID, DATE_REGISTERED, REGISTERED, ACADEMIC_SESSION)
</code>```

My database table i want save like this. this is sample one. i have to submit these two arrays all data for like this.

```<code> +-----------+----------+-----------+----------------+-------------+
|student id | course id| registered| data_registered| academic ses|
+-----------+----------+-----------+----------------+-------------+
|  2235     |    1     |     Y     |  2017.11.16    |  Level 4    |
|  2235     |    2     |     Y     |  2017.11.16    |  Level 4    |
|  2235     |    3     |     Y     |  2017.11.16    |  Level 4    |
|  2495     |    1     |     Y     |  2017.11.16    |  Level 4    |
|  2495     |    2     |     Y     |  2017.11.16    |  Level 4    |
|  2495     |    3     |     Y     |  2017.11.16    |  Level 4    |
+-----------+----------+-----------+----------------+-------------+
</code>```

答:
You can try something like this

```<code>for($i=0;$i<count($array1);$i++){

$student_id[$i]=$array1[$i]['STUDENT_ID'];
$accademic_ses[$i]=$array1[$i]['ACADEMIC_SESSION'];
for($j=0;$j<count($array2);$j++){

$sql= "INSERT INTO MODULE_REG (STUDENT_ID, COURSE_ID, DATE_REGISTERED, REGISTERED, ACADEMIC_SESSION) VALUES (".$student_id[$i].",".$course_id[$j].",/*add your registered and data_registered here/*,".$accademic_ses[$i].")";

/*execute your sql here*/
}
}
</code>```

I cannot see any values for registered and data_registered so I didnt add. You can add accordingly.

ContentLicense: CC BY-SA 4.0

Body:
I have two array. I want merge and insert to the database using php. here i put some array data. but my array is very big one.

Array1

Array
(
    [1] => Array
        (
            [ALT_ID] => 2003211
            [STUDENT_ID] => 2235
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [2] => Array
        (
            [ALT_ID] => 2003458
            [STUDENT_ID] => 2495
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [3] => Array
        (
            [ALT_ID] => 2003211
            [STUDENT_ID] => 2235
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [4] => Array
        (
            [ALT_ID] => 2003587
            [STUDENT_ID] => 2624
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [5] => Array
        (
            [ALT_ID] => 2003614
            [STUDENT_ID] => 2651
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [6] => Array
        (
            [ALT_ID] => 2003682
            [STUDENT_ID] => 2721
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [7] => Array
        (
            [ALT_ID] => 2003685
            [STUDENT_ID] => 2724
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )

    [8] => Array
        (
            [ALT_ID] => 2003777
            [STUDENT_ID] => 2814
            [CUSTOM_30] => JAN
            [TITLE] => Level 4
        )
)

Array2

Array
(
    [1] => Array
        (
            [COURSE_ID] => 1
            [TITLE] => Programming Methodology
            [SHORT_NAME] => ECSI402
            [MODULE_STATUS] => Core
        )

    [2] => Array
        (
            [COURSE_ID] => 2
            [TITLE] => Communication and Learning Skills in Computer Science  (SE)
            [SHORT_NAME] => ECSI400
            [MODULE_STATUS] => Core
        )

    [3] => Array
        (
            [COURSE_ID] => 3
            [TITLE] => Computer Systems Fundamentals
            [SHORT_NAME] => ECSI404
            [MODULE_STATUS] => Core
        )

    [4] => Array
        (
            [COURSE_ID] => 4
            [TITLE] => Information and Data Modeling  (SE)
            [SHORT_NAME] => EBSI401
            [MODULE_STATUS] => Core
        )

    [5] => Array
        (
            [COURSE_ID] => 5
            [TITLE] => Software Development Principles
            [SHORT_NAME] => ECSI406
            [MODULE_STATUS] => Core
        )
)

I want these two data submit to the one table. this is the SQL query for that.

INSERT INTO MODULE_REG (STUDENT_ID, COURSE_ID, DATE_REGISTERED, REGISTERED, ACADEMIC_SESSION)

My database table i want save like this. this is sample one. i have to submit these two arrays all data for like this.

 +-----------+----------+-----------+----------------+-------------+
|student id | course id| registered| data_registered| academic ses|
+-----------+----------+-----------+----------------+-------------+
|  2235     |    1     |     Y     |  2017.11.16    |  Level 4    |
|  2235     |    2     |     Y     |  2017.11.16    |  Level 4    |
|  2235     |    3     |     Y     |  2017.11.16    |  Level 4    |
|  2495     |    1     |     Y     |  2017.11.16    |  Level 4    |
|  2495     |    2     |     Y     |  2017.11.16    |  Level 4    |
|  2495     |    3     |     Y     |  2017.11.16    |  Level 4    |
+-----------+----------+-----------+----------------+-------------+

Body:
You can try something like this

for($i=0;$i<count($array1);$i++){

$student_id[$i]=$array1[$i]['STUDENT_ID'];
$accademic_ses[$i]=$array1[$i]['ACADEMIC_SESSION'];
for($j=0;$j<count($array2);$j++){

$sql= "INSERT INTO MODULE_REG (STUDENT_ID, COURSE_ID, DATE_REGISTERED, REGISTERED, ACADEMIC_SESSION) VALUES (".$student_id[$i].",".$course_id[$j].",/*add your registered and data_registered here/*,".$accademic_ses[$i].")";

/*execute your sql here*/
}
}

I cannot see any values for registered and data_registered so I didnt add. You can add accordingly.


问:
In Maven, Why Run 'mvn clean'?
I am wondering what the major difference between running mvn compile and mvn clean compile are, in practicality.

I understand what the actual difference is, that mvn clean compile deletes all the generated files and starts again from scratch, but why would we want to do this? I can assume mvn compile will regenerate files if it's necessary, right?

One thing I noticed in my project was that if you had deleted a source file, without running clean, the compiled file remains, which usually wouldn't be a problem, but could be I suppose.

答: If you don't do clean compile then it means you are still allowing to work with some obsolete classes. If your module suppose to migrate to new class then even you missed that, there won't be any compilation error due to old class exist in target/classes. This will remain unnoticed till same module is built at some other place/machine with clean compile goal.</p>

Title: In Maven, Why Run 'mvn clean'?


问:
How to Ignore class property from Json Serialization
I am creating a webservice using asp.net 4.0.

I have created a asmx file and creating a User.cs Class. It has 8 Properties.
I have return a service with json format.
If the userlogin is true i need to return all the properties of user.cs, if it's fail i need to return only 2 property.

How to achieve it.

User login is true. It will return all

{"message":"valid user","BranchId":1,"BranchName":"My branch Name","Id":1,"Name":"admin","Password":"admin","RoleId":1,"Status":1}

User login is failed i need to retun only message and Status. but it will return all like as foloows

{"message":"username or password is invalid","BranchId":0,"BranchName":null,"Id":0,"Name":null,"Password":null,"RoleId":0,"Status":0}

I have google it and get the following Link. How to use it based on my login status condition.

If i have used [ScriptIgnore] in my property it will ignore property both case. I need to ignore property when login failed.

My properties like this

```<code>// Properties
    public int BranchId
    {
        get { return _BranchId; }
        set { if (_BranchId != value) { _BranchId = value; } }
    }

    public string BranchName
    {
        get { return _BranchName; }
        set { _BranchName = value; }
    }

    private String _message;

    public String message
    {
        get { return _message; }
        set { _message = value; }
    }
</code>```

My webservice

```<code>[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void appLogin(String userName, String passWord)
    {
        Admin_AppUserBLL objusr = Admin_AppUserBLL.GetAdmin_AppUserBLL(userName);
        string strResponse = "";
        if (objusr != null)
        {
            if (objusr.Password == passWord)
            {
                objusr.message = "valid username";
                strResponse = new JavaScriptSerializer().Serialize(objusr);
            }
        }
        else
        {
            objusr = new Admin_AppUserBLL();
            objusr.message = "username or password is invalid";
            strResponse = new JavaScriptSerializer().Serialize(objusr);
        }
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";
        Context.Response.AddHeader("content-length", strResponse.Length.ToString());
        Context.Response.Flush();
        Context.Response.Write(strResponse);
    }
</code>```

答:
Add reference in Newtonsoft

```<code>using Newtonsoft.Json;
</code>```

while serialize the object

```<code>string strResponse = JsonConvert.SerializeObject(objusr, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
</code>```

it will avoid null value property

Body:
I am creating a webservice using asp.net 4.0.

I have created a asmx file and creating a User.cs Class. It has 8 Properties.
I have return a service with json format.
If the userlogin is true i need to return all the properties of user.cs, if it's fail i need to return only 2 property.

How to achieve it.

User login is true. It will return all

{"message":"valid user","BranchId":1,"BranchName":"My branch Name","Id":1,"Name":"admin","Password":"admin","RoleId":1,"Status":1}

User login is failed i need to retun only message and Status. but it will return all like as foloows

{"message":"username or password is invalid","BranchId":0,"BranchName":null,"Id":0,"Name":null,"Password":null,"RoleId":0,"Status":0}

I have google it and get the following Link. How to use it based on my login status condition.

If i have used [ScriptIgnore] in my property it will ignore property both case. I need to ignore property when login failed.

My properties like this

// Properties
    public int BranchId
    {
        get { return _BranchId; }
        set { if (_BranchId != value) { _BranchId = value; } }
    }

    public string BranchName
    {
        get { return _BranchName; }
        set { _BranchName = value; }
    }

    private String _message;

    public String message
    {
        get { return _message; }
        set { _message = value; }
    }

My webservice

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void appLogin(String userName, String passWord)
    {
        Admin_AppUserBLL objusr = Admin_AppUserBLL.GetAdmin_AppUserBLL(userName);
        string strResponse = "";
        if (objusr != null)
        {
            if (objusr.Password == passWord)
            {
                objusr.message = "valid username";
                strResponse = new JavaScriptSerializer().Serialize(objusr);
            }
        }
        else
        {
            objusr = new Admin_AppUserBLL();
            objusr.message = "username or password is invalid";
            strResponse = new JavaScriptSerializer().Serialize(objusr);
        }
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";
        Context.Response.AddHeader("content-length", strResponse.Length.ToString());
        Context.Response.Flush();
        Context.Response.Write(strResponse);
    }

Body:
Add reference in Newtonsoft

using Newtonsoft.Json;

while serialize the object

string strResponse = JsonConvert.SerializeObject(objusr, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

it will avoid null value property


问:
To convert dropdown id to text to store in sql
I want store text from dropdown which retrived from database,i am able to display in site

but now i am getting only id in sql DB.Please need suggestion

View

```<code><div class="form-group">
    <label class="control-label col-sm-3" for="email">Coachings:*</label>
    <div class="col-sm-8">@Html.DropDownListFor(model => model.MainCourseId, new SelectList(Model.MainCourseList, "Key", "Value"), "Select Main Course", new { @class = "form-control", required = "required" })</div>
</div>
</code>```

Controller

```<code>MainCourse = request.MainCourseId.ToString()
</code>```

答:
by default Html.DropDownListFor() will send the selected option "value" to the controller...if you want to send the text, then give your course name as value.......</p>

```<code>@Html.DropDownListFor(model => model.MainCourseId, new SelectList(Model.MainCourseList, "CourseName", "CourseName"), "Select Main Course", new { @class = "form-control", required = "required" })
</code>```

Body:
I want store text from dropdown which retrived from database,i am able to display in site

but now i am getting only id in sql DB.Please need suggestion

View

    Coachings:*

@Html.DropDownListFor(model => model.MainCourseId, new SelectList(Model.MainCourseList, "Key", "Value"), "Select Main Course", new { @class = "form-control", required = "required" })

Controller

MainCourse = request.MainCourseId.ToString()

Body:
by default Html.DropDownListFor() will send the selected option "value" to the controller...if you want to send the text, then give your course name as value.......

@Html.DropDownListFor(model => model.MainCourseId, new SelectList(Model.MainCourseList, "CourseName", "CourseName"), "Select Main Course", new { @class = "form-control", required = "required" })


问:
Angular 5 internationalization
I'm building an application using the latest Angular5 and what I need is for a user to be able to switch languages.  I've never had to implement this in an Angular2+ (actually I'm using Angular5).

I need to set translations in two places:

Component's template html - change labels to the specified language

In code in the component.ts file - I may need to translate some
strings that are built dynamically under particular conditions in the code

I was looking at ngx-translation and it looks to do everything I need, as in it allows you to change language without rebuilding your code, see here. However I read it was probably going to be deprecated due to the main developer moving to the angular team to develop their i18n code.

I also understand that the current i18n doesn't support everything I need right now, see here.

My question - what is the state of play for translations in the latest version of Angular?  Are there other libraries people would recommend instead, if indeed, Angular itself hasn't got full support as of yet (for changing language without recompiling)?  Is ngx-translate good for the future?

Any guidance in this area is greatly appreciated!

答:
Yes. ngx-translate is good till now, and I hope it will be in future as well.

I am using ngx-translate in my current Angular 5 project with 5+ languages.

It is working fine for me so far. I did not have to make any custom changes, it worked like plug and play thing.

I used this plugin https://github.com/ngx-translate/core

Title: Angular 5 internationalization


问:
Flask SSL receiving garbage requests
I've got a basic Flask server setup with some endpoints. I'm trying to test this out using curl (I've tried both from localhost and remotely, the result is the same).

If I curl the path over http, it works great.  If I do it over https, the request looks like garbage (see below) and curl returns "curl: (35) gnutls_handshake() failed: An unexpected TLS packet was received."

Requests received over https typically looks similar to:

```<code>136.152.142.32 - - [16/Nov/2017 01:32:56] code 400, message Bad request syntax ('\x16\x03\x01\x00\xe3\x01\x00\x00\xdf\x03\x03Z\x0c\xea\xcf\rG\x12,\xea}\xc4\x17n\xb7\x0c\x0b\xea\xdbM\x87n\xf3\x95\xa7(\x15+\xb5lyzY\x00\x00n\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0')
136.152.142.32 - - [16/Nov/2017 01:32:56] "??Z
G,?}?n?

                        ??
</code>```

I added SSL functionality by simply adding an ssl_context to my flask app.

```<code>if __name__ == '__main__':
    context = ('fullcert.pem', 'privkey.pem')
    app.run(debug=False, ssl_context=context)
</code>```

The keys are signed by a CA and worked fine in a comparable node application (I'm trying to convert that node application over to python/flask).

I've tried basically reinstalling from the ground up with no success.

This is being hosted on DigitalOcean in case anyone knows of some weird default configuration that they do that could be causing this.  I've specifically opened the port that the application is running on.

Does anyone have any other suggestions of what could be causing the problem?

答: I'm going to go ahead and chalk this up to some kind of problem with the Flask dev server.  I deployed my application using the exact same code with Apache (specifically, I followed this handy guide: https://www.digitalocean.com/community/tutorials/how-to-deploy-a-flask-application-on-an-ubuntu-vps) and it worked.</p>

Title: Flask SSL receiving garbage requests

Body:
I've got a basic Flask server setup with some endpoints. I'm trying to test this out using curl (I've tried both from localhost and remotely, the result is the same).

If I curl the path over http, it works great.  If I do it over https, the request looks like garbage (see below) and curl returns "curl: (35) gnutls_handshake() failed: An unexpected TLS packet was received."

Requests received over https typically looks similar to:

136.152.142.32 - - [16/Nov/2017 01:32:56] code 400, message Bad request syntax ('\x16\x03\x01\x00\xe3\x01\x00\x00\xdf\x03\x03Z\x0c\xea\xcf\rG\x12,\xea}\xc4\x17n\xb7\x0c\x0b\xea\xdbM\x87n\xf3\x95\xa7(\x15+\xb5lyzY\x00\x00n\x00\xff\xc0,\xc0+\xc0$\xc0#\xc0')
136.152.142.32 - - [16/Nov/2017 01:32:56] "??Z
G,?}?n?

                        ??

I added SSL functionality by simply adding an ssl_context to my flask app.

if __name__ == '__main__':
    context = ('fullcert.pem', 'privkey.pem')
    app.run(debug=False, ssl_context=context)

The keys are signed by a CA and worked fine in a comparable node application (I'm trying to convert that node application over to python/flask).

I've tried basically reinstalling from the ground up with no success.

This is being hosted on DigitalOcean in case anyone knows of some weird default configuration that they do that could be causing this.  I've specifically opened the port that the application is running on.

Does anyone have any other suggestions of what could be causing the problem?


问:
Server Setup - From dreamhost to what?
I've been using DreamHost for a long time - mostly for blogs and such.

But now that I'm developing web apps, I think it's time to switch. One reason is that DreamHost limits the number of emails I can send per hour/day. But I also don't see any startups using DreamHost, which is another sign.

What should I switch to? I haven no server experience at all besides my time with dreamhost.

答:
I'd recommend you get a VPS with a decent hosting company.

Pay the extra for a control panel (CPanel or Plesk are the main ones usually) so you have an easy way to add services, create virtual hosts and configure dns.. will save you some time.

You'll also get root access to it so you can do anything you want after that - including breaking it.

Title: Server Setup - From dreamhost to what?


问:
Warning: Each child in an array or iterator should have a unique "key" prop
G'Day.
I want to iterate over a bunch of JSON objects and turn them into React Elements.  The objects look like this

```<code>                                "fields":
                                    [
                                        {
                                            key: "testname",
                                            "name": "testname",
                                            "altName": "",
                                            "visible": true,
                                            "groupVisibility": "public",
                                            "type": "text",
                                            "component": "input",
                                            "label": "Test Smart Input",
                                            "placeholder": "Some default Value",
                                            "required": "required",
                                            "validated": false,
                                            "data": []
                                        },
                                        {
                                            key: "password",
                                            "name": "password",
                                            "altName": "",
                                            "visible": true,
                                            "groupVisibility": "public",
                                            "type": "password",
                                            "component": "input",
                                            "label": "Test Smart Input",
                                            "placeholder": "Password",
                                            "required": "required",
                                            "validated": false,
                                            "data": []
                                        }
                                    ]
</code>```

And the code that iterates over them is quite simple. Such:

```<code>//--------------------
formFields(fieldsIn) {

    const fieldsOut = [];                                           // ARRAY of FORM ELEMENTS to return
    console.log('doin fields');
    for (var fieldIn in fieldsIn) {                                 // array of FORM ELEMENT descriptions in JSON
        console.log(fieldIn);
        let field = React.createElement(SmartRender,                // go build the React Element
                                        fieldIn,
                                        null);                      // lowest level, no children, data is in props
        console.log('doin fields inside');
        fieldsOut.push(field);
    }
    return(fieldsOut);                                              // this ARRAY is the children of each PAGE
}
</code>```

And I get the error
Warning: Each child in an array or iterator should have a unique "key" prop.
Any hints?
Cheers

I changed the code to do this.

```<code>//--------------------
formFields(fieldsIn) {

    const fieldsOut = [];                                           // ARRAY of FORM ELEMENTS to return
    console.log('doin fields');
    for (var fieldIn in fieldsIn) {                                 // array of FORM ELEMENT descriptions in JSON
        console.log(fieldIn);
        let field = React.createElement(SmartRender,                // go build the React Element
                                        {key: fieldsIn[fieldIn].name, fieldIn},
                                        null);                      // lowest level, no children, data is in props
        console.log('doin fields inside');
        fieldsOut.push(field);
    }
    return(fieldsOut);                                              // this ARRAY is the children of each PAGE
}
</code>```

And I get the same error.  I don't understand why!
Fixed!  Thanks for the help.

Here is the code.

```<code>    //--------------------
    formFields(fieldsIn) {

        const fieldsOut = [];                                           // ARRAY of FORM ELEMENTS to return
        for (var fieldIn in fieldsIn) {                                 // array of FORM ELEMENT descriptions in JSON
            console.log(fieldIn);
            let field = React.createElement(SmartRender,                // go build the React Element
                                            {key: fieldsIn[fieldIn].key, fieldIn},
                                            null);                      // lowest level, no children, data is in props
            fieldsOut.push(field);
        }
        return(fieldsOut);                                              // this ARRAY is the children of each PAGE
    }

    //----------------------
    pages(pagesIn, format) {

        // I tried to do this in JSX, but no syntax I wrestled with would
        // allow me to access the childred when building this with the
        // BABEL transpiler.  Same goes for the METHOD just above, items().
        //
        // This method returns an array of pages this are React elements
        // this are treated as children by the smartForm.

        const pagesOut = [];                                            // array of pages to build and return
        let Section = {};                                               // Component to fire in the build
        switch(format) {
            case 'accordion': {
                Section = AccordionSection;
                break;
            }
            case 'workflow': {
                Section = null;                                         // I haven't written this yet
                break;
            }
            case 'simple': {
                Section = null;                                         // I haven't written this yet
                break;
            }
        }

        for (var pageIn in pagesIn) {                                   // pages, any format, any number 1..N
            let children = this.formFields(pagesIn[pageIn].fields);     // 1..N fields, we don't know beforehand
            let page = React.createElement( Section,
                                            pagesIn[pageIn].props,
                                            children);
            pagesOut.push(page);
        }
        return(pagesOut);                                               // this ARRAY is the children of each FORM
    }

    //--------
    render() {

        let formIn  = this.props.form;                                  // JSON description of FORM
        let formOut = null;                                             // contructed REACT/Javascript form

        switch (formIn.format) {                                        // what type of operation is this
            case 'accordion': {                                         // Accordion in a FORM, OK
                let children = this.pages(formIn.pages,
                                          formIn.format);               // build the children
                formOut = React.createElement(Accordion,                // construct the parent with ALL nested CHILDREN after
                                            {key: formIn.formName},     // just a unique key
                                            children);                  // N ACCORDION pages, N2 input fields
                break;
            }
            case 'workflow': {
                let children = this.pages(formIn.pages,                 // build the children
                                          formIn.format);               // build the children
                formOut = React.createElement(Workflow,                 // and create the complex sheet element
                                            { key: formIn.formName},
                                            children);                  // N SLIDING pages, N2 input fields
                break;
            }
            case 'simple': {
                let children = this.pages(formIn.pages,                 // build the children
                                          formIn.format);               // build the children
                formOut = React.createElement(Simple,
                                            { key: formIn.formName},
                                            children);                  // One page, N input fields
            break;
            }
        }

        return(
                <div>
                    <h2>SmartForm Parser</h2>
                    <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
                    {formOut}
                </div>
        );
    }
}
//-------------------------------------------------------------------------
export default SmartForm;

//-----------------   EOF -------------------------------------------------
</code>```

答:
You need to add a unique key prop to your React element.

According to the React docs:

Keys help React identify which items have changed, are added, or are
  removed. Keys should be given to the elements inside the array to give
  the elements a stable identity.

The best way to pick a key is to use a string that uniquely identifies
  a list item among its siblings. Most often you would use IDs from your
  data as keys

When you don’t have stable IDs for rendered items, you may use the
  item index as a key as a last resort

You can do it like

```<code>for (var fieldIn in fieldsIn) {                                 // array of FORM ELEMENT descriptions in JSON
        console.log(fieldIn);
        let field = React.createElement(SmartRender,                // go build the React Element
                                        {key: fieldsIn[fieldIn].key, fieldIn},
                                        null);                      // lowest level, no children, data is in props
        console.log('doin fields inside');
        fieldsOut.push(field);
    }
</code>```

Why are keys necessary?

By default, when recursing on the children of a DOM node, React just iterates over both lists of children at the same time and generates a mutation whenever there’s a difference.

For example, when adding an element at the end of the children, converting between these two trees works well:

```<code><ul>
  <li>first</li>
  <li>second</li>
</ul>

<ul>
  <li>first</li>
  <li>second</li>
  <li>third</li>
</ul>
</code>```

React will match the two
first
 trees, match the two
second
 trees, and then insert the
third
 tree.

If you implement it naively, inserting an element at the beginning has worse performance. For example, converting between these two trees works poorly.

```<code><ul>
  <li>first</li>
  <li>second</li>
</ul>

<ul>
  <li>third</li>
  <li>first</li>
  <li>second</li>
</ul>
</code>```

That is where keys come in handy.

Body:
G'Day.
I want to iterate over a bunch of JSON objects and turn them into React Elements.  The objects look like this

                                "fields":
                                    [
                                        {
                                            key: "testname",
                                            "name": "testname",
                                            "altName": "",
                                            "visible": true,
                                            "groupVisibility": "public",
                                            "type": "text",
                                            "component": "input",
                                            "label": "Test Smart Input",
                                            "placeholder": "Some default Value",
                                            "required": "required",
                                            "validated": false,
                                            "data": []
                                        },
                                        {
                                            key: "password",
                                            "name": "password",
                                            "altName": "",
                                            "visible": true,
                                            "groupVisibility": "public",
                                            "type": "password",
                                            "component": "input",
                                            "label": "Test Smart Input",
                                            "placeholder": "Password",
                                            "required": "required",
                                            "validated": false,
                                            "data": []
                                        }
                                    ]

And the code that iterates over them is quite simple. Such:

//--------------------
formFields(fieldsIn) {

    const fieldsOut = [];                                           // ARRAY of FORM ELEMENTS to return
    console.log('doin fields');
    for (var fieldIn in fieldsIn) {                                 // array of FORM ELEMENT descriptions in JSON
        console.log(fieldIn);
        let field = React.createElement(SmartRender,                // go build the React Element
                                        fieldIn,
                                        null);                      // lowest level, no children, data is in props
        console.log('doin fields inside');
        fieldsOut.push(field);
    }
    return(fieldsOut);                                              // this ARRAY is the children of each PAGE
}

And I get the error
Warning: Each child in an array or iterator should have a unique "key" prop.
Any hints?
Cheers

I changed the code to do this.

//--------------------
formFields(fieldsIn) {

    const fieldsOut = [];                                           // ARRAY of FORM ELEMENTS to return
    console.log('doin fields');
    for (var fieldIn in fieldsIn) {                                 // array of FORM ELEMENT descriptions in JSON
        console.log(fieldIn);
        let field = React.createElement(SmartRender,                // go build the React Element
                                        {key: fieldsIn[fieldIn].name, fieldIn},
                                        null);                      // lowest level, no children, data is in props
        console.log('doin fields inside');
        fieldsOut.push(field);
    }
    return(fieldsOut);                                              // this ARRAY is the children of each PAGE
}

And I get the same error.  I don't understand why!
Fixed!  Thanks for the help.

Here is the code.

    //--------------------
    formFields(fieldsIn) {

        const fieldsOut = [];                                           // ARRAY of FORM ELEMENTS to return
        for (var fieldIn in fieldsIn) {                                 // array of FORM ELEMENT descriptions in JSON
            console.log(fieldIn);
            let field = React.createElement(SmartRender,                // go build the React Element
                                            {key: fieldsIn[fieldIn].key, fieldIn},
                                            null);                      // lowest level, no children, data is in props
            fieldsOut.push(field);
        }
        return(fieldsOut);                                              // this ARRAY is the children of each PAGE
    }

    //----------------------
    pages(pagesIn, format) {

        // I tried to do this in JSX, but no syntax I wrestled with would
        // allow me to access the childred when building this with the
        // BABEL transpiler.  Same goes for the METHOD just above, items().
        //
        // This method returns an array of pages this are React elements
        // this are treated as children by the smartForm.

        const pagesOut = [];                                            // array of pages to build and return
        let Section = {};                                               // Component to fire in the build
        switch(format) {
            case 'accordion': {
                Section = AccordionSection;
                break;
            }
            case 'workflow': {
                Section = null;                                         // I haven't written this yet
                break;
            }
            case 'simple': {
                Section = null;                                         // I haven't written this yet
                break;
            }
        }

        for (var pageIn in pagesIn) {                                   // pages, any format, any number 1..N
            let children = this.formFields(pagesIn[pageIn].fields);     // 1..N fields, we don't know beforehand
            let page = React.createElement( Section,
                                            pagesIn[pageIn].props,
                                            children);
            pagesOut.push(page);
        }
        return(pagesOut);                                               // this ARRAY is the children of each FORM
    }

    //--------
    render() {

        let formIn  = this.props.form;                                  // JSON description of FORM
        let formOut = null;                                             // contructed REACT/Javascript form

        switch (formIn.format) {                                        // what type of operation is this
            case 'accordion': {                                         // Accordion in a FORM, OK
                let children = this.pages(formIn.pages,
                                          formIn.format);               // build the children
                formOut = React.createElement(Accordion,                // construct the parent with ALL nested CHILDREN after
                                            {key: formIn.formName},     // just a unique key
                                            children);                  // N ACCORDION pages, N2 input fields
                break;
            }
            case 'workflow': {
                let children = this.pages(formIn.pages,                 // build the children
                                          formIn.format);               // build the children
                formOut = React.createElement(Workflow,                 // and create the complex sheet element
                                            { key: formIn.formName},
                                            children);                  // N SLIDING pages, N2 input fields
                break;
            }
            case 'simple': {
                let children = this.pages(formIn.pages,                 // build the children
                                          formIn.format);               // build the children
                formOut = React.createElement(Simple,
                                            { key: formIn.formName},
                                            children);                  // One page, N input fields
            break;
            }
        }

        return(

SmartForm Parser

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

                    {formOut}

        );
    }
}
//-------------------------------------------------------------------------
export default SmartForm;

//-----------------   EOF -------------------------------------------------

Body:
You need to add a unique key prop to your React element.

According to the React docs:

Keys help React identify which items have changed, are added, or are
  removed. Keys should be given to the elements inside the array to give
  the elements a stable identity.

The best way to pick a key is to use a string that uniquely identifies
  a list item among its siblings. Most often you would use IDs from your
  data as keys

When you don’t have stable IDs for rendered items, you may use the
  item index as a key as a last resort

You can do it like

for (var fieldIn in fieldsIn) {                                 // array of FORM ELEMENT descriptions in JSON
        console.log(fieldIn);
        let field = React.createElement(SmartRender,                // go build the React Element
                                        {key: fieldsIn[fieldIn].key, fieldIn},
                                        null);                      // lowest level, no children, data is in props
        console.log('doin fields inside');
        fieldsOut.push(field);
    }

Why are keys necessary?

By default, when recursing on the children of a DOM node, React just iterates over both lists of children at the same time and generates a mutation whenever there’s a difference.

For example, when adding an element at the end of the children, converting between these two trees works well:

<ul>
  <li>first</li>
  <li>second</li>
</ul>

<ul>
  <li>first</li>
  <li>second</li>
  <li>third</li>
</ul>

React will match the two <li>first</li> trees, match the two <li>second</li> trees, and then insert the <li>third</li> tree.

If you implement it naively, inserting an element at the beginning has worse performance. For example, converting between these two trees works poorly.

<ul>
  <li>first</li>
  <li>second</li>
</ul>

<ul>
  <li>third</li>
  <li>first</li>
  <li>second</li>
</ul>

That is where keys come in handy.


问:
Swift - How to dismiss all of view controllers to go back to root
I want a my app can go to a first view controller when every time users want it.

So I want to create a function to dismiss all the view controllers, regardless of whether it is pushed in navigation controllers or presented modally or opened anything methods.

I tried various ways, but I failed to dismiss all the view controllers certainly.
Is there an easy way?

答:
Try This :

```<code>self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)
</code>```

it should dismiss all view controllers above the root view controller.

If that doesn't work than you can manually do that by running a while loop like this.

```<code>func dismissViewControllers() {

    guard let vc = self.presentingViewController else { return }

    while (vc.presentingViewController != nil) {
        vc.dismiss(animated: true, completion: nil)
    }
}
</code>```

It would dismiss all viewControllers until it has a presentingController.

Edit : if you want to dismiss/pop pushed ViewControllers you can use

```<code>self.navigationController?.popToRootViewController(animated: true)
</code>```

Hope it helps.

Body:
Try This :

self.view.window?.rootViewController?.dismiss(animated: true, completion: nil)

it should dismiss all view controllers above the root view controller.

If that doesn't work than you can manually do that by running a while loop like this.

func dismissViewControllers() {

    guard let vc = self.presentingViewController else { return }

    while (vc.presentingViewController != nil) {
        vc.dismiss(animated: true, completion: nil)
    }
}

It would dismiss all viewControllers until it has a presentingController.

Edit : if you want to dismiss/pop pushed ViewControllers you can use

self.navigationController?.popToRootViewController(animated: true)

Hope it helps.


问:
R data.table: 2 level grouping with storing result in new columns named by value one of levels
consider next:

```<code>dt1 <- data.table(id = c(1,1,1,2,2,2,2), status = c(0,1,1,2,3,0,2), val = c(2,2,4,1,2,3,1))
</code>```

I use group by (id, status) with mean func to make columns with names which consists status values from 0 to 3:

```<code>stat <- c(0:3)
for(i in 1:length(stat)) dt1[, eval(paste("meanval.stat.", stat[i], sep = "")) := mean(val, na.rm = TRUE), by = .(id, status == stat[i])]
</code>```

with next result:

```<code>   id status val meanval.stat.0 meanval.stat.1 meanval.stat.2 meanval.stat.3
1:  1      0   2       2.000000           2.00       2.666667       2.666667
2:  1      1   2       3.000000           3.00       2.666667       2.666667
3:  1      1   4       3.000000           3.00       2.666667       2.666667
4:  2      2   1       1.333333           1.75       1.000000       1.666667
5:  2      3   2       1.333333           1.75       2.500000       2.000000
6:  2      0   3       3.000000           1.75       2.500000       1.666667
7:  2      2   1       1.333333           1.75       1.000000       1.666667
</code>```

But I expected another result like next:

```<code>   id status val meanval.stat.0 meanval.stat.1 meanval.stat.2 meanval.stat.3
1:  1      0   2       2                  3          0              0
2:  1      1   2       2                  3          0              0
3:  1      1   4       2                  3          0              0
4:  2      2   1       3                  0          1              2
5:  2      3   2       3                  0          1              2
6:  2      0   3       3                  0          1              2
7:  2      2   1       3                  0          1              2
</code>```

I dont understand whats wrong with logic of my solution

答:
Perhaps the logic would be to group by 'id', subset the 'val' based on logical vector created by comparing the 'status' with each of the elements of 'stat', get the mean, assign it to new columns ('nm1'), and if there are NaN, set it to 0

```<code>nm1 <- paste0("meanval.stat.", stat)
for(i in seq_along(stat)) {
    dt1[, (nm1) :=  mean(val[status == stat[i]], na.rm = TRUE), .(id)][]
 }

for(j in nm1) {
   set(dt1, i = which(is.nan(dt1[[j]])), j = j, value = 0)[]
}
</code>```

Body:
consider next:

dt1 <- data.table(id = c(1,1,1,2,2,2,2), status = c(0,1,1,2,3,0,2), val = c(2,2,4,1,2,3,1))

I use group by (id, status) with mean func to make columns with names which consists status values from 0 to 3:

stat <- c(0:3)
for(i in 1:length(stat)) dt1[, eval(paste("meanval.stat.", stat[i], sep = "")) := mean(val, na.rm = TRUE), by = .(id, status == stat[i])]

with next result:

   id status val meanval.stat.0 meanval.stat.1 meanval.stat.2 meanval.stat.3
1:  1      0   2       2.000000           2.00       2.666667       2.666667
2:  1      1   2       3.000000           3.00       2.666667       2.666667
3:  1      1   4       3.000000           3.00       2.666667       2.666667
4:  2      2   1       1.333333           1.75       1.000000       1.666667
5:  2      3   2       1.333333           1.75       2.500000       2.000000
6:  2      0   3       3.000000           1.75       2.500000       1.666667
7:  2      2   1       1.333333           1.75       1.000000       1.666667

But I expected another result like next:

   id status val meanval.stat.0 meanval.stat.1 meanval.stat.2 meanval.stat.3
1:  1      0   2       2                  3          0              0
2:  1      1   2       2                  3          0              0
3:  1      1   4       2                  3          0              0
4:  2      2   1       3                  0          1              2
5:  2      3   2       3                  0          1              2
6:  2      0   3       3                  0          1              2
7:  2      2   1       3                  0          1              2

I dont understand whats wrong with logic of my solution

Body:
Perhaps the logic would be to group by 'id', subset the 'val' based on logical vector created by comparing the 'status' with each of the elements of 'stat', get the mean, assign it to new columns ('nm1'), and if there are NaN, set it to 0

nm1 <- paste0("meanval.stat.", stat)
for(i in seq_along(stat)) {
    dt1[, (nm1) :=  mean(val[status == stat[i]], na.rm = TRUE), .(id)][]
 }

for(j in nm1) {
   set(dt1, i = which(is.nan(dt1[[j]])), j = j, value = 0)[]
}


答:
Simply ask your rootViewController to dismiss any ViewController if presenting.

```<code>if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
   appDelegate.window?.rootViewController?.dismiss(animated: true, completion: nil)
   (appDelegate.window?.rootViewController as? UINavigationController)?.popToRootViewController(animated: true)
}
</code>```

Title: Swift - How to dismiss all of view controllers to go back to root

Body:
I want a my app can go to a first view controller when every time users want it.

So I want to create a function to dismiss all the view controllers, regardless of whether it is pushed in navigation controllers or presented modally or opened anything methods.

I tried various ways, but I failed to dismiss all the view controllers certainly.
Is there an easy way?

Body:
Simply ask your rootViewController to dismiss any ViewController if presenting.

if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
   appDelegate.window?.rootViewController?.dismiss(animated: true, completion: nil)
   (appDelegate.window?.rootViewController as? UINavigationController)?.popToRootViewController(animated: true)
}


问:
R & Fortran call
I don't have experience with Fortran, but I am trying to run a very simple loop in that language by calling it from R via the .Fortran() function. Whenever I run the last line of the R code that is pasted below, the R gui crashes and I get no result. I am interest in bringing back the vector of real values x from Fortran into R for further analysis. g is a numeric value between 0 and 1, and n an integer, and they are both supplied by the user in R.

Any help would be much appreciated! Best,

Vincent

Fortran code saved in bar.f:

```<code>    subroutine bar(n, g, x)

      integer n
      double precision g
      double precision x(n)
      integer i
      x(1)=1
      do 100 i = 2, n
          x(i) = x(i-1) * g + 1
  100 continue

      end
</code>```

Compiling the DLL in Cygwin with gfortran:

```<code>gfortran -shared -obar.dll bar.f
</code>```

R code:

```<code>dyn.load("d:/bar.dll")
is.loaded("bar")
.Fortran("bar", n=as.integer(15), g=as.double(5), x=as.double(rnorm(5)))
</code>```

答:
When I compile your code, I can execute the call to .Fortran once.  When I run it a second time, it crashes.  However, I noticed that if I make the vector passed for x the same length as the integer passed for n suggests it should be, i.e:

```<code>.Fortran('bar', n = as.integer(15), g = as.double (5), x = as.double(rnorm(15)) )
</code>```

I can run the function as many times as I want.  So the problem may be that you are telling the Fortran routine it has a vector of length 15 to work with, but are only sending in a vector of length 5.  This could be causing the Fortran routine to access memory it is not supposed to which would explain a crash.

Since it looks like you are generating all values of x in the routine anyway, you could skip generating random numbers and just send in an empty vector using R's double(n) function, where n is the length of the empty vector you want to generate:

```<code>.Fortran('bar', n = as.integer(15), g = as.double(5), x = double(15))
</code>```

integer and character are useful functions that return vectors like double.

Also some friendly suggestions concerning Fortran style since you mention you are just getting started with the language:

It might be wise to name your files with a .f90 extension---files ending in .f are assumed by most compilers to adhere to the old "fixed-form" format which is a PITA as it was designed to be used on punch cards.

The Do 100 ... 100    continue statements are an style of ending loops in Fortran 77.  The modern equivalent is Do .. end do.

With Fortran functions and subroutines, it is wise to declare the "intent" of variables passing in and out of the routine.  The available intent declarations are:

intent(in): Signifies variables that are entering the routine only as inputs.  Once inside the routine, they should be treated as parameters and the compiler will raise an error if any attempt is made to change them.

intent(out): Signifies variables whose values should be generated inside the routine as outputs.  The compiler will issue a warning if an intent out variable is not assigned within the routine.

intent(inout):  Signifies variables that may enter the routine carrying a certain set of values and leave the routine with different values.

Setting intents on variables will help the compiler generate warnings and errors that may save you some bug hunting.

Fortran has a default behavior where any variable not declared in the header of the routine will be an integer if its name starts with i-n and real otherwise.  This can cause misspelled variable names to "magically" become variables without the compiler batting an eye or telling you.  Setting implicit none at the top of your routines disables this behavior and allows the compiler to notify you of mistakes that can be very hard to track down otherwise.

A version of your subroutine that takes these suggestions into account would look like the following:

```<code>subroutine bar(n, g, x)
  implicit none

  integer, intent(in):: n
  double precision, intent(in):: g
  double precision, intent(inout):: x(n)

  integer:: i

  x(1) = 1
  do i = 2, n
    x(i) = x(i - 1) * g + 1
  end do

end subroutine bar
</code>```

Also, it is useful to let R compile your libraries using the SHLIB subcommand of R CMD:

```<code>R CMD SHLIB -o bar.dll bar.f90
</code>```

This will compile your programs against the R libraries which contain useful functions---such as BLAS routines, stats routines and methods that can print information to the R console.  See Writing R Extensions, Section 6 for more info.

Hope this helps!

Title: R & Fortran call

Body:
I don't have experience with Fortran, but I am trying to run a very simple loop in that language by calling it from R via the .Fortran() function. Whenever I run the last line of the R code that is pasted below, the R gui crashes and I get no result. I am interest in bringing back the vector of real values x from Fortran into R for further analysis. g is a numeric value between 0 and 1, and n an integer, and they are both supplied by the user in R.

Any help would be much appreciated! Best,

Vincent

Fortran code saved in bar.f:

    subroutine bar(n, g, x)

      integer n
      double precision g
      double precision x(n)
      integer i
      x(1)=1
      do 100 i = 2, n
          x(i) = x(i-1) * g + 1
  100 continue

      end

Compiling the DLL in Cygwin with gfortran:

gfortran -shared -obar.dll bar.f

R code:

dyn.load("d:/bar.dll")
is.loaded("bar")
.Fortran("bar", n=as.integer(15), g=as.double(5), x=as.double(rnorm(5)))

Body:
When I compile your code, I can execute the call to .Fortran once.  When I run it a second time, it crashes.  However, I noticed that if I make the vector passed for x the same length as the integer passed for n suggests it should be, i.e:

.Fortran('bar', n = as.integer(15), g = as.double (5), x = as.double(rnorm(15)) )

I can run the function as many times as I want.  So the problem may be that you are telling the Fortran routine it has a vector of length 15 to work with, but are only sending in a vector of length 5.  This could be causing the Fortran routine to access memory it is not supposed to which would explain a crash.

Since it looks like you are generating all values of x in the routine anyway, you could skip generating random numbers and just send in an empty vector using R's double(n) function, where n is the length of the empty vector you want to generate:

.Fortran('bar', n = as.integer(15), g = as.double(5), x = double(15))

integer and character are useful functions that return vectors like double.

Also some friendly suggestions concerning Fortran style since you mention you are just getting started with the language:

It might be wise to name your files with a .f90 extension---files ending in .f are assumed by most compilers to adhere to the old "fixed-form" format which is a PITA as it was designed to be used on punch cards.

The Do 100 ... 100    continue statements are an style of ending loops in Fortran 77.  The modern equivalent is Do .. end do.

With Fortran functions and subroutines, it is wise to declare the "intent" of variables passing in and out of the routine.  The available intent declarations are:

intent(in): Signifies variables that are entering the routine only as inputs.  Once inside the routine, they should be treated as parameters and the compiler will raise an error if any attempt is made to change them.

intent(out): Signifies variables whose values should be generated inside the routine as outputs.  The compiler will issue a warning if an intent out variable is not assigned within the routine.

intent(inout):  Signifies variables that may enter the routine carrying a certain set of values and leave the routine with different values.

Setting intents on variables will help the compiler generate warnings and errors that may save you some bug hunting.

Fortran has a default behavior where any variable not declared in the header of the routine will be an integer if its name starts with i-n and real otherwise.  This can cause misspelled variable names to "magically" become variables without the compiler batting an eye or telling you.  Setting implicit none at the top of your routines disables this behavior and allows the compiler to notify you of mistakes that can be very hard to track down otherwise.

A version of your subroutine that takes these suggestions into account would look like the following:

subroutine bar(n, g, x)
  implicit none

  integer, intent(in):: n
  double precision, intent(in):: g
  double precision, intent(inout):: x(n)

  integer:: i

  x(1) = 1
  do i = 2, n
    x(i) = x(i - 1) * g + 1
  end do

end subroutine bar

Also, it is useful to let R compile your libraries using the SHLIB subcommand of R CMD:

R CMD SHLIB -o bar.dll bar.f90

This will compile your programs against the R libraries which contain useful functions---such as BLAS routines, stats routines and methods that can print information to the R console.  See Writing R Extensions, Section 6 for more info.

Hope this helps!


问:
why this eclipse error showing and what should be the solution for it
Missing library: xdoclet-1.2.1.jar. Select the home directory for XDoclet. 1.2.1

why this eclipse error showing and what should be the solution for it alz

答:
If have maven version of the project, can also try by updating the project. I also had this XDoclet. 1.2.1.jar complaint, which got resolved once I update the project.

Right Click Project > Maven > Update Project ... > Check the projects > OK.


问:
Nodejs EJS helper functions?
Is there a way to register helper functions to EJS templates, so that they can be called from any EJS template? So, it should work something like this.

app.js

```<code>ejs.helpers.sayHi = function(name) {
    return 'Hello ' + name;
});
</code>```

index.ejs

```<code><%= sayHi('Bob') %>
</code>```

答:
I am using:

In helpers/helper.js

```<code>var func = {
    sayhi: function(name) {
        return "Hello " + name;
    },
    foo: function(date) {
        //do somethings
    }
};
module.exports = func;
</code>```

In router:

```<code>router.get('/', function(req, res, next) {
    res.render('home/index', {
        helper: require('../helpers/helper'),
        title: 'Express'
    });
});
</code>```

In template:

```<code><%= helper.sayhi("Dung Vu") %>
</code>```

goodluck

Title: Nodejs EJS helper functions?

Body:
Is there a way to register helper functions to EJS templates, so that they can be called from any EJS template? So, it should work something like this.

app.js

ejs.helpers.sayHi = function(name) {
    return 'Hello ' + name;
});

index.ejs

<%= sayHi('Bob') %>

Body:
I am using:

In helpers/helper.js

var func = {
    sayhi: function(name) {
        return "Hello " + name;
    },
    foo: function(date) {
        //do somethings
    }
};
module.exports = func;

In router:

router.get('/', function(req, res, next) {
    res.render('home/index', {
        helper: require('../helpers/helper'),
        title: 'Express'
    });
});

In template:

<%= helper.sayhi("Dung Vu") %>

goodluck


问:
How to apply borderRadius only for top side of Column or Bar in Highchart
According to API document of Highchart:
https://api.highcharts.com/highcharts/plotOptions.column.borderRadius

But I can't find solution to apply borderRadius only for Top Side of column.

```<code>plotOptions: {
    column: {
        borderRadius: 10  // How to make it only for top side. Don't apply it to bottom side ?
    }
},
</code>```

Sample Image

答:
Use this highcharts-border-radius plugin.

$(function() {
  'use strict';
  (function(factory) {
    if (typeof module === 'object' && module.exports) {
      module.exports = factory;
    } else {
      factory(Highcharts);
    }
  }(function(Highcharts) {
    (function(H) {
      H.wrap(H.seriesTypes.column.prototype, 'translate', function(proceed) {
        const options = this.options;
        const topMargin = options.topMargin || 0;
        const bottomMargin = options.bottomMargin || 0;

        proceed.call(this);

        H.each(this.points, function(point) {
          if (options.borderRadiusTopLeft || options.borderRadiusTopRight || options.borderRadiusBottomRight || options.borderRadiusBottomLeft) {
            const w = point.shapeArgs.width;
            const h = point.shapeArgs.height;
            const x = point.shapeArgs.x;
            const y = point.shapeArgs.y;

            let radiusTopLeft = H.relativeLength(options.borderRadiusTopLeft || 0, w);
            let radiusTopRight = H.relativeLength(options.borderRadiusTopRight || 0, w);
            let radiusBottomRight = H.relativeLength(options.borderRadiusBottomRight || 0, w);
            let radiusBottomLeft = H.relativeLength(options.borderRadiusBottomLeft || 0, w);

            const maxR = Math.min(w, h) / 2

            radiusTopLeft = radiusTopLeft > maxR ? maxR : radiusTopLeft;
            radiusTopRight = radiusTopRight > maxR ? maxR : radiusTopRight;
            radiusBottomRight = radiusBottomRight > maxR ? maxR : radiusBottomRight;
            radiusBottomLeft = radiusBottomLeft > maxR ? maxR : radiusBottomLeft;

            point.dlBox = point.shapeArgs;

            point.shapeType = 'path';
            point.shapeArgs = {
              d: [
                'M', x + radiusTopLeft, y + topMargin,
                'L', x + w - radiusTopRight, y + topMargin,
                'C', x + w - radiusTopRight / 2, y, x + w, y + radiusTopRight / 2, x + w, y + radiusTopRight,
                'L', x + w, y + h - radiusBottomRight,
                'C', x + w, y + h - radiusBottomRight / 2, x + w - radiusBottomRight / 2, y + h, x + w - radiusBottomRight, y + h + bottomMargin,
                'L', x + radiusBottomLeft, y + h + bottomMargin,
                'C', x + radiusBottomLeft / 2, y + h, x, y + h - radiusBottomLeft / 2, x, y + h - radiusBottomLeft,
                'L', x, y + radiusTopLeft,
                'C', x, y + radiusTopLeft / 2, x + radiusTopLeft / 2, y, x + radiusTopLeft, y,
                'Z'
              ]
            };
          }

        });
      });
    }(Highcharts));
  }));

  Highcharts.chart('container', {
    chart: {
      type: 'column'
    },
    xAxis: {
      categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    plotOptions: {
      column: {
        grouping: false,
        borderRadiusTopLeft: 10,
        borderRadiusTopRight: 10
      }
    },

    series: [{
      data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
    }]
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>

<div id="container" style="height: 400px"></div></code>```

Fiddle demo

Body:
According to API document of Highchart:
https://api.highcharts.com/highcharts/plotOptions.column.borderRadius

But I can't find solution to apply borderRadius only for Top Side of column.

plotOptions: {
    column: {
        borderRadius: 10  // How to make it only for top side. Don't apply it to bottom side ?
    }
},

Sample Image

Body:
Use this highcharts-border-radius plugin.

$(function() {
  'use strict';
  (function(factory) {
    if (typeof module === 'object' && module.exports) {
      module.exports = factory;
    } else {
      factory(Highcharts);
    }
  }(function(Highcharts) {
    (function(H) {
      H.wrap(H.seriesTypes.column.prototype, 'translate', function(proceed) {
        const options = this.options;
        const topMargin = options.topMargin || 0;
        const bottomMargin = options.bottomMargin || 0;

        proceed.call(this);

        H.each(this.points, function(point) {
          if (options.borderRadiusTopLeft || options.borderRadiusTopRight || options.borderRadiusBottomRight || options.borderRadiusBottomLeft) {
            const w = point.shapeArgs.width;
            const h = point.shapeArgs.height;
            const x = point.shapeArgs.x;
            const y = point.shapeArgs.y;

            let radiusTopLeft = H.relativeLength(options.borderRadiusTopLeft || 0, w);
            let radiusTopRight = H.relativeLength(options.borderRadiusTopRight || 0, w);
            let radiusBottomRight = H.relativeLength(options.borderRadiusBottomRight || 0, w);
            let radiusBottomLeft = H.relativeLength(options.borderRadiusBottomLeft || 0, w);

            const maxR = Math.min(w, h) / 2

            radiusTopLeft = radiusTopLeft > maxR ? maxR : radiusTopLeft;
            radiusTopRight = radiusTopRight > maxR ? maxR : radiusTopRight;
            radiusBottomRight = radiusBottomRight > maxR ? maxR : radiusBottomRight;
            radiusBottomLeft = radiusBottomLeft > maxR ? maxR : radiusBottomLeft;

            point.dlBox = point.shapeArgs;

            point.shapeType = 'path';
            point.shapeArgs = {
              d: [
                'M', x + radiusTopLeft, y + topMargin,
                'L', x + w - radiusTopRight, y + topMargin,
                'C', x + w - radiusTopRight / 2, y, x + w, y + radiusTopRight / 2, x + w, y + radiusTopRight,
                'L', x + w, y + h - radiusBottomRight,
                'C', x + w, y + h - radiusBottomRight / 2, x + w - radiusBottomRight / 2, y + h, x + w - radiusBottomRight, y + h + bottomMargin,
                'L', x + radiusBottomLeft, y + h + bottomMargin,
                'C', x + radiusBottomLeft / 2, y + h, x, y + h - radiusBottomLeft / 2, x, y + h - radiusBottomLeft,
                'L', x, y + radiusTopLeft,
                'C', x, y + radiusTopLeft / 2, x + radiusTopLeft / 2, y, x + radiusTopLeft, y,
                'Z'
              ]
            };
          }

        });
      });
    }(Highcharts));
  }));

  Highcharts.chart('container', {
    chart: {
      type: 'column'
    },
    xAxis: {
      categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },

    plotOptions: {
      column: {
        grouping: false,
        borderRadiusTopLeft: 10,
        borderRadiusTopRight: 10
      }
    },

    series: [{
      data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
    }]
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>

<div id="container" style="height: 400px"></div>

Fiddle demo


问:
jQuery can't catch the parent element
I am trying to access the parent element up to the button element to modify its css. I can access the span element via id. But when I try to go to the parent img it says undefined

Here is my html code

```<code><button type="button" class="buttonLike">\
    <img src = "../Image/thumbsUp.png" clas="test">\
            <span class="postID" id=' + idPost + '>' + likesPost + '</span>\
    </img>\
 </button>\
</code>```

and here is my jquery code that access the span element

```<code>$.each(result, function (index,data) {
                var liked = data.liked;
                if (liked == true) {
                    console.log($("#" + postId).parent("img").attr("src"));
                }
   });
</code>```

How can i do this right.

答:
I think you should not wrap the span inside the img. that will make more easy for you. But if you still want to. try this.
$("#postId").closest("img");</p>

Title: jQuery can't catch the parent element

Body:
I am trying to access the parent element up to the button element to modify its css. I can access the span element via id. But when I try to go to the parent img it says undefined

Here is my html code

<button type="button" class="buttonLike">\
    \
            ' + likesPost + '\
    \
 </button>\

and here is my jquery code that access the span element

$.each(result, function (index,data) {
                var liked = data.liked;
                if (liked == true) {
                    console.log($("#" + postId).parent("img").attr("src"));
                }
   });

How can i do this right.


问:
How is the database location decided when creating a copy using SQL Management client API?
This is the code to create a database copy in Azure using service management api's

```<code>SqlManagementClient sqlClient = new SqlManagementClient sqlClient ();
DatabaseCopyCreateParameters newDatabaseParameters = new DatabaseCopyCreateParameters()
                    {
                        IsContinuous = true,
                        PartnerDatabase = srcDB
                        PartnerServer = srcserver
                    };
sqlClient.DatabaseCopies.Create(dbservername, dbname, newDatabaseParameters);
</code>```

It got created in the location say "east asia".

As you can see I am not providing any location details, then how it is created in this location?

答: Location is decided based on the server location. Since my server is in East Asia, Obviously db will be in East Asia</p>

Body:
This is the code to create a database copy in Azure using service management api's

SqlManagementClient sqlClient = new SqlManagementClient sqlClient ();
DatabaseCopyCreateParameters newDatabaseParameters = new DatabaseCopyCreateParameters()
                    {
                        IsContinuous = true,
                        PartnerDatabase = srcDB
                        PartnerServer = srcserver
                    };
sqlClient.DatabaseCopies.Create(dbservername, dbname, newDatabaseParameters);

It got created in the location say "east asia".

As you can see I am not providing any location details, then how it is created in this location?