问:
How to prevent Jquery append more than once
I have some jQuery that checks if the user inputted a correct email address. The user can then go back and change his/her email if it is not valid. However, my code will result in the same error messege twice because the error keeps getting appended inside my errors div. How can I change this to only allow the error to be appended once? I also would like to remove the error if the email variable is true. There are also other validation errors being placed in this div.

jQuery:

```<code>var email = $('#email').val();
email = validateEmail(email);
if (email = "false") {
    $('#errors').append("<p>Please enter a valid email</p>");
}
</code>```

validateEmail will return either true or false depending on whether the email is valid.

答:
More appropriate way is to remove all the appended code from DOM tree:

Try this:

```<code>var email = $('#email').val();
email = validateEmail(email);
if (email == "false"){
      $('#email_error').parent().remove();
      $('#errors').append("<p id='email_error'>Please enter a valid email</p>");
}
</code>```

Body:
I have some jQuery that checks if the user inputted a correct email address. The user can then go back and change his/her email if it is not valid. However, my code will result in the same error messege twice because the error keeps getting appended inside my errors div. How can I change this to only allow the error to be appended once? I also would like to remove the error if the email variable is true. There are also other validation errors being placed in this div.

jQuery:

var email = $('#email').val();
email = validateEmail(email);
if (email = "false") {
    $('#errors').append("
Please enter a valid email
");
}

validateEmail will return either true or false depending on whether the email is valid.

Body:
More appropriate way is to remove all the appended code from DOM tree:

Try this:

var email = $('#email').val();
email = validateEmail(email);
if (email == "false"){
      $('#email_error').parent().remove();
      $('#errors').append("<p id='email_error'>Please enter a valid email</p>");
}


来源: stackexchange

问:
How do I add the value from textview to list view
I m trying to add the value from textview dynamically to listview.For that I have created another layout to take the values from user. but I'm not able to do that. I have tried many things. Kindly help.. Here is my code.
package com.example.chetan.assignment;</p>

```<code>import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // String[] name= {"Apple","Banana","Mango","PineApple"};
        //String[] price = {"Rs.40","Rs.60","Rs.70","Rs.80"};

        List<String> names = new ArrayList<String>();
        //String[] names = {"names"};
        List<String> prices = new ArrayList<String>();
        //String[] prices = {"prices"};

        String name = getIntent().getStringExtra("name");
        String price = getIntent().getStringExtra("price");
        if(count==0) {
            names.add(0, "name");
            prices.add(0, "price");
        }

        if (count>0) {
            names.add(count, name);
            prices.add(count,price);
        }
        count++;

        ListAdapter MyAdapter = new MyAdapter(names, prices, this);
        ListView theList = (ListView) findViewById(R.id.listView);

        theList.setAdapter(MyAdapter);
    }
    public void buttonClick(View view) {
        Intent i = new Intent(this, Addlayout.class);
        startActivity(i);
    }
}

        package com.example.chetan.assignment;

    package com.example.chetan.assignment;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.BaseAdapter;
    import android.widget.TextView;

    class MyAdapter extends BaseAdapter {

        String[] name;
        String[] price;
        Context context;
        private static LayoutInflater myInflater = null;

        public MyAdapter(String[] name, String[] price, Context context) {
            this.name = name;
            this.price = price;
            this.context = context;
            myInflater  = ( LayoutInflater )context.
                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return name.length;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }
        public class Holder
        {
            TextView nametext;
            TextView pricetext;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder myholder = new Holder();
            View myViews = myInflater.inflate(R.layout.myview,parent,false);
            myholder.nametext= (TextView) myViews.findViewById(R.id.textView);
            myholder.pricetext= (TextView) myViews.findViewById(R.id.textView2);
            myholder.nametext.setText(name[position]);
            myholder.pricetext.setText(price[position]);

            return myViews;

        }

    }
    package com.example.chetan.assignment;

    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.text.Editable;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.Toast;

    public class Addlayout extends AppCompatActivity {

         @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_addlayout);
        }

       public void Onclickbutton(View view){
            EditText nametext = (EditText)findViewById(R.id.editText);
            EditText pricetext = (EditText)findViewById(R.id.editText2);

            String namedata = nametext.getText().toString();
            String pricedata = pricetext.getText().toString();

            Intent intent = new Intent(this,MainActivity.class);
            intent.putExtra("name",namedata);
            intent.putExtra("price",pricedata);

           startActivity(intent);

        }
    }
</code>```

答:
```<code>    Here you can do something like this:
    Instead of simple listview I have used RecyclerView as it has better performance.

    //First create a Data class for name and price

    public class Data implements Serializable {

        private String name,price;

        public Data(){}

        public Data(String name,String price){
            this.name = name;
            this.price = price;
        }

        public String getPrice() {
            return price;
        }

        public void setPrice(String price) {
            this.price = price;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    //your Addlayout class

    public class Addlayout extends AppCompatActivity {

        List<Data> dataList = new ArrayList<>();
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_addlayout);

        }

        public void Onclickbutton(View view){
            EditText nameText = (EditText)findViewById(R.id.editText);
            EditText priceText = (EditText)findViewById(R.id.editText2);

            String nameData = nameText.getText().toString();
            String priceData = priceText.getText().toString();
            Data data = new Data(nameData, priceData);
            dataList.add(data);
            Intent intent = new Intent(this,MainActivity.class);
            intent.putExtra("List", (Serializable) dataList);
            startActivity(intent);

        }
    }

    //add layout xml
    //change layout according to you

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_addlayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.example.mmc.testproject.Addlayout">

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:hint="name"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"
            android:layout_marginStart="13dp"
            android:id="@+id/editText" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:hint="price"
            android:layout_below="@+id/editText"
            android:layout_alignEnd="@+id/editText"
            android:layout_marginTop="18dp"
            android:id="@+id/editText2" />

        <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/editText2"
            android:layout_alignStart="@+id/editText2"
            android:layout_marginStart="43dp"
            android:layout_marginTop="36dp"
            android:onClick="Onclickbutton"
            android:id="@+id/button" />
    </RelativeLayout>

    //Then your Listview Adapter

    public class ListViewAdaptor extends RecyclerView.Adapter<ListViewAdaptor.MyViewHolder> {
        private List<Data> mDataList;

        public class MyViewHolder extends RecyclerView.ViewHolder{
            public TextView name,price;

            public MyViewHolder(View view){
                super(view);
                name = (TextView) view.findViewById(R.id.name);
                price= (TextView) view.findViewById(R.id.price);
            }
        }

        public ListViewAdaptor(List<Data> dataList){
            this.mDataList = dataList;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.list_view_item, parent, false);

            return new MyViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            Data data = mDataList.get(position);
            holder.name.setText(data.getName());
            holder.price.setText(data.getPrice());
        }

        @Override
        public int getItemCount() {
            return mDataList.size();
        }
    }

    //your Listview layout to show name and price

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/name"
            android:text="name"
            android:gravity="center"
            android:textSize="26sp"
            android:layout_weight="1"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/price"
            android:text="price"
            android:gravity="center"
            android:textSize="26sp"
            android:layout_weight="1"/>

    </LinearLayout>

    //And finally the main Activity

    public class MainActivity extends AppCompatActivity {

        private RecyclerView mRecyclerView;
        private ListViewAdaptor mAdapter;
        private List<Data> mDataList;

        private static final String TAG = "MainActivity";
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
            Intent i = getIntent();
            mDataList = (List<Data>) i.getSerializableExtra("List");
            Log.e(TAG,"Datalist size : "+mDataList.size());
            mAdapter = new ListViewAdaptor(mDataList);
            RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
            mRecyclerView.setLayoutManager(mLayoutManager);
            mRecyclerView.setItemAnimator(new DefaultItemAnimator());
            mRecyclerView.setAdapter(mAdapter);
        }

    }

//and main Activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.mmc.testproject.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recycler_view">

    </android.support.v7.widget.RecyclerView>

</RelativeLayout>
</code>```

Hope it helps!!!

ContentLicense: CC BY-SA 3.0

Body:
I m trying to add the value from textview dynamically to listview.For that I have created another layout to take the values from user. but I'm not able to do that. I have tried many things. Kindly help.. Here is my code.
package com.example.chetan.assignment;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // String[] name= {"Apple","Banana","Mango","PineApple"};
        //String[] price = {"Rs.40","Rs.60","Rs.70","Rs.80"};

        List<String> names = new ArrayList<String>();
        //String[] names = {"names"};
        List<String> prices = new ArrayList<String>();
        //String[] prices = {"prices"};

        String name = getIntent().getStringExtra("name");
        String price = getIntent().getStringExtra("price");
        if(count==0) {
            names.add(0, "name");
            prices.add(0, "price");
        }

        if (count>0) {
            names.add(count, name);
            prices.add(count,price);
        }
        count++;

        ListAdapter MyAdapter = new MyAdapter(names, prices, this);
        ListView theList = (ListView) findViewById(R.id.listView);

        theList.setAdapter(MyAdapter);
    }
    public void buttonClick(View view) {
        Intent i = new Intent(this, Addlayout.class);
        startActivity(i);
    }
}

        package com.example.chetan.assignment;

    package com.example.chetan.assignment;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.BaseAdapter;
    import android.widget.TextView;

    class MyAdapter extends BaseAdapter {

        String[] name;
        String[] price;
        Context context;
        private static LayoutInflater myInflater = null;

        public MyAdapter(String[] name, String[] price, Context context) {
            this.name = name;
            this.price = price;
            this.context = context;
            myInflater  = ( LayoutInflater )context.
                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return name.length;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }
        public class Holder
        {
            TextView nametext;
            TextView pricetext;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder myholder = new Holder();
            View myViews = myInflater.inflate(R.layout.myview,parent,false);
            myholder.nametext= (TextView) myViews.findViewById(R.id.textView);
            myholder.pricetext= (TextView) myViews.findViewById(R.id.textView2);
            myholder.nametext.setText(name[position]);
            myholder.pricetext.setText(price[position]);

            return myViews;

        }

    }
    package com.example.chetan.assignment;

    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.text.Editable;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.Toast;

    public class Addlayout extends AppCompatActivity {

         @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_addlayout);
        }

       public void Onclickbutton(View view){
            EditText nametext = (EditText)findViewById(R.id.editText);
            EditText pricetext = (EditText)findViewById(R.id.editText2);

            String namedata = nametext.getText().toString();
            String pricedata = pricetext.getText().toString();

            Intent intent = new Intent(this,MainActivity.class);
            intent.putExtra("name",namedata);
            intent.putExtra("price",pricedata);

           startActivity(intent);

        }
    }

Body:
    Here you can do something like this:
    Instead of simple listview I have used RecyclerView as it has better performance.

    //First create a Data class for name and price

    public class Data implements Serializable {

        private String name,price;

        public Data(){}

        public Data(String name,String price){
            this.name = name;
            this.price = price;
        }

        public String getPrice() {
            return price;
        }

        public void setPrice(String price) {
            this.price = price;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    //your Addlayout class

    public class Addlayout extends AppCompatActivity {

        List<Data> dataList = new ArrayList<>();
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_addlayout);

        }

        public void Onclickbutton(View view){
            EditText nameText = (EditText)findViewById(R.id.editText);
            EditText priceText = (EditText)findViewById(R.id.editText2);

            String nameData = nameText.getText().toString();
            String priceData = priceText.getText().toString();
            Data data = new Data(nameData, priceData);
            dataList.add(data);
            Intent intent = new Intent(this,MainActivity.class);
            intent.putExtra("List", (Serializable) dataList);
            startActivity(intent);

        }
    }

    //add layout xml
    //change layout according to you

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_addlayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.example.mmc.testproject.Addlayout">

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:hint="name"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"
            android:layout_marginStart="13dp"
            android:id="@+id/editText" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:hint="price"
            android:layout_below="@+id/editText"
            android:layout_alignEnd="@+id/editText"
            android:layout_marginTop="18dp"
            android:id="@+id/editText2" />

        <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/editText2"
            android:layout_alignStart="@+id/editText2"
            android:layout_marginStart="43dp"
            android:layout_marginTop="36dp"
            android:onClick="Onclickbutton"
            android:id="@+id/button" />
    </RelativeLayout>

    //Then your Listview Adapter

    public class ListViewAdaptor extends RecyclerView.Adapter<ListViewAdaptor.MyViewHolder> {
        private List<Data> mDataList;

        public class MyViewHolder extends RecyclerView.ViewHolder{
            public TextView name,price;

            public MyViewHolder(View view){
                super(view);
                name = (TextView) view.findViewById(R.id.name);
                price= (TextView) view.findViewById(R.id.price);
            }
        }

        public ListViewAdaptor(List<Data> dataList){
            this.mDataList = dataList;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.list_view_item, parent, false);

            return new MyViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            Data data = mDataList.get(position);
            holder.name.setText(data.getName());
            holder.price.setText(data.getPrice());
        }

        @Override
        public int getItemCount() {
            return mDataList.size();
        }
    }

    //your Listview layout to show name and price

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/name"
            android:text="name"
            android:gravity="center"
            android:textSize="26sp"
            android:layout_weight="1"/>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/price"
            android:text="price"
            android:gravity="center"
            android:textSize="26sp"
            android:layout_weight="1"/>

    </LinearLayout>

    //And finally the main Activity

    public class MainActivity extends AppCompatActivity {

        private RecyclerView mRecyclerView;
        private ListViewAdaptor mAdapter;
        private List<Data> mDataList;

        private static final String TAG = "MainActivity";
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
            Intent i = getIntent();
            mDataList = (List<Data>) i.getSerializableExtra("List");
            Log.e(TAG,"Datalist size : "+mDataList.size());
            mAdapter = new ListViewAdaptor(mDataList);
            RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
            mRecyclerView.setLayoutManager(mLayoutManager);
            mRecyclerView.setItemAnimator(new DefaultItemAnimator());
            mRecyclerView.setAdapter(mAdapter);
        }

    }

//and main Activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.mmc.testproject.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/recycler_view">

    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

Hope it helps!!!


问:
Close Parent Tab after closing of child tab
```<code> ====================Apex Class Code========================
Public Boolean isClosed{get;set;}
isClosed = false;
List<Opportunity> Affre_main = new List<Opportunity>();
for(Opportunity opp: [select id,Afree_main_sol__c from Opportunity where Id in: oppVar] ){
        opp.Afree_main_sol__c = 'some value';
        Affre_main.add(opp)
}
if(!Affre_main.isEmpty()){
    insert Affre_main;
    isClosed = true;
}

========================ON VF Page=================================================
<script>
if("{!isClosed}"){
    window.close();
    //Now how to close its parent tab//
}

</script>
</code>```

I am looking for a workaround. I want to close a tab (say child tab) and then I want to auto-close the parent (main tab).

Is there any standard way then please tell me.

I want to use this solution with visualforce-salesforce.

Javascript/jquery solutions will also be helpful.

答:
I find it myself.

just a quick line solution.

Just need to use  window.opener.close(); to auto close the parent window from the open child window.

Body:
 ====================Apex Class Code========================
Public Boolean isClosed{get;set;}
isClosed = false;
List<Opportunity> Affre_main = new List<Opportunity>();
for(Opportunity opp: [select id,Afree_main_sol__c from Opportunity where Id in: oppVar] ){
        opp.Afree_main_sol__c = 'some value';
        Affre_main.add(opp)
}
if(!Affre_main.isEmpty()){
    insert Affre_main;
    isClosed = true;
}

========================ON VF Page=================================================

I am looking for a workaround. I want to close a tab (say child tab) and then I want to auto-close the parent (main tab).

Is there any standard way then please tell me.

I want to use this solution with visualforce-salesforce.

Javascript/jquery solutions will also be helpful.


问:
How do I open a file on server using the default program in Qt?
Everything I read indicates that QDesktopServices::openUrl is the platform-agnostic way to open a document using the default program, and it works great, almost all of the time.

I say almost, because it always seems to fail if I pass it a network path. Combing through the source I see that ShellExecute returns error code 2.

Example:

```<code>QUrl localpath = QUrl::fromLocalFile("C:/temp/myfile.txt");
QUrl networkpath = QUrl::fromLocalFile("//192.168.0.5/my folder/myfile.txt");

QDesktopServices::openUrl(localpath);     //works fine
QDesktopServices::openUrl(networkpath);   //always fails
</code>```

Is there a way I can clean up a network path to open correctly? I'm running Qt 4.8 on Windows. Switching the forward slashes to backslashes doesn't help.

答:
You should use QUrl::TolerantMode if you have spaces in your path.
try this:</p>

```<code>QDesktopServices::openUrl(QUrl("file:////192.168.0.5/my folder/myfile.txt", QUrl::TolerantMode));
</code>```

Body:
Everything I read indicates that QDesktopServices::openUrl is the platform-agnostic way to open a document using the default program, and it works great, almost all of the time.

I say almost, because it always seems to fail if I pass it a network path. Combing through the source I see that ShellExecute returns error code 2.

Example:

QUrl localpath = QUrl::fromLocalFile("C:/temp/myfile.txt");
QUrl networkpath = QUrl::fromLocalFile("//192.168.0.5/my folder/myfile.txt");

QDesktopServices::openUrl(localpath);     //works fine
QDesktopServices::openUrl(networkpath);   //always fails

Is there a way I can clean up a network path to open correctly? I'm running Qt 4.8 on Windows. Switching the forward slashes to backslashes doesn't help.

Body:
You should use QUrl::TolerantMode if you have spaces in your path.
try this:

QDesktopServices::openUrl(QUrl("file:////192.168.0.5/my folder/myfile.txt", QUrl::TolerantMode));


问:
Use GNU parallel to parallelise a bash for loop
I have a for loop which runs a Python script ~100 times on 100 different input folders. The python script is most efficient on 2 cores, and I have 50 cores available. So I'd like to use GNU parallel to run the script on 25 folders at a time.

Here's my for loop (works fine, but is sequential of course), the python script takes a bunch of input variables including the -p 2 which runs it on two cores:

```<code>for folder in $(find /home/rob/PartitionFinder/ -maxdepth 2 -type d); do
        python script.py --raxml --quick --no-ml-tree $folder --force -p 2
done
</code>```

and here's my attempt to parallelise it, which does not work:

```<code>folders=$(find /home/rob/PartitionFinder/ -maxdepth 2 -type d)

echo $folders | parallel -P 25 python script.py --raxml --quick --no-ml-tree {} --force -p 2
</code>```

The issue I'm hitting (perhaps it's just the first of many though) is that my folders variable is not a list, so it's really just passing a long string of 100 folders as the {} to the script.

All hints gratefully received.

答:
you can pipe find directly to parallel:

```<code> find /home/rob/PartitionFinder/ -maxdepth 2 -type d | parallel -P 25 python script.py --raxml --quick --no-ml-tree {} --force -p 2
</code>```

If you want to keep the string in $folder, you can pipe the echo to xargs.

```<code>echo $folders | xargs -n 1 | parallel -P 25 python script.py --raxml --quick --no-ml-tree {} --force -p 2
</code>```

Body:
I have a for loop which runs a Python script ~100 times on 100 different input folders. The python script is most efficient on 2 cores, and I have 50 cores available. So I'd like to use GNU parallel to run the script on 25 folders at a time.

Here's my for loop (works fine, but is sequential of course), the python script takes a bunch of input variables including the -p 2 which runs it on two cores:

for folder in $(find /home/rob/PartitionFinder/ -maxdepth 2 -type d); do
        python script.py --raxml --quick --no-ml-tree $folder --force -p 2
done

and here's my attempt to parallelise it, which does not work:

folders=$(find /home/rob/PartitionFinder/ -maxdepth 2 -type d)

echo $folders | parallel -P 25 python script.py --raxml --quick --no-ml-tree {} --force -p 2

The issue I'm hitting (perhaps it's just the first of many though) is that my folders variable is not a list, so it's really just passing a long string of 100 folders as the {} to the script.

All hints gratefully received.

Body:
you can pipe find directly to parallel:

 find /home/rob/PartitionFinder/ -maxdepth 2 -type d | parallel -P 25 python script.py --raxml --quick --no-ml-tree {} --force -p 2

If you want to keep the string in $folder, you can pipe the echo to xargs.

echo $folders | xargs -n 1 | parallel -P 25 python script.py --raxml --quick --no-ml-tree {} --force -p 2


问:
Twilio: how to warn users before call ends aggressively with time limited calls?
So here what i have, when a user A calls my Twilio number, the call is forwarded towards another user B number through a Twiml response which dials user B number. I have done a time limit for any calls which is 5 minutes, but i would like to prevent the two users when there is only 1 minute left that time is nearly up and avoid cutting out aggressively the call.

Any one has an idea how to do that ?

答:
Twilio developer evangelist here.

You could have the users actually call into a <Conference> (generating a call to user B when user A calls and enters the conference) and then start a timer for 4 minutes on your server. When the timer is done you can then check if the conference is still live (by calling the REST API and checking the conference status) and if it is dial one more caller into the conference.

That caller could be a recorded message that you play with <Play> or a message to be read out with text to speech using <Say> that lets the callers know that there's only one minute left.

For example:

```<code><Response>
  <Say voice="alice">Warning. There is only one minute of calling time left.</Say>
  <Hangup/>
</Response>
</code>```

Update

This is now better done with announcements that can be played into conferences. Check out the blog post here with details on how to announce messages into a conference.

Body:
Twilio developer evangelist here.

You could have the users actually call into a <Conference> (generating a call to user B when user A calls and enters the conference) and then start a timer for 4 minutes on your server. When the timer is done you can then check if the conference is still live (by calling the REST API and checking the conference status) and if it is dial one more caller into the conference.

That caller could be a recorded message that you play with <Play> or a message to be read out with text to speech using <Say> that lets the callers know that there's only one minute left.

For example:

<Response>
  <Say voice="alice">Warning. There is only one minute of calling time left.</Say>
  <Hangup/>
</Response>

Update

This is now better done with announcements that can be played into conferences. Check out the blog post here with details on how to announce messages into a conference.

ContentLicense: CC BY-SA 4.0


问:
Filling HTML Table with Dropwdownlists Change event in MVC
I was trying to implement change event equivalent in MVC dropdownlist where it will fill the table below with relavant data from database.

But my Ajax call is not hitting the controller action method. can anybody tell me where I am  mistaken

View and vavascript

```<code>@model WebArtSampler.Models.AssignRequestModel

@{
    ViewBag.Title = "AssignRequest";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>AssignRequest</h2>

@using (Html.BeginForm("AssignRequestNew", "SamCutAssignmentMasters"))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">

        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.CutAssignID)

        <div class="form-group">
            @Html.LabelFor(model => model.CutAssignID, "Cutting Request #", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">

                @*@Html.DropDownListFor(model => model.CutAssignID, (SelectList)ViewBag.CutAssignID, "--Select One--", htmlAttributes: new { @class = "form-control" })*@

                @Html.DropDownList("Id", (SelectList)ViewBag.CutAssignID, htmlAttributes: new { @class = "form-control" })

            </div>
        </div>

}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
<div id="div1">

    <table class="table">
        <tr>
            <th>
                Req#
            </th>
            <th>
                Buyer
            </th>
            <th>
                Pattern Ref#
            </th>

            <th>
                Style
            </th>
            <th>
                Style Description
            </th>
            <th>
                Fabric
            </th>

           </tr>

        @foreach (var student in Model.Reqnumlist)
        {

            <tr>
                <td>
                    @student.ReqNum
                </td>
                <td>
                    @student.BuyerName
                </td>
                <td>
                    @student.PatterRefNum
                </td>
                <td>
                    @student.StyleName
                </td>
                <td>
                    @student.StyleDescription
                </td>

                <td>
                    @student.Fabric
                </td>

            </tr>

        }

    </table>

</div>
</code>```

JQuery I used is

```<code>  <script type="text/javascript">

        $(document).ready(function () {

            debugger;
            $("#Id").change(function () {

                debugger
                var Id = $(this).find('option:selected').val();
                $.ajax({
                    url: "@Url.Action("PopulateDetails","SamCutAssignmentMasters")",
                    type: 'Get',
                    contentType: "application/json; charset=utf-8",
                    dataType: 'json',
                    data: { 'Id': Id },
                    success: function (data) {
                        if (data.success) {

                            debugger
                            document.getElementById("ProductName").value = data.productName;
                        }
                        else {
                            alert('invalid ID' + data.success);
                        }
                    }
                });

            });

        });

    </script>
</code>```

Model

```<code> public class SamCutAssignmentMastersController : Controller
    {
    [HttpGet]
        public JsonResult PopulateDetails(int id)
        {

            return Json(GetDetailsofaspecificTicket(id));
        }

   }
</code>```

答:
Firstly, check the specification for UrlHelper.Action, you're trying to use this overload:

```<code>public virtual string Action(
    string actionName,
    string controllerName
)
</code>```

You have the action and controller names the wrong way round. In circumstances like this it's usually worth doing a "View source" on your code, you could have then seen that the url was incorrect.

Also you will need to update the syntax of your ajax call where you are passing the id parameter to:

```<code>data: { 'Id': Id },
</code>```

Body:
I was trying to implement change event equivalent in MVC dropdownlist where it will fill the table below with relavant data from database.

But my Ajax call is not hitting the controller action method. can anybody tell me where I am  mistaken

View and vavascript

@model WebArtSampler.Models.AssignRequestModel

@{
    ViewBag.Title = "AssignRequest";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

AssignRequest

@using (Html.BeginForm("AssignRequestNew", "SamCutAssignmentMasters"))
{
    @Html.AntiForgeryToken()

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.CutAssignID)

            @Html.LabelFor(model => model.CutAssignID, "Cutting Request #", htmlAttributes: new { @class = "control-label col-md-2" })

                @*@Html.DropDownListFor(model => model.CutAssignID, (SelectList)ViewBag.CutAssignID, "--Select One--", htmlAttributes: new { @class = "form-control" })*@

                @Html.DropDownList("Id", (SelectList)ViewBag.CutAssignID, htmlAttributes: new { @class = "form-control" })

}

    @Html.ActionLink("Back to List", "Index")

                Req#

                Buyer

                Pattern Ref#

                Style

                Style Description

                Fabric

        @foreach (var student in Model.Reqnumlist)
        {

                    @student.ReqNum

                    @student.BuyerName

                    @student.PatterRefNum

                    @student.StyleName

                    @student.StyleDescription

                    @student.Fabric

        }

JQuery I used is

Model

 public class SamCutAssignmentMastersController : Controller
    {
    [HttpGet]
        public JsonResult PopulateDetails(int id)
        {

            return Json(GetDetailsofaspecificTicket(id));
        }

   }

Body:
Firstly, check the specification for UrlHelper.Action, you're trying to use this overload:

public virtual string Action(
    string actionName,
    string controllerName
)

You have the action and controller names the wrong way round. In circumstances like this it's usually worth doing a "View source" on your code, you could have then seen that the url was incorrect.

Also you will need to update the syntax of your ajax call where you are passing the id parameter to:

data: { 'Id': Id },


问:
Proguard processing interface will delete the interface method throws
When I use proguard on Android, I found proguard after dealing with interface, the interface method of throws was deleted.

before:

```<code>public interface Factory {

Card create(Profile profile) throws CardException;

}
</code>```

proguard-rules.pro:

```<code>-keep interface Factory { *; }
</code>```

after:

```<code>public interface Factory {
Card create(Profile var1);
}
</code>```

You can see that the throws of the method are removed.

I do not know the reason for optimize, obfuscator or shrink the reason.

答:
replace com.example with base package of CardException Class and
  put this line in proguard file

```<code>-keep class com.example.** { *; }
</code>```

Body:
When I use proguard on Android, I found proguard after dealing with interface, the interface method of throws was deleted.

before:

public interface Factory {

Card create(Profile profile) throws CardException;

}

proguard-rules.pro:

-keep interface Factory { *; }

after:

public interface Factory {
Card create(Profile var1);
}

You can see that the throws of the method are removed.

I do not know the reason for optimize, obfuscator or shrink the reason.

Body:
replace com.example with base package of CardException Class and
  put this line in proguard file

-keep class com.example.** { *; }


答:
Replace echo $folders | parallel ... with echo "$folders" | parallel ....

Without the double quotes, the shell parses spaces in $folders and passes them as separate arguments to echo, which causes them to be printed on one line. parallel provides each line as argument to the job.

To avoid such quoting issues altogether, it is always a good idea to pipe find to parallel directly, and use the null character as the delimiter:

```<code>find ... -print0 | parallel -0 ...
</code>```

This will work even when encountering file names that contain multiple spaces or a newline character.

Title: Use GNU parallel to parallelise a bash for loop

Body:
Replace echo $folders | parallel ... with echo "$folders" | parallel ....

Without the double quotes, the shell parses spaces in $folders and passes them as separate arguments to echo, which causes them to be printed on one line. parallel provides each line as argument to the job.

To avoid such quoting issues altogether, it is always a good idea to pipe find to parallel directly, and use the null character as the delimiter:

find ... -print0 | parallel -0 ...

This will work even when encountering file names that contain multiple spaces or a newline character.


问:
Angular 2 cli SCSS/CSS order
I'm trying to work out what order Angular 2 uses for its Css once its all compiled.

What I'm trying to work out is does it get all of the SCSS files from the individual components and then add them after the main styles.scss file? This would seem to be the obvious thing but does it do it the other way round and put the componet styles first then the main styles?

I know if I specify files in the styles array in the angular-cli.json file Angular will process them in that order but obviously component styles aren't specified there.

Apologies if this sounds a bit odd but I can't work it out and can't seem to find any info on it anywhwere.

答:
In general, we don't have to ensure a given style order. Component styles (by default) will work independently of other styles in other components and in the order that the styles are processed.

The processing order of the Sass files is not guaranteed in the CLI, there is an order which is the order in which the CLI plugins (Webpack based) process the files but that could change over time as the CLI evolves.

One of the main goals of Angular styling is to provide style encapsulation, meaning that the styles on the SASS file associated to the component are only applicable to that style.

To understand how this works and why in general we don't need to worry about style order, let's take as an example this style in a component SASS file:

```<code>.active {
    border-radius:4px;
}
</code>```

This will be converted at runtime to something like:

```<code>.active[_concontent-c1] {
    border-radius:4px;
}
</code>```

What goes inside the angle brackets is a unique attribute identifier that increases the specificity of the style and ensures its only applicable to elements inside the template of that particular component.

One of the main benefits of this mechanism is that the order on which the component styles are processed is not critical because the unique identifier will ensure they will not interfere.

Note: There are ways to do not have that unique ID applied to the style if needed

Have a look at this video to see more details of this mechanism in action.

Title: Angular 2 cli SCSS/CSS order

Body:
In general, we don't have to ensure a given style order. Component styles (by default) will work independently of other styles in other components and in the order that the styles are processed.

The processing order of the Sass files is not guaranteed in the CLI, there is an order which is the order in which the CLI plugins (Webpack based) process the files but that could change over time as the CLI evolves.

One of the main goals of Angular styling is to provide style encapsulation, meaning that the styles on the SASS file associated to the component are only applicable to that style.

To understand how this works and why in general we don't need to worry about style order, let's take as an example this style in a component SASS file:

.active {
    border-radius:4px;
}

This will be converted at runtime to something like:

.active[_concontent-c1] {
    border-radius:4px;
}

What goes inside the angle brackets is a unique attribute identifier that increases the specificity of the style and ensures its only applicable to elements inside the template of that particular component.

One of the main benefits of this mechanism is that the order on which the component styles are processed is not critical because the unique identifier will ensure they will not interfere.

Note: There are ways to do not have that unique ID applied to the style if needed

Have a look at this video to see more details of this mechanism in action.


问:
How to PROVE the precedence of '&&' and '||' by coding in Java?
I know from somewhere that logical AND: && has a higher precedence than logical OR: || in Java, but until now I haven't found any clue about how this precedence really acts. What would happen if I didn't know about the precedence of the two and what mistake would I make?
I tried to write some code to PROVE the precedence of && and || but failed, for example:

```<code>boolExp1 || boolExp2 && boolExp3 || boolExp4
</code>```

The code above produces the same results no matter the precedence of && and ||, that is,

```<code>false || false && true || false
</code>```

results in false no matter what the precedence is.

I want a method or function that can PROVE the precedence of && and ||. It should produce different results depending on the precedence of && and ||. Is it possible?

答:
You cannot prove anything useful about a programming language by just writing / running examples.  For all you know, the compiler might be implemented so as to compile code in an illogical, inconsistent or non-deterministic fashion.

Even if you assume deterministic compilation and deterministic execution, the only thing that compiling / running an example proves is that that particular example exhibits a particular behavior.  You cannot logically generalize from one example to another one, because without reference to a specification the compiler is just a black box.  (Your very next example could be the one that is handled in a totally counter-intuitive fashion.)

The correct way to develop an understanding of a programming language is to read the language specification, a good textbook or a good tutorial.  Combine this with writing code to confirm your understanding.

If you rely solely on reading example code and writing test programs, you are liable to pick up misconceptions, and bad habits that can be painful to unlearn.

Body:
I know from somewhere that logical AND: && has a higher precedence than logical OR: || in Java, but until now I haven't found any clue about how this precedence really acts. What would happen if I didn't know about the precedence of the two and what mistake would I make?
I tried to write some code to PROVE the precedence of && and || but failed, for example:

boolExp1 || boolExp2 && boolExp3 || boolExp4

The code above produces the same results no matter the precedence of && and ||, that is,

false || false && true || false

results in false no matter what the precedence is.

I want a method or function that can PROVE the precedence of && and ||. It should produce different results depending on the precedence of && and ||. Is it possible?


问:
getting errors when running "ionic serve"
My working environment is:

macOS

node  v6.9.1

npm   v3.10.8

ionic v2.1.14

I got these errors when I run ionic serve :

```<code>> ionic-app-base@ ionic:serve /Users/Hao/Project/OneCharacter
> ionic-app-scripts serve

module.js:597
  return process.dlopen(module, path._makeLong(filename));
                 ^

Error: dlopen(/Users/Hao/Project/OneCharacter/node_modules/@ionic/app-scripts/node_modules/node-sass/vendor/darwin-x64-48/binding.node, 1): no suitable image found.  Did find:
    /Users/Hao/Project/OneCharacter/node_modules/@ionic/app-scripts/node_modules/node-sass/vendor/darwin-x64-48/binding.node: truncated mach-o error: segment __TEXT extends to 1212416 which is past end of file 121392
    at Error (native)
    at Object.Module._extensions..node (module.js:597:18)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/Hao/Project/OneCharacter/node_modules/@ionic/app-scripts/node_modules/node-sass/lib/index.js:23:15)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)

npm ERR! Darwin 16.1.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "ionic:serve" "--"
npm ERR! node v6.9.1
npm ERR! npm  v3.10.8
npm ERR! code ELIFECYCLE
npm ERR! ionic-app-base@ ionic:serve: `ionic-app-scripts serve`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ionic-app-base@ ionic:serve script 'ionic-app-scripts serve'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the ionic-app-base package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     ionic-app-scripts serve
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs ionic-app-base
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls ionic-app-base
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/Hao/Project/OneCharacter/npm-debug.log
There was an error serving your Ionic application: There was an error with the spawned command: serve
</code>```

I have already run npm install in my project. It seems this is a problem about node-sass? Or maybe it is due to the bad network?

答:
If you have a bad network connection, then this is probably the problem. I faced a similar problem. "ionic serve" requires an internet connection to be executed properly.

Nevertheless, if this is not the case, try running the following command to serve your app in development mode:

```<code>npm run ionic:serve
</code>```

I also suggest you to update your ionic CLI to a more stable version with the following command:

```<code># May need "sudo"
npm install -g ionic@2.2.3
</code>```

Body:
My working environment is:

macOS

node  v6.9.1

npm   v3.10.8

ionic v2.1.14

I got these errors when I run ionic serve :

> ionic-app-base@ ionic:serve /Users/Hao/Project/OneCharacter
> ionic-app-scripts serve

module.js:597
  return process.dlopen(module, path._makeLong(filename));
                 ^

Error: dlopen(/Users/Hao/Project/OneCharacter/node_modules/@ionic/app-scripts/node_modules/node-sass/vendor/darwin-x64-48/binding.node, 1): no suitable image found.  Did find:
    /Users/Hao/Project/OneCharacter/node_modules/@ionic/app-scripts/node_modules/node-sass/vendor/darwin-x64-48/binding.node: truncated mach-o error: segment __TEXT extends to 1212416 which is past end of file 121392
    at Error (native)
    at Object.Module._extensions..node (module.js:597:18)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/Users/Hao/Project/OneCharacter/node_modules/@ionic/app-scripts/node_modules/node-sass/lib/index.js:23:15)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)

npm ERR! Darwin 16.1.0
npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "ionic:serve" "--"
npm ERR! node v6.9.1
npm ERR! npm  v3.10.8
npm ERR! code ELIFECYCLE
npm ERR! ionic-app-base@ ionic:serve: `ionic-app-scripts serve`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the ionic-app-base@ ionic:serve script 'ionic-app-scripts serve'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the ionic-app-base package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     ionic-app-scripts serve
npm ERR! You can get information on how to open an issue for this project with:
npm ERR!     npm bugs ionic-app-base
npm ERR! Or if that isn't available, you can get their info via:
npm ERR!     npm owner ls ionic-app-base
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/Hao/Project/OneCharacter/npm-debug.log
There was an error serving your Ionic application: There was an error with the spawned command: serve

I have already run npm install in my project. It seems this is a problem about node-sass? Or maybe it is due to the bad network?

Body:
If you have a bad network connection, then this is probably the problem. I faced a similar problem. "ionic serve" requires an internet connection to be executed properly.

Nevertheless, if this is not the case, try running the following command to serve your app in development mode:

npm run ionic:serve

I also suggest you to update your ionic CLI to a more stable version with the following command:

# May need "sudo"
npm install -g ionic@2.2.3


问:
How to add a node in front of boost property_tree
I have a xml

```<code><MyXML>
    <Tag2>2</Tag2>
    <Tag3>3</Tag2>
    <Tag4>4</Tag3>
</MyXML>
</code>```

and read it into boost::property_tree::ptree xmlroot using boost::property_tree::read_xml

Now if I add a new node by

```<code>xmlroot.add("MyXML.Tag1", "1");
</code>```

This new node will add to back of existing tags. After boost::property_tree::write_xml, I get

```<code><MyXML>
    <Tag2>2</Tag2>
    <Tag3>3</Tag2>
    <Tag4>4</Tag3>
    <Tag1>1</Tag1>
</MyXML>
</code>```

Is there a way to insert new node in front of Tag2?

答:
It's possible, but it's outside of scope of standard accessors like get and add so one has to go the longer and more cumbersome way of iterators. Basically you need to get an iterator for your node and use insert or push_front insert a new node at required place.

Full example.:

```<code>#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <string>
#include <exception>
#include <iostream>
namespace pt = boost::property_tree;

int main()
{
    try
    {
        std::string xml_content =
"<MyXML> \
    <Tag2>2</Tag2> \
    <Tag3>3</Tag2> \
    <Tag4>4</Tag3> \
</MyXML>";
        std::stringstream xml (xml_content);
        pt::ptree tree;
        pt::read_xml (xml, tree);
        /* ~~~~ KEY STUFF ~~~~ */
        auto root = tree.find("MyXML");
        root->second.push_front({"NewTag", decltype(tree)("1")});
        /* ~~~~ KEY STUFF ~~~~ */
        pt::write_xml (std::cout, tree);
    }
    catch (std::exception &e)
    {
        std::cout << "Error: " << e.what() << "\n";
    }
    return 0;
}
</code>```

Key stuff explained:

```<code>    auto root = tree.find("MyXML");
    root->second.push_front({"NewTag", decltype(tree)("1")});
</code>```

Ok, so 1st line is a no brainer, we need to get our "work" node.

Second line uses push_front, which inserts a new node at the front of the caller. But out caller is at the second field of the iterator, which is the result of find("MyXML").

Then push_front expects a pair of key and self_type. I used brace initialization for pair, and a string literal for key. Creating a new node of matching type is a little bit more tricky, since the constructor using value is marked as explicit. So, one has to use it's type. I got it using decltype of the tree.

If anything can be simplified I happily welcome all improvements.

Body:
I have a xml

<MyXML>
    <Tag2>2</Tag2>
    <Tag3>3</Tag2>
    <Tag4>4</Tag3>
</MyXML>

and read it into boost::property_tree::ptree xmlroot using boost::property_tree::read_xml

Now if I add a new node by

xmlroot.add("MyXML.Tag1", "1");

This new node will add to back of existing tags. After boost::property_tree::write_xml, I get

<MyXML>
    <Tag2>2</Tag2>
    <Tag3>3</Tag2>
    <Tag4>4</Tag3>
    <Tag1>1</Tag1>
</MyXML>

Is there a way to insert new node in front of Tag2?

Body:
It's possible, but it's outside of scope of standard accessors like get and add so one has to go the longer and more cumbersome way of iterators. Basically you need to get an iterator for your node and use insert or push_front insert a new node at required place.

Full example.:

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <string>
#include <exception>
#include <iostream>
namespace pt = boost::property_tree;

int main()
{
    try
    {
        std::string xml_content =
"<MyXML> \
    <Tag2>2</Tag2> \
    <Tag3>3</Tag2> \
    <Tag4>4</Tag3> \
</MyXML>";
        std::stringstream xml (xml_content);
        pt::ptree tree;
        pt::read_xml (xml, tree);
        /* ~~~~ KEY STUFF ~~~~ */
        auto root = tree.find("MyXML");
        root->second.push_front({"NewTag", decltype(tree)("1")});
        /* ~~~~ KEY STUFF ~~~~ */
        pt::write_xml (std::cout, tree);
    }
    catch (std::exception &e)
    {
        std::cout << "Error: " << e.what() << "\n";
    }
    return 0;
}

Key stuff explained:

    auto root = tree.find("MyXML");
    root->second.push_front({"NewTag", decltype(tree)("1")});

Ok, so 1st line is a no brainer, we need to get our "work" node.

Second line uses push_front, which inserts a new node at the front of the caller. But out caller is at the second field of the iterator, which is the result of find("MyXML").

Then push_front expects a pair of key and self_type. I used brace initialization for pair, and a string literal for key. Creating a new node of matching type is a little bit more tricky, since the constructor using value is marked as explicit. So, one has to use it's type. I got it using decltype of the tree.

If anything can be simplified I happily welcome all improvements.


问:
C programming usin cmd prompt on windows
```<code>#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main(){
    char command[20];

    system("dir");

    while(1){
    printf("\n\n");
    scanf("%s", &command);
    system(command);
    }

    return 0;
}
</code>```

this is my code, it's a console app written in C and I wanna be able to control the cmd prompt of my computer, whenever I run new command like cd.. the path always goes back to where it was before, how do i make it like a process? sorry I'm new to it.

答:
You can't.

The cd command in typical command-line interpreters is an internal command, i.e. built into the command interpreter itself. This is because the current directory is a property of the process itself, and a child process (which is what system() creates, in most cases) can't change the current directory of its parent.

Body:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main(){
    char command[20];

    system("dir");

    while(1){
    printf("\n\n");
    scanf("%s", &command);
    system(command);
    }

    return 0;
}

this is my code, it's a console app written in C and I wanna be able to control the cmd prompt of my computer, whenever I run new command like cd.. the path always goes back to where it was before, how do i make it like a process? sorry I'm new to it.


问:
Version numbers for Visual Studio 2017, Boost and CMake
From the Boost mailing list I understand that VS2017 has the following version numbers that we would probably be most interested in:

```<code>Visual Studio           15.0
cl; C/C++ Compiler      19.10
Platform Toolset:       v141
</code>```

The following macros are defined in the Visual Studio 2017 IDE:

```<code>CrtSDKReferenceVersion  14.0
MSBuildToolsVersion     15.0
PlatformToolsetVersion  141
VCToolsVersion          14.10.25017
VisualStudioVersion     15.0
</code>```

During compilation the following variables are  #define'd:

```<code>_MSC_VER                1910
_MSC_FULL_VER           191025017
</code>```

cl.exe is contained within an MSVC folder with the VC tools version. The complete x64 folder path is

```<code>C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\bin\HostX64\x64
</code>```

cl /Bv from the command line lists:

```<code>Compiler Passes:
 cl.exe:        Version 19.10.25017.0
 c1.dll:        Version 19.10.25017.0
 c1xx.dll:      Version 19.10.25017.0
 c2.dll:        Version 19.10.25017.0
 link.exe:      Version 14.10.25017.0
 mspdb140.dll:  Version 14.10.25017.0
 1033\clui.dll: Version 19.10.25017.0
</code>```

Notice mspdb140.dll and link.exe are listed with version 14.10.25017.0.

And here it seems that msvc : 14.1 should be used as the toolset for boost. And here is another answer where some comments talk about boost's compiler naming.

When I compile I get the libraries names with v141 e.g.: boost_atomic-vc141-mt-1_64.lib

But in CMake the _Boost_GUESS_COMPILER_PREFIX function has the following:

```<code>if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.10)
  set(_boost_COMPILER "-vc150")
elseif (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19)
  set(_boost_COMPILER "-vc140")
</code>```

So which version should be used? vc141 or vc150? Does

v141 imply vc141, or does

v141 imply vc150?

答:
CMake versions which are less than the official release v3.8.0, which includes the rc numbers have the following in their FindBoost.cmake.

```<code>if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.10)
  set(_boost_COMPILER "-vc150")
</code>```

which means that, if your Boost dlls are not named like e.g. boost_date_time-vc150-mt-1_55.dll they won't be found. Version v3.8.0 started matching the approach Boost was taking with regard to version numbers, though I don't recall the in depth discussion of the matter. The short answer is though, if you are using a cmake version v3.8.0 or greater, you need the following instead.

```<code>  if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 19.10)
    set(BOOST_TOOLSET msvc-14.1)
</code>```

For simplicity, in my Boost builds for Windows, I always add the following CMake code..

```<code>if(MSVC AND (NOT MSVC_VERSION LESS 1910))
  # Get the CMAKE version string and make sure it's not a release candidate and >= 3.8.0
  if( (CMAKE_VERSION MATCHES "^3\\.8\\.0-rc") OR (CMAKE_VERSION VERSION_LESS 3.8.0))
    message(FATAL_ERROR "CMake 3.8.0 is the minimum version required to use Boost with Visual Studio 2017 or greater")
  endif()
endif()
</code>```

That lets me forget about the whole issue of what the libraries should be named.

Body:
From the Boost mailing list I understand that VS2017 has the following version numbers that we would probably be most interested in:

Visual Studio           15.0
cl; C/C++ Compiler      19.10
Platform Toolset:       v141

The following macros are defined in the Visual Studio 2017 IDE:

CrtSDKReferenceVersion  14.0
MSBuildToolsVersion     15.0
PlatformToolsetVersion  141
VCToolsVersion          14.10.25017
VisualStudioVersion     15.0

During compilation the following variables are  #define'd:

_MSC_VER                1910
_MSC_FULL_VER           191025017

cl.exe is contained within an MSVC folder with the VC tools version. The complete x64 folder path is

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Tools\MSVC\14.10.25017\bin\HostX64\x64

cl /Bv from the command line lists:

Compiler Passes:
 cl.exe:        Version 19.10.25017.0
 c1.dll:        Version 19.10.25017.0
 c1xx.dll:      Version 19.10.25017.0
 c2.dll:        Version 19.10.25017.0
 link.exe:      Version 14.10.25017.0
 mspdb140.dll:  Version 14.10.25017.0
 1033\clui.dll: Version 19.10.25017.0

Notice mspdb140.dll and link.exe are listed with version 14.10.25017.0.

And here it seems that msvc : 14.1 should be used as the toolset for boost. And here is another answer where some comments talk about boost's compiler naming.

When I compile I get the libraries names with v141 e.g.: boost_atomic-vc141-mt-1_64.lib

But in CMake the _Boost_GUESS_COMPILER_PREFIX function has the following:

if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.10)
  set(_boost_COMPILER "-vc150")
elseif (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19)
  set(_boost_COMPILER "-vc140")

So which version should be used? vc141 or vc150? Does

v141 imply vc141, or does

v141 imply vc150?

Body:
CMake versions which are less than the official release v3.8.0, which includes the rc numbers have the following in their FindBoost.cmake.

if (NOT CMAKE_CXX_COMPILER_VERSION VERSION_LESS 19.10)
  set(_boost_COMPILER "-vc150")

which means that, if your Boost dlls are not named like e.g. boost_date_time-vc150-mt-1_55.dll they won't be found. Version v3.8.0 started matching the approach Boost was taking with regard to version numbers, though I don't recall the in depth discussion of the matter. The short answer is though, if you are using a cmake version v3.8.0 or greater, you need the following instead.

  if(CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 19.10)
    set(BOOST_TOOLSET msvc-14.1)

For simplicity, in my Boost builds for Windows, I always add the following CMake code..

if(MSVC AND (NOT MSVC_VERSION LESS 1910))
  # Get the CMAKE version string and make sure it's not a release candidate and >= 3.8.0
  if( (CMAKE_VERSION MATCHES "^3\\.8\\.0-rc") OR (CMAKE_VERSION VERSION_LESS 3.8.0))
    message(FATAL_ERROR "CMake 3.8.0 is the minimum version required to use Boost with Visual Studio 2017 or greater")
  endif()
endif()

That lets me forget about the whole issue of what the libraries should be named.


问:
How HTML React only Unescape some code
I have a some code

```<code>let red = 'red'
let blue = 'blue'
let formula = "1+2"
let answer = "3"
let string = "<span class="+red+">"+formula+"</span>"+"="+"<span class="+blue+">"+answer+"</span>"
</code>```

111
In render's return

```<code><div dangerouslySetInnerHTML={{__html: string]}} >
</code>```

the above will show "1+23" with no color, however, I want 1+2=3 with red and blue classes created

UPDATE: I found should not be "className", should be "class" even this is in jsx, I still cannot get the equal being shown, in fact the class is from a string also

答:
The problem is with the quotes in you HTML string, enclose the classes within single quotes like

class App extends React.Component {
    render() {
        let formula = "1+2"
        let answer = "3"
        let string = ""+formula+""+"="+""+answer+""
        return (

        )
    }
}

ReactDOM.render(<App/>, document.getElementById('app'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div></code>```

Title: How HTML React only Unescape some code

Body:
I have a some code

let red = 'red'
let blue = 'blue'
let formula = "1+2"
let answer = "3"
let string = ""+formula+""+"="+""+answer+""

111
In render's return

the above will show "1+23" with no color, however, I want 1+2=3 with red and blue classes created

UPDATE: I found should not be "className", should be "class" even this is in jsx, I still cannot get the equal being shown, in fact the class is from a string also

Body:
The problem is with the quotes in you HTML string, enclose the classes within single quotes like

class App extends React.Component {
    render() {
        let formula = "1+2"
        let answer = "3"
        let string = "<span className='red'>"+formula+"</span>"+"="+"<span className='blue'>"+answer+"</span>"
        return (
        <div dangerouslySetInnerHTML={{__html: string}} ></div>
        )
    }
}

ReactDOM.render(<App/>, document.getElementById('app'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>


问:
Room database using kotlin
I am converting java code to kotlin code and i am getting type unresolved java class error.

My Java Class is

```<code>Room.databaseBuilder(context.getApplicationContext(), EventDatabase.class, "event_db").build();
</code>```

Converted Kotlin class

```<code> Room.databaseBuilder<EventDatabase>(context.applicationContext, EventDatabase::class.java!!, "event_db").build()
</code>```

Thank you.

答: Error is resolved i need first add kotlin dependency in my gradle file.</p>

Title: Room database using kotlin

Body:
I am converting java code to kotlin code and i am getting type unresolved java class error.

My Java Class is

Room.databaseBuilder(context.getApplicationContext(), EventDatabase.class, "event_db").build();

Converted Kotlin class

 Room.databaseBuilder<EventDatabase>(context.applicationContext, EventDatabase::class.java!!, "event_db").build()

Thank you.


问:
Why variables start out with random values in C
I think this is wrong, it should start as NULL and not with a random value. In the case that you have a pointer with a random memory address as its default value it could be a very dangerous thing, no?</p>

答:
This has nothing to do with "if C were being designed today" or with efficiency of one initialization. Instead think of something like

```<code>void foo()
{
    struct bar *ptrs[10000];
    /* do something where only a few indices end up actually getting used */
}
</code>```

Any language that forces useless initialization on you is doomed to be slow as hell for algorithms that can make use of sparse arrays where you don't care about the majority of the values, and have an easy way of knowing which values you care about.

If you don't like my example with such a large object on the stack, substitute malloc instead. It has the same semantics with regard to initialization.

In either case, if you want zero-initialization, you can get it with {0} or calloc.

ContentLicense: CC BY-SA 2.5

Body:
This has nothing to do with "if C were being designed today" or with efficiency of one initialization. Instead think of something like

void foo()
{
    struct bar *ptrs[10000];
    /* do something where only a few indices end up actually getting used */
}

Any language that forces useless initialization on you is doomed to be slow as hell for algorithms that can make use of sparse arrays where you don't care about the majority of the values, and have an easy way of knowing which values you care about.

If you don't like my example with such a large object on the stack, substitute malloc instead. It has the same semantics with regard to initialization.

In either case, if you want zero-initialization, you can get it with {0} or calloc.


问:
Setting a custom userAgent in HTML or JavaScript
Is there any way to do this? I'm trying to send a GET request to a website, but I want to customize my UserAgent. Is there any way to do this in pure HTML and JavaScript? I'd like it to all execute locally.</p>

答:
This is working for me.

```<code>Object.defineProperty(navigator, 'userAgent', {
    get: function () { return 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0)'; }
});
</code>```

It is an updated version of code4coffee's answer as Object.prototype.__defineGetter__() is deprecated: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__

Body:
This is working for me.

Object.defineProperty(navigator, 'userAgent', {
    get: function () { return 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0)'; }
});

It is an updated version of code4coffee's answer as Object.prototype.__defineGetter__() is deprecated: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/__defineGetter__


问:
button doesn't click in android studio
```<code>private Button mfactbutton;
private TextView mfacttext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_fun_fact);

    Button mfactbutton = (Button) findViewById(R.id.button);
    TextView mfacttext = (TextView) findViewById(R.id.textView2);

    // now we need to make out button to click
    View.OnClickListener Listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String[] facts = {
                    "Ants stretch when they wake up in the morning.",
                    "Ostriches can run faster than horses.",
                    "Olympic gold medals are actually made mostly of silver.",
                    "You are born with 300 bones; by the time you are an adult you will have 206.",
                    "It takes about 8 minutes for light from the Sun to reach Earth.",
                    "Some bamboo plants can grow almost a meter in just one day.",
                    "The state of Florida is bigger than England.",
                    "Some penguins can leap 2-3 meters out of the water.",
                    "On average, it takes 66 days to form a new habit.",
                    "Mammoths still walked the earth when the Great Pyramid was being built." };

            String fact = "";

            // randomly select a fact

            Random randomGenerator = new Random();
            int randomNumber = randomGenerator.nextInt(facts.length);
            fact = facts[randomNumber] + "";
        }
    };
    mfactbutton.setOnClickListener(Listener);

}
</code>```

}

Hey everyone! i need help! my button doesn't just simply clicl!!!!! heeeeeeeeelp!i'm just trying to make a simple button that changes the textview2 with each click! at first it was working but now it started not to work.

答:
Do you set your selected fact to your textView ? Add

```<code>mfacttext.setText(fact);
</code>```

after selecting your random fact.

```<code>Random randomGenerator = new
int randomNumber = randomGenerator.nextInt(facts.length);
fact = facts[randomNumber] + "";

mfacttext.setText(fact);
</code>```

Title: button doesn't click in android studio

Body:
private Button mfactbutton;
private TextView mfacttext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_fun_fact);

    Button mfactbutton = (Button) findViewById(R.id.button);
    TextView mfacttext = (TextView) findViewById(R.id.textView2);

    // now we need to make out button to click
    View.OnClickListener Listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String[] facts = {
                    "Ants stretch when they wake up in the morning.",
                    "Ostriches can run faster than horses.",
                    "Olympic gold medals are actually made mostly of silver.",
                    "You are born with 300 bones; by the time you are an adult you will have 206.",
                    "It takes about 8 minutes for light from the Sun to reach Earth.",
                    "Some bamboo plants can grow almost a meter in just one day.",
                    "The state of Florida is bigger than England.",
                    "Some penguins can leap 2-3 meters out of the water.",
                    "On average, it takes 66 days to form a new habit.",
                    "Mammoths still walked the earth when the Great Pyramid was being built." };

            String fact = "";

            // randomly select a fact

            Random randomGenerator = new Random();
            int randomNumber = randomGenerator.nextInt(facts.length);
            fact = facts[randomNumber] + "";
        }
    };
    mfactbutton.setOnClickListener(Listener);

}

}

Hey everyone! i need help! my button doesn't just simply clicl!!!!! heeeeeeeeelp!i'm just trying to make a simple button that changes the textview2 with each click! at first it was working but now it started not to work.

Body:
Do you set your selected fact to your textView ? Add

mfacttext.setText(fact);

after selecting your random fact.

Random randomGenerator = new
int randomNumber = randomGenerator.nextInt(facts.length);
fact = facts[randomNumber] + "";

mfacttext.setText(fact);


问:
Is it possible to run a Spring Cloud AWS application on Elastic Beanstalk?
I'm trying to run a web application of "hello world" complexity on Elastic Beanstalk.  I have no problem doing this with Spring Boot on Elastic Beanstalk.

But when I try to use Spring Cloud AWS, I encounter a myriad of problems.  The reference guide never mentions that running on Beanstalk is possible, so perhaps I am barking up the wrong tree?

The root problem I seem to encounter is the stackResourceRegistryFactoryBean blowing up when trying to identify the "stack" being used - i.e. the CloudFormation stack.  But I'm using Elastic Beanstalk, not CloudFormation.  The root exception is:

```<code>Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cloud.aws.core.env.stack.config.StackResourceRegistryFactoryBean]: Factory method 'stackResourceRegistryFactoryBean' threw exception; nested exception is java.lang.IllegalAccessError: tried to access class org.springframework.cloud.aws.core.env.stack.config.AutoDetectingStackNameProvider from class org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 89 more
Caused by: java.lang.IllegalAccessError: tried to access class org.springframework.cloud.aws.core.env.stack.config.AutoDetectingStackNameProvider from class org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration
    at org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration.stackResourceRegistryFactoryBean(ContextStackAutoConfiguration.java:71)
    at org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration$$EnhancerBySpringCGLIB$$432c7658.CGLIB$stackResourceRegistryFactoryBean$0(<generated>)
    at org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration$$EnhancerBySpringCGLIB$$432c7658$$FastClassBySpringCGLIB$$47c6e7d2.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    ...
</code>```

There are tags present on the generated EC2 instance for "aws:cloudformation:stack-id" and "aws:cloudformation:stack-name" if it is relevant, and my understanding is that Beanstalk uses CloudFormation stacks behind the scenes.  I've tried manually specifying the name of the stack via @EnableStackConfiguration, but since the name is generated I'd rather not do this, even if it did work.

So my questions are:
1) Is it possible to run a Spring Cloud AWS-based application on Elastic Beanstalk?
2) If so, are there any special steps required?  For example, I already discovered the one about CloudFormation read access being required on the role.
3) Is there a way to disable the part of Spring Cloud AWS that attempts to obtain resource names from the stack?  At this point my app doesn't need this.

thanks in advance,
k

答:
spring-cloud-aws seems to assume by default that you're running your app using your custom CloudFormation template.

In case of Elastic Beanstalk, you simply need to tell spring-cloud-aws to resign from obtaining information about the stack automatically:

```<code>cloud.aws.stack.auto = false
</code>```

Not sure why it is not mentioned in the docs. For basic Java apps, Elastic Beanstalk seems to be an obvious choice.

Body:
I'm trying to run a web application of "hello world" complexity on Elastic Beanstalk.  I have no problem doing this with Spring Boot on Elastic Beanstalk.

But when I try to use Spring Cloud AWS, I encounter a myriad of problems.  The reference guide never mentions that running on Beanstalk is possible, so perhaps I am barking up the wrong tree?

The root problem I seem to encounter is the stackResourceRegistryFactoryBean blowing up when trying to identify the "stack" being used - i.e. the CloudFormation stack.  But I'm using Elastic Beanstalk, not CloudFormation.  The root exception is:

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cloud.aws.core.env.stack.config.StackResourceRegistryFactoryBean]: Factory method 'stackResourceRegistryFactoryBean' threw exception; nested exception is java.lang.IllegalAccessError: tried to access class org.springframework.cloud.aws.core.env.stack.config.AutoDetectingStackNameProvider from class org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 89 more
Caused by: java.lang.IllegalAccessError: tried to access class org.springframework.cloud.aws.core.env.stack.config.AutoDetectingStackNameProvider from class org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration
    at org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration.stackResourceRegistryFactoryBean(ContextStackAutoConfiguration.java:71)
    at org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration$$EnhancerBySpringCGLIB$$432c7658.CGLIB$stackResourceRegistryFactoryBean$0(<generated>)
    at org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration$StackAutoDetectConfiguration$$EnhancerBySpringCGLIB$$432c7658$$FastClassBySpringCGLIB$$47c6e7d2.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    ...

There are tags present on the generated EC2 instance for "aws:cloudformation:stack-id" and "aws:cloudformation:stack-name" if it is relevant, and my understanding is that Beanstalk uses CloudFormation stacks behind the scenes.  I've tried manually specifying the name of the stack via @EnableStackConfiguration, but since the name is generated I'd rather not do this, even if it did work.

So my questions are:
1) Is it possible to run a Spring Cloud AWS-based application on Elastic Beanstalk?
2) If so, are there any special steps required?  For example, I already discovered the one about CloudFormation read access being required on the role.
3) Is there a way to disable the part of Spring Cloud AWS that attempts to obtain resource names from the stack?  At this point my app doesn't need this.

thanks in advance,
k

Body:
spring-cloud-aws seems to assume by default that you're running your app using your custom CloudFormation template.

In case of Elastic Beanstalk, you simply need to tell spring-cloud-aws to resign from obtaining information about the stack automatically:

cloud.aws.stack.auto = false

Not sure why it is not mentioned in the docs. For basic Java apps, Elastic Beanstalk seems to be an obvious choice.


问:
Blocking read from std::ifstream
I am reading from a pipe (Linux) or a pipe-like device object (Windows) using std::ifstream::read. However, when there is no more data, read reads 0 bytes and sets EOF. Is there a way to make a blocking read from an ifstream, such that it only returns when there is some more data?

I'd rather not busy wait for the EOF flag to clear.

If it is not possible with the C++ standard library, what is the closest other option? Can I do it in plain C, or do I have to resort to operating system specific APIs?

答:
well there seems no way to do a blocking read. clearing the error bit will not help. Only a re-open of the fifo like in this example:

```<code>int main(int argc, char **argv)
{
    int rc=0;
    enum FATAL {ERR_ARGV,ERR_OPEN_FILE};
    try
    {
            if( argv[1] == NULL) throw ERR_ARGV;
            std::ifstream fifo;

            while(1)
            {
                    fifo.open(argv[1],std::ifstream::in);
                    if( !fifo.is_open() ) throw ERR_OPEN_FILE;

                    std::string line;
                    while(std::getline(fifo,line))
                    {
                            std::cout << line << "\n"; fflush(stdout);
                    }
                    fifo.close();
            }
            // never should come here
    }
    catch(FATAL e)
    {
            rc=e;
            switch(e)
            {
            case ERR_ARGV:
                    std::cerr << "ERROR: argument 1 should be a fifo file name\n";
                    break;
            case ERR_OPEN_FILE:
                    std::cerr << "ERROR: unabel to open file " << argv[1] << "\n";
                    break;
            }
    }
    return(rc);
}
</code>```

I have tested this code and it works to do an endless read from a fifo.

Title: Blocking read from std::ifstream

Body:
well there seems no way to do a blocking read. clearing the error bit will not help. Only a re-open of the fifo like in this example:

int main(int argc, char **argv)
{
    int rc=0;
    enum FATAL {ERR_ARGV,ERR_OPEN_FILE};
    try
    {
            if( argv[1] == NULL) throw ERR_ARGV;
            std::ifstream fifo;

            while(1)
            {
                    fifo.open(argv[1],std::ifstream::in);
                    if( !fifo.is_open() ) throw ERR_OPEN_FILE;

                    std::string line;
                    while(std::getline(fifo,line))
                    {
                            std::cout << line << "\n"; fflush(stdout);
                    }
                    fifo.close();
            }
            // never should come here
    }
    catch(FATAL e)
    {
            rc=e;
            switch(e)
            {
            case ERR_ARGV:
                    std::cerr << "ERROR: argument 1 should be a fifo file name\n";
                    break;
            case ERR_OPEN_FILE:
                    std::cerr << "ERROR: unabel to open file " << argv[1] << "\n";
                    break;
            }
    }
    return(rc);
}

I have tested this code and it works to do an endless read from a fifo.


问:
SELECT query with NO LOCK
I want to use SELECT WITH NOLOCK, the table on which i want to use SELECT WITH NOLOCK query have no updation query and the data i want to fetch are less the current inserted record.I want to use NOLOCK because sometime i am getting Timeout exception in SELECT query. I think this is because of Table would be LOCKED by Insert query which is running constantly and SELECT query have to wait for long time so it's giving Timeout error.

So please suggest should i use NOLOCK here, I have read some post were written about uncommitted transaction and they suggest not to use NOLOCK.

答:
As mentionned in the documentation (Table Hints on MSDN Docs), while using the NOLOCK hint, you can see results that are not yet committed (ie. committed by a transaction).

By using this hint you should be aware about these issues, but if it doesn't affect your logic, you can use it.

Title: SELECT query with NO LOCK