问:
Can't store a struct containing a pointer
I have three structs :

```<code>struct Map
{
    int width, height;
    int* cases;
};
typedef struct Map Map;

struct Ship
{
    int x, y, length, firstShoot, color, hasBeenDiscovered;
};
typedef struct Ship Ship;

struct Player
{
    int activeShips;
    Map map[2];
    char lastMoves[5][128];
    Ship ships[10];
    int shipcolor[4];
    int color;
};
typedef struct Player Player;
</code>```

I use the map structure as a 2d dynamic array. Here are my functions to manipulate the map :

```<code>void mallocMap(Map* map, int width, int height)
{
    map->cases = malloc(sizeof(int) * width * height);

    map->width = width;
    map->height = height;

    if (map->cases == NULL)
    {
        printf("Erreur d'allocation de memoire\n");
        exit(0);
    }
}

void freeMap(Map* map)
{
    free(map->cases);
}

int getMapValue(Map map, int x, int y)
{
    return *(map.cases + y*map.width + x);
}

void setMapValue(Map* map, int value, int x, int y)
{
    *(map->cases + y*map->width + x) = value;
}
</code>```

Now what I'm doing is I'm creating a variable player of type Player, asks the user the width and height of the map and allocate memory for the map (malloc(sizeof(int)*width*height)).
Next what I want to do is to be able to store the struct Player in a file and the values of the cases but I don't know how I could do it.
Any suggestion ?

答:
You're not reading the values back in properly:

```<code>    fseek(file, sizeof(Player), SEEK_SET); // set the cursor after the struct
    fread(&player->games, sizeof(int), 1, file); // read the value

    fseek(file, sizeof(int), SEEK_CUR); // set the cursor after the first value
    fread(&player->map.cases, sizeof(int), 1, file); // read the value
</code>```

In the first read, you pass in &player->games as the address to write to.  This expression has type int **.  Rather than writing into the memory you allocated, you're writing into the pointer that contains that address.  The same problem exists in the other read.

Remove the address-of operator from each of the fread calls.  Also, the calls to fseek are redundant since the file pointer is already at the correct place, so you can remove them.

```<code>    fread(player->games, sizeof(int), 1, file); // read the value
    fread(player->map.cases, sizeof(int), 1, file); // read the value
</code>```

Body:
I have three structs :

struct Map
{
    int width, height;
    int* cases;
};
typedef struct Map Map;

struct Ship
{
    int x, y, length, firstShoot, color, hasBeenDiscovered;
};
typedef struct Ship Ship;

struct Player
{
    int activeShips;
    Map map[2];
    char lastMoves[5][128];
    Ship ships[10];
    int shipcolor[4];
    int color;
};
typedef struct Player Player;

I use the map structure as a 2d dynamic array. Here are my functions to manipulate the map :

void mallocMap(Map* map, int width, int height)
{
    map->cases = malloc(sizeof(int) * width * height);

    map->width = width;
    map->height = height;

    if (map->cases == NULL)
    {
        printf("Erreur d'allocation de memoire\n");
        exit(0);
    }
}

void freeMap(Map* map)
{
    free(map->cases);
}

int getMapValue(Map map, int x, int y)
{
    return *(map.cases + y*map.width + x);
}

void setMapValue(Map* map, int value, int x, int y)
{
    *(map->cases + y*map->width + x) = value;
}

Now what I'm doing is I'm creating a variable player of type Player, asks the user the width and height of the map and allocate memory for the map (malloc(sizeof(int)*width*height)).
Next what I want to do is to be able to store the struct Player in a file and the values of the cases but I don't know how I could do it.
Any suggestion ?

Body:
You're not reading the values back in properly:

    fseek(file, sizeof(Player), SEEK_SET); // set the cursor after the struct
    fread(&player->games, sizeof(int), 1, file); // read the value

    fseek(file, sizeof(int), SEEK_CUR); // set the cursor after the first value
    fread(&player->map.cases, sizeof(int), 1, file); // read the value

In the first read, you pass in &player->games as the address to write to.  This expression has type int **.  Rather than writing into the memory you allocated, you're writing into the pointer that contains that address.  The same problem exists in the other read.

Remove the address-of operator from each of the fread calls.  Also, the calls to fseek are redundant since the file pointer is already at the correct place, so you can remove them.

    fread(player->games, sizeof(int), 1, file); // read the value
    fread(player->map.cases, sizeof(int), 1, file); // read the value


来源: stackexchange

问:
Why does mktime() need to know about daylight saving time?
So mktime() returns a time_t value which is defined as "an integral value representing the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC" (source). I can convert a date to a time_t value by using mktime(). For example, to convert the date 10-Sep-2017 08:34:56 to a time_t I'd do the following:

```<code>struct tm tm;
time_t tv;

tm.tm_sec = 56;
tm.tm_min = 34;
tm.tm_hour = 8;
tm.tm_mday = 10;
tm.tm_mon = 8;
tm.tm_year = 117;
tm.tm_isdst = ????;

tv = mktime(&tm);
</code>```

Now what I don't understand is the idea behind the tm_isdst parameter: It is described as "a flag that indicates whether daylight saving time is in effect at the time described" (source).

This description is somewhat confusing me because I'm of the opinion that the time I'm describing in struct tm is in fact already a UTC time and the time_t value I want to have from mktime() is UTC as well. But UTC time doesn't change with a change of seasons, so why does mktime() need to bother with daylight saving time at all? Isn't the advantage of using UTC instead of local time that I won't have to bother with daylight saving time? So why do I have to set tm_isdst then?

I'm sure the answer is really simple but at the moment I'm failing to see it. Could somebody please provide a simple example that illustrates why mktime() needs the tm_isdst parameter to convert a certain date and time to a time_t value?

答:
Now what I don't understand is the idea behind the tm_isdst parameter:
  It is described as "a flag that indicates whether daylight saving time
  is in effect at the time described" (source).

This description is somewhat confusing me because I'm of the opinion
  that the time I'm describing in struct tm is in fact already a UTC
  time

Well, that's your main problem.  Per its documentation, which you already linked, mktime() converts a time structure expressed as local time to a time_t.

and the time_t value I want to have from mktime() is UTC as well.

Again according to the docs, when a time_t is interpreted as an absolute time, it represents the number of seconds elapsed since the Epoch, in UTC, so that's indeed what you will get from mktime().  But that means that there is, in general, a time zone and possibly daylight-saving difference between the two representations.

The C library relies on contextual localization data for the time zone applicable to local time, but although it knows the current rules for daylight saving time, it does not necessarily know the rules that were in effect at the specified time.  Moreover, there are edge cases at the changeovers between daylight time and standard time.  For these and perhaps other reasons, you need to tell mktime() whether the time given refers to daylight saving time or standard time.

But UTC time doesn't change with a change of seasons, so why does
  mktime() need to bother with daylight saving time at all?

Because mktime() accepts local time as input.

Isn't the
  advantage of using UTC instead of local time that I won't have to
  bother with daylight saving time?

That is one of the advantages, yes.

So why do I have to set tm_isdst
  then?

Because mktime() accepts local time as input.

ContentLicense: CC BY-SA 3.0

Body:
So mktime() returns a time_t value which is defined as "an integral value representing the number of seconds elapsed since 00:00 hours, Jan 1, 1970 UTC" (source). I can convert a date to a time_t value by using mktime(). For example, to convert the date 10-Sep-2017 08:34:56 to a time_t I'd do the following:

struct tm tm;
time_t tv;

tm.tm_sec = 56;
tm.tm_min = 34;
tm.tm_hour = 8;
tm.tm_mday = 10;
tm.tm_mon = 8;
tm.tm_year = 117;
tm.tm_isdst = ????;

tv = mktime(&tm);

Now what I don't understand is the idea behind the tm_isdst parameter: It is described as "a flag that indicates whether daylight saving time is in effect at the time described" (source).

This description is somewhat confusing me because I'm of the opinion that the time I'm describing in struct tm is in fact already a UTC time and the time_t value I want to have from mktime() is UTC as well. But UTC time doesn't change with a change of seasons, so why does mktime() need to bother with daylight saving time at all? Isn't the advantage of using UTC instead of local time that I won't have to bother with daylight saving time? So why do I have to set tm_isdst then?

I'm sure the answer is really simple but at the moment I'm failing to see it. Could somebody please provide a simple example that illustrates why mktime() needs the tm_isdst parameter to convert a certain date and time to a time_t value?


问:
React Native how to change image source with crossfade animation?
I have 2 different images that I want to loop between. When the image source changes, I want to apply a crossfade transition. Right now, it changes the background every 5 seconds as I want to, however, it does not transition with a crossfade effect

I have tried using LayoutAnimation, but it does not work for this.

I am using Expo if that matters.

First off, I have two images that I'm using

```<code>import BackgroundeOne from '../../Images/login-background1-tint.jpg'
import BackgroundeTwo from '../../Images/login-background2.jpg'
</code>```

I have an array of my images

```<code> var backgrounds = [BackgroundeOne, BackgroundeTwo]
</code>```

In my state, I have my current background

```<code> this.state = { background: BackgroundeOne }
</code>```

I have a function that sets the state

```<code> changeBackground = () => {
    let currentBg = this.state.background
    let newIndex = backgrounds.indexOf(currentBg) + 1
    let newBg = (newIndex) == backgrounds.length ? backgrounds[0] : backgrounds[newIndex]

    this.setState({
        background: newBg
    })
}
</code>```

I start an intervall repeat calling this function every 5 seconds

```<code>componentDidMount() {
setInterval( () => {
        this.changeBackground()
     }, 5000);
}
</code>```

And finally, I have an Image component

```<code><Image source={this.state.background} />
</code>```

How can I change the source with a crossfade animation?

答:
The best solution is to use the lifecycle method componentWillUpdate. As stated in the docs (https://reactjs.org/docs/react-component.html#componentwillupdate):

componentWillUpdate() is invoked immediately before rendering when new
  props or state are being received. Use this as an opportunity to
  perform preparation before an update occurs. This method is not called
  for the initial render.

so if you define this method on your component like this:

```<code>componentWillUpdate(nextProps, nextState)
</code>```

You still have access to your current state using this.state and you can see what your new source will be using nextState. Inside this method you should put your logic to make the animation perform what your want.

Body:
I have 2 different images that I want to loop between. When the image source changes, I want to apply a crossfade transition. Right now, it changes the background every 5 seconds as I want to, however, it does not transition with a crossfade effect

I have tried using LayoutAnimation, but it does not work for this.

I am using Expo if that matters.

First off, I have two images that I'm using

import BackgroundeOne from '../../Images/login-background1-tint.jpg'
import BackgroundeTwo from '../../Images/login-background2.jpg'

I have an array of my images

 var backgrounds = [BackgroundeOne, BackgroundeTwo]

In my state, I have my current background

 this.state = { background: BackgroundeOne }

I have a function that sets the state

 changeBackground = () => {
    let currentBg = this.state.background
    let newIndex = backgrounds.indexOf(currentBg) + 1
    let newBg = (newIndex) == backgrounds.length ? backgrounds[0] : backgrounds[newIndex]

    this.setState({
        background: newBg
    })
}

I start an intervall repeat calling this function every 5 seconds

componentDidMount() {
setInterval( () => {
        this.changeBackground()
     }, 5000);
}

And finally, I have an Image component

<Image source={this.state.background} />

How can I change the source with a crossfade animation?

Body:
The best solution is to use the lifecycle method componentWillUpdate. As stated in the docs (https://reactjs.org/docs/react-component.html#componentwillupdate):

componentWillUpdate() is invoked immediately before rendering when new
  props or state are being received. Use this as an opportunity to
  perform preparation before an update occurs. This method is not called
  for the initial render.

so if you define this method on your component like this:

componentWillUpdate(nextProps, nextState)

You still have access to your current state using this.state and you can see what your new source will be using nextState. Inside this method you should put your logic to make the animation perform what your want.


问:
Tippy.js unwanted effect in IE 11
I'm using Tippy.js to create custom dropdowns and popovers in my app. I have them configured to display immediately on click. No effects. Everything works as expected in all browsers except Internet Explorer 11. When a target element is clicked, the tip comes flying in from the top of the viewport (either left or right depending on "placement" config). Is there a configuration I'm missing in Tippy.js or Popper.js (dependency) or is this an IE bug? Any help would be appreciated.</p>

答: option {flipDuration: 0} solved it for me

Title: Tippy.js unwanted effect in IE 11


问:
Get all Attributes XML in python and Make it into a dictionary
XML:

```<code><main>
    <item name="item1" image="a"></item>
    <item name="item2" image="b"></item>
    <item name="item3" image="c"></item>
    <item name="item4" image="d"></item>
</main>
</code>```

Python:

```<code>xmldoc = minidom.parse('blah.xml')
itemlist = xmldoc.getElementsByTagName('item')
for item in itemlist :
    #####I want to make a dictionary of each item
</code>```

So I would get

```<code>{'name':'item1','image':'a'}
{'name':'item2','image':'b'}
{'name':'item3','image':'c'}
{'name':'item4','image':'d'}
</code>```

Does anyone know how to do this? Is there a function?

答:
List/dictionary comprehension version of the accepted answer:</p>

```<code>dicts = [{a.name: a.value for a in item.attributes.values()} for item in itemlist]
print dicts
</code>```

Body:
XML:

    <item name="item1" image="a"></item>
    <item name="item2" image="b"></item>
    <item name="item3" image="c"></item>
    <item name="item4" image="d"></item>

Python:

xmldoc = minidom.parse('blah.xml')
itemlist = xmldoc.getElementsByTagName('item')
for item in itemlist :
    #####I want to make a dictionary of each item

So I would get

{'name':'item1','image':'a'}
{'name':'item2','image':'b'}
{'name':'item3','image':'c'}
{'name':'item4','image':'d'}

Does anyone know how to do this? Is there a function?

Body:
List/dictionary comprehension version of the accepted answer:

dicts = [{a.name: a.value for a in item.attributes.values()} for item in itemlist]
print dicts


问:
Android App crashes at the beginning: Database Sqlite
I'm developping an android application, and while I was programming, there was no problem or error, and when I did run it on device, the logcat:

```<code>    11-16 09:27:29.930 4261-4261/? I/zygote: Not late-enabling -Xcheck:jni (already on)
11-16 09:27:29.956 4261-4261/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
11-16 09:27:30.188 4261-4261/com.example.root.myapplication I/InstantRun: starting instant run server: is main process
11-16 09:27:30.616 4261-4261/com.example.root.myapplication E/SQLiteLog: (1) near "KEYMatriculeINTEGER": syntax error
11-16 09:27:30.617 4261-4261/com.example.root.myapplication D/AndroidRuntime: Shutting down VM
11-16 09:27:30.619 4261-4261/com.example.root.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: com.example.root.myapplication, PID: 4261
                                                                              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.root.myapplication/com.example.root.myapplication.MainActivity}: android.database.sqlite.SQLiteException: near "KEYMatriculeINTEGER": syntax error (code 1): , while compiling: CREATE TABLE User(id INTEGER PRIMARY KEYMatriculeINTEGER PRIMARY KEYNomTEXTPrenomTEXTTypeTEXT)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
                                                                               Caused by: android.database.sqlite.SQLiteException: near "KEYMatriculeINTEGER": syntax error (code 1): , while compiling: CREATE TABLE User(id INTEGER PRIMARY KEYMatriculeINTEGER PRIMARY KEYNomTEXTPrenomTEXTTypeTEXT)
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:890)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:501)
                                                                                at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                                at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1752)
                                                                                at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1682)
                                                                                at model.sqlite.data.ModelHelper.onCreate(ModelHelper.java:101)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:333)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:262)
                                                                                at com.example.root.myapplication.MainActivity.onCreate(MainActivity.java:38)
                                                                                at android.app.Activity.performCreate(Activity.java:7000)
                                                                                at android.app.Activity.performCreate(Activity.java:6991)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
</code>```

the mainactivity:

public class MainActivity extends AppCompatActivity {

```<code>SQLiteOpenHelper dbhelper;
SQLiteDatabase db;
Cursor cursor;

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

    //initialisation des références
    final EditText txtTo = (EditText) findViewById(R.id.TxtTO);
    Button btnlogin = (Button) findViewById(R.id.btn_cnx);
    TextView btnreg = (TextView) findViewById(R.id.btn_signup);

    //Ouverture de la BD
    dbhelper = new ModelHelper(this);
    db = dbhelper.getReadableDatabase();

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

            String TO = txtTo.getText().toString();

            cursor = db.rawQuery("SELECT * FROM " + ModelHelper.TABLE_USER + " WHERE " + ModelHelper.KEY_MATRICULE + " ='?'  ", new String[]{"TO"});
            if (cursor != null) {
                if (cursor.getCount() > 0) {

                    cursor.moveToFirst();
                    //Retrouver le TO dans la base de données USER
                    String nom = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_NOM));
                    String prenom = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PRENOM));
                    //message pour affichage du msg de réussite de cnx
                    Toast.makeText(MainActivity.this, "Login Success", Toast.LENGTH_SHORT).show();
                    //Passer à la page suivante
                    Intent intent = new Intent(MainActivity.this, kamiActivity.class);
                    intent.putExtra("nom", nom);
                    intent.putExtra("prenom", prenom);
                    startActivity(intent);

                    //Removing MainActivity[Login Screen] from the stack for preventing back button press.
                    finish();
                } else {

                    //I am showing Alert Dialog Box here for alerting user about wrong credentials
                    final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("Alert");
                    builder.setMessage("Votre TO n'existe pas, veuillez vous inscrire avant s'il vous plait.");
                    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                            dialogInterface.dismiss();

                        }
                    });

                    AlertDialog dialog = builder.create();
                    dialog.show();
                    //-------Alert Dialog Code Snippet End Here
                }
            }

        }

        });
}

public void Reg(View view) {
    Intent myint = new Intent(this,signup.class);
}
</code>```

}

and then the Modelhelper:

```<code>    package model.sqlite.data;

import android.util.Log;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

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

import model.sqlite.data.user;
import model.sqlite.data.question;
import model.sqlite.data.theme;
import model.sqlite.data.answer;

public class ModelHelper extends SQLiteOpenHelper {
    private static final String LOG = "ModelHelper";

    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_NAME = "model";

    // Table names
    public static final String TABLE_USER = "User";
    private static final String TABLE_QUESTION = "Question";
    private static final String TABLE_THEME = "Theme";
    private static final String TABLE_ANSWER = "Answer";

    // Common column names
    private static final String KEY_ID = "id";
    private static final String KEY_ID_QUESTION = "ID_question";
    public static final String KEY_MATRICULE = "Matricule";
    private static final String KEY_ID_THEME = "ID_Theme";

    // Table User columns
    public static final String KEY_NOM = "Nom";
    public static final String KEY_PRENOM = "Prenom";
    public static final String KEY_TYPE = "Type";
    // Table Question columns
    private static final String KEY_QUESTION = "Question";
    private static final String KEY_PROFIL_CIBLE = "Profil cible";
    private static final String KEY_REGLE = "Regle";
    private static final String KEY_PLANACT = "PlanAct";
    // Table Theme columns
    private static final String KEY_THEME = "Theme";
    // Table Answer columns
    private static final String KEY_DATE = "Date";
    private static final String KEY_REPONSE = "Reponse";
    private static final String KEY_COMMENTAIRE = "Commentaire";
    // User table create statement
    private static final String CREATE_TABLE_USER =
        "CREATE TABLE " + TABLE_USER + "("
    +    KEY_MATRICULE + "INTEGER PRIMARY KEY"
    +    KEY_NOM + "TEXT"
    +    KEY_PRENOM + "TEXT"
    +    KEY_TYPE + "TEXT"
    +    ")";

    // Question table create statement
    private static final String CREATE_TABLE_QUESTION =
        "CREATE TABLE " + TABLE_QUESTION + "("
    +    KEY_ID + " INTEGER PRIMARY KEY"
    +    KEY_ID_QUESTION + "INTEGER PRIMARY KEY"
    +    KEY_QUESTION + "TEXT"
    +    KEY_PROFIL_CIBLE + "TEXT"
    +    KEY_REGLE + "TEXT"
    +    KEY_PLANACT + "TEXT"
    +    KEY_ID_THEME + "INTEGER"
    +    ")";

    // Theme table create statement
    private static final String CREATE_TABLE_THEME =
        "CREATE TABLE " + TABLE_THEME + "("
    +    KEY_ID + " INTEGER PRIMARY KEY"
    +    KEY_ID_THEME + "INTEGER PRIMARY KEY"
    +    KEY_THEME + "TEXT"
    +    ")";

    // Answer table create statement
    private static final String CREATE_TABLE_ANSWER =
        "CREATE TABLE " + TABLE_ANSWER + "("
    +    KEY_ID + " INTEGER PRIMARY KEY"
    +    KEY_MATRICULE + "INTEGER PRIMARY KEY"
    +    KEY_ID_QUESTION + "INTEGER PRIMARY KEY"
    +    KEY_DATE + "TEXT PRIMARY KEY"
    +    KEY_REPONSE + "TEXT"
    +    KEY_COMMENTAIRE + "TEXT"
    +    ")";

    public ModelHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // creating required tables
        db.execSQL(CREATE_TABLE_USER);
        db.execSQL(CREATE_TABLE_QUESTION);
        db.execSQL(CREATE_TABLE_THEME);
        db.execSQL(CREATE_TABLE_ANSWER);
    }

     @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // on upgrade drop older tables
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUESTION);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_THEME);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_ANSWER);

        // create new tables
        onCreate(db);
    }

    // closing database
    public void closeDB() {
        SQLiteDatabase db = this.getReadableDatabase();
        if (db != null && db.isOpen())
            db.close();
    }

    // CRUD operations for User

    public long createuser(user arg) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_MATRICULE, arg.getmatricule());
        values.put(KEY_NOM, arg.getnom());
        values.put(KEY_PRENOM, arg.getprenom());
        values.put(KEY_TYPE, arg.gettype());

        return db.insert(TABLE_USER, null, values);
    }

    public user getuser(long id) {
        SQLiteDatabase db = this.getReadableDatabase();

        String selectQuery = "SELECT  * FROM " + TABLE_USER + " WHERE "
            + KEY_ID + " = " + id;

        Log.e(LOG, selectQuery);

        Cursor c = db.rawQuery(selectQuery, null);

        if (c != null) {
            c.moveToFirst();
        }

        user entry = new user();
        entry.setmatricule(c.getInt(c.getColumnIndex(KEY_MATRICULE)));
        entry.setnom(c.getString(c.getColumnIndex(KEY_NOM)));
        entry.setprenom(c.getString(c.getColumnIndex(KEY_PRENOM)));
        entry.settype(c.getString(c.getColumnIndex(KEY_TYPE)));

        return entry;
    }

    public List<user> getAlluser() {
        List<user> list = new ArrayList<user>();
        String selectQuery = "SELECT  * FROM " + TABLE_USER;

        Log.e(LOG, selectQuery);

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                user entry = new user();
                entry.setmatricule(c.getInt(c.getColumnIndex(KEY_MATRICULE)));
                entry.setnom(c.getString(c.getColumnIndex(KEY_NOM)));
                entry.setprenom(c.getString(c.getColumnIndex(KEY_PRENOM)));
                entry.settype(c.getString(c.getColumnIndex(KEY_TYPE)));

                // adding to todo list
                list.add(entry);
            } while (c.moveToNext());
        }

        return list;
    }

    public long updateuser(user arg) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(KEY_MATRICULE, arg.getmatricule());
        values.put(KEY_NOM, arg.getnom());
        values.put(KEY_PRENOM, arg.getprenom());
        values.put(KEY_TYPE, arg.gettype());

        // updating row
        return db.update(TABLE_USER, values, KEY_ID + " = ?",
                new String[] { String.valueOf(arg.getId()) });
    }

    public void deleteuser(long id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_USER, KEY_ID + " = ?",
                new String[] { String.valueOf(id) });
    }

    // CRUD operations for Question

    public long createquestion(question arg) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ID_QUESTION, arg.getiDQuestion());
        values.put(KEY_QUESTION, arg.getquestion());
        values.put(KEY_PROFIL_CIBLE, arg.getprofilCible());
        values.put(KEY_REGLE, arg.getregle());
        values.put(KEY_PLANACT, arg.getplanAct());
        values.put(KEY_ID_THEME, arg.getiDTheme());

        return db.insert(TABLE_QUESTION, null, values);
    }

    public question getquestion(long id) {
        SQLiteDatabase db = this.getReadableDatabase();

        String selectQuery = "SELECT  * FROM " + TABLE_QUESTION + " WHERE "
            + KEY_ID + " = " + id;

        Log.e(LOG, selectQuery);

        Cursor c = db.rawQuery(selectQuery, null);

        if (c != null) {
            c.moveToFirst();
        }

        question entry = new question();
        entry.setiDQuestion(c.getInt(c.getColumnIndex(KEY_ID_QUESTION)));
        entry.setquestion(c.getString(c.getColumnIndex(KEY_QUESTION)));
        entry.setprofilCible(c.getString(c.getColumnIndex(KEY_PROFIL_CIBLE)));
        entry.setregle(c.getString(c.getColumnIndex(KEY_REGLE)));
        entry.setplanAct(c.getString(c.getColumnIndex(KEY_PLANACT)));
        entry.setiDTheme(c.getInt(c.getColumnIndex(KEY_ID_THEME)));

        return entry;
    }

    public List<question> getAllquestion() {
        List<question> list = new ArrayList<question>();
        String selectQuery = "SELECT  * FROM " + TABLE_QUESTION;

        Log.e(LOG, selectQuery);

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                question entry = new question();
                entry.setiDQuestion(c.getInt(c.getColumnIndex(KEY_ID_QUESTION)));
                entry.setquestion(c.getString(c.getColumnIndex(KEY_QUESTION)));
                entry.setprofilCible(c.getString(c.getColumnIndex(KEY_PROFIL_CIBLE)));
                entry.setregle(c.getString(c.getColumnIndex(KEY_REGLE)));
                entry.setplanAct(c.getString(c.getColumnIndex(KEY_PLANACT)));
                entry.setiDTheme(c.getInt(c.getColumnIndex(KEY_ID_THEME)));

                // adding to todo list
                list.add(entry);
            } while (c.moveToNext());
        }

        return list;
    }

    public long updatequestion(question arg) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(KEY_ID_QUESTION, arg.getiDQuestion());
        values.put(KEY_QUESTION, arg.getquestion());
        values.put(KEY_PROFIL_CIBLE, arg.getprofilCible());
        values.put(KEY_REGLE, arg.getregle());
        values.put(KEY_PLANACT, arg.getplanAct());
        values.put(KEY_ID_THEME, arg.getiDTheme());

        // updating row
        return db.update(TABLE_QUESTION, values, KEY_ID + " = ?",
                new String[] { String.valueOf(arg.getId()) });
    }

    public void deletequestion(long id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_QUESTION, KEY_ID + " = ?",
                new String[] { String.valueOf(id) });
    }

    // CRUD operations for Theme

    public long createtheme(theme arg) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ID_THEME, arg.getiDTheme());
        values.put(KEY_THEME, arg.gettheme());

        return db.insert(TABLE_THEME, null, values);
    }

    public theme gettheme(long id) {
        SQLiteDatabase db = this.getReadableDatabase();

        String selectQuery = "SELECT  * FROM " + TABLE_THEME + " WHERE "
            + KEY_ID + " = " + id;

        Log.e(LOG, selectQuery);

        Cursor c = db.rawQuery(selectQuery, null);

        if (c != null) {
            c.moveToFirst();
        }

        theme entry = new theme();
        entry.setiDTheme(c.getInt(c.getColumnIndex(KEY_ID_THEME)));
        entry.settheme(c.getString(c.getColumnIndex(KEY_THEME)));

        return entry;
    }

    public List<theme> getAlltheme() {
        List<theme> list = new ArrayList<theme>();
        String selectQuery = "SELECT  * FROM " + TABLE_THEME;

        Log.e(LOG, selectQuery);

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                theme entry = new theme();
                entry.setiDTheme(c.getInt(c.getColumnIndex(KEY_ID_THEME)));
                entry.settheme(c.getString(c.getColumnIndex(KEY_THEME)));

                // adding to todo list
                list.add(entry);
            } while (c.moveToNext());
        }

        return list;
    }

    public long updatetheme(theme arg) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(KEY_ID_THEME, arg.getiDTheme());
        values.put(KEY_THEME, arg.gettheme());

        // updating row
        return db.update(TABLE_THEME, values, KEY_ID + " = ?",
                new String[] { String.valueOf(arg.getId()) });
    }

    public void deletetheme(long id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_THEME, KEY_ID + " = ?",
                new String[] { String.valueOf(id) });
    }

    // CRUD operations for Answer

    public long createanswer(answer arg) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_MATRICULE, arg.getmatricule());
        values.put(KEY_ID_QUESTION, arg.getiDQuestion());
        values.put(KEY_DATE, arg.getdate());
        values.put(KEY_REPONSE, arg.getreponse());
        values.put(KEY_COMMENTAIRE, arg.getcommentaire());

        return db.insert(TABLE_ANSWER, null, values);
    }

    public answer getanswer(long id) {
        SQLiteDatabase db = this.getReadableDatabase();

        String selectQuery = "SELECT  * FROM " + TABLE_ANSWER + " WHERE "
            + KEY_ID + " = " + id;

        Log.e(LOG, selectQuery);

        Cursor c = db.rawQuery(selectQuery, null);

        if (c != null) {
            c.moveToFirst();
        }

        answer entry = new answer();
        entry.setmatricule(c.getInt(c.getColumnIndex(KEY_MATRICULE)));
        entry.setiDQuestion(c.getInt(c.getColumnIndex(KEY_ID_QUESTION)));
        entry.setdate(c.getString(c.getColumnIndex(KEY_DATE)));
        entry.setreponse(c.getString(c.getColumnIndex(KEY_REPONSE)));
        entry.setcommentaire(c.getString(c.getColumnIndex(KEY_COMMENTAIRE)));

        return entry;
    }

    public List<answer> getAllanswer() {
        List<answer> list = new ArrayList<answer>();
        String selectQuery = "SELECT  * FROM " + TABLE_ANSWER;

        Log.e(LOG, selectQuery);

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                answer entry = new answer();
                entry.setmatricule(c.getInt(c.getColumnIndex(KEY_MATRICULE)));
                entry.setiDQuestion(c.getInt(c.getColumnIndex(KEY_ID_QUESTION)));
                entry.setdate(c.getString(c.getColumnIndex(KEY_DATE)));
                entry.setreponse(c.getString(c.getColumnIndex(KEY_REPONSE)));
                entry.setcommentaire(c.getString(c.getColumnIndex(KEY_COMMENTAIRE)));

                // adding to todo list
                list.add(entry);
            } while (c.moveToNext());
        }

        return list;
    }

    public long updateanswer(answer arg) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(KEY_MATRICULE, arg.getmatricule());
        values.put(KEY_ID_QUESTION, arg.getiDQuestion());
        values.put(KEY_DATE, arg.getdate().toString());
        values.put(KEY_REPONSE, arg.getreponse());
        values.put(KEY_COMMENTAIRE, arg.getcommentaire());

        // updating row
        return db.update(TABLE_ANSWER, values, KEY_ID + " = ?",
                new String[] { String.valueOf(arg.getId()) });
    }

    public void deleteanswer(long id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_ANSWER, KEY_ID + " = ?",
                new String[] { String.valueOf(id) });
    }

}
</code>```

I saw that the problem is using the int: matricule but I checked everywhere I didn't found an error or a problem in the code.
Thanks

答:
This is the actual error:

java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.root.myapplication/com.example.root.myapplication.MainActivity}:
  android.database.sqlite.SQLiteException: near "KEYMatriculeINTEGER":
  syntax error (code 1): , while compiling: CREATE TABLE User(id INTEGER
  PRIMARY KEYMatriculeINTEGER PRIMARY KEYNomTEXTPrenomTEXTTypeTEXT)

You are missing some commas:

```<code>private static final String CREATE_TABLE_USER =
    "CREATE TABLE " + TABLE_USER + "("
+    KEY_MATRICULE + " INTEGER PRIMARY KEY, "
+    KEY_NOM + " TEXT, "
+    KEY_PRENOM + " TEXT, "
+    KEY_TYPE + " TEXT"
+    ")";
</code>```

Body:
I'm developping an android application, and while I was programming, there was no problem or error, and when I did run it on device, the logcat:

    11-16 09:27:29.930 4261-4261/? I/zygote: Not late-enabling -Xcheck:jni (already on)
11-16 09:27:29.956 4261-4261/? W/zygote: Unexpected CPU variant for X86 using defaults: x86
11-16 09:27:30.188 4261-4261/com.example.root.myapplication I/InstantRun: starting instant run server: is main process
11-16 09:27:30.616 4261-4261/com.example.root.myapplication E/SQLiteLog: (1) near "KEYMatriculeINTEGER": syntax error
11-16 09:27:30.617 4261-4261/com.example.root.myapplication D/AndroidRuntime: Shutting down VM
11-16 09:27:30.619 4261-4261/com.example.root.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: com.example.root.myapplication, PID: 4261
                                                                              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.root.myapplication/com.example.root.myapplication.MainActivity}: android.database.sqlite.SQLiteException: near "KEYMatriculeINTEGER": syntax error (code 1): , while compiling: CREATE TABLE User(id INTEGER PRIMARY KEYMatriculeINTEGER PRIMARY KEYNomTEXTPrenomTEXTTypeTEXT)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
                                                                               Caused by: android.database.sqlite.SQLiteException: near "KEYMatriculeINTEGER": syntax error (code 1): , while compiling: CREATE TABLE User(id INTEGER PRIMARY KEYMatriculeINTEGER PRIMARY KEYNomTEXTPrenomTEXTTypeTEXT)
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:890)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:501)
                                                                                at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                                at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                                at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                                at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1752)
                                                                                at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1682)
                                                                                at model.sqlite.data.ModelHelper.onCreate(ModelHelper.java:101)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:333)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:262)
                                                                                at com.example.root.myapplication.MainActivity.onCreate(MainActivity.java:38)
                                                                                at android.app.Activity.performCreate(Activity.java:7000)
                                                                                at android.app.Activity.performCreate(Activity.java:6991)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                                                                                at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                at android.os.Looper.loop(Looper.java:164)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6494)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

the mainactivity:

public class MainActivity extends AppCompatActivity {

SQLiteOpenHelper dbhelper;
SQLiteDatabase db;
Cursor cursor;

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

    //initialisation des références
    final EditText txtTo = (EditText) findViewById(R.id.TxtTO);
    Button btnlogin = (Button) findViewById(R.id.btn_cnx);
    TextView btnreg = (TextView) findViewById(R.id.btn_signup);

    //Ouverture de la BD
    dbhelper = new ModelHelper(this);
    db = dbhelper.getReadableDatabase();

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

            String TO = txtTo.getText().toString();

            cursor = db.rawQuery("SELECT * FROM " + ModelHelper.TABLE_USER + " WHERE " + ModelHelper.KEY_MATRICULE + " ='?'  ", new String[]{"TO"});
            if (cursor != null) {
                if (cursor.getCount() > 0) {

                    cursor.moveToFirst();
                    //Retrouver le TO dans la base de données USER
                    String nom = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_NOM));
                    String prenom = cursor.getString(cursor.getColumnIndex(ModelHelper.KEY_PRENOM));
                    //message pour affichage du msg de réussite de cnx
                    Toast.makeText(MainActivity.this, "Login Success", Toast.LENGTH_SHORT).show();
                    //Passer à la page suivante
                    Intent intent = new Intent(MainActivity.this, kamiActivity.class);
                    intent.putExtra("nom", nom);
                    intent.putExtra("prenom", prenom);
                    startActivity(intent);

                    //Removing MainActivity[Login Screen] from the stack for preventing back button press.
                    finish();
                } else {

                    //I am showing Alert Dialog Box here for alerting user about wrong credentials
                    final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("Alert");
                    builder.setMessage("Votre TO n'existe pas, veuillez vous inscrire avant s'il vous plait.");
                    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                            dialogInterface.dismiss();

                        }
                    });

                    AlertDialog dialog = builder.create();
                    dialog.show();
                    //-------Alert Dialog Code Snippet End Here
                }
            }

        }

        });
}

public void Reg(View view) {
    Intent myint = new Intent(this,signup.class);
}

}

and then the Modelhelper:

    package model.sqlite.data;

import android.util.Log;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

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

import model.sqlite.data.user;
import model.sqlite.data.question;
import model.sqlite.data.theme;
import model.sqlite.data.answer;

public class ModelHelper extends SQLiteOpenHelper {
    private static final String LOG = "ModelHelper";

    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_NAME = "model";

    // Table names
    public static final String TABLE_USER = "User";
    private static final String TABLE_QUESTION = "Question";
    private static final String TABLE_THEME = "Theme";
    private static final String TABLE_ANSWER = "Answer";

    // Common column names
    private static final String KEY_ID = "id";
    private static final String KEY_ID_QUESTION = "ID_question";
    public static final String KEY_MATRICULE = "Matricule";
    private static final String KEY_ID_THEME = "ID_Theme";

    // Table User columns
    public static final String KEY_NOM = "Nom";
    public static final String KEY_PRENOM = "Prenom";
    public static final String KEY_TYPE = "Type";
    // Table Question columns
    private static final String KEY_QUESTION = "Question";
    private static final String KEY_PROFIL_CIBLE = "Profil cible";
    private static final String KEY_REGLE = "Regle";
    private static final String KEY_PLANACT = "PlanAct";
    // Table Theme columns
    private static final String KEY_THEME = "Theme";
    // Table Answer columns
    private static final String KEY_DATE = "Date";
    private static final String KEY_REPONSE = "Reponse";
    private static final String KEY_COMMENTAIRE = "Commentaire";
    // User table create statement
    private static final String CREATE_TABLE_USER =
        "CREATE TABLE " + TABLE_USER + "("
    +    KEY_MATRICULE + "INTEGER PRIMARY KEY"
    +    KEY_NOM + "TEXT"
    +    KEY_PRENOM + "TEXT"
    +    KEY_TYPE + "TEXT"
    +    ")";

    // Question table create statement
    private static final String CREATE_TABLE_QUESTION =
        "CREATE TABLE " + TABLE_QUESTION + "("
    +    KEY_ID + " INTEGER PRIMARY KEY"
    +    KEY_ID_QUESTION + "INTEGER PRIMARY KEY"
    +    KEY_QUESTION + "TEXT"
    +    KEY_PROFIL_CIBLE + "TEXT"
    +    KEY_REGLE + "TEXT"
    +    KEY_PLANACT + "TEXT"
    +    KEY_ID_THEME + "INTEGER"
    +    ")";

    // Theme table create statement
    private static final String CREATE_TABLE_THEME =
        "CREATE TABLE " + TABLE_THEME + "("
    +    KEY_ID + " INTEGER PRIMARY KEY"
    +    KEY_ID_THEME + "INTEGER PRIMARY KEY"
    +    KEY_THEME + "TEXT"
    +    ")";

    // Answer table create statement
    private static final String CREATE_TABLE_ANSWER =
        "CREATE TABLE " + TABLE_ANSWER + "("
    +    KEY_ID + " INTEGER PRIMARY KEY"
    +    KEY_MATRICULE + "INTEGER PRIMARY KEY"
    +    KEY_ID_QUESTION + "INTEGER PRIMARY KEY"
    +    KEY_DATE + "TEXT PRIMARY KEY"
    +    KEY_REPONSE + "TEXT"
    +    KEY_COMMENTAIRE + "TEXT"
    +    ")";

    public ModelHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // creating required tables
        db.execSQL(CREATE_TABLE_USER);
        db.execSQL(CREATE_TABLE_QUESTION);
        db.execSQL(CREATE_TABLE_THEME);
        db.execSQL(CREATE_TABLE_ANSWER);
    }

     @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // on upgrade drop older tables
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USER);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_QUESTION);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_THEME);
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_ANSWER);

        // create new tables
        onCreate(db);
    }

    // closing database
    public void closeDB() {
        SQLiteDatabase db = this.getReadableDatabase();
        if (db != null && db.isOpen())
            db.close();
    }

    // CRUD operations for User

    public long createuser(user arg) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_MATRICULE, arg.getmatricule());
        values.put(KEY_NOM, arg.getnom());
        values.put(KEY_PRENOM, arg.getprenom());
        values.put(KEY_TYPE, arg.gettype());

        return db.insert(TABLE_USER, null, values);
    }

    public user getuser(long id) {
        SQLiteDatabase db = this.getReadableDatabase();

        String selectQuery = "SELECT  * FROM " + TABLE_USER + " WHERE "
            + KEY_ID + " = " + id;

        Log.e(LOG, selectQuery);

        Cursor c = db.rawQuery(selectQuery, null);

        if (c != null) {
            c.moveToFirst();
        }

        user entry = new user();
        entry.setmatricule(c.getInt(c.getColumnIndex(KEY_MATRICULE)));
        entry.setnom(c.getString(c.getColumnIndex(KEY_NOM)));
        entry.setprenom(c.getString(c.getColumnIndex(KEY_PRENOM)));
        entry.settype(c.getString(c.getColumnIndex(KEY_TYPE)));

        return entry;
    }

    public List<user> getAlluser() {
        List<user> list = new ArrayList<user>();
        String selectQuery = "SELECT  * FROM " + TABLE_USER;

        Log.e(LOG, selectQuery);

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                user entry = new user();
                entry.setmatricule(c.getInt(c.getColumnIndex(KEY_MATRICULE)));
                entry.setnom(c.getString(c.getColumnIndex(KEY_NOM)));
                entry.setprenom(c.getString(c.getColumnIndex(KEY_PRENOM)));
                entry.settype(c.getString(c.getColumnIndex(KEY_TYPE)));

                // adding to todo list
                list.add(entry);
            } while (c.moveToNext());
        }

        return list;
    }

    public long updateuser(user arg) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(KEY_MATRICULE, arg.getmatricule());
        values.put(KEY_NOM, arg.getnom());
        values.put(KEY_PRENOM, arg.getprenom());
        values.put(KEY_TYPE, arg.gettype());

        // updating row
        return db.update(TABLE_USER, values, KEY_ID + " = ?",
                new String[] { String.valueOf(arg.getId()) });
    }

    public void deleteuser(long id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_USER, KEY_ID + " = ?",
                new String[] { String.valueOf(id) });
    }

    // CRUD operations for Question

    public long createquestion(question arg) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ID_QUESTION, arg.getiDQuestion());
        values.put(KEY_QUESTION, arg.getquestion());
        values.put(KEY_PROFIL_CIBLE, arg.getprofilCible());
        values.put(KEY_REGLE, arg.getregle());
        values.put(KEY_PLANACT, arg.getplanAct());
        values.put(KEY_ID_THEME, arg.getiDTheme());

        return db.insert(TABLE_QUESTION, null, values);
    }

    public question getquestion(long id) {
        SQLiteDatabase db = this.getReadableDatabase();

        String selectQuery = "SELECT  * FROM " + TABLE_QUESTION + " WHERE "
            + KEY_ID + " = " + id;

        Log.e(LOG, selectQuery);

        Cursor c = db.rawQuery(selectQuery, null);

        if (c != null) {
            c.moveToFirst();
        }

        question entry = new question();
        entry.setiDQuestion(c.getInt(c.getColumnIndex(KEY_ID_QUESTION)));
        entry.setquestion(c.getString(c.getColumnIndex(KEY_QUESTION)));
        entry.setprofilCible(c.getString(c.getColumnIndex(KEY_PROFIL_CIBLE)));
        entry.setregle(c.getString(c.getColumnIndex(KEY_REGLE)));
        entry.setplanAct(c.getString(c.getColumnIndex(KEY_PLANACT)));
        entry.setiDTheme(c.getInt(c.getColumnIndex(KEY_ID_THEME)));

        return entry;
    }

    public List<question> getAllquestion() {
        List<question> list = new ArrayList<question>();
        String selectQuery = "SELECT  * FROM " + TABLE_QUESTION;

        Log.e(LOG, selectQuery);

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                question entry = new question();
                entry.setiDQuestion(c.getInt(c.getColumnIndex(KEY_ID_QUESTION)));
                entry.setquestion(c.getString(c.getColumnIndex(KEY_QUESTION)));
                entry.setprofilCible(c.getString(c.getColumnIndex(KEY_PROFIL_CIBLE)));
                entry.setregle(c.getString(c.getColumnIndex(KEY_REGLE)));
                entry.setplanAct(c.getString(c.getColumnIndex(KEY_PLANACT)));
                entry.setiDTheme(c.getInt(c.getColumnIndex(KEY_ID_THEME)));

                // adding to todo list
                list.add(entry);
            } while (c.moveToNext());
        }

        return list;
    }

    public long updatequestion(question arg) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(KEY_ID_QUESTION, arg.getiDQuestion());
        values.put(KEY_QUESTION, arg.getquestion());
        values.put(KEY_PROFIL_CIBLE, arg.getprofilCible());
        values.put(KEY_REGLE, arg.getregle());
        values.put(KEY_PLANACT, arg.getplanAct());
        values.put(KEY_ID_THEME, arg.getiDTheme());

        // updating row
        return db.update(TABLE_QUESTION, values, KEY_ID + " = ?",
                new String[] { String.valueOf(arg.getId()) });
    }

    public void deletequestion(long id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_QUESTION, KEY_ID + " = ?",
                new String[] { String.valueOf(id) });
    }

    // CRUD operations for Theme

    public long createtheme(theme arg) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_ID_THEME, arg.getiDTheme());
        values.put(KEY_THEME, arg.gettheme());

        return db.insert(TABLE_THEME, null, values);
    }

    public theme gettheme(long id) {
        SQLiteDatabase db = this.getReadableDatabase();

        String selectQuery = "SELECT  * FROM " + TABLE_THEME + " WHERE "
            + KEY_ID + " = " + id;

        Log.e(LOG, selectQuery);

        Cursor c = db.rawQuery(selectQuery, null);

        if (c != null) {
            c.moveToFirst();
        }

        theme entry = new theme();
        entry.setiDTheme(c.getInt(c.getColumnIndex(KEY_ID_THEME)));
        entry.settheme(c.getString(c.getColumnIndex(KEY_THEME)));

        return entry;
    }

    public List<theme> getAlltheme() {
        List<theme> list = new ArrayList<theme>();
        String selectQuery = "SELECT  * FROM " + TABLE_THEME;

        Log.e(LOG, selectQuery);

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                theme entry = new theme();
                entry.setiDTheme(c.getInt(c.getColumnIndex(KEY_ID_THEME)));
                entry.settheme(c.getString(c.getColumnIndex(KEY_THEME)));

                // adding to todo list
                list.add(entry);
            } while (c.moveToNext());
        }

        return list;
    }

    public long updatetheme(theme arg) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(KEY_ID_THEME, arg.getiDTheme());
        values.put(KEY_THEME, arg.gettheme());

        // updating row
        return db.update(TABLE_THEME, values, KEY_ID + " = ?",
                new String[] { String.valueOf(arg.getId()) });
    }

    public void deletetheme(long id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_THEME, KEY_ID + " = ?",
                new String[] { String.valueOf(id) });
    }

    // CRUD operations for Answer

    public long createanswer(answer arg) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_MATRICULE, arg.getmatricule());
        values.put(KEY_ID_QUESTION, arg.getiDQuestion());
        values.put(KEY_DATE, arg.getdate());
        values.put(KEY_REPONSE, arg.getreponse());
        values.put(KEY_COMMENTAIRE, arg.getcommentaire());

        return db.insert(TABLE_ANSWER, null, values);
    }

    public answer getanswer(long id) {
        SQLiteDatabase db = this.getReadableDatabase();

        String selectQuery = "SELECT  * FROM " + TABLE_ANSWER + " WHERE "
            + KEY_ID + " = " + id;

        Log.e(LOG, selectQuery);

        Cursor c = db.rawQuery(selectQuery, null);

        if (c != null) {
            c.moveToFirst();
        }

        answer entry = new answer();
        entry.setmatricule(c.getInt(c.getColumnIndex(KEY_MATRICULE)));
        entry.setiDQuestion(c.getInt(c.getColumnIndex(KEY_ID_QUESTION)));
        entry.setdate(c.getString(c.getColumnIndex(KEY_DATE)));
        entry.setreponse(c.getString(c.getColumnIndex(KEY_REPONSE)));
        entry.setcommentaire(c.getString(c.getColumnIndex(KEY_COMMENTAIRE)));

        return entry;
    }

    public List<answer> getAllanswer() {
        List<answer> list = new ArrayList<answer>();
        String selectQuery = "SELECT  * FROM " + TABLE_ANSWER;

        Log.e(LOG, selectQuery);

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor c = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (c.moveToFirst()) {
            do {
                answer entry = new answer();
                entry.setmatricule(c.getInt(c.getColumnIndex(KEY_MATRICULE)));
                entry.setiDQuestion(c.getInt(c.getColumnIndex(KEY_ID_QUESTION)));
                entry.setdate(c.getString(c.getColumnIndex(KEY_DATE)));
                entry.setreponse(c.getString(c.getColumnIndex(KEY_REPONSE)));
                entry.setcommentaire(c.getString(c.getColumnIndex(KEY_COMMENTAIRE)));

                // adding to todo list
                list.add(entry);
            } while (c.moveToNext());
        }

        return list;
    }

    public long updateanswer(answer arg) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(KEY_MATRICULE, arg.getmatricule());
        values.put(KEY_ID_QUESTION, arg.getiDQuestion());
        values.put(KEY_DATE, arg.getdate().toString());
        values.put(KEY_REPONSE, arg.getreponse());
        values.put(KEY_COMMENTAIRE, arg.getcommentaire());

        // updating row
        return db.update(TABLE_ANSWER, values, KEY_ID + " = ?",
                new String[] { String.valueOf(arg.getId()) });
    }

    public void deleteanswer(long id) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_ANSWER, KEY_ID + " = ?",
                new String[] { String.valueOf(id) });
    }

}

I saw that the problem is using the int: matricule but I checked everywhere I didn't found an error or a problem in the code.
Thanks

Body:
This is the actual error:

java.lang.RuntimeException: Unable to start activity
  ComponentInfo{com.example.root.myapplication/com.example.root.myapplication.MainActivity}:
  android.database.sqlite.SQLiteException: near "KEYMatriculeINTEGER":
  syntax error (code 1): , while compiling: CREATE TABLE User(id INTEGER
  PRIMARY KEYMatriculeINTEGER PRIMARY KEYNomTEXTPrenomTEXTTypeTEXT)

You are missing some commas:

private static final String CREATE_TABLE_USER =
    "CREATE TABLE " + TABLE_USER + "("
+    KEY_MATRICULE + " INTEGER PRIMARY KEY, "
+    KEY_NOM + " TEXT, "
+    KEY_PRENOM + " TEXT, "
+    KEY_TYPE + " TEXT"
+    ")";


问:
Symfony serializer doesn't work with --no-dev
I'm using symfony serializer. But if I install composer packages with --no-dev flag, it deserializes data that supposed to be array of objects in array of arrays instead.

This is serialization:

```<code>$result = $this->get('serializer')->deserialize(
    $request->getContent(),
    InputDto::class,
    'json'
);
</code>```

And for deserialization I use annotations in DTO.

This is how "field" looks in DTO for objects array:

```<code>/**
 * @var OrderItemDto[]|Collection
 */
private $items = [];
</code>```

答:
To make object sublevel work you need to add to app/config/config.yml
in framework section next lines:

```<code>property_info:
    enabled: true
</code>```

Body:
I'm using symfony serializer. But if I install composer packages with --no-dev flag, it deserializes data that supposed to be array of objects in array of arrays instead.

This is serialization:

$result = $this->get('serializer')->deserialize(
    $request->getContent(),
    InputDto::class,
    'json'
);

And for deserialization I use annotations in DTO.

This is how "field" looks in DTO for objects array:

/**
 * @var OrderItemDto[]|Collection
 */
private $items = [];

Body:
To make object sublevel work you need to add to app/config/config.yml
in framework section next lines:

property_info:
    enabled: true


问:
Genetic Algorithm in cryptography
Can anyone explain how genetic algorithms can be used in cryptography?
Genetic algorithms are optimizing problems, and they use some kind of pseudorandom code as key. How this key can be transferred to the receiver? </p>

答:
They are unlikely to be of much use in general.  Genetic algorithms rely on a reasonably small change in output for a small change in input -- that allows them to close in on a good solution to the problem.

Cryptographic algorithms are designed to have a large change in output for a small change in input.  A good hash algorithm will flip around half the output bits if a single input bit is changed.

That makes genetic algorithms in general little better than a brute force search.

Title: Genetic Algorithm in cryptography


问:
Using NOT LIKE for multiple mutiple columns
I want to search for particular value in multiple columns. Is there any way to optimize this query?

```<code>SELECT TOP (200) Events.EventDate, AVDCAV.CAVCH1, AVDCAV.CAVCH2, AVDCAV.CAVCH3, AVDCAV.CAVCH4, AVDCAV.CAVCH5, AVDCAV.CAVCH6, AVDCAV.CAVCH7, AVDCAV.CAVCH8, AVDCAV.CAVCH9
FROM AVDCAV
   INNER JOIN Events ON AVDCAV.IDEvent=Events.EventID
WHERE CAVCH9 NOT LIKE '0.0000000000' OR CAVCH8 NOT LIKE '0.0000000000' OR CAVCH7 NOT LIKE '0.0000000000' OR CAVCH1 NOT LIKE '0.0000000000'
ORDER BY AVDCAV.IDEvent DESC
</code>```

I'm getting the data from SQL Express 2008 R2.

答:
Because you aren't using any wildcard you don't need LIKE.

```<code>WHERE '0.0000000000' NOT IN  (CAVCH1, CAVCH7, CAVCH8, CAVCH9)
</code>```

Btw the performance is the same, but easier to read.

Body:
I want to search for particular value in multiple columns. Is there any way to optimize this query?

SELECT TOP (200) Events.EventDate, AVDCAV.CAVCH1, AVDCAV.CAVCH2, AVDCAV.CAVCH3, AVDCAV.CAVCH4, AVDCAV.CAVCH5, AVDCAV.CAVCH6, AVDCAV.CAVCH7, AVDCAV.CAVCH8, AVDCAV.CAVCH9
FROM AVDCAV
   INNER JOIN Events ON AVDCAV.IDEvent=Events.EventID
WHERE CAVCH9 NOT LIKE '0.0000000000' OR CAVCH8 NOT LIKE '0.0000000000' OR CAVCH7 NOT LIKE '0.0000000000' OR CAVCH1 NOT LIKE '0.0000000000'
ORDER BY AVDCAV.IDEvent DESC

I'm getting the data from SQL Express 2008 R2.

Body:
Because you aren't using any wildcard you don't need LIKE.

WHERE '0.0000000000' NOT IN  (CAVCH1, CAVCH7, CAVCH8, CAVCH9)

Btw the performance is the same, but easier to read.


问:
newbie question memory and code optimisation
this is what i write

```<code>domaine *detailsDomaine = [search_result objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:@"%@",[detailsDomaine valueForKey:@"nom"]];
</code>```

Is it possible to not assign a variable (detailsDomaine)to reach the same result ?
Do i have to release detailsDomaine variable after that ?

I'm not using it anywhere else in the rest of the code...

答: The other answers are correct, let me just add this: What Johnny Grass said is true. It's ugly, i.e. harder to read. It also won't gain you anything. The compiler will probably note the excess assignment, and optimize it out. And even if it does, unless this is going to be called 10,000 times in a second, it's not worth optimizing it.</p>

ContentLicense: CC BY-SA 2.5

Body:
this is what i write

domaine *detailsDomaine = [search_result objectAtIndex:indexPath.row];
cell.textLabel.text = [NSString stringWithFormat:@"%@",[detailsDomaine valueForKey:@"nom"]];

Is it possible to not assign a variable (detailsDomaine)to reach the same result ?
Do i have to release detailsDomaine variable after that ?

I'm not using it anywhere else in the rest of the code...


问:
Sweetalert2 redirection
I'm struggling with this for a few hours already and I think that the solution is very simple. First a bit of background.

So, I have a php page where I can enter a number in a texfield. If the number entered is higher than the credit the user has, then I have to show an error message. When the user clicks on the button to send the form, I go to makeTransfer.php and I do several checks in here. If, as I said, the user has not credit enough I want to show him an error message using SweetAlert2 and then redirect him to the previous page (let's call it cashier). At the moment, I can show the alert but I'm unable to redirect him :(.

Here is the code:

```<code>echo '<script type="text/javascript">';
echo 'setTimeout(function () { swal("WOW!","Message!","error");';
echo '});</script>';
</code>```

Any help, please? I just want to show the alert, and as soon as the user clicks on Accept button, redirects him to cashier.php

Thanks in advance!

答:
```<code>swal({
  title: 'Redirect',
  text: "Message",
  type: 'success',
}).then(function (result) {
  if (true) {
    window.location = "cashier.php";
  }
})
</code>```

like this it will redirect to cahsier.php in that same directory as it is in right now if the if returns true, you can also leave it away

Title: Sweetalert2 redirection

Body:
I'm struggling with this for a few hours already and I think that the solution is very simple. First a bit of background.

So, I have a php page where I can enter a number in a texfield. If the number entered is higher than the credit the user has, then I have to show an error message. When the user clicks on the button to send the form, I go to makeTransfer.php and I do several checks in here. If, as I said, the user has not credit enough I want to show him an error message using SweetAlert2 and then redirect him to the previous page (let's call it cashier). At the moment, I can show the alert but I'm unable to redirect him :(.

Here is the code:

echo '';

Any help, please? I just want to show the alert, and as soon as the user clicks on Accept button, redirects him to cashier.php

Thanks in advance!

Body:
swal({
  title: 'Redirect',
  text: "Message",
  type: 'success',
}).then(function (result) {
  if (true) {
    window.location = "cashier.php";
  }
})

like this it will redirect to cahsier.php in that same directory as it is in right now if the if returns true, you can also leave it away


问:
Summary of outputs from for loop so it outputs a summary
Trying to get a summary from my current output. E.g. Hello: 5, World: 8, HelloWorld: 20, integer: 5. Currently this accepts a user input e.g. 1,10, 1 being minimum and 10 being maximum and outputs the following from the for loop. Don't know how to get the output into an array and then aggregate this.

Code so far:

```<code> Console.WriteLine("Please enter a range?");
        string range = Console.ReadLine();
        string first = range.Split(',')[0];
        string last = range.Split(',')[1];
        int min = Int32.Parse(first);
        int max = Int32.Parse(last);
        Console.WriteLine("");
        Console.WriteLine("Heres the Output");
        Console.WriteLine("");

        for (int i = min; i < max ; i++ )
        {
            bool hello = i % 3 == 0;
            bool world = i % 5 == 0;

            if (hello && world)
                Console.WriteLine("HelloWorld");

            else if (hello)
                Console.WriteLine("Hello");
            else if (world)
                Console.WriteLine("World");
            else
                Console.WriteLine(i);
        }

        string list = Console.ReadLine();
        Console.WriteLine(list);
</code>```

答:
All you have to do is to use modular arithmetics; providing that 0 <= min < max :

```<code>private static int CountDivs(int value, int divisor) {
  return value < 0 ? 0 : value / divisor + 1;
}

private static string Solution(int min, int max) {
  int hello = CountDivs(max - 1, 3) - CountDivs(min - 1, 3);
  int world = CountDivs(max - 1, 5) - CountDivs(min - 1, 5);
  int helloWorld = CountDivs(max - 1, 3 * 5) - CountDivs(min - 1, 3 * 5);
  // others: Inclusion–exclusion principle
  int other = max - min - hello - world + helloWorld;

  return $"hello: {hello} world: {world} integer: {other}";
}

// Test (your example)
Console.WriteLine(Solution(1, 10));
// My comment [8..14) i.e. 8, 9, 10, 11, 12, 13
Console.WriteLine(Solution(8, 14));
</code>```

Outcome:

```<code>hello: 3 world: 1 integer: 5
hello: 2 world: 1 integer: 3
</code>```

Please, notice, that the solution has O(1) time complexity (loop will be inefficient, on inputs like Solution(100, 1000000000))

Edit: if you want to change your current code a bit and have an aggregate solution, you can try to extract the loop into a method and use Linq to aggregate the items:

```<code>using System.Linq;

...

private static IEnumerable<string> Generator(int min, int max) {
  // Your loop extracted: put "yield return ..." instead of "Console.WriteLine(...)"
  for (int i = min; i < max; ++i) {
    bool hello = i % 3 == 0;
    bool world = i % 5 == 0;

    if (hello && world) {
      // Or if you want return twice, just do it twice:
      // yield return "Hello";
      // yield return "World";

      yield return "HelloWorld";
    }
    else if (hello)
      yield return "Hello";
    else if (world)
      yield return "World";
    else
      yield return "integer";
  }
}

...

var data = Generator(1, 10)
  .GroupBy(item => item)
  .OrderBy(chunk => chunk.Key)
  .Select(chunk => $"{chunk.Key}: {chunk.Count()}");

var result = string.Join(" ", data);

Console.WriteLine(result);
</code>```

Outcome:

```<code>Hello: 3 integer: 5 World: 1
</code>```

Edit 2: No Linq solution, manual grouping

```<code>int min = 1;
int max = 10;

Dictionary<string, int> counts = new Dictionary<string, int>() {
  { "HelloWorld", 0},
  { "Hello", 0},
  { "World", 0},
  { "integer", 0},
};

foreach (var item in Generator(1, 10))
  counts[item] += 1;

string result =
  $"Hello: {counts["Hello"]} World: {counts["World"]} integer: {counts["integer"]}";

Console.Write(result);
</code>```

Outcome:

```<code>Hello: 3 World: 1 integer: 5
</code>```

Body:
Trying to get a summary from my current output. E.g. Hello: 5, World: 8, HelloWorld: 20, integer: 5. Currently this accepts a user input e.g. 1,10, 1 being minimum and 10 being maximum and outputs the following from the for loop. Don't know how to get the output into an array and then aggregate this.

Code so far:

 Console.WriteLine("Please enter a range?");
        string range = Console.ReadLine();
        string first = range.Split(',')[0];
        string last = range.Split(',')[1];
        int min = Int32.Parse(first);
        int max = Int32.Parse(last);
        Console.WriteLine("");
        Console.WriteLine("Heres the Output");
        Console.WriteLine("");

        for (int i = min; i < max ; i++ )
        {
            bool hello = i % 3 == 0;
            bool world = i % 5 == 0;

            if (hello && world)
                Console.WriteLine("HelloWorld");

            else if (hello)
                Console.WriteLine("Hello");
            else if (world)
                Console.WriteLine("World");
            else
                Console.WriteLine(i);
        }

        string list = Console.ReadLine();
        Console.WriteLine(list);

Body:
All you have to do is to use modular arithmetics; providing that 0 <= min < max :

private static int CountDivs(int value, int divisor) {
  return value < 0 ? 0 : value / divisor + 1;
}

private static string Solution(int min, int max) {
  int hello = CountDivs(max - 1, 3) - CountDivs(min - 1, 3);
  int world = CountDivs(max - 1, 5) - CountDivs(min - 1, 5);
  int helloWorld = CountDivs(max - 1, 3 * 5) - CountDivs(min - 1, 3 * 5);
  // others: Inclusion–exclusion principle
  int other = max - min - hello - world + helloWorld;

  return $"hello: {hello} world: {world} integer: {other}";
}

// Test (your example)
Console.WriteLine(Solution(1, 10));
// My comment [8..14) i.e. 8, 9, 10, 11, 12, 13
Console.WriteLine(Solution(8, 14));

Outcome:

hello: 3 world: 1 integer: 5
hello: 2 world: 1 integer: 3

Please, notice, that the solution has O(1) time complexity (loop will be inefficient, on inputs like Solution(100, 1000000000))

Edit: if you want to change your current code a bit and have an aggregate solution, you can try to extract the loop into a method and use Linq to aggregate the items:

using System.Linq;

...

private static IEnumerable<string> Generator(int min, int max) {
  // Your loop extracted: put "yield return ..." instead of "Console.WriteLine(...)"
  for (int i = min; i < max; ++i) {
    bool hello = i % 3 == 0;
    bool world = i % 5 == 0;

    if (hello && world) {
      // Or if you want return twice, just do it twice:
      // yield return "Hello";
      // yield return "World";

      yield return "HelloWorld";
    }
    else if (hello)
      yield return "Hello";
    else if (world)
      yield return "World";
    else
      yield return "integer";
  }
}

...

var data = Generator(1, 10)
  .GroupBy(item => item)
  .OrderBy(chunk => chunk.Key)
  .Select(chunk => $"{chunk.Key}: {chunk.Count()}");

var result = string.Join(" ", data);

Console.WriteLine(result);

Outcome:

Hello: 3 integer: 5 World: 1

Edit 2: No Linq solution, manual grouping

int min = 1;
int max = 10;

Dictionary<string, int> counts = new Dictionary<string, int>() {
  { "HelloWorld", 0},
  { "Hello", 0},
  { "World", 0},
  { "integer", 0},
};

foreach (var item in Generator(1, 10))
  counts[item] += 1;

string result =
  $"Hello: {counts["Hello"]} World: {counts["World"]} integer: {counts["integer"]}";

Console.Write(result);

Outcome:

Hello: 3 World: 1 integer: 5


问:
How to filter a sequence and retain evaluated pred values?
This is a scenario I encountered many times, yet didn't find an idiomatic approach for it...

Suppose one would like to use a self-defined self-pred function to filter a seq. This self-pred function returns nil for unwanted elements, and useful information for wanted elements. It is desirable to keep the evaluated self-pred values for these wanted elements.

My general solution is:

```<code>;; self-pred is a pred function which returns valuable info
;; in general, they are unique and can be used as key
(let [new-seq (filter self-pred aseq)]
   (zipmap (map self-pred new-seq) new-seq))
</code>```

Basically, it is to call self-pred twice on all wanted elements. I feel it is so ugly...

Wonder if there is any better ways. Much appreciated for any input!

答:
I wouldn't bother with keep, but would just use plain map & filter like so:

```<code>(def data (range 6))

(def my-pred odd?)

(defn zip [& colls] (apply map vector colls))  ; like Python zip
(defn filter-with-pred
  [vals pred]
  (filter #(first %)
    (zip (map pred vals) vals)))

(println (filter-with-pred data my-pred))
</code>```

with result:

```<code>([true 1] [true 3] [true 5])
</code>```

Body:
This is a scenario I encountered many times, yet didn't find an idiomatic approach for it...

Suppose one would like to use a self-defined self-pred function to filter a seq. This self-pred function returns nil for unwanted elements, and useful information for wanted elements. It is desirable to keep the evaluated self-pred values for these wanted elements.

My general solution is:

;; self-pred is a pred function which returns valuable info
;; in general, they are unique and can be used as key
(let [new-seq (filter self-pred aseq)]
   (zipmap (map self-pred new-seq) new-seq))

Basically, it is to call self-pred twice on all wanted elements. I feel it is so ugly...

Wonder if there is any better ways. Much appreciated for any input!

Body:
I wouldn't bother with keep, but would just use plain map & filter like so:

(def data (range 6))

(def my-pred odd?)

(defn zip [& colls] (apply map vector colls))  ; like Python zip
(defn filter-with-pred
  [vals pred]
  (filter #(first %)
    (zip (map pred vals) vals)))

(println (filter-with-pred data my-pred))

with result:

([true 1] [true 3] [true 5])


问:
How can I check if a Lucene IndexWriter instance is valid/open?
Sorry for the simple question, but there doesn't seem to be any obvious way. According to the documentation, it is recommended to keep a single instance of IndexWriter in memory that can be used again and again for updates, as opposed to opening and closing one for each change (which is much more costly).

However, the documentation also states that the IndexWriter should be closed if an exception occurs (e.g. OutOfMemoryException).

Therefore, I need some way to check if my instance of IndexWriter is valid or not, assuming it could be closed by some other operation.

I realize I will get an exception if I try to use it when it's closed, but rather than fail, I would like to check to see if I need to create a new IndexWriter before I need it so no failure occurs.

It seems to me a simple IsOpen property/method would be such an obvious addition.

Thoughts:

I suppose that if I could ensure that my class is the only thing capable of closing the IndexWriter, I could simply set it to null when it was closed and just check to make sure it's not null whenever I go to use it, however this would not handle cases where the IndexWriter closes itself (if such a case is possible now or in the future).

Another thought is that I could wrap an attempt to use it in a try/catch block and use the exception to indicate that it needs to be reopened, but this doesn't seem very efficient/elegant. What method would I use to test the validity of the IndexWriter?

答:
I suppose the IndexWriter would throw an AlreadyClosedException (see ensureOpen), if it is closed on access. So you could handle that in case the IndexWriter is not null.

HTH


问:
awk include column value in pattern
I am looking for a way to pattern match against another column in awk. For example, I wish to find rows for which the value in column 4 is nested in column 5.

Performing awk '$4 ~ /$5/' doesn't work, as the dollar sign is interpreted as part of the regular expression. How do I get the column 5 value into this pattern match!

Many thanks!

答:
```<code>> awk '$2 ~ $1' <<< "field another_field"
field another_field
</code>```

this will print lines when $2 contains the value of $1

Title: awk include column value in pattern

Body:
> awk '$2 ~ $1' <<< "field another_field"
field another_field

this will print lines when $2 contains the value of $1


问:
Python Payment details paypal
Im new with Paypal SDK, I want to get the payment details from the transaction id, my code is below:

```<code>import libs.paypalrestsdk as Paypals

api = Paypals.configure({
    "mode": "sandbox",
    "client_id": "MY-CLIENT_ID",
    "client_secret": "MY-SECRET"
})

payment = Paypals.Payment.find("5LA50068PM345884U")
</code>```

How can execute it?

How can pass my client_id and secret to use in the transaction?

答:
pip install paypalrestsdk</p>

```<code>    import paypalrestsdk
    sdk_mode = 'sandbox'
    paypal_client_id = "paypal_client_id"
    paypal_client_secret = "paypal_client_secret"
    paypal_api = paypalrestsdk.Api({
      'mode': sdk_mode,
      'client_id': paypal_client_id,
      'client_secret': paypal_client_secret})
    payment = paypalrestsdk.Payment.find("pay-xxx1233", api=paypal_api)
</code>```

Title: Python Payment details paypal

Body:
Im new with Paypal SDK, I want to get the payment details from the transaction id, my code is below:

import libs.paypalrestsdk as Paypals

api = Paypals.configure({
    "mode": "sandbox",
    "client_id": "MY-CLIENT_ID",
    "client_secret": "MY-SECRET"
})

payment = Paypals.Payment.find("5LA50068PM345884U")

How can execute it?

How can pass my client_id and secret to use in the transaction?

Body:
pip install paypalrestsdk

    import paypalrestsdk
    sdk_mode = 'sandbox'
    paypal_client_id = "paypal_client_id"
    paypal_client_secret = "paypal_client_secret"
    paypal_api = paypalrestsdk.Api({
      'mode': sdk_mode,
      'client_id': paypal_client_id,
      'client_secret': paypal_client_secret})
    payment = paypalrestsdk.Payment.find("pay-xxx1233", api=paypal_api)


问:
could not load file or assembly 'System.Web.MVC, version 4.0.0.0,'
I am getting run time error from one of the projects which is not an MVC project. I recently upgraded .net framework from 4.0 to 4.5.2 and am building the solution for deployment using MS Build 12.0. The solution builds just fine but am seeing the above exception when I run the service which has no reference to the said assembly.

The project is run as a windows service which uses windows workflow foundation to run some rules. I don't have IIS enabled on the target server and the web related dlls haven't been deployed as well

答:
You could try to check Windows service assemblies by this tool to understand what assembly requires MVC:

Could not load file or assembly or one of its dependencies


问:
NSTextField handling Enter key presses strangely
I'm sure I'm just using it incorrectly, but what I'm doing is I have a NSTextField with a attributed string with a few characters of text in a different font at the end of it. When the user clicks the text field, the text at the end should disappear, and when the user finishes editing their text and removes focus from the text field, the text gets added back to the end of the string they entered.

It's working fine when then user tabs out of the box, or clicks somewhere on the window to remove focus from the textfield. The only time it doesn't work is if they hit the "return" key in the text box. The text still gets added to the end of their string in this case, but it's in the same font as the rest of the string.

Here is the relevant portion of my code. I've verified that both methods are being called in the same sequence both when I tab out of a field and when I hit enter in the field.

```<code>- (void) selectText:(id)sender
{
    [titleText setStringValue: [NSString stringWithFormat:@"%@", userEditableText]];
}

- (void) textDidEndEditing:(NSNotification *)notification
{
    userEditableText = [textField stringValue];
    NSString* fullText = [NSString stringWithFormat:@"%@ (%@)", userEditableText, nonUserEditableText];

    NSRange range1;
    range1.location = 0;
    range1.length = [userEditableText length] - ([nonUserEditableText length] + 2);
    NSRange range2;
    range2.location = range1.length;
    range2.length = ([[nonUserEditableText length] length] + 2);
    NSRange range3;
    range3.location = 0;
    range3.length = [fullText length];

    NSFont *font = [NSFont fontWithName:@"Arial" size:14.0];

    NSMutableDictionary* stringAttributes = [[NSMutableDictionary alloc] init];
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:fullText attributes:stringAttributes];

    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    [paragraphStyle setLineBreakMode:NSLineBreakByTruncatingMiddle];

    [attrString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range1];
    [attrString addAttribute:NSFontAttributeName value:font range:range2];

    [textField setAttributedStringValue:attrString];
}
</code>```

答: Not sure exactly what I did, but I changed around a bunch of code in several classes and now everything is working properly. Wish I knew what I did...</p>

Body:
I'm sure I'm just using it incorrectly, but what I'm doing is I have a NSTextField with a attributed string with a few characters of text in a different font at the end of it. When the user clicks the text field, the text at the end should disappear, and when the user finishes editing their text and removes focus from the text field, the text gets added back to the end of the string they entered.

It's working fine when then user tabs out of the box, or clicks somewhere on the window to remove focus from the textfield. The only time it doesn't work is if they hit the "return" key in the text box. The text still gets added to the end of their string in this case, but it's in the same font as the rest of the string.

Here is the relevant portion of my code. I've verified that both methods are being called in the same sequence both when I tab out of a field and when I hit enter in the field.

- (void) selectText:(id)sender
{
    [titleText setStringValue: [NSString stringWithFormat:@"%@", userEditableText]];
}

- (void) textDidEndEditing:(NSNotification *)notification
{
    userEditableText = [textField stringValue];
    NSString* fullText = [NSString stringWithFormat:@"%@ (%@)", userEditableText, nonUserEditableText];

    NSRange range1;
    range1.location = 0;
    range1.length = [userEditableText length] - ([nonUserEditableText length] + 2);
    NSRange range2;
    range2.location = range1.length;
    range2.length = ([[nonUserEditableText length] length] + 2);
    NSRange range3;
    range3.location = 0;
    range3.length = [fullText length];

    NSFont *font = [NSFont fontWithName:@"Arial" size:14.0];

    NSMutableDictionary* stringAttributes = [[NSMutableDictionary alloc] init];
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:fullText attributes:stringAttributes];

    NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    [paragraphStyle setLineBreakMode:NSLineBreakByTruncatingMiddle];

    [attrString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range1];
    [attrString addAttribute:NSFontAttributeName value:font range:range2];

    [textField setAttributedStringValue:attrString];
}


问:
AppleScript: How do I activate an app when it is in fullscreen mode?
I have tried tell application Emacs to activate but it doesn't work when emacs is in fullscreen mode and focuses desktop instead (with the toolbar set on emacs).

答:
If your talking about Emacs For Mac OS X, then there should be a Dock Tile of the Emacs.app showing on the Dock, and you can set focus to the fullscreen occurrence, assuming there is only one occurrence of the Emacs.app running, with the following AppleScript code:

```<code>if application "Emacs" is running then
    tell application "System Events" to click UI element "Emacs" of list 1 of application process "Dock"
end if
</code>```

By clicking the Dock Tile, it takes you to the fullscreen occurrence where you can then run other code in your script to interact with Emacs. Obviously if Emacs is not in fullscreen view, this will bring the Emacs window forward the same as tell application "Emacs" to activate does.

Body:
If your talking about Emacs For Mac OS X, then there should be a Dock Tile of the Emacs.app showing on the Dock, and you can set focus to the fullscreen occurrence, assuming there is only one occurrence of the Emacs.app running, with the following AppleScript code:

if application "Emacs" is running then
    tell application "System Events" to click UI element "Emacs" of list 1 of application process "Dock"
end if

By clicking the Dock Tile, it takes you to the fullscreen occurrence where you can then run other code in your script to interact with Emacs. Obviously if Emacs is not in fullscreen view, this will bring the Emacs window forward the same as tell application "Emacs" to activate does.


问:
RxJava filter list inside observable
I have object

Response

```<code>public class Response {
    private List<Content> content;

    public static class Content {
        private boolean rated;
    }
}
</code>```

and I would like to filter List<Content> content by rated value. Im trying to do this like this

```<code>mResponseProvider.reponse()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .flatMapIterable(response -> response.getContent())
                .filter(content -> mAAA.isRated(content.getRated()))
                .toList()
                .subscribe(response -> {
                    doSomethingWithResponse(response);
                });
</code>```

But the problem is that my response in .subscribe() is List<Content>. How can I get in .subscribe() Response object with filtered values for List<Content> ?

答:
```<code>mResponseProvider.reponse()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .filter(response -> mAAA.isRated(response.getContent())) //1
            .subscribe(response -> {
                doSomethingWithResponse(response);
            });
</code>```

<p>//1  try to change argument to List in isRated </p>

Title: RxJava filter list inside observable

Body:
I have object

Response

public class Response {
    private List<Content> content;

    public static class Content {
        private boolean rated;
    }
}

and I would like to filter List<Content> content by rated value. Im trying to do this like this

mResponseProvider.reponse()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .flatMapIterable(response -> response.getContent())
                .filter(content -> mAAA.isRated(content.getRated()))
                .toList()
                .subscribe(response -> {
                    doSomethingWithResponse(response);
                });

But the problem is that my response in .subscribe() is List<Content>. How can I get in .subscribe() Response object with filtered values for List<Content> ?

Body:
mResponseProvider.reponse()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .filter(response -> mAAA.isRated(response.getContent())) //1
            .subscribe(response -> {
                doSomethingWithResponse(response);
            });

//1  try to change argument to List in isRated