问:
Recycleview's onClick and put extra
Please help!  i have a recycleview with search function(base on JSON search). i wanna click-able this recycleview(mean that getting item's ID where shown in item's view ) and then PutExtra this ID to another activity . then another activity get ID. and finally another activity post ID and get values!

this my code , somebody tell my wrongs:):

AdapterFish.java

```<code>public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private Context context;
private LayoutInflater inflater;
List<DataFish> data= Collections.emptyList();
DataFish current;
int currentPos=0;
public String IDHOLDER;
private Context activity;

// create constructor to initialize context and data sent from MainActivity
public AdapterFish(Context context, List<DataFish> data){
    this.context=context;
    inflater= LayoutInflater.from(context);
    this.data=data;
}

// Inflate the layout when ViewHolder created
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view=inflater.inflate(R.layout.container_fish, parent,false);
    MyHolder holder=new MyHolder(view);
    return holder;
}

// Bind data
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    // Get current position of item in RecyclerView to bind data and assign values from list
    MyHolder myHolder= (MyHolder) holder;
    DataFish current=data.get(position);
    myHolder.company.setText(current.company);
    myHolder.name.setText(current.name);
    myHolder.family.setText(current.family);
    myHolder.id.setText(current.id);
    myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

}

// return total item from List
@Override
public int getItemCount() {
    return data.size();
}

public Context getActivity() {
    return activity;
}

public void setActivity(Context activity) {
    this.activity = activity;
}

class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    TextView company;
    TextView name;
    TextView family;
    TextView id;

    // create constructor to get widget reference
    public MyHolder(View itemView) {
        super(itemView);
        company= (TextView) itemView.findViewById(R.id.company);
        name = (TextView) itemView.findViewById(R.id.name);
        family = (TextView) itemView.findViewById(R.id.family);
        id = (TextView) itemView.findViewById(R.id.id);
        itemView.setOnClickListener(this);
    }

    // Click event for all items
    @Override
    public void onClick(View v) {

        Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
        final String ItemId = id.getText().toString().trim();
        Intent intent = new Intent(context, ShowSingleRecordActivity.class);
        intent.putExtra("ID", ItemId);
        context.startActivity(intent);

    }

}}
</code>```

ShowSingleRecordActivity.java (Receiving ID)

```<code>public class ShowSingleRecordActivity extends AppCompatActivity {

HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;

// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://192.168.137.1/namayeshgah/FilterStudentData.php";

// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://192.168.137.1/namayeshgah/DeleteStudent.php";

String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView COMPANY,NAME,FAMILY,GENDER,EMAIL1,EMAIL2,PHONE,FAX,TELLFAX,MOBILE;
String  CompanyHolder ,NameHolder,FamilyHolder,GenderHolder,Email1Holder,Email2Holder,PhoneHolder,FaxHolder,TellfaxHolder,MobileHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;

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

    COMPANY = (TextView)findViewById(R.id.ncompany);
    NAME = (TextView)findViewById(R.id.nname);
    FAMILY=(TextView)findViewById(R.id.nfamily);
    GENDER =(TextView)findViewById(R.id.ngender);
    EMAIL1= (TextView)findViewById(R.id.nemail1);
    EMAIL2= (TextView)findViewById(R.id.nemail2);
    PHONE= (TextView)findViewById(R.id.nphone);
    FAX = (TextView)findViewById(R.id.nfax);
    TELLFAX = (TextView)findViewById(R.id.ntellfax);
    MOBILE = (TextView)findViewById(R.id.nmobile);

    UpdateButton = (Button)findViewById(R.id.buttonUpdate);
    DeleteButton = (Button)findViewById(R.id.buttonDelete);

    //Receiving the ListView Clicked item value send by previous activity.
    TempItem = getIntent().getStringExtra("ID");

    //Calling method to filter Student Record and open selected record.
    HttpWebCall(TempItem);

    UpdateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(ShowSingleRecordActivity.this,UpdateActivity.class);

            // Sending Student Id, Name, Number and Class to next UpdateActivity.
            intent.putExtra("Id", TempItem);
            intent.putExtra("company",CompanyHolder );
            intent.putExtra("name", NameHolder);
            intent.putExtra("family",FamilyHolder );
            intent.putExtra("gender",GenderHolder );
            intent.putExtra("email1",Email1Holder );
            intent.putExtra("email2",Email2Holder );
            intent.putExtra("phone",PhoneHolder );
            intent.putExtra("fax",FaxHolder );
            intent.putExtra("tellfax",TellfaxHolder );
            intent.putExtra("mobile",MobileHolder );

            startActivity(intent);

            // Finishing current activity after opening next activity.
            finish();

        }
    });

    // Add Click listener on Delete button.
    DeleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Calling Student delete method to delete current record using Student ID.
            StudentDelete(TempItem);

        }
    });

}

// Method to Delete Student Record
public void StudentDelete(final String StudentID) {

    class StudentDeleteClass extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog2 = ProgressDialog.show(ShowSingleRecordActivity.this, "Loading Data", null, true, true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            progressDialog2.dismiss();

            Toast.makeText(ShowSingleRecordActivity.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

            finish();

        }

        @Override
        protected String doInBackground(String... params) {

            // Sending STUDENT id.
            hashMap.put("StudentID", params[0]);

            finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);

            return finalResult;
        }
    }

    StudentDeleteClass studentDeleteClass = new StudentDeleteClass();

    studentDeleteClass.execute(StudentID);
}

//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){

    class HttpWebCallFunction extends AsyncTask<String,Void,String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            pDialog.dismiss();

            //Storing Complete JSon Object into String Variable.
            FinalJSonObject = httpResponseMsg ;

            //Parsing the Stored JSOn String to GetHttpResponse Method.
            new GetHttpResponse(ShowSingleRecordActivity.this).execute();

        }

        @Override
        protected String doInBackground(String... params) {

            ResultHash.put("StudentID",params[0]);

            ParseResult = httpParse.postRequest(ResultHash, HttpURL);

            return ParseResult;
        }
    }

    HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();

    httpWebCallFunction.execute(PreviousListViewClickedItem);
}

// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
    public Context context;

    public GetHttpResponse(Context context)
    {
        this.context = context;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0)
    {
        try
        {
            if(FinalJSonObject != null)
            {
                JSONArray jsonArray = null;

                try {
                    jsonArray = new JSONArray(FinalJSonObject);

                    JSONObject jsonObject;

                    for(int i=0; i<jsonArray.length(); i++)
                    {
                        jsonObject = jsonArray.getJSONObject(i);

                        // Storing Student Name, Phone Number, Class into Variables.
                        CompanyHolder = jsonObject.getString("company");
                        NameHolder = jsonObject.getString("name");
                        FamilyHolder= jsonObject.getString("family");
                        GenderHolder= jsonObject.getString("gender");
                        Email1Holder = jsonObject.getString("email1");
                        Email2Holder = jsonObject.getString("email2");
                        PhoneHolder = jsonObject.getString("phone");
                        FaxHolder = jsonObject.getString("fax");
                        TellfaxHolder = jsonObject.getString("tellfax");
                        MobileHolder = jsonObject.getString("mobile");

                    }
                }
                catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {

        // Setting Student Name, Phone Number, Class into TextView after done all process .
        COMPANY.setText(CompanyHolder);
        NAME.setText(NameHolder);
        FAMILY.setText(FamilyHolder);
        GENDER.setText(GenderHolder);
        EMAIL1.setText(Email1Holder);
        EMAIL2.setText(Email2Holder);
        PHONE.setText(PhoneHolder);
        FAX.setText(FaxHolder);
        TELLFAX.setText(TellfaxHolder);
        MOBILE.setText(MobileHolder);

    }
}
</code>```

and Searching.java

```<code>public class searching extends AppCompatActivity {

// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;

SearchView searchView = null;

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // adds item to action bar
    getMenuInflater().inflate(R.menu.search_main, menu);

    // Get Search item from action bar and Get Search service
    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchManager searchManager = (SearchManager) searching.this.getSystemService(Context.SEARCH_SERVICE);
    if (searchItem != null) {
        searchView = (SearchView) searchItem.getActionView();
    }
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(searching.this.getComponentName()));
        searchView.setIconified(false);
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    return super.onOptionsItemSelected(item);
}

// Every time when you press search button on keypad an Activity is recreated which in turn calls this function
@Override
protected void onNewIntent(Intent intent) {
    // Get search query and create object of class AsyncFetch
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        if (searchView != null) {
            searchView.clearFocus();
        }
        new AsyncFetch(query).execute();

    }
}

// Create class AsyncFetch
private class AsyncFetch extends AsyncTask<String, String, String> {

    ProgressDialog pdLoading = new ProgressDialog(searching.this);
    HttpURLConnection conn;
    URL url = null;
    String searchQuery;

    public AsyncFetch(String searchQuery){
        this.searchQuery=searchQuery;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides
            url = new URL("http://192.168.137.1/namayeshgah/search/fish-search.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput to true as we send and recieve data
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // add parameter to our above url
            Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {
                return("Connection error");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }

    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread
        pdLoading.dismiss();
        List<DataFish> data=new ArrayList<>();

        pdLoading.dismiss();
        if(result.equals("no rows")) {
            Toast.makeText(searching.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
        }else{

            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataFish fishData = new DataFish();
                    fishData.company = json_data.getString("company");
                    fishData.name = json_data.getString("name");
                    fishData.family = json_data.getString("family");
                    fishData.id = json_data.getString("id");

                    data.add(fishData);
                }

                // Setup and Handover data to recyclerview
                mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
                mAdapter = new AdapterFish(searching.this, data);
                mRVFish.setAdapter(mAdapter);
                mRVFish.setLayoutManager(new LinearLayoutManager(searching.this));

            } catch (JSONException e) {
                // You to understand what actually error is and handle it appropriately
                Toast.makeText(searching.this, e.toString(), Toast.LENGTH_LONG).show();
                Toast.makeText(searching.this, result.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }

}
</code>```

答:
Replace this line in ShowSingleRecordActivity

```<code>TempItem = getIntent().getStringExtra("ID");
</code>```

to

```<code>TempItem = getIntent().getExtras().getString("ID");
</code>```

Title: Recycleview's onClick and put extra

Body:
Please help!  i have a recycleview with search function(base on JSON search). i wanna click-able this recycleview(mean that getting item's ID where shown in item's view ) and then PutExtra this ID to another activity . then another activity get ID. and finally another activity post ID and get values!

this my code , somebody tell my wrongs:):

AdapterFish.java

public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private Context context;
private LayoutInflater inflater;
List<DataFish> data= Collections.emptyList();
DataFish current;
int currentPos=0;
public String IDHOLDER;
private Context activity;

// create constructor to initialize context and data sent from MainActivity
public AdapterFish(Context context, List<DataFish> data){
    this.context=context;
    inflater= LayoutInflater.from(context);
    this.data=data;
}

// Inflate the layout when ViewHolder created
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view=inflater.inflate(R.layout.container_fish, parent,false);
    MyHolder holder=new MyHolder(view);
    return holder;
}

// Bind data
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    // Get current position of item in RecyclerView to bind data and assign values from list
    MyHolder myHolder= (MyHolder) holder;
    DataFish current=data.get(position);
    myHolder.company.setText(current.company);
    myHolder.name.setText(current.name);
    myHolder.family.setText(current.family);
    myHolder.id.setText(current.id);
    myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

}

// return total item from List
@Override
public int getItemCount() {
    return data.size();
}

public Context getActivity() {
    return activity;
}

public void setActivity(Context activity) {
    this.activity = activity;
}

class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    TextView company;
    TextView name;
    TextView family;
    TextView id;

    // create constructor to get widget reference
    public MyHolder(View itemView) {
        super(itemView);
        company= (TextView) itemView.findViewById(R.id.company);
        name = (TextView) itemView.findViewById(R.id.name);
        family = (TextView) itemView.findViewById(R.id.family);
        id = (TextView) itemView.findViewById(R.id.id);
        itemView.setOnClickListener(this);
    }

    // Click event for all items
    @Override
    public void onClick(View v) {

        Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
        final String ItemId = id.getText().toString().trim();
        Intent intent = new Intent(context, ShowSingleRecordActivity.class);
        intent.putExtra("ID", ItemId);
        context.startActivity(intent);

    }

}}

ShowSingleRecordActivity.java (Receiving ID)

public class ShowSingleRecordActivity extends AppCompatActivity {

HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;

// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://192.168.137.1/namayeshgah/FilterStudentData.php";

// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://192.168.137.1/namayeshgah/DeleteStudent.php";

String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView COMPANY,NAME,FAMILY,GENDER,EMAIL1,EMAIL2,PHONE,FAX,TELLFAX,MOBILE;
String  CompanyHolder ,NameHolder,FamilyHolder,GenderHolder,Email1Holder,Email2Holder,PhoneHolder,FaxHolder,TellfaxHolder,MobileHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;

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

    COMPANY = (TextView)findViewById(R.id.ncompany);
    NAME = (TextView)findViewById(R.id.nname);
    FAMILY=(TextView)findViewById(R.id.nfamily);
    GENDER =(TextView)findViewById(R.id.ngender);
    EMAIL1= (TextView)findViewById(R.id.nemail1);
    EMAIL2= (TextView)findViewById(R.id.nemail2);
    PHONE= (TextView)findViewById(R.id.nphone);
    FAX = (TextView)findViewById(R.id.nfax);
    TELLFAX = (TextView)findViewById(R.id.ntellfax);
    MOBILE = (TextView)findViewById(R.id.nmobile);

    UpdateButton = (Button)findViewById(R.id.buttonUpdate);
    DeleteButton = (Button)findViewById(R.id.buttonDelete);

    //Receiving the ListView Clicked item value send by previous activity.
    TempItem = getIntent().getStringExtra("ID");

    //Calling method to filter Student Record and open selected record.
    HttpWebCall(TempItem);

    UpdateButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent(ShowSingleRecordActivity.this,UpdateActivity.class);

            // Sending Student Id, Name, Number and Class to next UpdateActivity.
            intent.putExtra("Id", TempItem);
            intent.putExtra("company",CompanyHolder );
            intent.putExtra("name", NameHolder);
            intent.putExtra("family",FamilyHolder );
            intent.putExtra("gender",GenderHolder );
            intent.putExtra("email1",Email1Holder );
            intent.putExtra("email2",Email2Holder );
            intent.putExtra("phone",PhoneHolder );
            intent.putExtra("fax",FaxHolder );
            intent.putExtra("tellfax",TellfaxHolder );
            intent.putExtra("mobile",MobileHolder );

            startActivity(intent);

            // Finishing current activity after opening next activity.
            finish();

        }
    });

    // Add Click listener on Delete button.
    DeleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Calling Student delete method to delete current record using Student ID.
            StudentDelete(TempItem);

        }
    });

}

// Method to Delete Student Record
public void StudentDelete(final String StudentID) {

    class StudentDeleteClass extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog2 = ProgressDialog.show(ShowSingleRecordActivity.this, "Loading Data", null, true, true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            progressDialog2.dismiss();

            Toast.makeText(ShowSingleRecordActivity.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

            finish();

        }

        @Override
        protected String doInBackground(String... params) {

            // Sending STUDENT id.
            hashMap.put("StudentID", params[0]);

            finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);

            return finalResult;
        }
    }

    StudentDeleteClass studentDeleteClass = new StudentDeleteClass();

    studentDeleteClass.execute(StudentID);
}

//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){

    class HttpWebCallFunction extends AsyncTask<String,Void,String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            pDialog.dismiss();

            //Storing Complete JSon Object into String Variable.
            FinalJSonObject = httpResponseMsg ;

            //Parsing the Stored JSOn String to GetHttpResponse Method.
            new GetHttpResponse(ShowSingleRecordActivity.this).execute();

        }

        @Override
        protected String doInBackground(String... params) {

            ResultHash.put("StudentID",params[0]);

            ParseResult = httpParse.postRequest(ResultHash, HttpURL);

            return ParseResult;
        }
    }

    HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();

    httpWebCallFunction.execute(PreviousListViewClickedItem);
}

// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
    public Context context;

    public GetHttpResponse(Context context)
    {
        this.context = context;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0)
    {
        try
        {
            if(FinalJSonObject != null)
            {
                JSONArray jsonArray = null;

                try {
                    jsonArray = new JSONArray(FinalJSonObject);

                    JSONObject jsonObject;

                    for(int i=0; i<jsonArray.length(); i++)
                    {
                        jsonObject = jsonArray.getJSONObject(i);

                        // Storing Student Name, Phone Number, Class into Variables.
                        CompanyHolder = jsonObject.getString("company");
                        NameHolder = jsonObject.getString("name");
                        FamilyHolder= jsonObject.getString("family");
                        GenderHolder= jsonObject.getString("gender");
                        Email1Holder = jsonObject.getString("email1");
                        Email2Holder = jsonObject.getString("email2");
                        PhoneHolder = jsonObject.getString("phone");
                        FaxHolder = jsonObject.getString("fax");
                        TellfaxHolder = jsonObject.getString("tellfax");
                        MobileHolder = jsonObject.getString("mobile");

                    }
                }
                catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {

        // Setting Student Name, Phone Number, Class into TextView after done all process .
        COMPANY.setText(CompanyHolder);
        NAME.setText(NameHolder);
        FAMILY.setText(FamilyHolder);
        GENDER.setText(GenderHolder);
        EMAIL1.setText(Email1Holder);
        EMAIL2.setText(Email2Holder);
        PHONE.setText(PhoneHolder);
        FAX.setText(FaxHolder);
        TELLFAX.setText(TellfaxHolder);
        MOBILE.setText(MobileHolder);

    }
}

and Searching.java

public class searching extends AppCompatActivity {

// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;

SearchView searchView = null;

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // adds item to action bar
    getMenuInflater().inflate(R.menu.search_main, menu);

    // Get Search item from action bar and Get Search service
    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchManager searchManager = (SearchManager) searching.this.getSystemService(Context.SEARCH_SERVICE);
    if (searchItem != null) {
        searchView = (SearchView) searchItem.getActionView();
    }
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(searching.this.getComponentName()));
        searchView.setIconified(false);
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    return super.onOptionsItemSelected(item);
}

// Every time when you press search button on keypad an Activity is recreated which in turn calls this function
@Override
protected void onNewIntent(Intent intent) {
    // Get search query and create object of class AsyncFetch
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        if (searchView != null) {
            searchView.clearFocus();
        }
        new AsyncFetch(query).execute();

    }
}

// Create class AsyncFetch
private class AsyncFetch extends AsyncTask<String, String, String> {

    ProgressDialog pdLoading = new ProgressDialog(searching.this);
    HttpURLConnection conn;
    URL url = null;
    String searchQuery;

    public AsyncFetch(String searchQuery){
        this.searchQuery=searchQuery;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides
            url = new URL("http://192.168.137.1/namayeshgah/search/fish-search.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

            // Setup HttpURLConnection class to send and receive data from php and mysql
            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(READ_TIMEOUT);
            conn.setConnectTimeout(CONNECTION_TIMEOUT);
            conn.setRequestMethod("POST");

            // setDoInput and setDoOutput to true as we send and recieve data
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // add parameter to our above url
            Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

                // Read data sent from server
                InputStream input = conn.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                StringBuilder result = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {
                return("Connection error");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }

    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread
        pdLoading.dismiss();
        List<DataFish> data=new ArrayList<>();

        pdLoading.dismiss();
        if(result.equals("no rows")) {
            Toast.makeText(searching.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
        }else{

            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataFish fishData = new DataFish();
                    fishData.company = json_data.getString("company");
                    fishData.name = json_data.getString("name");
                    fishData.family = json_data.getString("family");
                    fishData.id = json_data.getString("id");

                    data.add(fishData);
                }

                // Setup and Handover data to recyclerview
                mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
                mAdapter = new AdapterFish(searching.this, data);
                mRVFish.setAdapter(mAdapter);
                mRVFish.setLayoutManager(new LinearLayoutManager(searching.this));

            } catch (JSONException e) {
                // You to understand what actually error is and handle it appropriately
                Toast.makeText(searching.this, e.toString(), Toast.LENGTH_LONG).show();
                Toast.makeText(searching.this, result.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }

}

Body:
Replace this line in ShowSingleRecordActivity

TempItem = getIntent().getStringExtra("ID");

to

TempItem = getIntent().getExtras().getString("ID");


来源: stackexchange

问:
how to attach a PDF document (from documents directory) to an email
I was wondering how to attach a PDF that I have generated to an email on iPhone/iPad. I have found examples of how to attach a image, but I don't know the mime type for a PDF.

Thanks.

答:
Use

```<code>[picker addAttachmentData:[NSData dataWithContentsOfFile:Your attachment file] mimeType:@"application/pdf" fileName:@"file name.pdf"];
</code>```

Cheers

ContentLicense: CC BY-SA 2.5

Body:
Use

[picker addAttachmentData:[NSData dataWithContentsOfFile:Your attachment file] mimeType:@"application/pdf" fileName:@"file name.pdf"];

Cheers


问:
Why is map reduce job poinitng to localhost:8080?
I am working with Map Reduce job and executing it using ToolRunner's run method.
Here is my code:

```<code>public class MaxTemperature extends Configured implements Tool {

  public static void main(String[] args) throws Exception {
      System.setProperty("hadoop.home.dir", "/");
      int exitCode = ToolRunner.run(new MaxTemperature(), args);
      System.exit(exitCode);
  }

  @Override
    public int run(String[] args) throws Exception {
        if (args.length != 2) {
              System.err.println("Usage: MaxTemperature <input path> <output path>");
              System.exit(-1);
            }
        System.out.println("Starting job");
        Job job = new Job();
        job.setJarByClass(MaxTemperature.class);
        job.setJobName("Max temperature");

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        job.setMapperClass(MaxTemperatureMapper.class);
        job.setReducerClass(MaxTemperatureReducer.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        int returnValue = job.waitForCompletion(true) ? 0:1;

        if(job.isSuccessful()) {
            System.out.println("Job was successful");
        } else if(!job.isSuccessful()) {
            System.out.println("Job was not successful");
        }
        return returnValue;
    }
}
</code>```

The job executed well as expected. But when i looked into the logs which displays the information abou the job tracking, I found that the Map reduce is pointing to localhost:8080 for the tracking of the job.

Here is the snapshot of logs:

```<code>20521 [main] INFO  org.apache.hadoop.mapreduce.JobSubmitter  - number of splits:1
20670 [main] INFO  org.apache.hadoop.mapreduce.JobSubmitter  - Submitting tokens for job: job_local1454583076_0001
20713 [main] WARN  org.apache.hadoop.conf.Configuration  - file:/tmp/hadoop-KV/mapred/staging/KV1454583076/.staging/job_local1454583076_0001/job.xml:an attempt to override final parameter: mapreduce.job.end-notification.max.retry.interval;  Ignoring.
20716 [main] WARN  org.apache.hadoop.conf.Configuration  - file:/tmp/hadoop-KV/mapred/staging/KV1454583076/.staging/job_local1454583076_0001/job.xml:an attempt to override final parameter: mapreduce.job.end-notification.max.attempts;  Ignoring.
20818 [main] WARN  org.apache.hadoop.conf.Configuration  - file:/tmp/hadoop-KV/mapred/local/localRunner/KV/job_local1454583076_0001/job_local1454583076_0001.xml:an attempt to override final parameter: mapreduce.job.end-notification.max.retry.interval;  Ignoring.
20820 [main] WARN  org.apache.hadoop.conf.Configuration  - file:/tmp/hadoop-KV/mapred/local/localRunner/KV/job_local1454583076_0001/job_local1454583076_0001.xml:an attempt to override final parameter: mapreduce.job.end-notification.max.attempts;  Ignoring.
**20826 [main] INFO  org.apache.hadoop.mapreduce.Job  - The url to track the job: http://localhost:8080/**
20827 [main] INFO  org.apache.hadoop.mapreduce.Job  - Running job: job_local1454583076_0001
20829 [Thread-10] INFO  org.apache.hadoop.mapred.LocalJobRunner  - OutputCommitter set in config null
</code>```

So my question is why is map reduce pointing to localhost:8080

The url to track the job: http://localhost:8080/

There is no configuration file or properties file where i manually set this. Also, is it possible that i can change it to some other port? If yes, how can i achieve this?

答:
We need to change the default configuration and create a Configuration object and set the properties to this configuration object and then create a Job object using this Configuration as follows:</p>

```<code>    Configuration configuration  = getConf();

    //configuration.set("fs.defaultFS", "hdfs://192.**.***.2**");
    //configuration.set("mapred.job.tracker", "jobtracker:jtPort");
    configuration.set("mapreduce.jobtracker.address", "localhost:54311");
    configuration.set("mapreduce.framework.name", "yarn");
    configuration.set("yarn.resourcemanager.address", "127.0.0.1:8032");

    //configuration.set("yarn.resourcemanager.webapp.address", "127.0.0.1:8032");

    //Initialize the Hadoop job and set the jar as well as the name of the Job
    Job job = new Job(configuration);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am working with Map Reduce job and executing it using ToolRunner's run method.
Here is my code:

public class MaxTemperature extends Configured implements Tool {

  public static void main(String[] args) throws Exception {
      System.setProperty("hadoop.home.dir", "/");
      int exitCode = ToolRunner.run(new MaxTemperature(), args);
      System.exit(exitCode);
  }

  @Override
    public int run(String[] args) throws Exception {
        if (args.length != 2) {
              System.err.println("Usage: MaxTemperature <input path> <output path>");
              System.exit(-1);
            }
        System.out.println("Starting job");
        Job job = new Job();
        job.setJarByClass(MaxTemperature.class);
        job.setJobName("Max temperature");

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        job.setMapperClass(MaxTemperatureMapper.class);
        job.setReducerClass(MaxTemperatureReducer.class);

        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        int returnValue = job.waitForCompletion(true) ? 0:1;

        if(job.isSuccessful()) {
            System.out.println("Job was successful");
        } else if(!job.isSuccessful()) {
            System.out.println("Job was not successful");
        }
        return returnValue;
    }
}

The job executed well as expected. But when i looked into the logs which displays the information abou the job tracking, I found that the Map reduce is pointing to localhost:8080 for the tracking of the job.

Here is the snapshot of logs:

20521 [main] INFO  org.apache.hadoop.mapreduce.JobSubmitter  - number of splits:1
20670 [main] INFO  org.apache.hadoop.mapreduce.JobSubmitter  - Submitting tokens for job: job_local1454583076_0001
20713 [main] WARN  org.apache.hadoop.conf.Configuration  - file:/tmp/hadoop-KV/mapred/staging/KV1454583076/.staging/job_local1454583076_0001/job.xml:an attempt to override final parameter: mapreduce.job.end-notification.max.retry.interval;  Ignoring.
20716 [main] WARN  org.apache.hadoop.conf.Configuration  - file:/tmp/hadoop-KV/mapred/staging/KV1454583076/.staging/job_local1454583076_0001/job.xml:an attempt to override final parameter: mapreduce.job.end-notification.max.attempts;  Ignoring.
20818 [main] WARN  org.apache.hadoop.conf.Configuration  - file:/tmp/hadoop-KV/mapred/local/localRunner/KV/job_local1454583076_0001/job_local1454583076_0001.xml:an attempt to override final parameter: mapreduce.job.end-notification.max.retry.interval;  Ignoring.
20820 [main] WARN  org.apache.hadoop.conf.Configuration  - file:/tmp/hadoop-KV/mapred/local/localRunner/KV/job_local1454583076_0001/job_local1454583076_0001.xml:an attempt to override final parameter: mapreduce.job.end-notification.max.attempts;  Ignoring.
**20826 [main] INFO  org.apache.hadoop.mapreduce.Job  - The url to track the job: http://localhost:8080/**
20827 [main] INFO  org.apache.hadoop.mapreduce.Job  - Running job: job_local1454583076_0001
20829 [Thread-10] INFO  org.apache.hadoop.mapred.LocalJobRunner  - OutputCommitter set in config null

So my question is why is map reduce pointing to localhost:8080

The url to track the job: http://localhost:8080/

There is no configuration file or properties file where i manually set this. Also, is it possible that i can change it to some other port? If yes, how can i achieve this?

Body:
We need to change the default configuration and create a Configuration object and set the properties to this configuration object and then create a Job object using this Configuration as follows:

    Configuration configuration  = getConf();

    //configuration.set("fs.defaultFS", "hdfs://192.**.***.2**");
    //configuration.set("mapred.job.tracker", "jobtracker:jtPort");
    configuration.set("mapreduce.jobtracker.address", "localhost:54311");
    configuration.set("mapreduce.framework.name", "yarn");
    configuration.set("yarn.resourcemanager.address", "127.0.0.1:8032");

    //configuration.set("yarn.resourcemanager.webapp.address", "127.0.0.1:8032");

    //Initialize the Hadoop job and set the jar as well as the name of the Job
    Job job = new Job(configuration);


问:
Dependency injection with custom Doctrine 2 hydrator
I'm setting up a custom hydrator in Doctrine 2 in a Symfony 2 project, but for it to do what it needs it requires another service. The documentation for custom hydrators only shows how to provide a hydrator class, so there's no way to inject dependencies.

For example:

```<code>$em->getConfiguration()->addCustomHydrationMode('CustomHydrator', 'MyProject\Hydrators\CustomHydrator');
</code>```

I suspect Doctrine is initialising the hydrators itself and as such any dependencies would need to be passed through some other Doctrine classes first.

Is there a way to provide a custom "hydration factory" or similar to Doctrine that would allow injection of additional dependencies? Custom hydrators seem fairly limited without this capability.

Answer: Thanks to Denis V

I got this working as follows. I can't post the actual code so I've put together some dummy placeholders so you can see how it fits together.

src/Acme/ExampleBundle/resources/config/services.yml

```<code>services:
    doctrine.orm.entity_manager.abstract:
        class:          Acme\ExampleBundle\Entity\DoctrineEntityManager
        factory_class:  Acme\ExampleBundle\Entity\DoctrineEntityManager
        factory_method: create
        abstract:       true
        calls:
            - [ setMyDependency, [@acme.my_custom_service]]
</code>```

src/Acme/ExampleBundle/Entity/DoctrineEntityManager.php

```<code>namespace Acme\ExampleBundle\Entity;

use Acme\ExampleBundle\Hydrator\MyHydrator;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManager as BaseEntityManager;
use Doctrine\ORM\ORMException;
use Doctrine\ORM\Query;

class DoctrineEntityManager extends BaseEntityManager
{
    protected $myDependency;

    /**
     * Note: This must be redefined as Doctrine's own entity manager has its own class name hardcoded in.
     */
    public static function create($conn, Configuration $config, EventManager $eventManager = null)
    {
        if (!$config->getMetadataDriverImpl()) {
            throw ORMException::missingMappingDriverImpl();
        }

        switch (true) {
            case (is_array($conn)):
                $conn = \Doctrine\DBAL\DriverManager::getConnection(
                    $conn, $config, ($eventManager ?: new EventManager())
                );
                break;

            case ($conn instanceof Connection):
                if ($eventManager !== null && $conn->getEventManager() !== $eventManager) {
                     throw ORMException::mismatchedEventManager();
                }
                break;

            default:
                throw new \InvalidArgumentException("Invalid argument: " . $conn);
        }

        return new self($conn, $config, $conn->getEventManager());
    }

    public function setMyDependency($myCustomService)
    {
        $this->myDependency = $myCustomService;
    }

    public function newHydrator($hydrationMode)
    {
        if ($hydrationMode == 'MyHydrationMode') {
            return new MyHydrator($this, $this->myDependency);
        }

        return parent::newHydrator($hydrationMode);
    }
}
</code>```

src/Acme/ExampleBundle/Hydrator/MyHydrator.php

```<code>namespace Acme\ExampleBundle\Hydrator;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Internal\Hydration\ObjectHydrator;

class MyHydrator extends ObjectHydrator
{
    protected $myDependency;

    public __construct(EntityManager $em, $myDependency)
    {
        parent::__construct($em);

        $this->myDependency = $myDependency;
    }

    protected function hydrateAllData()
    {
        /* hydration stuff with my dependency here */
    }
}
</code>```

答:
Really good answer but please be advised that Doctrine maintainers explicitly said not to extend Doctrine\ORM\EntityManager and I suppose that in the future they will make it final to enforce this.

So instead of the proposed solution without breaking rules here is the cleaner solution:

```<code><?php

declare(strict_types=1);

namespace App\Doctrine\ORM;

use Doctrine\Common\EventManager;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\Decorator\EntityManagerDecorator;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\ORMException;

class EntityManager extends EntityManagerDecorator
{
    public function __construct(EntityManagerInterface $wrapped)
    {
        parent::__construct($wrapped);
    }

    public static function create($conn, Configuration $config, EventManager $eventManager = null)
    {
        if ( ! $config->getMetadataDriverImpl()) {
            throw ORMException::missingMappingDriverImpl();
        }

        switch (true) {
            case (is_array($conn)):
                $conn = \Doctrine\DBAL\DriverManager::getConnection(
                    $conn, $config, ($eventManager ?: new EventManager())
                );
                break;

            case ($conn instanceof Connection):
                if ($eventManager !== null && $conn->getEventManager() !== $eventManager) {
                    throw ORMException::mismatchedEventManager();
                }
                break;

            default:
                throw new \InvalidArgumentException("Invalid argument: " . $conn);
        }

        return new EntityManager($conn, $config, $conn->getEventManager());
    }
}
</code>```

And now define this service in your services.xml file as decorating the desired entity manager:

```<code><?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <defaults autowire="true" autoconfigure="true" public="false" />

        <service
            id="decorated.doctrine.orm.default_entity_manager"
            class="App\Doctrine\ORM\EntityManager"
            decorates="doctrine.orm.default_entity_manager"
        >
            <argument type="service" id="decorated.doctrine.orm.default_entity_manager.inner" />
        </service>

    </services>
</container>
</code>```

Body:
I'm setting up a custom hydrator in Doctrine 2 in a Symfony 2 project, but for it to do what it needs it requires another service. The documentation for custom hydrators only shows how to provide a hydrator class, so there's no way to inject dependencies.

For example:

$em->getConfiguration()->addCustomHydrationMode('CustomHydrator', 'MyProject\Hydrators\CustomHydrator');

I suspect Doctrine is initialising the hydrators itself and as such any dependencies would need to be passed through some other Doctrine classes first.

Is there a way to provide a custom "hydration factory" or similar to Doctrine that would allow injection of additional dependencies? Custom hydrators seem fairly limited without this capability.

Answer: Thanks to Denis V

I got this working as follows. I can't post the actual code so I've put together some dummy placeholders so you can see how it fits together.

src/Acme/ExampleBundle/resources/config/services.yml

services:
    doctrine.orm.entity_manager.abstract:
        class:          Acme\ExampleBundle\Entity\DoctrineEntityManager
        factory_class:  Acme\ExampleBundle\Entity\DoctrineEntityManager
        factory_method: create
        abstract:       true
        calls:
            - [ setMyDependency, [@acme.my_custom_service]]

src/Acme/ExampleBundle/Entity/DoctrineEntityManager.php

namespace Acme\ExampleBundle\Entity;

use Acme\ExampleBundle\Hydrator\MyHydrator;
use Doctrine\Common\EventManager;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\EntityManager as BaseEntityManager;
use Doctrine\ORM\ORMException;
use Doctrine\ORM\Query;

class DoctrineEntityManager extends BaseEntityManager
{
    protected $myDependency;

    /**
     * Note: This must be redefined as Doctrine's own entity manager has its own class name hardcoded in.
     */
    public static function create($conn, Configuration $config, EventManager $eventManager = null)
    {
        if (!$config->getMetadataDriverImpl()) {
            throw ORMException::missingMappingDriverImpl();
        }

        switch (true) {
            case (is_array($conn)):
                $conn = \Doctrine\DBAL\DriverManager::getConnection(
                    $conn, $config, ($eventManager ?: new EventManager())
                );
                break;

            case ($conn instanceof Connection):
                if ($eventManager !== null && $conn->getEventManager() !== $eventManager) {
                     throw ORMException::mismatchedEventManager();
                }
                break;

            default:
                throw new \InvalidArgumentException("Invalid argument: " . $conn);
        }

        return new self($conn, $config, $conn->getEventManager());
    }

    public function setMyDependency($myCustomService)
    {
        $this->myDependency = $myCustomService;
    }

    public function newHydrator($hydrationMode)
    {
        if ($hydrationMode == 'MyHydrationMode') {
            return new MyHydrator($this, $this->myDependency);
        }

        return parent::newHydrator($hydrationMode);
    }
}

src/Acme/ExampleBundle/Hydrator/MyHydrator.php

namespace Acme\ExampleBundle\Hydrator;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Internal\Hydration\ObjectHydrator;

class MyHydrator extends ObjectHydrator
{
    protected $myDependency;

    public __construct(EntityManager $em, $myDependency)
    {
        parent::__construct($em);

        $this->myDependency = $myDependency;
    }

    protected function hydrateAllData()
    {
        /* hydration stuff with my dependency here */
    }
}

Body:
Really good answer but please be advised that Doctrine maintainers explicitly said not to extend Doctrine\ORM\EntityManager and I suppose that in the future they will make it final to enforce this.

So instead of the proposed solution without breaking rules here is the cleaner solution:

<?php

declare(strict_types=1);

namespace App\Doctrine\ORM;

use Doctrine\Common\EventManager;
use Doctrine\DBAL\Connection;
use Doctrine\ORM\Configuration;
use Doctrine\ORM\Decorator\EntityManagerDecorator;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\ORMException;

class EntityManager extends EntityManagerDecorator
{
    public function __construct(EntityManagerInterface $wrapped)
    {
        parent::__construct($wrapped);
    }

    public static function create($conn, Configuration $config, EventManager $eventManager = null)
    {
        if ( ! $config->getMetadataDriverImpl()) {
            throw ORMException::missingMappingDriverImpl();
        }

        switch (true) {
            case (is_array($conn)):
                $conn = \Doctrine\DBAL\DriverManager::getConnection(
                    $conn, $config, ($eventManager ?: new EventManager())
                );
                break;

            case ($conn instanceof Connection):
                if ($eventManager !== null && $conn->getEventManager() !== $eventManager) {
                    throw ORMException::mismatchedEventManager();
                }
                break;

            default:
                throw new \InvalidArgumentException("Invalid argument: " . $conn);
        }

        return new EntityManager($conn, $config, $conn->getEventManager());
    }
}

And now define this service in your services.xml file as decorating the desired entity manager:

<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <defaults autowire="true" autoconfigure="true" public="false" />

        <service
            id="decorated.doctrine.orm.default_entity_manager"
            class="App\Doctrine\ORM\EntityManager"
            decorates="doctrine.orm.default_entity_manager"
        >
            <argument type="service" id="decorated.doctrine.orm.default_entity_manager.inner" />
        </service>

    </services>
</container>


问:
Hibernate Configuration from SpringMVC to SpringBoot
I'm (damn me) porting a SpringMVC application, deployed as a war in Tomcat to a SpringBootApplication and i'm facing a lot of problems, basically from Hibernate.

The application was made with DAO/Service pattern.
I know Spring boot would like to use Spring data JPA but i don't want to refactor all the application.

The problem is especially that somewhere i get hibernate exception of No Session and more ofter the org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role where  the old SpringMVC application works.

For instance, i have this Entity

@Entity
@Table(name = "PARK")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "idPark")
public class Park implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -7630704706109692038L;
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id_park", unique = true, nullable = false)
    private int idPark;

    @NotEmpty
    @Column(name = "nome_park")
    private String nomePark;

    @Column(name = "latitude")
    private double latitude;

    @Column(name = "longitude")
    private double longitude;

    @OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.DETACH, CascadeType.REFRESH}, mappedBy = "park")
    @JsonIgnore
    private List<Piano> piani;
//getters and setters
}
```
<p>In a controller if i call</p>
<pre class="lang-java prettyprint-override"><code>List<Piano> piani = pianoService.findPianoByPark(park);
</code>```

from my service class with @Transactional annotation, i still get the exception

This is how i configured Hibernate

@Configuration
@EnableTransactionManagement
@ComponentScan({ "it.besmart.epark.persistence" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {

@Autowired
private Environment environment;

@Bean
public LocalSessionFactoryBean sessionfactory(){
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] {"it.besmart.epark.persistence.model"});
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
}

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
    dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
    dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
    dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
    return dataSource;
}

private Properties hibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
    properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
    properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
    return properties;
}

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
   HibernateTransactionManager txManager = new HibernateTransactionManager();
   txManager.setSessionFactory(s);
   return txManager;
}
```

I think it's a matter of configuration because the old application works with this schema so maybe with Spring boot we need to configure something else to work with Hibernate.
I'm using Spring Boot 1.5.8 and so Hibernate 5.0.12.Final

答:
If you have all the required dependencies in the classpath you shouldn't have to explicitly configure hibernate anymore.
So make sure that you have added spring-boot-starter-data-jpa or spring-boot-starter-data-jdbc as a dependency.

Try to delete HibernateConfiguration and add your configuration in your application.properties so Spring Boot can handle the setup:

```<code>spring.jpa.database-platform = org.hibernate.dialect.PostgreSQL94Dialect
spring.jpa.show-sql = false
spring.datasource.url = jdbc:...
spring.datasource.username = ...
spring.datasource.password = ...
spring.datasource.driver-class-name=...jdbc.Driver
</code>```

You can read more about database configuration with Spring Boot here:
https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
Reference for available application properties:
https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

Spring Boot should automatically pick up your entities as long as you don't deactivate it.
If you definitely need to specify a package you can do so with @EntityScan. For example we had to do this once our Entities where in a different project than our Application class.

```<code>@SpringBootApplication
@EntityScan(basePackages = { "it.besmart.epark.persistence" })
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
</code>```

Body:
I'm (damn me) porting a SpringMVC application, deployed as a war in Tomcat to a SpringBootApplication and i'm facing a lot of problems, basically from Hibernate.

The application was made with DAO/Service pattern.
I know Spring boot would like to use Spring data JPA but i don't want to refactor all the application.

The problem is especially that somewhere i get hibernate exception of No Session and more ofter the org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role where  the old SpringMVC application works.

For instance, i have this Entity

@Entity
@Table(name = "PARK")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "idPark")
public class Park implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = -7630704706109692038L;
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "id_park", unique = true, nullable = false)
    private int idPark;

    @NotEmpty
    @Column(name = "nome_park")
    private String nomePark;

    @Column(name = "latitude")
    private double latitude;

    @Column(name = "longitude")
    private double longitude;

    @OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.DETACH, CascadeType.REFRESH}, mappedBy = "park")
    @JsonIgnore
    private List<Piano> piani;
//getters and setters
}

In a controller if i call

List<Piano> piani = pianoService.findPianoByPark(park);

from my service class with @Transactional annotation, i still get the exception

This is how i configured Hibernate

@Configuration
@EnableTransactionManagement
@ComponentScan({ "it.besmart.epark.persistence" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {

@Autowired
private Environment environment;

@Bean
public LocalSessionFactoryBean sessionfactory(){
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] {"it.besmart.epark.persistence.model"});
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
}

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
    dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
    dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
    dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
    return dataSource;
}

private Properties hibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
    properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
    properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
    return properties;
}

@Bean
@Autowired
public HibernateTransactionManager transactionManager(SessionFactory s) {
   HibernateTransactionManager txManager = new HibernateTransactionManager();
   txManager.setSessionFactory(s);
   return txManager;
}

I think it's a matter of configuration because the old application works with this schema so maybe with Spring boot we need to configure something else to work with Hibernate.
I'm using Spring Boot 1.5.8 and so Hibernate 5.0.12.Final

Body:
If you have all the required dependencies in the classpath you shouldn't have to explicitly configure hibernate anymore.
So make sure that you have added spring-boot-starter-data-jpa or spring-boot-starter-data-jdbc as a dependency.

Try to delete HibernateConfiguration and add your configuration in your application.properties so Spring Boot can handle the setup:

spring.jpa.database-platform = org.hibernate.dialect.PostgreSQL94Dialect
spring.jpa.show-sql = false
spring.datasource.url = jdbc:...
spring.datasource.username = ...
spring.datasource.password = ...
spring.datasource.driver-class-name=...jdbc.Driver

You can read more about database configuration with Spring Boot here:
https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
Reference for available application properties:
https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html

Spring Boot should automatically pick up your entities as long as you don't deactivate it.
If you definitely need to specify a package you can do so with @EntityScan. For example we had to do this once our Entities where in a different project than our Application class.

@SpringBootApplication
@EntityScan(basePackages = { "it.besmart.epark.persistence" })
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}


问:
Map Promise.all output with promises index
I am using nodejs v8+ which supports default async await style of code.

In my problem, I am trying to push all the promises into an array and then use Promise.all to with await keyword to get the responses. But the problem is, I am not able to map the promises with the keys.

Here is the example:

```<code>let users = ["user1", "user2", "user3"];

    let promises = [];
    for(let i = 0; i < users.length; i++){
      let response = this.myApiHelper.getUsersData(users[i]);
      promises.push(response);
    }
    let allResponses = await Promise.all(promises);
</code>```

Here I get all the collected response of all the responses, but I actually want to map this by user.
For example currently I am getting data in this format:

```<code>[
{
  user1 Data from promise 1
},
{
  user2 Data from promise 2
},
{
  user3 Data from promise 3
}
]
</code>```

But I want data in this format:

```<code>[
 {
  "user1": Data from promise 1
 },
 {
   "user2": Data from promise 2
 },
 {
   "user3": Data from promise 3
 }
]
</code>```

I am sure there must be a way to map every promise by user, but I am not aware of.

答:
Though the answer accepted by me is one of the solution, which I think is perfect and I will keep as accepted answer but I would like to post my solution which I figured out later which is much simpler:

We could simply use this:

```<code>let finalData = {};
let users = ["user1", "user2", "user3"];
await Promise.all(users.map(async(eachUser) => {
    finalData[user] = await this.myApiHelper.getUsersData(eachUser);
}))
console.log(finalData);
</code>```

Body:
I am using nodejs v8+ which supports default async await style of code.

In my problem, I am trying to push all the promises into an array and then use Promise.all to with await keyword to get the responses. But the problem is, I am not able to map the promises with the keys.

Here is the example:

let users = ["user1", "user2", "user3"];

    let promises = [];
    for(let i = 0; i < users.length; i++){
      let response = this.myApiHelper.getUsersData(users[i]);
      promises.push(response);
    }
    let allResponses = await Promise.all(promises);

Here I get all the collected response of all the responses, but I actually want to map this by user.
For example currently I am getting data in this format:

[
{
  user1 Data from promise 1
},
{
  user2 Data from promise 2
},
{
  user3 Data from promise 3
}
]

But I want data in this format:

[
 {
  "user1": Data from promise 1
 },
 {
   "user2": Data from promise 2
 },
 {
   "user3": Data from promise 3
 }
]

I am sure there must be a way to map every promise by user, but I am not aware of.

Body:
Though the answer accepted by me is one of the solution, which I think is perfect and I will keep as accepted answer but I would like to post my solution which I figured out later which is much simpler:

We could simply use this:

let finalData = {};
let users = ["user1", "user2", "user3"];
await Promise.all(users.map(async(eachUser) => {
    finalData[user] = await this.myApiHelper.getUsersData(eachUser);
}))
console.log(finalData);


问:
How to finish an android application?
I need to finish an android application. For that i wrote

```<code>@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure You want to exit")
        .setCancelable(false)
        .setPositiveButton("YES"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "Yes"
            // button

            public void onClick(DialogInterface dialog,int id) {
                System.out.println(" onClick ");
                closeApplication(); // Close Application method called
            }
        })
        .setNegativeButton("NO"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "No"
            // button
            public void onClick(DialogInterface dialog,int id) {
                dialog.cancel();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    private void closeApplication() {
        System.out.println("closeApplication ");
        this.finish();
    }
}
</code>```

But if any activity is not finished in the application, when i tried to exit the application that activity is finished first and the application is not exiting.. i tried 2 times to exit this application... How i can finish all the activities in an application when i need to exit... or is there any way to finish the entire application

答:
To close application just call:

```<code>android.os.Process.killProcess(android.os.Process.myPid());
</code>```

Otherwise due-to specific life-cycling of Android activities you can't be sure that application is closed/killed.

Title: How to finish an android application?

Body:
I need to finish an android application. For that i wrote

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure You want to exit")
        .setCancelable(false)
        .setPositiveButton("YES"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "Yes"
            // button

            public void onClick(DialogInterface dialog,int id) {
                System.out.println(" onClick ");
                closeApplication(); // Close Application method called
            }
        })
        .setNegativeButton("NO"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "No"
            // button
            public void onClick(DialogInterface dialog,int id) {
                dialog.cancel();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    private void closeApplication() {
        System.out.println("closeApplication ");
        this.finish();
    }
}

But if any activity is not finished in the application, when i tried to exit the application that activity is finished first and the application is not exiting.. i tried 2 times to exit this application... How i can finish all the activities in an application when i need to exit... or is there any way to finish the entire application

Body:
To close application just call:

android.os.Process.killProcess(android.os.Process.myPid());

Otherwise due-to specific life-cycling of Android activities you can't be sure that application is closed/killed.


问:
Error during initialization of VM on fresh eclipse/Java install
I've just installed the JDK 9 and eclipse-java Photon (the .rar that you can download from their webpage).

Opened eclipse for the first time + Set the workspace.

Configured some visual things.

Created an empty project (some test package -> some test Class).

Tried to run it (a 100% EMPTY Class, just an empty main() and that's it).

Got this error (the 'D:\Boludeces' displayed path is not at all related with any installation of eclipse nor JDK/JRE. That's confuses me).

I'm not sure what's wrong here. I'm using Windows 7 64-bits. Software versions (both of JDK/JRE and eclipse) are 64-bits also (completely sure about that), so they should be complatible with each other.
The Run configuration is also completely untouched.
Those are my installation paths:

eclipse: D:\Boludeces ^_^\Programas\Carpetas de programas\eclipse\java-photon.

eclipse's default workspace: D:\Boludeces ^_^\Programas\Carpetas de programas\eclipse\Workspace.

JDK: C:\Program Files\Java\jdk-9.0.1.

JRE: C:\Program Files\Java\jre-9.0.1.

Some useful pictures below:

1 CLASSPATH environment variable

2 PATH environment variable

3 Other Java's environment variables

2 java -version on cmd

Do somebody has any ideas? Thanks in advance. Best regards,

Viciecal

答:
Eclipse Photon will be released on June 27, 2018. There are currently only milestones pre-releases of Eclipse Photon which might be unstable.

If you have problems, you can use an Eclipse IDE package of the current release (which is currently Oxygen.1a) instead.


问:
How to stop scrolling as half item can be visible in HorizontalScrollView
Can you plz share any suggestion or library to achieve below,

e.g. If you see in Google Play Store, when you scroll HorizontalScrollView, your scrolling will stop as half of the next item user can able to see. App forcefully stops scroll like this so the user gets to know, there are more items available.

I do not have any code to share. I just want your hints/libs.

Thank you!

答:
You can change item's width dynamically based on device's width to manage this scenario.</p>

```<code>horizontalScrollView.post(new Runnable() {

            @Override
            public void run() {
                DisplayMetrics dm = getResources().getDisplayMetrics();
                int screenWidth = dm.widthPixels;
                // based on this width, the space between the children and their
                // widths calculate new widths so you get a half clipped
                // children on the right side.
            }
        });
</code>```

Body:
You can change item's width dynamically based on device's width to manage this scenario.

horizontalScrollView.post(new Runnable() {

            @Override
            public void run() {
                DisplayMetrics dm = getResources().getDisplayMetrics();
                int screenWidth = dm.widthPixels;
                // based on this width, the space between the children and their
                // widths calculate new widths so you get a half clipped
                // children on the right side.
            }
        });


问:
How to maintain an image's aspect ratio inside an SVG without an aspect ratio
I have an SVG functioning properly as a clipping path masking an image. The SVG shape has preserveAspectRatio="none" and is behaving how I want it to (full-width but maintaining a static height).

The problem is that the image I am clipping is stretching and squishing along with the SVG whereas I'd like it to behave the same as a background image with background-size: cover; (always filling the SVG, cropping if necessary, but maintaing aspect ratio).

Is it possible to do this with cross-browser compatibility (the latest Chrome, Firefox, Safari, and Internat Explorer)?

HTML:

```<code><div class="outer-wrapper">
  <div class="svg-wrapper">
    <!-- hidden SVG -->
    <svg class="shadow-svg">
      <!-- create drop shadow -->
      <filter id="drop-shadow">
        <feGaussianBlur in="SourceAlpha" stdDeviation="5"/>
        <feOffset dx="0" dy="0" result="offsetblur"/>
        <feFlood flood-color="rgb(0,0,0)" flood-opacity="0.75"/>
        <feComposite in2="offsetblur" operator="in"/>
        <feMerge>
          <feMergeNode/>
          <feMergeNode in="SourceGraphic"/>
        </feMerge>
      </filter>
      <!-- create shape-->
      <symbol id="shadow" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xml:space="preserve">
        <defs>
          <polygon id="clipShape" points="0 0 0 260 20 260 20 210 1350 210 1350 260 1370 260 1370 0 0 0" style="filter:url(#dropshadow)"/>
        </defs>
      </symbol>
      <!-- set shape as clipping path -->
      <clipPath id="clipPath">
        <use xlink:href="#clipShape" />
      </clipPath>
    </svg>
    <!-- visible SVG -->
    <svg class="shape-svg" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1370 260" enable-background="new 0 0 1370 260" xml:space="preserve" preserveAspectRatio="none">
      <!-- add drop shadow -->
      <use xlink:href="#shadow" />
      <!-- add clipping path shape -->
      <g transform="matrix(1 0 0 1 0 0)" clip-path="url(#clipPath)" >
        <!-- add image inside clipping path shape -->
        <image width="1370" height="260" xlink:href="https://www.unsplash.it/1370/260" transform="matrix(1 0 0 1 0 0)"></image>
      </g>
    </svg>
  </div><!-- .svg-wrapper -->
  <!-- text block -->
  <div class="header-text">
    <h2>Test Header Placeholder</h2>
    <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Velit exercitationem quibusdam sed natus blanditiis quia assumenda, magni tenetur veritatis itaque iure explicabo veniam maiores magnam architecto et corporis possimus.</p>
  </div>
</div><!-- .outer-wrapper -->
</code>```

SCSS:

```<code>* {
  margin: 0;
  padding: 0;
}

body {
  height: 100vh;
  background: repeating-linear-gradient(-45deg, palegreen, palegreen 3px, lightgreen 3px, lightgreen 40px);
}

.outer-wrapper {
  display: block;
  width: 100%;
  margin: 0 auto;
}

.svg-wrapper {
  width: 96%;
  height: 150px;
  margin: 0 auto;
}

.shadow-svg {
  width: 0;
  height: 0;
  position: absolute;
}

.shape-svg {
  width: 100%;
  height: 150px;
  filter: url(#drop-shadow);
}

.header-text {
  width: 90%;
  margin: -20px auto 0;
  font-family: monaco, courier;
}
</code>```

CodePen Here

Note: it's currently not working in Firefox or IE11. I'd appreciate any assistance in getting all this working across those browsers as well.

Thank you.

答:
About the aspect ratio

You could just set the svg as a background-image of a div. And style it with css; background-size: cover; and background-position: center bottom; will probably do the trick.

Here is an answer of the question "why it doesn't it work in MS-Edge?".

Define your clipPath in a <defs> element.

The defs element should be a direct child of one of the ancestors of the referencing element Which is not the case in your example. Placing the defs element as a child of the <svg> element always works. Source: https://www.w3.org/TR/SVG/struct.html#DefsElement

Rule of life: Keep it simple when you can. That means not using unnecessary references. Just show the clipping path inside the <clipPath> element.
The <defs> element ended up looking like this for me and is a child of the <svg> element.

<defs>

  <clipPath id="clipPath">
    <polygon points="0 0 0 260 20 260 20 210 1350 210 1350 260 1370 260 1370 0 0 0"/>
  </clipPath>
</defs>```

Body:
I have an SVG functioning properly as a clipping path masking an image. The SVG shape has preserveAspectRatio="none" and is behaving how I want it to (full-width but maintaining a static height).

The problem is that the image I am clipping is stretching and squishing along with the SVG whereas I'd like it to behave the same as a background image with background-size: cover; (always filling the SVG, cropping if necessary, but maintaing aspect ratio).

Is it possible to do this with cross-browser compatibility (the latest Chrome, Firefox, Safari, and Internat Explorer)?

HTML:

    <svg class="shadow-svg">

      <filter id="drop-shadow">
        <feGaussianBlur in="SourceAlpha" stdDeviation="5"/>
        <feOffset dx="0" dy="0" result="offsetblur"/>
        <feFlood flood-color="rgb(0,0,0)" flood-opacity="0.75"/>
        <feComposite in2="offsetblur" operator="in"/>
        <feMerge>
          <feMergeNode/>
          <feMergeNode in="SourceGraphic"/>
        </feMerge>
      </filter>

      <symbol id="shadow" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xml:space="preserve">
        <defs>
          <polygon id="clipShape" points="0 0 0 260 20 260 20 210 1350 210 1350 260 1370 260 1370 0 0 0" style="filter:url(#dropshadow)"/>
        </defs>
      </symbol>

      <clipPath id="clipPath">
        <use xlink:href="#clipShape" />
      </clipPath>
    </svg>

    <svg class="shape-svg" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1370 260" enable-background="new 0 0 1370 260" xml:space="preserve" preserveAspectRatio="none">

      <use xlink:href="#shadow" />

      <g transform="matrix(1 0 0 1 0 0)" clip-path="url(#clipPath)" >

        <image width="1370" height="260" xlink:href="https://www.unsplash.it/1370/260" transform="matrix(1 0 0 1 0 0)"></image>
      </g>
    </svg>

Test Header Placeholder

Lorem ipsum dolor, sit amet consectetur adipisicing elit. Velit exercitationem quibusdam sed natus blanditiis quia assumenda, magni tenetur veritatis itaque iure explicabo veniam maiores magnam architecto et corporis possimus.

SCSS:

* {
  margin: 0;
  padding: 0;
}

body {
  height: 100vh;
  background: repeating-linear-gradient(-45deg, palegreen, palegreen 3px, lightgreen 3px, lightgreen 40px);
}

.outer-wrapper {
  display: block;
  width: 100%;
  margin: 0 auto;
}

.svg-wrapper {
  width: 96%;
  height: 150px;
  margin: 0 auto;
}

.shadow-svg {
  width: 0;
  height: 0;
  position: absolute;
}

.shape-svg {
  width: 100%;
  height: 150px;
  filter: url(#drop-shadow);
}

.header-text {
  width: 90%;
  margin: -20px auto 0;
  font-family: monaco, courier;
}

CodePen Here

Note: it's currently not working in Firefox or IE11. I'd appreciate any assistance in getting all this working across those browsers as well.

Thank you.

Body:
About the aspect ratio

You could just set the svg as a background-image of a div. And style it with css; background-size: cover; and background-position: center bottom; will probably do the trick.

Here is an answer of the question "why it doesn't it work in MS-Edge?".

Define your clipPath in a <defs> element.

The defs element should be a direct child of one of the ancestors of the referencing element Which is not the case in your example. Placing the defs element as a child of the <svg> element always works. Source: https://www.w3.org/TR/SVG/struct.html#DefsElement

Rule of life: Keep it simple when you can. That means not using unnecessary references. Just show the clipping path inside the <clipPath> element.
The <defs> element ended up looking like this for me and is a child of the <svg> element.

<defs>
  <!-- set shape as clipping path -->
  <clipPath id="clipPath">
    <polygon points="0 0 0 260 20 260 20 210 1350 210 1350 260 1370 260 1370 0 0 0"/>
  </clipPath>
</defs>


问:
Unique Id for java object for 100% collision free storage in a data structure
I have a method that checks if two objects are equal(by reference).

```<code>public boolean isUnique( T uniqueIdOfFirstObject, T uniqueIdOfSecondObject ) {
    return (uniqueIdOfFirstObject ==  uniqueIdOfSecondObject);
}
</code>```

(Use case) Assuming that I don't have any control over creation of the object.
I have a method

```<code>void currentNodeExistOrAddToHashSet(Object newObject, HashSet<T> objectHash) {
    // will it be 100% precise? Assuming both object have the same field values.
    if(!objectHash.contains(newObject){
        objectHash.add(newObject);
    }
}
</code>```

or I could do something like this

```<code>void currentNodeExistOrAddToHashSet(Object newObject, HashSet<T> objectHash){
    //as per my knowledge, there might be collision for different objects.
    int uniqueId =  System.identityHashCode(newObject);
    if(!objectHash.contains(uniqueId){
        objectHash.add(uniqueId);
    }
}
</code>```

Is it possible to get a 100% collision proof Id in java i.e different object having different IDs, the same object having same ids irrespective of the content of the object?

答:
Since you put them into a HashSet that uses hashcode/equals and hashCode is 32 bits long - this has a limit; thus collision will happen. Especially since a HashSet actually only cares about n-last bits before making itself bigger in size and thus adding one more bit and so on. You can read a lot more about this here for example.

The question is different here: why you want a collision free structure in the first place? If you define a fairly well distributed hashCode and a fairly decent equals - these things should not matter to you at all. If you worry about performance of a search, it is O(1) for HashSet.

You could define hashCode and equality based on UUID, like let's say UUID#randomUUID - but this still bounds your hashCode to the same 32-bits, thus collision could still happen.

Body:
I have a method that checks if two objects are equal(by reference).

public boolean isUnique( T uniqueIdOfFirstObject, T uniqueIdOfSecondObject ) {
    return (uniqueIdOfFirstObject ==  uniqueIdOfSecondObject);
}

(Use case) Assuming that I don't have any control over creation of the object.
I have a method

void currentNodeExistOrAddToHashSet(Object newObject, HashSet<T> objectHash) {
    // will it be 100% precise? Assuming both object have the same field values.
    if(!objectHash.contains(newObject){
        objectHash.add(newObject);
    }
}

or I could do something like this

void currentNodeExistOrAddToHashSet(Object newObject, HashSet<T> objectHash){
    //as per my knowledge, there might be collision for different objects.
    int uniqueId =  System.identityHashCode(newObject);
    if(!objectHash.contains(uniqueId){
        objectHash.add(uniqueId);
    }
}

Is it possible to get a 100% collision proof Id in java i.e different object having different IDs, the same object having same ids irrespective of the content of the object?


问:
Concatenating two strings into a Textbox
I have been just learning about the basics of cryptography, and I wanted to give
one of the methods called zigzag transposition a try.

 All this method does is combining the entire sentence and give them index starting from zero.

it then separates the even indexed characters into an array and the odd ones into a different array .

When I convert the two arrays to strings and then place them in a textbox only the first string shows up.

```<code>private void ZigzagBu_Click(object sender, EventArgs e) {
    string s = PlaintextTB.Text;
    s = s.Replace(" ","");

    char[] whole = s.ToCharArray();
    char[] even = new char[whole.Length];
    char[] odd = new char[whole.Length];

    int evenIndex = 0;
    int oddIndex = 0;

    for(int i =0;i<whole.Length;i++) {
        if (i % 2 == 0) {
            even[evenIndex] = whole[i];
            evenIndex++;
        }
        else {
            odd[oddIndex] = whole[i];
            oddIndex++;
        }
    }

    s = new String(even);
    string m = new String(odd);

    CiphertextTB.Text = s+m;
}
</code>```

答:
Actually, your code is over complicated.
The same thing can be done with simple strings, no need to convert to char arrays:

```<code>var s = "0123456";
var even = "";
var odd = "";
for(int i=0; i<s.Length;i++)
{
    if(i % 2 == 0)
    {
        even  += s[i];
    }
    else
    {
        odd += s[i];
    }
}
var result = even + odd;
</code>```

However, if your plain text string is even a bit long (say, 10, 20 chars) - a better implementation would be to use StringBuilder:

```<code>var s = "0123456";
var even = new StringBuilder();
var odd = StringBuilder();
for(int i=0; i<s.Length;i++)
{
    if(i % 2 == 0)
    {
        even.Append(s[i]);
    }
    else
    {
        oddAppend(s[i]);
    }
}
var result = even.Append(odd.ToString()).ToString();
</code>```

Body:
I have been just learning about the basics of cryptography, and I wanted to give
one of the methods called zigzag transposition a try.

 All this method does is combining the entire sentence and give them index starting from zero.

it then separates the even indexed characters into an array and the odd ones into a different array .

When I convert the two arrays to strings and then place them in a textbox only the first string shows up.

private void ZigzagBu_Click(object sender, EventArgs e) {
    string s = PlaintextTB.Text;
    s = s.Replace(" ","");

    char[] whole = s.ToCharArray();
    char[] even = new char[whole.Length];
    char[] odd = new char[whole.Length];

    int evenIndex = 0;
    int oddIndex = 0;

    for(int i =0;i<whole.Length;i++) {
        if (i % 2 == 0) {
            even[evenIndex] = whole[i];
            evenIndex++;
        }
        else {
            odd[oddIndex] = whole[i];
            oddIndex++;
        }
    }

    s = new String(even);
    string m = new String(odd);

    CiphertextTB.Text = s+m;
}

Body:
Actually, your code is over complicated.
The same thing can be done with simple strings, no need to convert to char arrays:

var s = "0123456";
var even = "";
var odd = "";
for(int i=0; i<s.Length;i++)
{
    if(i % 2 == 0)
    {
        even  += s[i];
    }
    else
    {
        odd += s[i];
    }
}
var result = even + odd;

However, if your plain text string is even a bit long (say, 10, 20 chars) - a better implementation would be to use StringBuilder:

var s = "0123456";
var even = new StringBuilder();
var odd = StringBuilder();
for(int i=0; i<s.Length;i++)
{
    if(i % 2 == 0)
    {
        even.Append(s[i]);
    }
    else
    {
        oddAppend(s[i]);
    }
}
var result = even.Append(odd.ToString()).ToString();


问:
if else condition in shell script to check empty input by user
I am taking input from the user, and wants that if user give empty input , it should display the error message , I am trying below code , please correct me where I am wrong  .

```<code>  #!/bin/bash
    echo "please enter previous version number"
    read prevversion
    echo "please enter new version number"
    read newversion
    echo "please enter environment [DEV2/QAT2/PPE2/PRD]"
    read env

    if[["$env"=" " &&"$prevversion"=" " &&"$newversion"= " "]]
    then
        echo "Please enter the details and try again"

    else

        if [ "$env" = "QAT2" ]
        then
                prevversion="$prevversion"_QAT2
                echo "previous version is $prevversion"
                newversion="$newversion"_QAT2
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "PPE2" ]
        then
                prevversion="$prevversion"
                echo "previous version is $prevversion"
                newversion="$newversion"
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "PRD" ]
        then
                prevversion="$prevversion"
                echo "previous version is $prevversion"
                newversion="$newversion"
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "DEV2" ]
        then
                prevversion="$prevversion"_DEV2
                echo "previous version is $prevversion"
                newversion="$newversion"_DEV2
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        fi

    fi
</code>```

please provide me with correct solution

答:
Change your code in the following way:

```<code>if [ -z "$env" ] || [ -z "$prevversion" ] || [ -z "$newversion" ]; then
    echo "either one of the vars is empty"
    exit 1
fi
</code>```

this will check that at least one of the tree var is empty.
If this is the case print your error message and exit the script with return code 1 to show that the script exit in error.

Body:
I am taking input from the user, and wants that if user give empty input , it should display the error message , I am trying below code , please correct me where I am wrong  .

  #!/bin/bash
    echo "please enter previous version number"
    read prevversion
    echo "please enter new version number"
    read newversion
    echo "please enter environment [DEV2/QAT2/PPE2/PRD]"
    read env

    if[["$env"=" " &&"$prevversion"=" " &&"$newversion"= " "]]
    then
        echo "Please enter the details and try again"

    else

        if [ "$env" = "QAT2" ]
        then
                prevversion="$prevversion"_QAT2
                echo "previous version is $prevversion"
                newversion="$newversion"_QAT2
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "PPE2" ]
        then
                prevversion="$prevversion"
                echo "previous version is $prevversion"
                newversion="$newversion"
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "PRD" ]
        then
                prevversion="$prevversion"
                echo "previous version is $prevversion"
                newversion="$newversion"
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        elif [ "$env" = "DEV2" ]
        then
                prevversion="$prevversion"_DEV2
                echo "previous version is $prevversion"
                newversion="$newversion"_DEV2
                echo "new version is $newversion"
                env="$env"
                echo "enviornment is $env"
        fi

    fi

please provide me with correct solution

Body:
Change your code in the following way:

if [ -z "$env" ] || [ -z "$prevversion" ] || [ -z "$newversion" ]; then
    echo "either one of the vars is empty"
    exit 1
fi

this will check that at least one of the tree var is empty.
If this is the case print your error message and exit the script with return code 1 to show that the script exit in error.


问:
Automatically log Android lifecycle events using ActivityLifecycleCallbacks?
I am trying to automatically capture and log Android lifecycle events using ActivityLifecycleCallbacks, however documentation on this matter is scarce, to say the least:

```<code>    public void registerActivityLifecycleCallbacks (Application.ActivityLifecycleCallbacks callback)
</code>```

I don't want to have to extend the Activity class or override the existing lifecycle methods (onCreate, onResume, etc...)  I'm looking to have a separate class listening for these events and acting accordingly.

Does anyone have any experience in this, or have links to good solid documentation or tutorials on how this works?  Specifically, how to register for ActivityLifecycleCallbacks, and how to handle them?

答:
```<code>@Override
public void onCreate() {
    super.onCreate();
    registerActivityLifecycleCallbacks(MyApplication.this/*(Your Application Name)*/);
}
</code>```

Only add this line on Application class and all works well.

Body:
I am trying to automatically capture and log Android lifecycle events using ActivityLifecycleCallbacks, however documentation on this matter is scarce, to say the least:

    public void registerActivityLifecycleCallbacks (Application.ActivityLifecycleCallbacks callback)

I don't want to have to extend the Activity class or override the existing lifecycle methods (onCreate, onResume, etc...)  I'm looking to have a separate class listening for these events and acting accordingly.

Does anyone have any experience in this, or have links to good solid documentation or tutorials on how this works?  Specifically, how to register for ActivityLifecycleCallbacks, and how to handle them?

Body:
@Override
public void onCreate() {
    super.onCreate();
    registerActivityLifecycleCallbacks(MyApplication.this/*(Your Application Name)*/);
}

Only add this line on Application class and all works well.

ContentLicense: CC BY-SA 4.0