问:
How to save Listview state in shared preference
Hello friends i am new in android using custom listview with help of arrayadopter when user click on item in listview it change color of the item now i want save this state in  shared preference please help me how can do this here is my code if any expert is here please help me i appreciate your help thanks you in advance

// here i want save state when item color changed

```<code>    holder.linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Toasty.success(activity, "PICK COLOR", Toast.LENGTH_SHORT, true).show();

          highlight=true;

            Vibrator vibe = (Vibrator)activity.getSystemService(Context.VIBRATOR_SERVICE);
            vibe.vibrate(100);

            ColorPicker colorPicker = new ColorPicker(activity);
            ArrayList<String>colors=new ArrayList<>();
            colors.add("#e0e0eb");
            colors.add("#ccffff");
            colors.add("#ffe6ff");
            colors.add("#ffffcc");
            colors.add("#ccffcc");
            colors.add("#e6f2ff");
            colorPicker.setColors(colors).setColumns(4).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
                @Override
                public void onChooseColor(int position, int color) {

//color is change and want save this in sharedperfence

 holder.linearLayout.setBackgroundColor(color);

                }

                @Override
                public void onCancel() {

                }
            }).show();

            return false;
        }
    });

my full adopter class

package bible.swordof.God;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.opengl.Visibility;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;

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

import es.dmoral.toasty.Toasty;
import petrov.kristiyan.colorpicker.ColorPicker;

import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static android.support.constraint.Constraints.TAG;
import static android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext;
import static android.support.v4.content.ContextCompat.startActivity;

public class FullverseAdopter extends ArrayAdapter<String> {
    private ALLVERSE activity;

    private List<String> versenumber;
    private List<String>verseid;
    private List<String> verselist;
    private List<String> refernce;
    TextToSpeech textToSpeech;
    private DatabaseHelper mDBHelper;
    private SQLiteDatabase mDb;
    private boolean highlight;

public  String ex="switch";

    //check for availabe language
    int result;

    public FullverseAdopter(ALLVERSE context, int resource, List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid) {
        super(context, resource, versenumber);
        this.activity = context;
        this.versenumber = versenumber;
        this.verselist = verselist;
        this.refernce = refernce;
        this.verseid=verseid;

    }

    @Override
    public int getCount() {
        return versenumber.size();
    }

    @Override
    public String getItem(int position) {
        return versenumber.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        final ViewHolder holder;

        LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        // If holder not exist then locate all view from UI file.
        if (convertView == null) {
            // inflate UI from XML file
             convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
            // get all UI view
            holder = new ViewHolder(convertView);
            // set tag for holder
           holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
            holder.verselist = (TextView) convertView.findViewById(R.id.verse);
           holder.addfavoruite=(ToggleButton)convertView.findViewById(R.id.adbookmark);

         holder.linearLayout=(LinearLayout)convertView.findViewById(R.id.layout);

            convertView.setTag(holder);
        } else {
            // if holder created, get tag from view
            holder = (ViewHolder) convertView.getTag();
        }
        holder.versenumber.setText(versenumber.get(position));

        holder.verselist.setText(verselist.get(position));

holder.linearLayout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

    }
});

holder.linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        Toasty.success(activity, "PICK COLOR", Toast.LENGTH_SHORT, true).show();

      highlight=true;

        Vibrator vibe = (Vibrator)activity.getSystemService(Context.VIBRATOR_SERVICE);
        vibe.vibrate(100);

        ColorPicker colorPicker = new ColorPicker(activity);
        ArrayList<String>colors=new ArrayList<>();
        colors.add("#e0e0eb");
        colors.add("#ccffff");
        colors.add("#ffe6ff");
        colors.add("#ffffcc");
        colors.add("#ccffcc");
        colors.add("#e6f2ff");
        colorPicker.setColors(colors).setColumns(4).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
            @Override
            public void onChooseColor(int position, int color) {

                holder.linearLayout.setBackgroundColor(color);

            }

            @Override
            public void onCancel() {

            }
        }).show();

        return false;
    }
});
        /*holder.verselist.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                holder.verselist.setBackgroundColor(Color.parseColor("#e0e0eb"));
                return false;
            }
        });*/

//verselist highlight

/*holder.verselist.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

    }
});*/

        //share verse
        holder.share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n'   + verselist.get(position));
                sendIntent.setType("text/plain");
                activity.startActivity(sendIntent);

            }
        });

//add in favourite
      holder.addfavoruite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if(isChecked){
                    mDBHelper = new DatabaseHelper(activity);
                    mDb = mDBHelper.getWritableDatabase();
                    ContentValues contentValues=new ContentValues();
                  contentValues.put("id",verseid.get(position));
                  contentValues.put("bookname",refernce.get(position));
                   contentValues.put("versenumber",versenumber.get(position));
                   contentValues.put("verse",verselist.get(position));
                   long check=mDb.insert("favourite",null,contentValues);
                   Log.d("MY_TAG","DB IS NOW "+check);
                   Toasty.success(activity, "Added in favouite", Toast.LENGTH_SHORT, true).show();

                }else {

                    mDBHelper = new DatabaseHelper(activity);
                    mDb = mDBHelper.getWritableDatabase();
                    long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
                   Toasty.error(activity, "Remove in favouite", Toast.LENGTH_SHORT, true).show();
                }

            }
        });

       /* textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {

                if (status == TextToSpeech.SUCCESS) {
                    result = textToSpeech.setLanguage(Locale.ENGLISH);
                } else {

                    Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
                }
            }
        });
*/

        //My toggle button

       /* holder.speakverse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();

                if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {

                    Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();

                } else {

                    textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);

                }
            }
        });*/

        return convertView;
    }

    static class ViewHolder {
        private TextView versenumber;
        private TextView verselist;

        private ImageView share;
        private  ToggleButton addfavoruite;
        private ImageView speakverse;
        private LinearLayout linearLayout;

        public ViewHolder(View v) {
            versenumber = (TextView) v.findViewById(R.id.versenumber);
            verselist = (TextView) v.findViewById(R.id.verse);
           share = (ImageView) v.findViewById(R.id.share);
            /*speakverse = (ImageView) v.findViewById(R.id.speakverse);*/
        addfavoruite=(ToggleButton)v.findViewById(R.id.adbookmark);
        linearLayout=(LinearLayout)v.findViewById(R.id.layout);

        }

    }
    public boolean CheckIsDataAlreadyInDBorNot(String TableName,  String dbfield, String fieldValue) {

        mDBHelper = new DatabaseHelper(activity);
        mDb = mDBHelper.getReadableDatabase();
        String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
        Cursor cursor = mDb.rawQuery(Query, null);
        if(cursor.getCount() <= 0){
            cursor.close();

            Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
            return false;
        }else {

            Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();

        }
        cursor.close();

        return true;
    }
    public  void opecolorpicker(){

    }

}
</code>```

答:
One way of achieving it is create a new class like this

```<code>class MySaveInstanceClass {
  static ArrayList<Boolean> selectStatusArray;
}
</code>```

Initialize this array when you get the data as

```<code>MySaveInstanceClass.selectStatusArray = new ArrayList<>(yourList.size());
</code>```

At this point every value in array will be false. And you have one flag for every list item.

When you set color of your layout just access this array and check the corresponding position.

```<code>holder.linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
  @Override
  public boolean onLongClick(View v) {
    if (MySaveInstanceClass.selectStatusArray.get(posiiton) == true) {
      // set background color
    }
  }
}
</code>```

Now you want to save state. You will have access to that array in your activity too.

There is a lifecycle method onDestroy() there you open your shared preference and save it. It will look something like this

```<code>Set<String> set = myScores.getStringSet("key", null);
//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();
</code>```

Now you have your state saved. access the same shared preference in onStart() or onCreate() method and get the array and intitialize the class

```<code>MySaveInstanceClass.selectStatusArray = <array found from shared preference>;
</code>```

Body:
Hello friends i am new in android using custom listview with help of arrayadopter when user click on item in listview it change color of the item now i want save this state in  shared preference please help me how can do this here is my code if any expert is here please help me i appreciate your help thanks you in advance

// here i want save state when item color changed

    holder.linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            Toasty.success(activity, "PICK COLOR", Toast.LENGTH_SHORT, true).show();

          highlight=true;

            Vibrator vibe = (Vibrator)activity.getSystemService(Context.VIBRATOR_SERVICE);
            vibe.vibrate(100);

            ColorPicker colorPicker = new ColorPicker(activity);
            ArrayList<String>colors=new ArrayList<>();
            colors.add("#e0e0eb");
            colors.add("#ccffff");
            colors.add("#ffe6ff");
            colors.add("#ffffcc");
            colors.add("#ccffcc");
            colors.add("#e6f2ff");
            colorPicker.setColors(colors).setColumns(4).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
                @Override
                public void onChooseColor(int position, int color) {

//color is change and want save this in sharedperfence

 holder.linearLayout.setBackgroundColor(color);

                }

                @Override
                public void onCancel() {

                }
            }).show();

            return false;
        }
    });

my full adopter class

package bible.swordof.God;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.opengl.Visibility;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;

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

import es.dmoral.toasty.Toasty;
import petrov.kristiyan.colorpicker.ColorPicker;

import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static android.support.constraint.Constraints.TAG;
import static android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext;
import static android.support.v4.content.ContextCompat.startActivity;

public class FullverseAdopter extends ArrayAdapter<String> {
    private ALLVERSE activity;

    private List<String> versenumber;
    private List<String>verseid;
    private List<String> verselist;
    private List<String> refernce;
    TextToSpeech textToSpeech;
    private DatabaseHelper mDBHelper;
    private SQLiteDatabase mDb;
    private boolean highlight;

public  String ex="switch";

    //check for availabe language
    int result;

    public FullverseAdopter(ALLVERSE context, int resource, List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid) {
        super(context, resource, versenumber);
        this.activity = context;
        this.versenumber = versenumber;
        this.verselist = verselist;
        this.refernce = refernce;
        this.verseid=verseid;

    }

    @Override
    public int getCount() {
        return versenumber.size();
    }

    @Override
    public String getItem(int position) {
        return versenumber.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        final ViewHolder holder;

        LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        // If holder not exist then locate all view from UI file.
        if (convertView == null) {
            // inflate UI from XML file
             convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
            // get all UI view
            holder = new ViewHolder(convertView);
            // set tag for holder
           holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
            holder.verselist = (TextView) convertView.findViewById(R.id.verse);
           holder.addfavoruite=(ToggleButton)convertView.findViewById(R.id.adbookmark);

         holder.linearLayout=(LinearLayout)convertView.findViewById(R.id.layout);

            convertView.setTag(holder);
        } else {
            // if holder created, get tag from view
            holder = (ViewHolder) convertView.getTag();
        }
        holder.versenumber.setText(versenumber.get(position));

        holder.verselist.setText(verselist.get(position));

holder.linearLayout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

    }
});

holder.linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View v) {
        Toasty.success(activity, "PICK COLOR", Toast.LENGTH_SHORT, true).show();

      highlight=true;

        Vibrator vibe = (Vibrator)activity.getSystemService(Context.VIBRATOR_SERVICE);
        vibe.vibrate(100);

        ColorPicker colorPicker = new ColorPicker(activity);
        ArrayList<String>colors=new ArrayList<>();
        colors.add("#e0e0eb");
        colors.add("#ccffff");
        colors.add("#ffe6ff");
        colors.add("#ffffcc");
        colors.add("#ccffcc");
        colors.add("#e6f2ff");
        colorPicker.setColors(colors).setColumns(4).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
            @Override
            public void onChooseColor(int position, int color) {

                holder.linearLayout.setBackgroundColor(color);

            }

            @Override
            public void onCancel() {

            }
        }).show();

        return false;
    }
});
        /*holder.verselist.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                holder.verselist.setBackgroundColor(Color.parseColor("#e0e0eb"));
                return false;
            }
        });*/

//verselist highlight

/*holder.verselist.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

    }
});*/

        //share verse
        holder.share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
                Intent sendIntent = new Intent();
                sendIntent.setAction(Intent.ACTION_SEND);
                sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n'   + verselist.get(position));
                sendIntent.setType("text/plain");
                activity.startActivity(sendIntent);

            }
        });

//add in favourite
      holder.addfavoruite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if(isChecked){
                    mDBHelper = new DatabaseHelper(activity);
                    mDb = mDBHelper.getWritableDatabase();
                    ContentValues contentValues=new ContentValues();
                  contentValues.put("id",verseid.get(position));
                  contentValues.put("bookname",refernce.get(position));
                   contentValues.put("versenumber",versenumber.get(position));
                   contentValues.put("verse",verselist.get(position));
                   long check=mDb.insert("favourite",null,contentValues);
                   Log.d("MY_TAG","DB IS NOW "+check);
                   Toasty.success(activity, "Added in favouite", Toast.LENGTH_SHORT, true).show();

                }else {

                    mDBHelper = new DatabaseHelper(activity);
                    mDb = mDBHelper.getWritableDatabase();
                    long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
                   Toasty.error(activity, "Remove in favouite", Toast.LENGTH_SHORT, true).show();
                }

            }
        });

       /* textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {

                if (status == TextToSpeech.SUCCESS) {
                    result = textToSpeech.setLanguage(Locale.ENGLISH);
                } else {

                    Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
                }
            }
        });
*/

        //My toggle button

       /* holder.speakverse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();

                if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {

                    Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();

                } else {

                    textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);

                }
            }
        });*/

        return convertView;
    }

    static class ViewHolder {
        private TextView versenumber;
        private TextView verselist;

        private ImageView share;
        private  ToggleButton addfavoruite;
        private ImageView speakverse;
        private LinearLayout linearLayout;

        public ViewHolder(View v) {
            versenumber = (TextView) v.findViewById(R.id.versenumber);
            verselist = (TextView) v.findViewById(R.id.verse);
           share = (ImageView) v.findViewById(R.id.share);
            /*speakverse = (ImageView) v.findViewById(R.id.speakverse);*/
        addfavoruite=(ToggleButton)v.findViewById(R.id.adbookmark);
        linearLayout=(LinearLayout)v.findViewById(R.id.layout);

        }

    }
    public boolean CheckIsDataAlreadyInDBorNot(String TableName,  String dbfield, String fieldValue) {

        mDBHelper = new DatabaseHelper(activity);
        mDb = mDBHelper.getReadableDatabase();
        String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
        Cursor cursor = mDb.rawQuery(Query, null);
        if(cursor.getCount() <= 0){
            cursor.close();

            Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
            return false;
        }else {

            Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();

        }
        cursor.close();

        return true;
    }
    public  void opecolorpicker(){

    }

}

Body:
One way of achieving it is create a new class like this

class MySaveInstanceClass {
  static ArrayList<Boolean> selectStatusArray;
}

Initialize this array when you get the data as

MySaveInstanceClass.selectStatusArray = new ArrayList<>(yourList.size());

At this point every value in array will be false. And you have one flag for every list item.

When you set color of your layout just access this array and check the corresponding position.

holder.linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
  @Override
  public boolean onLongClick(View v) {
    if (MySaveInstanceClass.selectStatusArray.get(posiiton) == true) {
      // set background color
    }
  }
}

Now you want to save state. You will have access to that array in your activity too.

There is a lifecycle method onDestroy() there you open your shared preference and save it. It will look something like this

Set<String> set = myScores.getStringSet("key", null);
//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();

Now you have your state saved. access the same shared preference in onStart() or onCreate() method and get the array and intitialize the class

MySaveInstanceClass.selectStatusArray = <array found from shared preference>;


来源: stackexchange

问:
> library(ez) Error: package or namespace load failed for ‘ez’ in loadNamespace
```<code>> library(ez)
</code>```

Error: package or namespace load failed for ‘ez’ in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]):
there is no package called ‘zip’

答:
You have to install the zip package manually and it will work.

```<code>install.packages("zip")
install.packages("ez")

library(ez)
</code>```

Warning message:
  Paket ‘ez’ wurde unter R Version 3.5.3 erstellt

Should work!

ContentLicense: CC BY-SA 4.0

Body:
> library(ez)

Error: package or namespace load failed for ‘ez’ in loadNamespace(j <- i[[1L]], c(lib.loc, .libPaths()), versionCheck = vI[[j]]):
there is no package called ‘zip’

Body:
You have to install the zip package manually and it will work.

install.packages("zip")
install.packages("ez")

library(ez)

Warning message:
  Paket ‘ez’ wurde unter R Version 3.5.3 erstellt

Should work!


问:
Count Instances of Class
I am looking for a way to programatically get the number of instances of a certain class type in .NET and Java.

Say for example I have class Foo.  I want to be able to, in the same process, get a current count of all instance of Foo.

However I cannot modify Foo, so a static int with counting is out.  Also I cannot just add all instances I make to some static list and count that.  I want to be able to just say:

```<code>System.GC.numberOf< Foo >()
</code>```

or something.

I was looking through the garbage collectors but I could not find any relevant methods.

答:
As already commented, there are similar questions in SO.

One hack you can use - a big one IMO - is to change the Object class: see this answer

Resume:

copy the source of Object

add counting to its constructor (finalize)

add method to read the count

prepend the directory with the compiled class to the boot classpath (-Xbootclasspath)

ContentLicense: CC BY-SA 3.0

Title: Count Instances of Class

Body:
I am looking for a way to programatically get the number of instances of a certain class type in .NET and Java.

Say for example I have class Foo.  I want to be able to, in the same process, get a current count of all instance of Foo.

However I cannot modify Foo, so a static int with counting is out.  Also I cannot just add all instances I make to some static list and count that.  I want to be able to just say:

System.GC.numberOf< Foo >()

or something.

I was looking through the garbage collectors but I could not find any relevant methods.


问:
Why react-native doesn't render all content when 2 render methods included in it?
I have some content to be rendered conditionally and some fixed content i.e. footer. I dont want to render footer every time when state changes, hence I've added two methods renderContent() and renderFooter to be called in render() method.

Below code, doesn't render both methods.

```<code>'use strict';

import React, { Component } from 'react';
import { Alert, FlatList, View, StyleSheet, Text, Linking, Button } from 'react-native';
import { AsyncStorage } from 'react-native';
import getEnvVars from '../environment';
const { apiUrl } = getEnvVars();
import Moment from 'moment';
import { Ionicons } from '@expo/vector-icons';
import FootBar from '../screens/FootBar';
import { LinesLoader } from 'react-native-indicator';

export default class SubscriptionsToEnd extends Component {
    static navigationOptions = ({ navigation }) => {
        const { state } = navigation;

        return {
            title: `${state.params && state.params.title ? state.params.title : 'Subscriptions Due'}`,
        };
    };

    constructor(props) {
        super(props);
        this.state = {
            isLoaded: false,
            dataSource: [],
            title: 'Subscriptions Due'
        };
    }

    componentDidMount() {
        this._getAllCustomers();
    }

    _getAllCustomers() {
        let url;
        if (this.state.title === 'Subscriptions Due') {
            url = apiUrl + "/customersWithSubscriptionNearToEnd/";
            this.props.navigation.setParams({ title: 'Subscriptions Due' })
        }
        if (this.state.title === 'Customers') {
            url = apiUrl + "/customers/";
            this.props.navigation.setParams({ title: 'Customers' })
        }

        this.setState({ isLoaded: false })

        try {
            AsyncStorage.multiGet(['role', 'jwt']).then((data) => {
                let role = data[0][1];
                let jwt = data[1][1];
                if (role === 'Admin') {
                    fetch(url, {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json',
                            'jwt': jwt
                        },
                    }).then(res => res.json())
                        .then(
                            (result) => {
                                if (result.message != 'Unauthorized user!' && this.state.title === 'Customers') {
                                    this.setState({
                                        isLoaded: true,
                                        dataSource: result,
                                        title: 'Subscriptions Due'

                                    });
                                } else if (result.message != 'Unauthorized user!' && this.state.title === 'Subscriptions Due') {
                                    this.setState({
                                        isLoaded: true,
                                        dataSource: result,
                                        title: 'Customers'

                                    });
                                } else if (result.message === 'Unauthorized user!') {
                                    this.props.navigation.navigate('Login');
                                }
                            },
                            (error) => {
                                console.log(error);
                                this.setState({
                                    isLoaded: true
                                });
                                this.props.navigation.navigate('Login');
                            }
                        )
                }
            })

        } catch (error) {
            console.log('Error at getting token \n' + error)
        }
    }

    GetGridViewItem(id) {
        Alert.alert(id);
    }

    _logOutAsync = async () => {
        await AsyncStorage.clear();
        this.props.navigation.navigate('Auth');
    };

    _addCustomer() {
        // TBD
    }

    renderContent() {
        if (!this.state.isLoaded) {
            return (
                <View style={styles.loader}>
                    <LinesLoader color='#1d91a5' barWidth={5} barHeight={60} barNumber={5} betweenSpace={5} />
                </View>
            )
        }

        if (this.state.isLoaded) {
            return (
                <View style={styles.container}>
                    <View style={styles.grid}>
                        <FlatList
                            data={this.state.dataSource}
                            renderItem={({ item }) =>
                                <View style={styles.GridViewContainer}>
                                    <Text style={styles.GridViewTextLayout}>
                                        <Text onPress={this.GetGridViewItem.bind(this, item._id)}>
                                            <Text style={styles.Name}>{item.firstname}</Text> <Text style={styles.Name}>{item.lastname}</Text> {"\n"}
                                            <Text>{Moment(item.till_date).format('Do MMM YYYY')} </Text>{"\n\n"}
                                        </Text>
                                        <Text onPress={() => { Linking.openURL('tel:+44' + item.mobile); }}><Ionicons name="md-phone-portrait" size={22} color="#1d91a5" />  {item.mobile}</Text> {"\n\n"}
                                        <Text><Ionicons name="md-mail" size={22} color="#1d91a5" />{item.email}</Text>
                                    </Text>
                                </View>}
                            numColumns={2}
                            keyExtractor={(item, index) => index.toString()}
                        />
                    </View >
                </View>
            )
        };
    }
    renderFooter() {
        return (
            <View style={styles.buttonsContainer}>
                <View style={styles.button}>
                    <Button color='#1d91a5' title={this.state.title} onPress={this._getAllCustomers.bind(this)} />
                </View>
                <View style={styles.button}>
                    <Button color='#1d91a5' title="+Customer" onPress={this._addCustomer.bind(this)} />
                </View>
                <View style={styles.button}>
                    <Button color='#1d91a5' title="Logout" onPress={this._logOutAsync.bind(this)} />
                </View>
            </View>
        );
    }

    render() {
        return (
            this.renderContent(),
            this.renderFooter()
        );
    }

}
</code>```

Above code only renders this.renderFooter() method. If I swap methods in render(), it renders this.renderContent().

Can someone please tell me why it is failing to render both?

答:
It looks like you figured it out just before I could post my answer.

The return function can only return one view. Your 2 functions each return a view. So wrapping both functions in a single view solves the problem.

Body:
I have some content to be rendered conditionally and some fixed content i.e. footer. I dont want to render footer every time when state changes, hence I've added two methods renderContent() and renderFooter to be called in render() method.

Below code, doesn't render both methods.

'use strict';

import React, { Component } from 'react';
import { Alert, FlatList, View, StyleSheet, Text, Linking, Button } from 'react-native';
import { AsyncStorage } from 'react-native';
import getEnvVars from '../environment';
const { apiUrl } = getEnvVars();
import Moment from 'moment';
import { Ionicons } from '@expo/vector-icons';
import FootBar from '../screens/FootBar';
import { LinesLoader } from 'react-native-indicator';

export default class SubscriptionsToEnd extends Component {
    static navigationOptions = ({ navigation }) => {
        const { state } = navigation;

        return {
            title: `${state.params && state.params.title ? state.params.title : 'Subscriptions Due'}`,
        };
    };

    constructor(props) {
        super(props);
        this.state = {
            isLoaded: false,
            dataSource: [],
            title: 'Subscriptions Due'
        };
    }

    componentDidMount() {
        this._getAllCustomers();
    }

    _getAllCustomers() {
        let url;
        if (this.state.title === 'Subscriptions Due') {
            url = apiUrl + "/customersWithSubscriptionNearToEnd/";
            this.props.navigation.setParams({ title: 'Subscriptions Due' })
        }
        if (this.state.title === 'Customers') {
            url = apiUrl + "/customers/";
            this.props.navigation.setParams({ title: 'Customers' })
        }

        this.setState({ isLoaded: false })

        try {
            AsyncStorage.multiGet(['role', 'jwt']).then((data) => {
                let role = data[0][1];
                let jwt = data[1][1];
                if (role === 'Admin') {
                    fetch(url, {
                        method: 'GET',
                        headers: {
                            'Content-Type': 'application/json',
                            'jwt': jwt
                        },
                    }).then(res => res.json())
                        .then(
                            (result) => {
                                if (result.message != 'Unauthorized user!' && this.state.title === 'Customers') {
                                    this.setState({
                                        isLoaded: true,
                                        dataSource: result,
                                        title: 'Subscriptions Due'

                                    });
                                } else if (result.message != 'Unauthorized user!' && this.state.title === 'Subscriptions Due') {
                                    this.setState({
                                        isLoaded: true,
                                        dataSource: result,
                                        title: 'Customers'

                                    });
                                } else if (result.message === 'Unauthorized user!') {
                                    this.props.navigation.navigate('Login');
                                }
                            },
                            (error) => {
                                console.log(error);
                                this.setState({
                                    isLoaded: true
                                });
                                this.props.navigation.navigate('Login');
                            }
                        )
                }
            })

        } catch (error) {
            console.log('Error at getting token \n' + error)
        }
    }

    GetGridViewItem(id) {
        Alert.alert(id);
    }

    _logOutAsync = async () => {
        await AsyncStorage.clear();
        this.props.navigation.navigate('Auth');
    };

    _addCustomer() {
        // TBD
    }

    renderContent() {
        if (!this.state.isLoaded) {
            return (
                <View style={styles.loader}>
                    <LinesLoader color='#1d91a5' barWidth={5} barHeight={60} barNumber={5} betweenSpace={5} />
                </View>
            )
        }

        if (this.state.isLoaded) {
            return (
                <View style={styles.container}>
                    <View style={styles.grid}>
                        <FlatList
                            data={this.state.dataSource}
                            renderItem={({ item }) =>
                                <View style={styles.GridViewContainer}>
                                    <Text style={styles.GridViewTextLayout}>
                                        <Text onPress={this.GetGridViewItem.bind(this, item._id)}>
                                            <Text style={styles.Name}>{item.firstname}</Text> <Text style={styles.Name}>{item.lastname}</Text> {"\n"}
                                            <Text>{Moment(item.till_date).format('Do MMM YYYY')} </Text>{"\n\n"}
                                        </Text>
                                        <Text onPress={() => { Linking.openURL('tel:+44' + item.mobile); }}><Ionicons name="md-phone-portrait" size={22} color="#1d91a5" />  {item.mobile}</Text> {"\n\n"}
                                        <Text><Ionicons name="md-mail" size={22} color="#1d91a5" />{item.email}</Text>
                                    </Text>
                                </View>}
                            numColumns={2}
                            keyExtractor={(item, index) => index.toString()}
                        />
                    </View >
                </View>
            )
        };
    }
    renderFooter() {
        return (
            <View style={styles.buttonsContainer}>
                <View style={styles.button}>
                    <Button color='#1d91a5' title={this.state.title} onPress={this._getAllCustomers.bind(this)} />
                </View>
                <View style={styles.button}>
                    <Button color='#1d91a5' title="+Customer" onPress={this._addCustomer.bind(this)} />
                </View>
                <View style={styles.button}>
                    <Button color='#1d91a5' title="Logout" onPress={this._logOutAsync.bind(this)} />
                </View>
            </View>
        );
    }

    render() {
        return (
            this.renderContent(),
            this.renderFooter()
        );
    }

}

Above code only renders this.renderFooter() method. If I swap methods in render(), it renders this.renderContent().

Can someone please tell me why it is failing to render both?


问:
Basic function call in node.js
If I write following code, I get "Hello World", but not "Hey from function". What am I doing wrong? Same if I try to write to console from called function. Seems it is not called.

This is very basic testing of node.js

```<code>const http = require('http');
const express = require('express');

const app = express();

const port = 3000;

function writetest(req, res) {
    res.send("Hey from function");
}

app.get('/nodejs/', function(req, res) {
    res.send('Hello World!');
    writetest(req,res);
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));
</code>```

No error messages, it just seems not to call he function.

答: You cant executeres.send twice in one api call.You can use if else loop to do such operation but at the same time two res.send cant execute.

Title: Basic function call in node.js

Body:
If I write following code, I get "Hello World", but not "Hey from function". What am I doing wrong? Same if I try to write to console from called function. Seems it is not called.

This is very basic testing of node.js

const http = require('http');
const express = require('express');

const app = express();

const port = 3000;

function writetest(req, res) {
    res.send("Hey from function");
}

app.get('/nodejs/', function(req, res) {
    res.send('Hello World!');
    writetest(req,res);
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

No error messages, it just seems not to call he function.


问:
Copy an image and preserve its EXIF/IPTC data with PHP imageCreateFromJpeg?
I having some problems with an image that has EXIF/IPTC data stored in it.

When I use imageCreateFromJpeg (to rotate/crop or etc) the newly stored file doesn't preserve the EXIF/IPTC data.

My current code looks like this:

```<code><?php
// Before executing - EXIF/IPTC data is there (checked)
$image = "/path/to/my/image.jpg";
$source = imagecreatefromjpeg($image);
$rotate = imagerotate($source,90,0);
imageJPEG($rotate,$image);
// After executing  - EXIF/IPTC data doesn't exist anymore.
?>
</code>```

Am I doing something wrong?

答:
Here is an example of image scaling using gd, and copying Exif and ICC color profile using PEL:

```<code>function scaleImage($inputPath, $outputPath, $scale) {
    $inputImage = imagecreatefromjpeg($inputPath);
    list($width, $height) = getimagesize($inputPath);
    $outputImage = imagecreatetruecolor($width * $scale, $height * $scale);
    imagecopyresampled($outputImage, $inputImage, 0, 0, 0, 0, $width * $scale, $height * $scale, $width, $height);
    imagejpeg($outputImage, $outputPath, 100);
}

function copyMeta($inputPath, $outputPath) {
    $inputPel = new \lsolesen\pel\PelJpeg($inputPath);
    $outputPel = new \lsolesen\pel\PelJpeg($outputPath);
    if ($exif = $inputPel->getExif()) {
        $outputPel->setExif($exif);
    }
    if ($icc = $inputPel->getIcc()) {
        $outputPel->setIcc($icc);
    }
    $outputPel->saveFile($outputPath);
}

copy('https://i.stack.imgur.com/p42W6.jpg', 'input.jpg');
scaleImage('input.jpg', 'without_icc.jpg', 0.2);
scaleImage('input.jpg', 'with_icc.jpg', 0.2);
copyMeta('input.jpg', 'with_icc.jpg');
</code>```

Output images:

Input image:

Body:
I having some problems with an image that has EXIF/IPTC data stored in it.

When I use imageCreateFromJpeg (to rotate/crop or etc) the newly stored file doesn't preserve the EXIF/IPTC data.

My current code looks like this:

<?php
// Before executing - EXIF/IPTC data is there (checked)
$image = "/path/to/my/image.jpg";
$source = imagecreatefromjpeg($image);
$rotate = imagerotate($source,90,0);
imageJPEG($rotate,$image);
// After executing  - EXIF/IPTC data doesn't exist anymore.
?>

Am I doing something wrong?

Body:
Here is an example of image scaling using gd, and copying Exif and ICC color profile using PEL:

function scaleImage($inputPath, $outputPath, $scale) {
    $inputImage = imagecreatefromjpeg($inputPath);
    list($width, $height) = getimagesize($inputPath);
    $outputImage = imagecreatetruecolor($width * $scale, $height * $scale);
    imagecopyresampled($outputImage, $inputImage, 0, 0, 0, 0, $width * $scale, $height * $scale, $width, $height);
    imagejpeg($outputImage, $outputPath, 100);
}

function copyMeta($inputPath, $outputPath) {
    $inputPel = new \lsolesen\pel\PelJpeg($inputPath);
    $outputPel = new \lsolesen\pel\PelJpeg($outputPath);
    if ($exif = $inputPel->getExif()) {
        $outputPel->setExif($exif);
    }
    if ($icc = $inputPel->getIcc()) {
        $outputPel->setIcc($icc);
    }
    $outputPel->saveFile($outputPath);
}

copy('https://i.stack.imgur.com/p42W6.jpg', 'input.jpg');
scaleImage('input.jpg', 'without_icc.jpg', 0.2);
scaleImage('input.jpg', 'with_icc.jpg', 0.2);
copyMeta('input.jpg', 'with_icc.jpg');

Output images:

Input image:


答:
Use res.write() and you have to call res.end() at the end.

Because res.send() calls res.end() internally and you can't write to res anymore

Title: Basic function call in node.js


问:
Get the sum of all collectionViewCells' heights inside a CollectionView
I have a CollectionView created inside CollectionView cell class.

The thing is I can't get the CollectionView that lives inside the first collectionView get the perfect size to fit all cells' sizes if any.

First level comments Line is the First CollectionView Cell, enclosing the second level comments(contentView is blue and the collectionView holding the cells is red)

I am using constraints to set the second collectionView height. It's basically fixed now.

I know how to make the comments cells have dynamic height, but how can I make the second collectionView have dynamic height to fit all cells if any?

Possible solution, doing something with:

```<code>for cell in collectionView.visibleCells as! [MyCellClass] {
   let sumOfAllCells += cell.frame.height

}
</code>```

答:
```<code>var height: CGFloat = 0
collectionView.visibleCells.forEach({ height += $0.bounds.height })
</code>```

Body:
I have a CollectionView created inside CollectionView cell class.

The thing is I can't get the CollectionView that lives inside the first collectionView get the perfect size to fit all cells' sizes if any.

First level comments Line is the First CollectionView Cell, enclosing the second level comments(contentView is blue and the collectionView holding the cells is red)

I am using constraints to set the second collectionView height. It's basically fixed now.

I know how to make the comments cells have dynamic height, but how can I make the second collectionView have dynamic height to fit all cells if any?

Possible solution, doing something with:

for cell in collectionView.visibleCells as! [MyCellClass] {
   let sumOfAllCells += cell.frame.height

}


问:
How to fix " [FirebaseMessaging] Unable to log event: analytics library is missing" in Xamarin.Android
I want to do FCM in Xamarin.Android.

So I following this tutorial (Xamarin.Android)Remote Notifications with Firebase Cloud Messaging to do.

but my phone can't receive message.

my output get :

[FirebaseMessaging] Unable to log event: analytics library is missing

I had add two NuGet:

Xamarin.GooglePlayServices.Base.

Xamarin.Firebase.Messaging.

I tried this Xamarin.Android

Updating Xamarin.Build.Download to 0.4.11

but it's still not working...

What can I do ?

答:
I am at the same step and faced the same situation, until I read forward and found this:

On the Android device (or emulator), background the app by tapping the Android Overview button and touching the home screen. When the device is ready, click SEND MESSAGE in the Firebase Console:

By doing it that way the message can be seen at the notification bar:

I am new to this but I am realizing that the purpose of this first test is to receive the message when the app is not in the foreground... See also: Send Message paragraph in the Remote Notifications with Firebase Cloud Messaging tutorial.


问:
Visual Studio Key Strokes: Swapping lines
Is there a keystroke in visual studio similar to Eclipse's Alt + ↑/↓?

For example:

```<code>int x = 0; // Cursor is anywhere on this line.
int y = 1;
</code>```

and Alt + Down were pressed, then:

```<code>int y = 1;
int x = 0; // Cursor is anywhere on this line.
</code>```

答:
As an alternative solution, you could write a Visual Studio Extension to do this for you. Extensions are written in your favorite .NET language.

Refer to the MSDN article on creating Visual Studio Extensions for more information.

Body:
Is there a keystroke in visual studio similar to Eclipse's Alt + ↑/↓?

For example:

int x = 0; // Cursor is anywhere on this line.
int y = 1;

and Alt + Down were pressed, then:

int y = 1;
int x = 0; // Cursor is anywhere on this line.


问:
Updating a WordPress site and database from Localhost to third-party host using FTP
Following this tutorial, https://medium.com/pen-bold-kiln-press/making-a-wordpress-website-live-from-localhost-198026ccd1c0 I've:

1.) Export localhost database from phpmyadmin

2.) Upload localhost files to live site through FTP

3.) Create a new MySQL database for the new site

4.) Import the localhost database to the live database

5.) Change the site URL and home in the database

6.) Configure wp.config on the live site

I am used to making webpages without Wordpress (custom html + css) and then just uploading the files to public.html....

My question is: If/when I make changes to the site on localhost, do I have to export the database and create a new MySQL database on the webhost each time or can I simply upload the wordpress files to publichtml each time to see my changes.

Do I only need to export the database once, on the initial push live?

(I make alot of changes usually)

答:
If you change only theme file html+css or PHP to change view or print something, so not. You need to upload only changed files, without database.

If you make changes thru admin panel, like install plugins or change some option on a site then you need to update DB.

Also if you create some PHP code that change database like create something( new DB tables, change info inside tables, etc).


问:
Search substring in a string using regex
I'm trying to search for a set of words, contained within an ArrayList(terms_1pers), inside a string and, since the precondition is that before and after the search word there should be no letters, I thought of using expression regular.

I just don't know what I'm doing wrong using the matches operator. In the code reported, if the matching is not verified, it writes to an external file.

```<code>String url = csvRecord.get("url");
String text = csvRecord.get("review");
String var = null;
for(String term : terms_1pers)
{
   if(!text.matches("[^a-z]"+term+"[^a-z]"))
   {
      var="true";
   }
}
if(!var.equals("true"))
{
    bw.write(url+";"+text+"\n");
}
</code>```

答:
There are several things to note:

matches requires a full string match, so [^a-z]term[^a-z] will only match a string like :term.. You need to use .find() to find partial matches

If you pass a literal string to a regex, you need to Pattern.quote it, or if it contains special chars, it will not get matched

To check if a word has some pattern before or after or at the start/end, you should either use alternations with anchors (like (?:^|[^a-z]) or (?:$|[^a-z])) or lookarounds, (?<![a-z]) and (?![a-z]).

To match any letter just use \p{Alpha} or - if you plan to match any Unicode letter - \p{L}.

The var variable is more logical to set to Boolean type.

Fixed code:

```<code>String url = csvRecord.get("url");
String text = csvRecord.get("review");
Boolean var = false;
for(String term : terms_1pers)
{
   Matcher m = Pattern.compile("(?<!\\p{L})" + Pattern.quote(term) + "(?!\\p{L})").matcher(text);
   // If the search must be case insensitive use
   // Matcher m = Pattern.compile("(?i)(?<!\\p{L})" + Pattern.quote(term) + "(?!\\p{L})").matcher(text);
   if(!m.find())
   {
       var = true;
   }
}
if (!var) {
   bw.write(url+";"+text+"\n");
}
</code>```

Body:
I'm trying to search for a set of words, contained within an ArrayList(terms_1pers), inside a string and, since the precondition is that before and after the search word there should be no letters, I thought of using expression regular.

I just don't know what I'm doing wrong using the matches operator. In the code reported, if the matching is not verified, it writes to an external file.

String url = csvRecord.get("url");
String text = csvRecord.get("review");
String var = null;
for(String term : terms_1pers)
{
   if(!text.matches("[^a-z]"+term+"[^a-z]"))
   {
      var="true";
   }
}
if(!var.equals("true"))
{
    bw.write(url+";"+text+"\n");
}

Body:
There are several things to note:

matches requires a full string match, so [^a-z]term[^a-z] will only match a string like :term.. You need to use .find() to find partial matches

If you pass a literal string to a regex, you need to Pattern.quote it, or if it contains special chars, it will not get matched

To check if a word has some pattern before or after or at the start/end, you should either use alternations with anchors (like (?:^|[^a-z]) or (?:$|[^a-z])) or lookarounds, (?<![a-z]) and (?![a-z]).

To match any letter just use \p{Alpha} or - if you plan to match any Unicode letter - \p{L}.

The var variable is more logical to set to Boolean type.

Fixed code:

String url = csvRecord.get("url");
String text = csvRecord.get("review");
Boolean var = false;
for(String term : terms_1pers)
{
   Matcher m = Pattern.compile("(?<!\\p{L})" + Pattern.quote(term) + "(?!\\p{L})").matcher(text);
   // If the search must be case insensitive use
   // Matcher m = Pattern.compile("(?i)(?<!\\p{L})" + Pattern.quote(term) + "(?!\\p{L})").matcher(text);
   if(!m.find())
   {
       var = true;
   }
}
if (!var) {
   bw.write(url+";"+text+"\n");
}


问:
Multiprocessing/multithreading for database query in Python
I have millions of records in database and I want to read it through Python and store it in pandas data frame .
The problem is the select query processing time is very high.
To reduce the query processing time I try to perform multi threading on it
I created 3 threads and make the query on basis of each thread like

```<code>Select * from ( select *,rownum over (order by col1) rn from table) where rn%3=0

Select * from ( select *,rownum over (order by col1) rn from table) where rn%3=1

Select * from ( select *,rownum over (order by col1) rn from table) where rn%3=2
</code>```

Then I run the each query with threading in Python by threading package.

But it also not reducing the time much

Is there any other approach I can take to reduce the query  reading time.
Note- I have used both jdbc and odbc connection

答:
The below link helped me
Multiprocessing with JDBC connection and pooling
I can get around 25%  gain on my local.machine.</p>

Body:
I have millions of records in database and I want to read it through Python and store it in pandas data frame .
The problem is the select query processing time is very high.
To reduce the query processing time I try to perform multi threading on it
I created 3 threads and make the query on basis of each thread like

Select * from ( select *,rownum over (order by col1) rn from table) where rn%3=0

Select * from ( select *,rownum over (order by col1) rn from table) where rn%3=1

Select * from ( select *,rownum over (order by col1) rn from table) where rn%3=2

Then I run the each query with threading in Python by threading package.

But it also not reducing the time much

Is there any other approach I can take to reduce the query  reading time.
Note- I have used both jdbc and odbc connection


问:
Model.Classify() gives GL_INVALID_OPERATION: Object cannot be used because it has not been generated
https://github.com/tensorflow/tfjs/issues/1384#issue-421174127

TensorFlow.js version
1.0.0

Browser version
Google Chrome: Version 73.0.3683.75 (Official Build) (64-bit)

Describe the problem or feature request

I followed the steps from Google Codelab: https://codelabs.developers.google.com/codelabs/tensorflowjs-teachablemachine-codelab/index.html#0

The given example works fine, but when I made some changes to the example for my Blog with multiple images, it gives this error:

As you can see, when I click on the first image, it works fine. Loads the model, does classification, displays the results. As I click on a second image, it gives these errors. This seems to be happening on this Windows Laptop [Dell Inspiron, Windows 10] with this Version of Chrome only as I am also testing the same thing on a MacBook Pro with the exact same version of Chrome without any errors.

Code to reproduce the bug/link to feature request

You can check my Blog here [https://anujdutt9.github.io/TFjs-ImageClassifier.html] and look for errors in the console. Also, you can find the complete code for this here [https://github.com/anujdutt9/anujdutt9.github.io/blob/master/TFjs-ImageClassifier.html].

答: This issue was resolved by using an updated version of TensorFlow.js. Take a look at the code with the update here: https://github.com/anujdutt9/anujdutt9.github.io/blob/master/TFjs-ImageClassifier.html</p>


问:
Removing white space at the beginning of values in multiple columns

I found a solution to this:

df['Name']=df['Name'].str.lstrip
df['Parent']=df['Name'].str.lstrip

I have this DataFrame df (there is a white space at the left of "A" and "C" in the second row (which doesn't show well here). I would like to remove that space.

Mark    Name    Parent  age

10  A   C   1

12   A   C  2

13  B   D   3

I tried

df['Name'].str.lstrip()

df['Parent'].str.lstrip()

then tried

df.to_excel('test.xlsx')

but the result in excel didn't remove the white spaces

I then tried defining another variable

x=df['Name'].str.lstrip

x.to_excel('test.xlsx')

that worked fine in Excel, but this is a new dataFrame, and only had the x column

I then tried repeating the same for 'Parent', and to play around with joining multiple dataframes to the original dataframe, but I still couldnt' get it to work, and that seems too convoluted anyway

Finally, even if my first attempt had worked, I would like to be able to replace the white spaces in one go, without having to do a separate call for each column name

答:
You could try using

df['Name'].replace(" ", "")

this would delete all whitespaces though.


问:
Remove first element of JSON object array
I'm struggling to find a way to cut down this JSON array so I can use the values remaining. Below is what's returned to me from the API I'm fetching and I'm looking to remove the excess so I just have an array with the LGA results. Really unsure where to even start.</p>

```<code>{
  "query": {
    "offence": "Dangerous Operation of a Vehicle",
    "area": "",
    "age": "",
    "year": "",
    "gender": ""
  },
  "result": [
    {
      "LGA": "Aurukun Shire Council",
      "total": 156,
      "lat": -13.354875,
      "lng": 141.729058
    },
    {
      "LGA": "Balonne Shire Council",
      "total": 99,
      "lat": -28.464607,
      "lng": 148.189292
    },
    {
      "LGA": "Yarrabah Shire Council",
      "total": 28,
      "lat": -16.910135,
      "lng": 145.868659
    }
  ]
}
</code>```

答:
If I am reading your question correctly, you want to get a string array containing the LGA properties:

```<code>const data = {
  query: {
    offence: "Dangerous Operation of a Vehicle",
    area: "",
    age: "",
    year: "",
    gender: ""
  },
  result: [{}, {}] // your current large array
};

const lgaArray = data.result.map(({ LGA }) => ({ LGA }));

console.table(lgaArray);

</code>```

A screenshot to give a visual aid:

Body:
I'm struggling to find a way to cut down this JSON array so I can use the values remaining. Below is what's returned to me from the API I'm fetching and I'm looking to remove the excess so I just have an array with the LGA results. Really unsure where to even start.

{
  "query": {
    "offence": "Dangerous Operation of a Vehicle",
    "area": "",
    "age": "",
    "year": "",
    "gender": ""
  },
  "result": [
    {
      "LGA": "Aurukun Shire Council",
      "total": 156,
      "lat": -13.354875,
      "lng": 141.729058
    },
    {
      "LGA": "Balonne Shire Council",
      "total": 99,
      "lat": -28.464607,
      "lng": 148.189292
    },
    {
      "LGA": "Yarrabah Shire Council",
      "total": 28,
      "lat": -16.910135,
      "lng": 145.868659
    }
  ]
}

Body:
If I am reading your question correctly, you want to get a string array containing the LGA properties:

const data = {
  query: {
    offence: "Dangerous Operation of a Vehicle",
    area: "",
    age: "",
    year: "",
    gender: ""
  },
  result: [{}, {}] // your current large array
};

const lgaArray = data.result.map(({ LGA }) => ({ LGA }));

console.table(lgaArray);

A screenshot to give a visual aid:


问:
How to generate table using Python
I am quite struggling with as I tried many libraries to print table but no success - so I thought to post here and ask.

My data is in a text file (resource.txt) which looks like this (the exact same way it prints)

```<code>pipelined  8   8  0  17  0   0
nonpipelined  2 2  0  10  0  0
</code>```

I want my data print in the following manner

```<code>Design name       LUT       Lut as m    Lut as I    FF  DSP   BRAM
-------------------------------------------------------------------
pipelined          8          8            0        17  0      0
Non piplined       2          2            0        10  0      0
</code>```

Some time data may be more line column remain same but rows may increase.

(i have python 2.7 version)

I am using this part in my python code all code working but am couldn't able print data which i extracted to text file in tabular form. As I can't use panda library as it won't support for python 2.7, but I can use tabulate and all library. Can anyone please help me?

I tried using tabulate and all but I keep getting errors.

I tried at end simple method to print but its not working (same code works if I put at top of code but at the end of code this won't work). Does anyone have any idea?

```<code>q11=open( "resource.txt","r")
for line in q11:
   print(line)
</code>```

答:
Here's a self contained function that makes a left-justified, technical paper styled table.

```<code>def makeTable(headerRow,columnizedData,columnSpacing=2):
    """Creates a technical paper style, left justified table

    Author: Christopher Collett
    Date: 6/1/2019"""
    from numpy import array,max,vectorize

    cols = array(columnizedData,dtype=str)
    colSizes = [max(vectorize(len)(col)) for col in cols]

    header = ''
    rows = ['' for i in cols[0]]

    for i in range(0,len(headerRow)):
        if len(headerRow[i]) > colSizes[i]: colSizes[i]=len(headerRow[i])
        headerRow[i]+=' '*(colSizes[i]-len(headerRow[i]))
        header+=headerRow[i]
        if not i == len(headerRow)-1: header+=' '*columnSpacing

        for j in range(0,len(cols[i])):
            if len(cols[i][j]) < colSizes[i]:
                cols[i][j]+=' '*(colSizes[i]-len(cols[i][j])+columnSpacing)
            rows[j]+=cols[i][j]
            if not i == len(headerRow)-1: rows[j]+=' '*columnSpacing

    line = '-'*len(header)
    print(line)
    print(header)
    print(line)
    for row in rows: print(row)
    print(line)
</code>```

And here's an example using this function.

```<code>>>> header = ['Name','Age']
>>> names = ['George','Alberta','Frank']
>>> ages = [8,9,11]
>>> makeTable(header,[names,ages])
------------
Name     Age
------------
George   8
Alberta  9
Frank    11
------------
</code>```

Title: How to generate table using Python

Body:
I am quite struggling with as I tried many libraries to print table but no success - so I thought to post here and ask.

My data is in a text file (resource.txt) which looks like this (the exact same way it prints)

pipelined  8   8  0  17  0   0
nonpipelined  2 2  0  10  0  0

I want my data print in the following manner

Design name       LUT       Lut as m    Lut as I    FF  DSP   BRAM
-------------------------------------------------------------------
pipelined          8          8            0        17  0      0
Non piplined       2          2            0        10  0      0

Some time data may be more line column remain same but rows may increase.

(i have python 2.7 version)

I am using this part in my python code all code working but am couldn't able print data which i extracted to text file in tabular form. As I can't use panda library as it won't support for python 2.7, but I can use tabulate and all library. Can anyone please help me?

I tried using tabulate and all but I keep getting errors.

I tried at end simple method to print but its not working (same code works if I put at top of code but at the end of code this won't work). Does anyone have any idea?

q11=open( "resource.txt","r")
for line in q11:
   print(line)

Body:
Here's a self contained function that makes a left-justified, technical paper styled table.

def makeTable(headerRow,columnizedData,columnSpacing=2):
    """Creates a technical paper style, left justified table

    Author: Christopher Collett
    Date: 6/1/2019"""
    from numpy import array,max,vectorize

    cols = array(columnizedData,dtype=str)
    colSizes = [max(vectorize(len)(col)) for col in cols]

    header = ''
    rows = ['' for i in cols[0]]

    for i in range(0,len(headerRow)):
        if len(headerRow[i]) > colSizes[i]: colSizes[i]=len(headerRow[i])
        headerRow[i]+=' '*(colSizes[i]-len(headerRow[i]))
        header+=headerRow[i]
        if not i == len(headerRow)-1: header+=' '*columnSpacing

        for j in range(0,len(cols[i])):
            if len(cols[i][j]) < colSizes[i]:
                cols[i][j]+=' '*(colSizes[i]-len(cols[i][j])+columnSpacing)
            rows[j]+=cols[i][j]
            if not i == len(headerRow)-1: rows[j]+=' '*columnSpacing

    line = '-'*len(header)
    print(line)
    print(header)
    print(line)
    for row in rows: print(row)
    print(line)

And here's an example using this function.

>>> header = ['Name','Age']
>>> names = ['George','Alberta','Frank']
>>> ages = [8,9,11]
>>> makeTable(header,[names,ages])
------------
Name     Age
------------
George   8
Alberta  9
Frank    11
------------


问:
java.time.DateTimeException: Invalid ID for region-based ZoneId, invalid format: Java
I want to get by city UTC and GMT time without underscore. Firstly, I'm writting to get zone ids:

```<code> List<String> utc = new ArrayList<>(ZoneId.getAvailableZoneIds());
 List<String> gmt = new ArrayList<>(ZoneId.getAvailableZoneIds());
</code>```

But I have underscore and I'm changing to empty space:

```<code>  List<String> newList_utc = new ArrayList<>();
  List<String> newList_gmt = new ArrayList<>();

    for (String anUtc : utc) {
        if (anUtc.contains("_")) {
            newList_utc.add(anUtc.replace("_", " "));
        } else {
            newList_utc.add(anUtc);
        }
    }

    for (String aGmt : gmt) {
        if (aGmt.contains("_")) {
            newList_gmt.add(aGmt.replace("_", " "));
        } else {
            newList_gmt.add(aGmt);
        }
    }
</code>```

After splitting I have specific city, e.g. - El Salvador. Before splitting and changing was America/El_Salvador as format.

And I'm using the following code to output time zones with offset:

```<code>newList_utc.stream().filter(it -> it.contains("El Salvador")).collect(Collectors.toList());
newList_utc.stream().filter(it -> it.contains("America/El Salvador")).map(Class::getOffset).collect(Collectors.toList());

...
...

private static String getOffset(String zone) {
       ZonedDateTime zdt = LDT.atZone(ZoneId.of(zone));
       return zdt.getOffset().getId().replace("Z", "+00:00");
}
</code>```

Finally, I get the error:

```<code>java.time.DateTimeException: Invalid ID for region-based ZoneId, invalid format: America/El Salvador
    at java.time.ZoneRegion.checkName(ZoneRegion.java:151)
    at java.time.ZoneRegion.ofId(ZoneRegion.java:116)
    at java.time.ZoneId.of(ZoneId.java:411)
    at java.time.ZoneId.of(ZoneId.java:359)
    at project.Bot.getOffset(Bot.java:5822)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
    at project.Bot.getOutputZone(Bot.java:6070)
    at project.Bot.getTimeZone(Bot.java:6041)
    at project.Bot.onUpdateReceived(Bot.java:399)
</code>```

During debugging, it happens because of getOffset()method on this line ZonedDateTime zdt = LDT.atZone(ZoneId.of(zone)); where I set America/El Salvador. If I write America/El_Salvador then I don't have this issue.

But why I can't use empty space instead of underscore?

答:
Time Zone IDs are actually not defined by Java standard, but outside of Java in a data set known as the tz database which is a public domain time zone standard, designed for interoperability between applications and programming languages.

The rules behind time zone names are:

The time zones have unique names in the form "Area/Location", e.g. "America/New_York". A choice was also made to use English names or equivalents, and to omit punctuation and common suffixes. The underscore character is used in place of spaces. Hyphens are used where they appear in the name of a location. The Area and Location names have a maximum length of 14 characters.

So, the underscore is required based on the format, so using time zones with spaces instead of underscores will not work, not because Java doesn't support it, but because there is no matching tz entry for it.

If you want to convert from a tz to a clean display, you can replace the underscores with a space, and vice versa to convert a clean display back into a timezone id.

Ref: relatively current tz codes

Body:
I want to get by city UTC and GMT time without underscore. Firstly, I'm writting to get zone ids:

 List<String> utc = new ArrayList<>(ZoneId.getAvailableZoneIds());
 List<String> gmt = new ArrayList<>(ZoneId.getAvailableZoneIds());

But I have underscore and I'm changing to empty space:

  List<String> newList_utc = new ArrayList<>();
  List<String> newList_gmt = new ArrayList<>();

    for (String anUtc : utc) {
        if (anUtc.contains("_")) {
            newList_utc.add(anUtc.replace("_", " "));
        } else {
            newList_utc.add(anUtc);
        }
    }

    for (String aGmt : gmt) {
        if (aGmt.contains("_")) {
            newList_gmt.add(aGmt.replace("_", " "));
        } else {
            newList_gmt.add(aGmt);
        }
    }

After splitting I have specific city, e.g. - El Salvador. Before splitting and changing was America/El_Salvador as format.

And I'm using the following code to output time zones with offset:

newList_utc.stream().filter(it -> it.contains("El Salvador")).collect(Collectors.toList());
newList_utc.stream().filter(it -> it.contains("America/El Salvador")).map(Class::getOffset).collect(Collectors.toList());

...
...

private static String getOffset(String zone) {
       ZonedDateTime zdt = LDT.atZone(ZoneId.of(zone));
       return zdt.getOffset().getId().replace("Z", "+00:00");
}

Finally, I get the error:

java.time.DateTimeException: Invalid ID for region-based ZoneId, invalid format: America/El Salvador
    at java.time.ZoneRegion.checkName(ZoneRegion.java:151)
    at java.time.ZoneRegion.ofId(ZoneRegion.java:116)
    at java.time.ZoneId.of(ZoneId.java:411)
    at java.time.ZoneId.of(ZoneId.java:359)
    at project.Bot.getOffset(Bot.java:5822)
    at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
    at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
    at project.Bot.getOutputZone(Bot.java:6070)
    at project.Bot.getTimeZone(Bot.java:6041)
    at project.Bot.onUpdateReceived(Bot.java:399)

During debugging, it happens because of getOffset()method on this line ZonedDateTime zdt = LDT.atZone(ZoneId.of(zone)); where I set America/El Salvador. If I write America/El_Salvador then I don't have this issue.

But why I can't use empty space instead of underscore?


问:
pointers between dynamic structs memory
I am trying to solve a little problem from my university, but i get into trouble completing it.

The task is to write a code defining all the data structures and create a link between them using pointers and mallocs.

ASSIGNMENT :

There are 3 blocks.
1) is a static block with 2 fields, 1st field is an integer, and a second field points to another block.

2) a block with 2 fields. 1st field points to the first block and 2nd field points to the 3rd block.

3) a block with 2 fields. 1st field is an integer and 2nd field points to the first block.

I have started creating the code and making the links but i keep getting errors which i cant seem to find thier logic.

```<code>struct A;
struct B;
struct C;
typedef struct {
int element;
struct A * pointer3;
}C;

typedef struct {
    struct A * pointer 1;
    struct C * pointer 2;
}B;

typedef struct {
    int element;
    struct B * pointer 0;
 }A;

int main (){
    A a;
    a.pointer0 = (B*)malloc(sizeof(B));
</code>```

I have reached farther then that, but the problem i get is in the last line.
Gives me the error warning: assignment from incompatible pointer type

答:
Question: What does struct A look like? Answer: Your compiler has no idea because you never defined it.

You're assuming forward-declaring a structure type, then formally declaring a typedef alias to a structure where the alias name (but not tag) is the same as the structure tag (with no name) will resolve. It won't. You have to do that yourself.

Start with simple. Get rid of the type aliases entirely. And get rid of any unnecessary forward decls as well (B and C) What would it look like?

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

struct A; // fwd decl

struct C
{
    int element;
    struct A *pointer3; // uses fwd decl
};

struct B
{
    struct A *pointer1; // uses fwd decl
    struct C *pointer2; // uses prior def
};

struct A // resolves fwd decl
{
    int element;
    struct B *pointer0; // uses prior def
};

int main()
{
    struct A a;
    a.pointer0 = malloc(sizeof(struct B));
}
</code>```

That works (in the most optimistic definition of the term). If you want to use typedef aliases, you can add them in now. For example, here is all three structures both tagged and aliased.

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

struct A;
typedef struct A A;

typedef struct C
{
    int element;
    A *pointer3;
} C;

typedef struct B
{
    A *pointer1;
    C *pointer2;
} B;

struct A
{
    int element;
    B *pointer0;
};

int main()
{
    A a;
    a.pointer0 = malloc(sizeof(B));
}
</code>```

Title: pointers between dynamic structs memory

Body:
I am trying to solve a little problem from my university, but i get into trouble completing it.

The task is to write a code defining all the data structures and create a link between them using pointers and mallocs.

ASSIGNMENT :

There are 3 blocks.
1) is a static block with 2 fields, 1st field is an integer, and a second field points to another block.

2) a block with 2 fields. 1st field points to the first block and 2nd field points to the 3rd block.

3) a block with 2 fields. 1st field is an integer and 2nd field points to the first block.

I have started creating the code and making the links but i keep getting errors which i cant seem to find thier logic.

struct A;
struct B;
struct C;
typedef struct {
int element;
struct A * pointer3;
}C;

typedef struct {
    struct A * pointer 1;
    struct C * pointer 2;
}B;

typedef struct {
    int element;
    struct B * pointer 0;
 }A;

int main (){
    A a;
    a.pointer0 = (B*)malloc(sizeof(B));

I have reached farther then that, but the problem i get is in the last line.
Gives me the error warning: assignment from incompatible pointer type

Body:
Question: What does struct A look like? Answer: Your compiler has no idea because you never defined it.

You're assuming forward-declaring a structure type, then formally declaring a typedef alias to a structure where the alias name (but not tag) is the same as the structure tag (with no name) will resolve. It won't. You have to do that yourself.

Start with simple. Get rid of the type aliases entirely. And get rid of any unnecessary forward decls as well (B and C) What would it look like?

#include <stdio.h>
#include <stdlib.h>

struct A; // fwd decl

struct C
{
    int element;
    struct A *pointer3; // uses fwd decl
};

struct B
{
    struct A *pointer1; // uses fwd decl
    struct C *pointer2; // uses prior def
};

struct A // resolves fwd decl
{
    int element;
    struct B *pointer0; // uses prior def
};

int main()
{
    struct A a;
    a.pointer0 = malloc(sizeof(struct B));
}

That works (in the most optimistic definition of the term). If you want to use typedef aliases, you can add them in now. For example, here is all three structures both tagged and aliased.

#include <stdio.h>
#include <stdlib.h>

struct A;
typedef struct A A;

typedef struct C
{
    int element;
    A *pointer3;
} C;

typedef struct B
{
    A *pointer1;
    C *pointer2;
} B;

struct A
{
    int element;
    B *pointer0;
};

int main()
{
    A a;
    a.pointer0 = malloc(sizeof(B));
}


问:
connect to mongodb in docker from node app in AWS SAM
I am getting errors connecting to mongodb running in a docker container from my Nodejs app running in AWS SAM (used to say "in my host").

I run mongodb like:

```<code>$ docker run --name mongo-myapp --rm -d -p 27018:27017 mongo
</code>```

and I see the results:

```<code>$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                      NAMES
ab8248d17d2d        mongo               "docker-entrypoint.s…"   6 minutes ago       Up 6 minutes        0.0.0.0:27018->27017/tcp   mongo-myapp
</code>```

~~I can successfully connect and insert data using clients running on my host like MongoDB Compass and Robo 3T Community Edition, specifying port 27018.~~

When I attempt to connect with this code running on my host, (not in a docker container):

```<code>const { MongoClient } = require('mongodb');
const mongoConnection = 'mongodb://127.0.0.1:27018';
MongoClient.connect(mongoConnection, (err, db) => {
    if (err) {
        console.error("Failed to connect to mongodb server", err);
        return reject(err);
    }
    console.log("Connected successfully to mongodb server");
    resolve(db);
});
</code>```

I always see the error:

MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27018

I get the same error using another port with all steps, like 27017.

UPDATE

It turns out my code was not running on the host. It was running in another docker container. I did not realize AWS SAM would put my code into a docker container so I did not mention it in the original question.

Now I run my code with mocha test to make sure it will run on my host, and it connects to the mongo database with no problems.

When I launched a local server using AWS SAM's start-api, I had problems. Perhaps the solution will be to specify a network when starting the mongo container as well as the SAM environment.

答:
Install the necessary dependency for mongodb in node.js https://www.npmjs.com/package/mongodb

```<code>const MongoClient = require('mongodb').MongoClient;

const url = "mongodb://localhost:27018/testdb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Database created!");
  db.close();
});
</code>```

Body:
I am getting errors connecting to mongodb running in a docker container from my Nodejs app running in AWS SAM (used to say "in my host").

I run mongodb like:

$ docker run --name mongo-myapp --rm -d -p 27018:27017 mongo

and I see the results:

$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                      NAMES
ab8248d17d2d        mongo               "docker-entrypoint.s…"   6 minutes ago       Up 6 minutes        0.0.0.0:27018->27017/tcp   mongo-myapp

~~I can successfully connect and insert data using clients running on my host like MongoDB Compass and Robo 3T Community Edition, specifying port 27018.~~

When I attempt to connect with this code running on my host, (not in a docker container):

const { MongoClient } = require('mongodb');
const mongoConnection = 'mongodb://127.0.0.1:27018';
MongoClient.connect(mongoConnection, (err, db) => {
    if (err) {
        console.error("Failed to connect to mongodb server", err);
        return reject(err);
    }
    console.log("Connected successfully to mongodb server");
    resolve(db);
});

I always see the error:

MongoNetworkError: connect ECONNREFUSED 127.0.0.1:27018

I get the same error using another port with all steps, like 27017.

UPDATE

It turns out my code was not running on the host. It was running in another docker container. I did not realize AWS SAM would put my code into a docker container so I did not mention it in the original question.

Now I run my code with mocha test to make sure it will run on my host, and it connects to the mongo database with no problems.

When I launched a local server using AWS SAM's start-api, I had problems. Perhaps the solution will be to specify a network when starting the mongo container as well as the SAM environment.

Body:
Install the necessary dependency for mongodb in node.js https://www.npmjs.com/package/mongodb

const MongoClient = require('mongodb').MongoClient;

const url = "mongodb://localhost:27018/testdb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Database created!");
  db.close();
});


问:
It seems like laravel boot Trait doesn't work
Recently I'm having problems with using traits, I created some before and it seemed to work, but now I created another one to take action on a creating event, here it is

```<code>trait Contributes
{

public static function bootContributes()
{
    static::creating(function ($model) {
        if (!$model->getKey())
        {
            Contribution::create([
                'contributing_id' => $model->id,
                'contributing_type' => $model->class_table,
            ]);
        }
    });
}

}
</code>```

and I included it in multiple models like use Contributes; I think there is something I don't know about it.

I tried dd($model); inside the trait, it works outside of the event but not inside the event

答:
Instead of the above method, I figured this one is a better practice and works a lot more better with laravel:</p>

```<code>public static function boot()
{
    self::created(
        function($model)
        {
            Contribution::create([
                'contributing_id' => $model->id,
                'contributing_type' => $model->table
            ]);
        }
    );
}
</code>```

Body:
Recently I'm having problems with using traits, I created some before and it seemed to work, but now I created another one to take action on a creating event, here it is

trait Contributes
{

public static function bootContributes()
{
    static::creating(function ($model) {
        if (!$model->getKey())
        {
            Contribution::create([
                'contributing_id' => $model->id,
                'contributing_type' => $model->class_table,
            ]);
        }
    });
}

}

and I included it in multiple models like use Contributes; I think there is something I don't know about it.

I tried dd($model); inside the trait, it works outside of the event but not inside the event

Body:
Instead of the above method, I figured this one is a better practice and works a lot more better with laravel:

public static function boot()
{
    self::created(
        function($model)
        {
            Contribution::create([
                'contributing_id' => $model->id,
                'contributing_type' => $model->table
            ]);
        }
    );
}


问:
Dynamically created form values persisting after postback
I have a usercontrol which contains dynamically generated webcontrols (TextBox, DropDownList, etc...)

The usercontrol is loaded on certain button click events.

On the usercontrol, there are occasionally postback events which need to be processed (Button.OnClick, etc...).

In order to accommodate the fact that the usercontrol is loaded on a click event, during Page_Load() of the usercontrol's parents, I'm re-executing the code that loads the usercontrol.

IE - I have, essentially, the following:

```<code>public partial class parentPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        If(Page.IsPostBack)
        {
            // Conditions are usually here to make sure this only happens when I want it to
            userControl.LoadUserControl();
        }
    }

    protected void Button_Click(object sender, EventArgs e)
    {
        userControl.LoadUserControl();
    }
}

public partial class userControl : System.Web.UI.UserControl
{
    public void LoadUserControl()
    {
        // Generate dynamic controls and bind events
    }

    protected void Button_Click(object sender, EventArgs e)
    {
        // Do stuff
    }
}
</code>```

The problem I'm facing is that, after the Button_Click() event of the usercontrol is processed, the next time I click the button on the parent, the usercontrol's dynamically generated fields are somehow being automatically populated by what they were before the usercontrol's button was clicked - despite the fact that I'm explicitly setting the values when the LoadUserControl() function is called during the parent's button click.

What's even stranger is that the fields which are populated aren't necessarily consistent. In some cases TextBoxes have the correct text but DropDownLists have the old selected item. In other cases, DropDownLists are properly selected, but the TextBoxes retain the old text.

Does anyone have any suggestions or insights? I've tried a million different ideas and nothing seems to work.

** EDIT **

A bit of insight, perhaps - if I set the usercontrol to ViewStateMode=Disabled, it seems to solve the problem. I am reluctant to do this though, as I'm really not sure whether it will affect other functionality. I've already discovered a few glitches with the change, and I've a feeling even if I fix those, I'll end up finding more later. So hopefully any solution will not require such a drastic change. Perhaps the fact that it does solve this problem may help find a more elegant solution, though?

** EDIT 2 **

Debugging using dotPeek into the framework for System.Web.UI.ControlCollection.Add() reveals that, after adding the control to the collection, System.Web.UI.Control.AddedControl() is called. At the end of that, System.Web.UI.Control.LoadViewStateRecursive() is called. It's within there that the trouble arises. Despite the fact that this is a dynamically generated control, it still seems to persist in the ViewState. Continuing to dig...

答:
Alright! After two days of debugging through the deep, dark innards of the .NET Framework, I've finally arrived at a solution.

I'm still not really sure why this problem is happening, but the solution was to disable the ViewState for the controls which I want to manually load, but only on initial load.

Since the loading of the controls is happening on Postback, I couldn't go with a simple if(!Page.IsPostBack) option, so what I did use a function which I'd already written, that returns the Postback Control ID of the control doing the Postback. If the ID matches with the buttons that I know are being used to initially load the controls, then when creating the different inputs, I set their ViewStateMode to Disabled, and, for bonus points, also set the EnableViewState to false.

The key is that, when those controls then do their own Postbacks (IE, DropDownList.SelectedIndexChanged, Button.Click, etc...), the ViewStateMode for them is enabled - so all works properly!

Body:
I have a usercontrol which contains dynamically generated webcontrols (TextBox, DropDownList, etc...)

The usercontrol is loaded on certain button click events.

On the usercontrol, there are occasionally postback events which need to be processed (Button.OnClick, etc...).

In order to accommodate the fact that the usercontrol is loaded on a click event, during Page_Load() of the usercontrol's parents, I'm re-executing the code that loads the usercontrol.

IE - I have, essentially, the following:

public partial class parentPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        If(Page.IsPostBack)
        {
            // Conditions are usually here to make sure this only happens when I want it to
            userControl.LoadUserControl();
        }
    }

    protected void Button_Click(object sender, EventArgs e)
    {
        userControl.LoadUserControl();
    }
}

public partial class userControl : System.Web.UI.UserControl
{
    public void LoadUserControl()
    {
        // Generate dynamic controls and bind events
    }

    protected void Button_Click(object sender, EventArgs e)
    {
        // Do stuff
    }
}

The problem I'm facing is that, after the Button_Click() event of the usercontrol is processed, the next time I click the button on the parent, the usercontrol's dynamically generated fields are somehow being automatically populated by what they were before the usercontrol's button was clicked - despite the fact that I'm explicitly setting the values when the LoadUserControl() function is called during the parent's button click.

What's even stranger is that the fields which are populated aren't necessarily consistent. In some cases TextBoxes have the correct text but DropDownLists have the old selected item. In other cases, DropDownLists are properly selected, but the TextBoxes retain the old text.

Does anyone have any suggestions or insights? I've tried a million different ideas and nothing seems to work.

** EDIT **

A bit of insight, perhaps - if I set the usercontrol to ViewStateMode=Disabled, it seems to solve the problem. I am reluctant to do this though, as I'm really not sure whether it will affect other functionality. I've already discovered a few glitches with the change, and I've a feeling even if I fix those, I'll end up finding more later. So hopefully any solution will not require such a drastic change. Perhaps the fact that it does solve this problem may help find a more elegant solution, though?

** EDIT 2 **

Debugging using dotPeek into the framework for System.Web.UI.ControlCollection.Add() reveals that, after adding the control to the collection, System.Web.UI.Control.AddedControl() is called. At the end of that, System.Web.UI.Control.LoadViewStateRecursive() is called. It's within there that the trouble arises. Despite the fact that this is a dynamically generated control, it still seems to persist in the ViewState. Continuing to dig...


问:
Usage of document.getElementsByClassName in a different path
I have my JavaScript file located in a different folder, so right now it can't find the class that it's looking for. I'd like it to know the path of the class while being in a separate folder.

var slideIndex = 0;
showSlides();

function showSlides() {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("dot");
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > slides.length) {
    slideIndex = 1
  }
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex - 1].style.display = "block";
  dots[slideIndex - 1].className += " active";
  setTimeout(showSlides, 2000); // Change image every 2 seconds
}
```

答:
Your code has nothing whatsoever to do with path

Perhaps you load the script in the head before the slideshow html exists.

Try

```<code>var slideIndex = 0;
window.addEventListener("load",showSlides);
</code>```

Body:
Your code has nothing whatsoever to do with path

Perhaps you load the script in the head before the slideshow html exists.

Try

var slideIndex = 0;
window.addEventListener("load",showSlides);


问:
Use Graphql variables to define fields
I am trying to do something effectively like this

```<code>`query GetAllUsers($fields: [String]) {
    users {
        ...$fields
    }
}`
</code>```

Where my client (currently Apollo for react) then passes in an array of fields in the variables section. The goal is to be able to pass in an array for what fields I want back, and that be interpolated to the appropriate graphql query. This currently returns a GraphQL Syntax error at $fields (expects a { but sees $ ). Is this even possible? Am I approaching this the wrong way?

One other option I had considered was invoking a JavaScript function and passing that result to query(), where the function would do something like the following:

```<code>buildQuery(fields) {
    return gql`
        query {
                users {
                    ${fields}
                }
        }`
}
</code>```

This however feels like an unecessary workaround.

答:
Comments summary:

Non standard requirements requires workarounds ;)

You can use fragments (for predefined fieldsets) but they probably won't be freely granular (field level).

Variables are definitely not for query definition (but for variables used in query).

Daniel's suggestion: gql-query-builder

It seams that graphQL community is great and full of people working on all possible use cases ... it's enough to search for solutions or ask on SO ;)

Title: Use Graphql variables to define fields

Body:
I am trying to do something effectively like this

`query GetAllUsers($fields: [String]) {
    users {
        ...$fields
    }
}`

Where my client (currently Apollo for react) then passes in an array of fields in the variables section. The goal is to be able to pass in an array for what fields I want back, and that be interpolated to the appropriate graphql query. This currently returns a GraphQL Syntax error at $fields (expects a { but sees $ ). Is this even possible? Am I approaching this the wrong way?

One other option I had considered was invoking a JavaScript function and passing that result to query(), where the function would do something like the following:

buildQuery(fields) {
    return gql`
        query {
                users {
                    ${fields}
                }
        }`
}

This however feels like an unecessary workaround.