问:
App has stopped while trying to display data from database. Android Studio
I'm currently trying to display a data from my database which I currently created. But when I try to run it in my phone, it always stops. This is my code

Edit Users Screen.java

```<code>    TextView textView;
    String text = " ";
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_users);

        // added

        textView = (TextView) findViewById(R.id.textView);

        DatabaseHelper db = new DatabaseHelper(this);

        // inserting users
        db.addUsers(new Users("1", "Julian", "juliankurtseguiran@gmail.com",      "seguiran"));

        // reading and displaying all users (you can remove it on where it should be placed

        List<Users> users = db.getAllUsers();

        for (Users u : users)
        {
            String log = "ID number:" + u.getIDnumber() + "Name:" + u.getName() +
                    "Email:" + u.getEmail() + "Password:" + u.getPassword();

            text = text + log;
        }

        textView.setText(text);
    }
</code>```

DatabaseHelper.java

```<code>    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_USERS_TABLE = "CREATE TABLE" + TABLE_USERS + "("
                + KEY_IDNUMBER + "INTEGER PRIMARY KEY," + KEY_NAME + "TEXT,"
                +  KEY_EMAIL + "TEXT," + KEY_PASSWORD + "TEXT," + ")";

        db.execSQL(CREATE_USERS_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS" + TABLE_USERS);
        onCreate(db);

    }

    void addUsers (Users users) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values  =  new ContentValues();
        values.put("KEY_NAME", users.getName());
        values.put("KEY_EMAIL", users.getEmail());
        values.put("KEY_PASSWORD", users.getPassword());

        db.insert(TABLE_USERS, null, values);
        db.close();

    }

    Users getUsers (int idnumber) {
        SQLiteDatabase db = this.getWritableDatabase();

        Cursor cursor = db.query(TABLE_USERS, new String[] {KEY_IDNUMBER, KEY_NAME, KEY_EMAIL, KEY_PASSWORD}, KEY_IDNUMBER
         + "=?", new String[] {String.valueOf(idnumber)}, null, null, null, null);

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

        Users users = new Users (Integer.parseInt(cursor.getString(0)),       cursor.getString(1), cursor.getString(2), cursor.getString(3));

        return users;

    }

    public List<Users> getAllUsers(){
        List<Users> usersList = new ArrayList<>();

        String selectQuery ="SELECT * FROM " + TABLE_USERS;

        SQLiteDatabase db  = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                Users users = new Users();
                users.setIDnumber(Integer.parseInt(cursor.getString(0)));
                users.setName(cursor.getString(1));
                users.setEmail(cursor.getString(2));
                users.setPassword(cursor.getString(3));

                usersList.add(users);
            } while (cursor.moveToNext());
        }

        return usersList;
    }

    public int updateUsers (Users users) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put("KEY_NAME", users.getName());
        values.put("KEY_EMAIL", users.getEmail());
        values.put("KEY_PASSWORD", users.getPassword());

        return db.update(TABLE_USERS, values, KEY_IDNUMBER + "=?",
                new String[]{String.valueOf(users.getIDnumber())});

    }

    public void deleteUsers (Users users) {

        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_USERS, KEY_IDNUMBER + "=?",
        new String[]{String.valueOf(users.getIDnumber())});

        db.close();
    }

    public int getUsersCount() {

        String countQuery = "SELECT * FROM " + TABLE_USERS;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        return cursor.getCount();
    }
</code>```

Users.java

```<code>    public class Users
    {
        int IDnumber;
        String Name;
        String Email;
        String Password;

        public Users(int i, String string, String cursorString, String s) {
            this.Name = Name;
            this.Email = Email;
            this.Password = Password;
        }

        public Users() {

        }

        public Users(String s, String julian, String cursorString, String seguiran) {
        }

        public int getIDnumber() {
            return IDnumber;
        }

        public void setIDnumber(int IDnumber) {
            this.IDnumber = IDnumber;
        }

        public String getName() {
            return Name;
        }

        public void setName(String name) {
            Name = name;
        }

        public String getEmail() {
            return Email;
        }

        public void setEmail(String email) {
            Email = email;
        }

        public String getPassword() {
            return Password;
        }

        public void setPassword(String password) {
            Password = password;
        }
    }
</code>```

Logcat

```<code>4-03 12:14:14.591 2418-2418/com.example.aadre.saferhomeph V/FA: onActivityCreated
04-03 12:14:14.651 2418-2418/com.example.aadre.saferhomeph E/SQLiteLog: (1) near "TABLEusers": syntax error
04-03 12:14:14.651 2418-2418/com.example.aadre.saferhomeph D/AndroidRuntime: Shutting down VM
04-03 12:14:14.651 2418-2418/com.example.aadre.saferhomeph W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41d85c08)
04-03 12:14:14.671 2418-2418/com.example.aadre.saferhomeph E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.aadre.saferhomeph, PID: 2418
                                                                             java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aadre.saferhomeph/com.example.aadre.saferhomeph.Edit_Users_Screen}: android.database.sqlite.SQLiteException: near "TABLEusers": syntax error (code 1): , while compiling: CREATE TABLEusers(idnumber INTEGER PRIMARY KEY, nameTEXT, email TEXT, password TEXT )
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:166)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:146)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5511)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                                                                                at dalvik.system.NativeStart.main(Native Method)
                                                                              Caused by: android.database.sqlite.SQLiteException: near "TABLEusers": syntax error (code 1): , while compiling: CREATE TABLEusers(idnumber INTEGER PRIMARY KEY, nameTEXT, email TEXT, password TEXT )
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:690)
                                                                                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:1806)
                                                                                at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1737)
                                                                                at com.example.aadre.saferhomeph.DatabaseHelper.onCreate(DatabaseHelper.java:38)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
                                                                                at com.example.aadre.saferhomeph.DatabaseHelper.addUsers(DatabaseHelper.java:50)
                                                                                at com.example.aadre.saferhomeph.Edit_Users_Screen.onCreate(Edit_Users_Screen.java:33)
                                                                                at android.app.Activity.performCreate(Activity.java:5322)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2303)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:166)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:146)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5511)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                                                                                at dalvik.system.NativeStart.main(Native Method)
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: message received msg=2, ext1=0, ext2=0
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: playback complete
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: callback application
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: back from callback
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: message received msg=7, ext1=0, ext2=0
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: unrecognized message: (7, 0, 0)
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: callback application
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: back from callback
04-03 12:14:19.561 2418-2456/com.example.aadre.saferhomeph W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.
</code>```

pls help

答:
write create query this way
String CREATE_USERS_TABLE ="create table  if not exists contactmaster(id integer primary key AUTOINCREMENT,name varchar(50),mob number(10))";</p>

Body:
I'm currently trying to display a data from my database which I currently created. But when I try to run it in my phone, it always stops. This is my code

Edit Users Screen.java

    TextView textView;
    String text = " ";
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_users);

        // added

        textView = (TextView) findViewById(R.id.textView);

        DatabaseHelper db = new DatabaseHelper(this);

        // inserting users
        db.addUsers(new Users("1", "Julian", "juliankurtseguiran@gmail.com",      "seguiran"));

        // reading and displaying all users (you can remove it on where it should be placed

        List<Users> users = db.getAllUsers();

        for (Users u : users)
        {
            String log = "ID number:" + u.getIDnumber() + "Name:" + u.getName() +
                    "Email:" + u.getEmail() + "Password:" + u.getPassword();

            text = text + log;
        }

        textView.setText(text);
    }

DatabaseHelper.java

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_USERS_TABLE = "CREATE TABLE" + TABLE_USERS + "("
                + KEY_IDNUMBER + "INTEGER PRIMARY KEY," + KEY_NAME + "TEXT,"
                +  KEY_EMAIL + "TEXT," + KEY_PASSWORD + "TEXT," + ")";

        db.execSQL(CREATE_USERS_TABLE);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS" + TABLE_USERS);
        onCreate(db);

    }

    void addUsers (Users users) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values  =  new ContentValues();
        values.put("KEY_NAME", users.getName());
        values.put("KEY_EMAIL", users.getEmail());
        values.put("KEY_PASSWORD", users.getPassword());

        db.insert(TABLE_USERS, null, values);
        db.close();

    }

    Users getUsers (int idnumber) {
        SQLiteDatabase db = this.getWritableDatabase();

        Cursor cursor = db.query(TABLE_USERS, new String[] {KEY_IDNUMBER, KEY_NAME, KEY_EMAIL, KEY_PASSWORD}, KEY_IDNUMBER
         + "=?", new String[] {String.valueOf(idnumber)}, null, null, null, null);

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

        Users users = new Users (Integer.parseInt(cursor.getString(0)),       cursor.getString(1), cursor.getString(2), cursor.getString(3));

        return users;

    }

    public List<Users> getAllUsers(){
        List<Users> usersList = new ArrayList<>();

        String selectQuery ="SELECT * FROM " + TABLE_USERS;

        SQLiteDatabase db  = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                Users users = new Users();
                users.setIDnumber(Integer.parseInt(cursor.getString(0)));
                users.setName(cursor.getString(1));
                users.setEmail(cursor.getString(2));
                users.setPassword(cursor.getString(3));

                usersList.add(users);
            } while (cursor.moveToNext());
        }

        return usersList;
    }

    public int updateUsers (Users users) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put("KEY_NAME", users.getName());
        values.put("KEY_EMAIL", users.getEmail());
        values.put("KEY_PASSWORD", users.getPassword());

        return db.update(TABLE_USERS, values, KEY_IDNUMBER + "=?",
                new String[]{String.valueOf(users.getIDnumber())});

    }

    public void deleteUsers (Users users) {

        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_USERS, KEY_IDNUMBER + "=?",
        new String[]{String.valueOf(users.getIDnumber())});

        db.close();
    }

    public int getUsersCount() {

        String countQuery = "SELECT * FROM " + TABLE_USERS;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        return cursor.getCount();
    }

Users.java

    public class Users
    {
        int IDnumber;
        String Name;
        String Email;
        String Password;

        public Users(int i, String string, String cursorString, String s) {
            this.Name = Name;
            this.Email = Email;
            this.Password = Password;
        }

        public Users() {

        }

        public Users(String s, String julian, String cursorString, String seguiran) {
        }

        public int getIDnumber() {
            return IDnumber;
        }

        public void setIDnumber(int IDnumber) {
            this.IDnumber = IDnumber;
        }

        public String getName() {
            return Name;
        }

        public void setName(String name) {
            Name = name;
        }

        public String getEmail() {
            return Email;
        }

        public void setEmail(String email) {
            Email = email;
        }

        public String getPassword() {
            return Password;
        }

        public void setPassword(String password) {
            Password = password;
        }
    }

Logcat

4-03 12:14:14.591 2418-2418/com.example.aadre.saferhomeph V/FA: onActivityCreated
04-03 12:14:14.651 2418-2418/com.example.aadre.saferhomeph E/SQLiteLog: (1) near "TABLEusers": syntax error
04-03 12:14:14.651 2418-2418/com.example.aadre.saferhomeph D/AndroidRuntime: Shutting down VM
04-03 12:14:14.651 2418-2418/com.example.aadre.saferhomeph W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41d85c08)
04-03 12:14:14.671 2418-2418/com.example.aadre.saferhomeph E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: com.example.aadre.saferhomeph, PID: 2418
                                                                             java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.aadre.saferhomeph/com.example.aadre.saferhomeph.Edit_Users_Screen}: android.database.sqlite.SQLiteException: near "TABLEusers": syntax error (code 1): , while compiling: CREATE TABLEusers(idnumber INTEGER PRIMARY KEY, nameTEXT, email TEXT, password TEXT )
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:166)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:146)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5511)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                                                                                at dalvik.system.NativeStart.main(Native Method)
                                                                              Caused by: android.database.sqlite.SQLiteException: near "TABLEusers": syntax error (code 1): , while compiling: CREATE TABLEusers(idnumber INTEGER PRIMARY KEY, nameTEXT, email TEXT, password TEXT )
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:1113)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:690)
                                                                                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:1806)
                                                                                at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1737)
                                                                                at com.example.aadre.saferhomeph.DatabaseHelper.onCreate(DatabaseHelper.java:38)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:164)
                                                                                at com.example.aadre.saferhomeph.DatabaseHelper.addUsers(DatabaseHelper.java:50)
                                                                                at com.example.aadre.saferhomeph.Edit_Users_Screen.onCreate(Edit_Users_Screen.java:33)
                                                                                at android.app.Activity.performCreate(Activity.java:5322)
                                                                                at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
                                                                                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2303)
                                                                                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
                                                                                at android.app.ActivityThread.access$900(ActivityThread.java:166)
                                                                                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:146)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5511)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
                                                                                at dalvik.system.NativeStart.main(Native Method)
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: message received msg=2, ext1=0, ext2=0
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: playback complete
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: callback application
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: back from callback
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: message received msg=7, ext1=0, ext2=0
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: unrecognized message: (7, 0, 0)
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: callback application
04-03 12:14:14.791 2418-2430/com.example.aadre.saferhomeph V/MediaPlayer: back from callback
04-03 12:14:19.561 2418-2456/com.example.aadre.saferhomeph W/DynamiteModule: Local module descriptor class for com.google.firebase.auth not found.

pls help


来源: stackexchange

问:
Python Json. Getting only the last element in the json array
I just started trying out python, and right now i am in a little bit of a dilemma.

I am trying to print from a json documents, and i am only getting the last element in the array.

```<code>[{
    "FullMeasure": "1/2 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1142,
    "IngredientName": "frozen corn",
    "IngredientStep": 10,
    "LanguageId": 0,
    "PostPreparation": ", thawed, drained",
    "PrePreparation": "",
    "QuantityNum": 0,
    "QuantityText": "1/2",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291555,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "1/4 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1523,
    "IngredientName": "red pepper",
    "IngredientStep": 20,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "chopped",
    "QuantityNum": 0,
    "QuantityText": "1/4",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291554,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "2 Tbsp.",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 20197,
    "IngredientName": "chopped green chiles",
    "IngredientStep": 30,
    "LanguageId": 0,
    "PostPreparation": ", drained",
    "PrePreparation": "canned ",
    "QuantityNum": 2,
    "QuantityText": "2",
    "QuantityUnit": "Tbsp.",
    "RecipeIngredientID": 6291552,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
{
    "FullMeasure": "",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 19682,
    "IngredientName": "KRAFT DELI DELUXE Process American Cheese Slice",
    "IngredientStep": 80,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "",
    "QuantityNum": 4,
    "QuantityText": "4",
    "QuantityUnit": "",
    "RecipeIngredientID": 6291558,
    "TrialMeasure": "",
    "TrialWeight": ""
  }
]
</code>```

I will like to get all the  ingredientID, so i wrote this little piece of code to grab the IngredientID

```<code>rec = recipes['Recipes'][0]['Ingredients']
        for records in rec:
            value = {
                        'Ingredient ID': records['IngredientID']
                    }
</code>```

when i return the value, i get

```<code>{
  "Ingreient ID": 19682
}
</code>```

I am trying to get the ingredient ID of each element and i just can't seem to figure it out. Any pointers will be well appreciated. Thank you

答:
If you want just the list of the IngredientID, then use [rec['IngredientID'] for rec in records]

```<code>records = [{
    "FullMeasure": "1/2 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1142,
    "IngredientName": "frozen corn",
    "IngredientStep": 10,
    "LanguageId": 0,
    "PostPreparation": ", thawed, drained",
    "PrePreparation": "",
    "QuantityNum": 0,
    "QuantityText": "1/2",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291555,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "1/4 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1523,
    "IngredientName": "red pepper",
    "IngredientStep": 20,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "chopped",
    "QuantityNum": 0,
    "QuantityText": "1/4",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291554,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "2 Tbsp.",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 20197,
    "IngredientName": "chopped green chiles",
    "IngredientStep": 30,
    "LanguageId": 0,
    "PostPreparation": ", drained",
    "PrePreparation": "canned ",
    "QuantityNum": 2,
    "QuantityText": "2",
    "QuantityUnit": "Tbsp.",
    "RecipeIngredientID": 6291552,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
{
    "FullMeasure": "",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 19682,
    "IngredientName": "KRAFT DELI DELUXE Process American Cheese Slice",
    "IngredientStep": 80,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "",
    "QuantityNum": 4,
    "QuantityText": "4",
    "QuantityUnit": "",
    "RecipeIngredientID": 6291558,
    "TrialMeasure": "",
    "TrialWeight": ""
  }
]

[rec['IngredientID'] for rec in records]
</code>```

Output:

```<code>[1142, 1523, 20197, 19682]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I just started trying out python, and right now i am in a little bit of a dilemma.

I am trying to print from a json documents, and i am only getting the last element in the array.

[{
    "FullMeasure": "1/2 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1142,
    "IngredientName": "frozen corn",
    "IngredientStep": 10,
    "LanguageId": 0,
    "PostPreparation": ", thawed, drained",
    "PrePreparation": "",
    "QuantityNum": 0,
    "QuantityText": "1/2",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291555,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "1/4 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1523,
    "IngredientName": "red pepper",
    "IngredientStep": 20,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "chopped",
    "QuantityNum": 0,
    "QuantityText": "1/4",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291554,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "2 Tbsp.",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 20197,
    "IngredientName": "chopped green chiles",
    "IngredientStep": 30,
    "LanguageId": 0,
    "PostPreparation": ", drained",
    "PrePreparation": "canned ",
    "QuantityNum": 2,
    "QuantityText": "2",
    "QuantityUnit": "Tbsp.",
    "RecipeIngredientID": 6291552,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
{
    "FullMeasure": "",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 19682,
    "IngredientName": "KRAFT DELI DELUXE Process American Cheese Slice",
    "IngredientStep": 80,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "",
    "QuantityNum": 4,
    "QuantityText": "4",
    "QuantityUnit": "",
    "RecipeIngredientID": 6291558,
    "TrialMeasure": "",
    "TrialWeight": ""
  }
]

I will like to get all the  ingredientID, so i wrote this little piece of code to grab the IngredientID

rec = recipes['Recipes'][0]['Ingredients']
        for records in rec:
            value = {
                        'Ingredient ID': records['IngredientID']
                    }

when i return the value, i get

{
  "Ingreient ID": 19682
}

I am trying to get the ingredient ID of each element and i just can't seem to figure it out. Any pointers will be well appreciated. Thank you

Body:
If you want just the list of the IngredientID, then use [rec['IngredientID'] for rec in records]

records = [{
    "FullMeasure": "1/2 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1142,
    "IngredientName": "frozen corn",
    "IngredientStep": 10,
    "LanguageId": 0,
    "PostPreparation": ", thawed, drained",
    "PrePreparation": "",
    "QuantityNum": 0,
    "QuantityText": "1/2",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291555,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "1/4 cup",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 1523,
    "IngredientName": "red pepper",
    "IngredientStep": 20,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "chopped",
    "QuantityNum": 0,
    "QuantityText": "1/4",
    "QuantityUnit": "cup",
    "RecipeIngredientID": 6291554,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
  {
    "FullMeasure": "2 Tbsp.",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 20197,
    "IngredientName": "chopped green chiles",
    "IngredientStep": 30,
    "LanguageId": 0,
    "PostPreparation": ", drained",
    "PrePreparation": "canned ",
    "QuantityNum": 2,
    "QuantityText": "2",
    "QuantityUnit": "Tbsp.",
    "RecipeIngredientID": 6291552,
    "TrialMeasure": "",
    "TrialWeight": ""
  },
{
    "FullMeasure": "",
    "FullWeight": "",
    "IngredientGridHeaders": null,
    "IngredientID": 19682,
    "IngredientName": "KRAFT DELI DELUXE Process American Cheese Slice",
    "IngredientStep": 80,
    "LanguageId": 0,
    "PostPreparation": "s",
    "PrePreparation": "",
    "QuantityNum": 4,
    "QuantityText": "4",
    "QuantityUnit": "",
    "RecipeIngredientID": 6291558,
    "TrialMeasure": "",
    "TrialWeight": ""
  }
]

[rec['IngredientID'] for rec in records]

Output:

[1142, 1523, 20197, 19682]


问:
Angular 2 Dropdown Options Default Value
In Angular 1 I could select the default option for a drop down box using the following:

```<code><select
    data-ng-model="carSelection"
    data-ng-options = "x.make for x in cars" data-ng-selected="$first">
</select>
</code>```

In Angular 2 I have:

```<code><select class="form-control" [(ngModel)]="selectedWorkout" (ngModelChange)="updateWorkout($event)">
    <option *ngFor="#workout of workouts">{{workout.name}}</option>
</select>
</code>```

How could I select a default option given my option data is:

[{name: 'arm'}, {name: 'back'}, {name:'leg'}] and my value I to default on on is back?

答:
Add this Code at o position of the select list.

<option [ngValue]="undefined" selected>Select</option>

Body:
In Angular 1 I could select the default option for a drop down box using the following:

<select
    data-ng-model="carSelection"
    data-ng-options = "x.make for x in cars" data-ng-selected="$first">
</select>

In Angular 2 I have:

<select class="form-control" [(ngModel)]="selectedWorkout" (ngModelChange)="updateWorkout($event)">
    <option *ngFor="#workout of workouts">{{workout.name}}</option>
</select>

How could I select a default option given my option data is:

[{name: 'arm'}, {name: 'back'}, {name:'leg'}] and my value I to default on on is back?


问:
Why is EF trying to insert NULL in id-column?
I am writing my project using Entity Framework 4.0 (Model first). At the beginning of the project, I faced with this problem: I am trying to insert the filled object in the database, but I get an exeption:

Cannot insert the value NULL into column 'CategoryId', table 'ForumDB.dbo.Categories'; column does not allow nulls. INSERT fails. The statement has been terminated.

Code:

```<code>    Category usingCategory = new Category("Using Forums", "usingforums", 0);
    using (Context)
    {
        Context.Categories.AddObject(usingCategory);
        Context.SaveChanges();
    }
</code>```

I checked this object, and I am sure that it is filled.

Just in case:

```<code>public Category(string name, string urlName, int index)
{
    CategoryId = Guid.NewGuid();
    Name = name;
    UrlName = urlName;
    CategoryIndex = index;
}
</code>```

What is going on?

答: I had created the table with int Id as PK, but had forgotten to set "Identity Specification" = True</p>

ContentLicense: CC BY-SA 4.0

Body:
I am writing my project using Entity Framework 4.0 (Model first). At the beginning of the project, I faced with this problem: I am trying to insert the filled object in the database, but I get an exeption:

Cannot insert the value NULL into column 'CategoryId', table 'ForumDB.dbo.Categories'; column does not allow nulls. INSERT fails. The statement has been terminated.

Code:

    Category usingCategory = new Category("Using Forums", "usingforums", 0);
    using (Context)
    {
        Context.Categories.AddObject(usingCategory);
        Context.SaveChanges();
    }

I checked this object, and I am sure that it is filled.

Just in case:

public Category(string name, string urlName, int index)
{
    CategoryId = Guid.NewGuid();
    Name = name;
    UrlName = urlName;
    CategoryIndex = index;
}

What is going on?


问:
Laravel how to sort multidimensional array
I'd like to sort 4 arrays that are enclosed within 1 array, but I have no clue how to do it.

```<code>    $poster = [];
    $character = [];
    $title = [];
    $date = [];

    foreach($person->getMovieCredits()->getCast() as $movie)
    {
        array_push($poster, $movie->getPosterPath());
        array_push($character, $movie->getCharacter());
        array_push($title, $movie->getTitle());
        array_push($date, $movie->getReleaseDate()->format('Y'));
    }

    $personArray = [
        'date' => $date,
        'title' => $title,
        'character' => $character,
        'poster' => $poster
    ];
</code>```

The thing is that I would like to sort them by date, but not losing data integrity with other arrays.

How should I do that?

答:
Try this</p>

```<code><?php
$date = ['2014-04-03', '2013-04-03', '2015-04-03', '2017-04-03', '2013-09-03'];
$title = ['title1', 'title2', 'title4', 'title5', 'title6'];
$character = ['character2', 'character5', 'character1', 'character8', 'character0'];
$poster = ['poster4', 'poster1', 'poster7', 'poster9', 'poster0'];

$personArray = [
    'date' => $date,
    'title' => $title,
    'character' => $character,
    'poster' => $poster
];

/*echo "```";
print_r( $personArray);*/

$length_count = count($date);

$new_array = array();
for($i=0; $i<$length_count ; $i++){
$new_array[$i] = array();
    foreach($personArray as $key => $value){
        $new_array[$i][$key] = $personArray[$key][$i];
    }
}

function date_compare($a, $b){
    $t1 = strtotime($a['date']);
    $t2 = strtotime($b['date']);
    return $t1 - $t2;
}
usort($new_array, 'date_compare');

//print_r( $new_array);
$sorted_array = array();
$sorted_array['date'] = array();
$sorted_array['title'] = array();
$sorted_array['character'] = array();
$sorted_array['poster'] = array();
foreach($new_array as $data){
     array_push($sorted_array['date'], $data['date']);
     array_push($sorted_array['title'], $data['title']);
     array_push($sorted_array['character'], $data['character']);
     array_push($sorted_array['poster'], $data['poster']);
}
//print_r( $sorted_array);

?>
</code>```

Body:
I'd like to sort 4 arrays that are enclosed within 1 array, but I have no clue how to do it.

    $poster = [];
    $character = [];
    $title = [];
    $date = [];

    foreach($person->getMovieCredits()->getCast() as $movie)
    {
        array_push($poster, $movie->getPosterPath());
        array_push($character, $movie->getCharacter());
        array_push($title, $movie->getTitle());
        array_push($date, $movie->getReleaseDate()->format('Y'));
    }

    $personArray = [
        'date' => $date,
        'title' => $title,
        'character' => $character,
        'poster' => $poster
    ];

The thing is that I would like to sort them by date, but not losing data integrity with other arrays.

How should I do that?

Body:
Try this

<?php
$date = ['2014-04-03', '2013-04-03', '2015-04-03', '2017-04-03', '2013-09-03'];
$title = ['title1', 'title2', 'title4', 'title5', 'title6'];
$character = ['character2', 'character5', 'character1', 'character8', 'character0'];
$poster = ['poster4', 'poster1', 'poster7', 'poster9', 'poster0'];

$personArray = [
    'date' => $date,
    'title' => $title,
    'character' => $character,
    'poster' => $poster
];

/*echo "<pre>";
print_r( $personArray);*/

$length_count = count($date);

$new_array = array();
for($i=0; $i<$length_count ; $i++){
$new_array[$i] = array();
    foreach($personArray as $key => $value){
        $new_array[$i][$key] = $personArray[$key][$i];
    }
}

function date_compare($a, $b){
    $t1 = strtotime($a['date']);
    $t2 = strtotime($b['date']);
    return $t1 - $t2;
}
usort($new_array, 'date_compare');

//print_r( $new_array);
$sorted_array = array();
$sorted_array['date'] = array();
$sorted_array['title'] = array();
$sorted_array['character'] = array();
$sorted_array['poster'] = array();
foreach($new_array as $data){
     array_push($sorted_array['date'], $data['date']);
     array_push($sorted_array['title'], $data['title']);
     array_push($sorted_array['character'], $data['character']);
     array_push($sorted_array['poster'], $data['poster']);
}
//print_r( $sorted_array);

?>


问:
Align a child class vertically to parent class
I am developing a webpage in which a user can show the larger image or preview of every thumbnails by hovering it.

I am using this Jquery code to show and center the larger image on the screen responsively.

```<code>var timer;
$(".theme-preview").hover(function() {
    var self = $(this);

    timer = setTimeout(function() {
      timer = false;

      $(self).children('.popup-preview').fadeIn("slow");

      $(self).children('.popup-preview').css("position", "fixed");
      $(self).children('.popup-preview').css("top", ($(window).height() / 2) - ($(self).children('.popup-preview').outerHeight() / 2));
      $(self).children('.popup-preview').css("left", ($(window).width() / 2) - ($(self).children('.popup-preview').outerWidth() / 2));

    }, 800);

    //return false;
  },
  function() {
    if (timer) {
      clearTimeout(timer);
      timer = false;
    } else {
      $(this).children('.popup-preview').fadeOut("fast");
    }

    //return false;
  }
);
</code>```

How can I align the larger image vertically the same with the parent class?

Here is my working sample code.

Update: Example is when the thumbnail is on the top or bottom of the screen and was hovered. The larger image should display vertically center of the screen.

答:
Jus make your .popup-preview 'absolute'
and left: 0; top: 50%; and add transform: translateY(-50%);

var timer;
  $(".theme-preview").hover(function() {
      var self = $(this);

      timer = setTimeout(function(){
        timer = false;

        $(self).children('.popup-preview').fadeIn("slow");

        $(self).children('.popup-preview').css("position","absolute");
        $(self).children('.popup-preview').css("left","0");
        $(self).children('.popup-preview').css("top","50%");
      }, 800);

      //return false;
    },
    function () {
      if(timer){
        clearTimeout(timer);
        timer = false;
      }else{
          $(this).children('.popup-preview').fadeOut("fast");
      }

      //return false;
    }
  );```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.popup-preview{
  background: black;
 position: absolute;
  -webkit-transform: translateY(-50%);
  -moz-transform: translateY(-50%);
  -o-transform:translateY(-50%);
  -ms-transform:translateY(-50%);
  transform: translateY(-50%);
 z-index: 1;
 display: none;
}

.col-md-6{
  float: left;
  margin-top: 50px;
}

.theme-preview {
  position: relative;
}</code>```

THEME 1-1

           Preview

THEME 1-1

           Preview

THEME 1-1

           Preview

THEME 1-1

           Preview

```

Body:
I am developing a webpage in which a user can show the larger image or preview of every thumbnails by hovering it.

I am using this Jquery code to show and center the larger image on the screen responsively.

var timer;
$(".theme-preview").hover(function() {
    var self = $(this);

    timer = setTimeout(function() {
      timer = false;

      $(self).children('.popup-preview').fadeIn("slow");

      $(self).children('.popup-preview').css("position", "fixed");
      $(self).children('.popup-preview').css("top", ($(window).height() / 2) - ($(self).children('.popup-preview').outerHeight() / 2));
      $(self).children('.popup-preview').css("left", ($(window).width() / 2) - ($(self).children('.popup-preview').outerWidth() / 2));

    }, 800);

    //return false;
  },
  function() {
    if (timer) {
      clearTimeout(timer);
      timer = false;
    } else {
      $(this).children('.popup-preview').fadeOut("fast");
    }

    //return false;
  }
);

How can I align the larger image vertically the same with the parent class?

Here is my working sample code.

Update: Example is when the thumbnail is on the top or bottom of the screen and was hovered. The larger image should display vertically center of the screen.

Body:
Jus make your .popup-preview 'absolute'
and left: 0; top: 50%; and add transform: translateY(-50%);

var timer;
  $(".theme-preview").hover(function() {
      var self = $(this);

      timer = setTimeout(function(){
        timer = false;

        $(self).children('.popup-preview').fadeIn("slow");

        $(self).children('.popup-preview').css("position","absolute");
        $(self).children('.popup-preview').css("left","0");
        $(self).children('.popup-preview').css("top","50%");
      }, 800);

      //return false;
    },
    function () {
      if(timer){
        clearTimeout(timer);
        timer = false;
      }else{
          $(this).children('.popup-preview').fadeOut("fast");
      }

      //return false;
    }
  );

.popup-preview{
  background: black;
 position: absolute;
  -webkit-transform: translateY(-50%);
  -moz-transform: translateY(-50%);
  -o-transform:translateY(-50%);
  -ms-transform:translateY(-50%);
  transform: translateY(-50%);
 z-index: 1;
 display: none;
}

.col-md-6{
  float: left;
  margin-top: 50px;
}

.theme-preview {
  position: relative;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="row">
  <div class="col-md-6 col-sm-6">
    <div class="theme-preview"><img class="img-responsive center-block" src="http://lorempixel.com/output/technics-q-c-140-80-6.jpg">
      <div class="popup-preview">
        <div class="title">THEME 1-1</div>
        <img src="http://lorempixel.com/output/technics-q-c-240-180-6.jpg" width="100%">
        <div class="preview-btn">
          <a href="#"> <span>Preview</span></a>
        </div>
      </div>
    </div>

  </div>
  <div class="col-md-6 col-sm-6">
    <div class="theme-preview"><img class="img-responsive center-block" src="http://lorempixel.com/output/technics-q-c-140-80-4.jpg">
      <div class="popup-preview">
        <div class="title">THEME 1-1</div>
        <img src="http://lorempixel.com/output/technics-q-c-240-180-4.jpg" width="100%">
        <div class="preview-btn">
          <a href="#"> <span>Preview</span></a>
        </div>
      </div>
    </div>
  </div>

  <div class="col-md-6 col-sm-6">
    <div class="theme-preview"><img class="img-responsive center-block" src="http://lorempixel.com/output/technics-q-c-140-80-3.jpg">
      <div class="popup-preview">
        <div class="title">THEME 1-1</div>
        <img src="http://lorempixel.com/output/technics-q-c-240-180-3.jpg" width="100%">
        <div class="preview-btn">
          <a href="#"> <span>Preview</span></a>
        </div>
      </div>
    </div>
  </div>
  <div class="col-md-6 col-sm-6">
    <div class="theme-preview"><img class="img-responsive center-block" src="http://lorempixel.com/output/technics-q-c-140-80-5.jpg">
      <div class="popup-preview">
        <div class="title">THEME 1-1</div>
        <img src="http://lorempixel.com/output/technics-q-c-240-180-5.jpg" width="100%">
        <div class="preview-btn">
          <a href="#"> <span>Preview</span></a>
        </div>
      </div>
    </div>
  </div>
</div>


问:
How to avoid showing characters like Ä in android keyboard
I am stuck in an issue where one of my user entering characters like Ä in an edittext and I am preparing an XML from that data. Due to encoding issue I can't prepare a valid XML from these kind of characters. Is there anyway I can stop user to enter such kind of characters or can I hide these characters from android default keyboard itself ?

Regards

答:
you can restrict the user to enter only specific characters in the edit text like below,

```<code><EditText
    android:id="@+id/YourEdittextId"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textNoSuggestions"
    android:privateImeOptions="nm"
    android:digits="0123456789 abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ" />
</code>```

Above code restrict user to enter only English digits, letters and space

Body:
you can restrict the user to enter only specific characters in the edit text like below,

<EditText
    android:id="@+id/YourEdittextId"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inputType="textNoSuggestions"
    android:privateImeOptions="nm"
    android:digits="0123456789 abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ" />

Above code restrict user to enter only English digits, letters and space


问:
Spinner does not show selected value
I have implemented the spinner by populating the array list through database.I can get and show the array list in my spinner array adapter but if I select the item in spinner it does not shown in spinner?What I had mistake here?

Here is my code,

```<code> Spinner spinner1 = (Spinner) findViewById(R.id.prospin);
     ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, providerlist);

  adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);
</code>```

I get the selected item string by using this,

```<code>Spinner provid = (Spinner)findViewById(R.id.prospin);
String provider =provid.getSelectedItem().toString();
</code>```

Can anyone help me out pls!!!

答:
Try This code</p>

```<code>ArrayAdapter<String> arrayAdapte=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,states);
    arrayAdapte.setDropDownViewResource(android.R.layout.simple_list_item_1 );
    spinnerState.setAdapter(arrayAdapte);

    String data=spinnerState.getSelectedItem().toString(); // this is select particular item from list;

    int position=spinnerState.getSelectedItemPosition(); // this return position of data selected in list;
</code>```

Title: Spinner does not show selected value

Body:
I have implemented the spinner by populating the array list through database.I can get and show the array list in my spinner array adapter but if I select the item in spinner it does not shown in spinner?What I had mistake here?

Here is my code,

 Spinner spinner1 = (Spinner) findViewById(R.id.prospin);
     ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, providerlist);

  adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);

I get the selected item string by using this,

Spinner provid = (Spinner)findViewById(R.id.prospin);
String provider =provid.getSelectedItem().toString();

Can anyone help me out pls!!!

Body:
Try This code

ArrayAdapter<String> arrayAdapte=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,states);
    arrayAdapte.setDropDownViewResource(android.R.layout.simple_list_item_1 );
    spinnerState.setAdapter(arrayAdapte);

    String data=spinnerState.getSelectedItem().toString(); // this is select particular item from list;

    int position=spinnerState.getSelectedItemPosition(); // this return position of data selected in list;


问:
In C++, How std::list in a struct will allocate memory and while using this in file mapping, the list result as empty
Problem faced :
List shared by using file mapping does'nt provide any data inside the list...

I have a process 1, in which i store all my datas as a List of hash_map and then i try to share that using File mapping ... in Process2 while i try to retrieve the datas inside list, there is no data found inside list..

PS: My exe is bundled with dll, I make my dll as process1 and exe as process2...

Here is my code,

Process1

```<code>/* this is in common headerFile */
typedef hash_map <std::wstring,std::wstring> AttrValues;
CString FileName = L"E:\\DataLog.txt";
</code>```

TCHAR szName[]=TEXT("Local\MyFileMappingObject");

```<code>struct ADstruct
{
    std::list<AttrValues> StList;
    int i;
};

/*Sharememory.cpp*/
DWORD SharedMemory()
{
                AttrValues HardCode;//Sample data which i am hard coding for testing
                HardCode[L"NAme"] = L"Test";
                HardCode[L"D.Name"] = L"SAP";
                std::list <AttrValues> HardCodedList;
                HardCodedList.push_back(HardCode);

ADstruct CheckStruct;

CheckStruct.i = 10;
        CheckStruct.StList = HardCodedList;

HANDLE hFile = INVALID_HANDLE_VALUE;// HANDLE  hFile;

    hFile = CreateFile(FileName.GetBuffer(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, 0, NULL);

    if(hFile == INVALID_HANDLE_VALUE)
    {
        printf("Error in creating a file..!");
        return 0;
    }
hMapFile = CreateFileMapping(
        hFile, // use paging file
        NULL, // default security
        PAGE_READWRITE, // read/write access
        0, // maximum object size (high-order DWORD)
        sizeof(ADstruct), // maximum object size (low-order DWORD)
        szName); // name of mapping object

    if (hMapFile == NULL)
    {
        _tprintf(TEXT("Could not create file mapping object (%d).\n"),
                                                                     GetLastError());
        return 1;
    }
ADstruct *ADobj = new ADstruct;

ADobj = (ADstruct *) MapViewOfFile(hMapFile, // handle to map object
                                  FILE_MAP_ALL_ACCESS, // read/write permission
                                  0,
                                  0,
                                sizeof(ADstruct) );

    CopyMemory( (ADstruct *) ADobj, &CheckStruct , sizeof(ADstruct) );
UnmapViewOfFile(pBuf);

    CloseHandle(hMapFile);
return 0
}
</code>```

Process 2:

```<code>BOOL ReadMemoryMapping()
{
    hash_map<LPWSTR,LPWSTR> ADdata;

   HANDLE hMapFile;

   HANDLE hFile = INVALID_HANDLE_VALUE;
   hMapFile = OpenFileMapping(
                   FILE_MAP_ALL_ACCESS,   // read/write access
                   FALSE,                 // do not inherit the name
                   szName);               // name of mapping object

   if (hMapFile == NULL)
   {
      _tprintf(TEXT("Could not open file mapping object (%d).\n"),
             GetLastError());
      return 1;
   }
ADstruct * readstruct;

    readstruct = (ADstruct *) MapViewOfFile(hMapFile, // handle to map object
               FILE_MAP_ALL_ACCESS,  // read/write permission
               0,
               0,
              sizeof(ADstruct));
    _tprintf(L"\nprint data%d\n",readstruct->i);

    AttrValues At ;
    for(std::list<AttrValues>::iterator list_iter = readstruct->StList.begin();
        list_iter != readstruct->StList.end(); list_iter++)
    {
        At.clear();
         At = *list_iter; //*****Here the code crashes as there is no datas inside***
        if(At.empty() == 1)
            printf("List is empty\n");
        std::wcout<<endl<<endl<<"Attribute List In EXE : StList"<<endl;

        for(AttrValues :: iterator it1 = list_iter->begin(); it1!= list_iter->end(); it1++)
        {
            std::wcout<<it1->first<<endl;
            std::wcout<<it1->second<<endl;

        }
    }
 UnmapViewOfFile(readstruct);

   CloseHandle(hMapFile);

   return 0;
}
</code>```

答:
Firstly, regular std::list is a multi-level data structure, which contains references to other locations in address space. The actual list elements are not stored inside the std::list object. They are stored elsewhere in memory. And std::list simply refers to these elements through pointers. Your file mapping simply shares the top-level std::list object but it does not even attempt to share the actual list elements.

Secondly, even if you somehow manage to magically determine and share the entire region of address space that holds everyhting related to your std::list it still would not work, unless you somehow ensured that in all processes that memory is mapped to exactly the same region in address space.  That applies to any data structure that uses pointers.

In other words, it can't be done. You can't just take an existing plain std::list and share it through memory mapping.

In fact, your attempts to copy non-trivial object (like std::list) by using such functions as CopyMemory might be already enough to destroy the object's integrity. No need to involve memory mappings.

Body:
Problem faced :
List shared by using file mapping does'nt provide any data inside the list...

I have a process 1, in which i store all my datas as a List of hash_map and then i try to share that using File mapping ... in Process2 while i try to retrieve the datas inside list, there is no data found inside list..

PS: My exe is bundled with dll, I make my dll as process1 and exe as process2...

Here is my code,

Process1

/* this is in common headerFile */
typedef hash_map <std::wstring,std::wstring> AttrValues;
CString FileName = L"E:\\DataLog.txt";

TCHAR szName[]=TEXT("Local\MyFileMappingObject");

struct ADstruct
{
    std::list<AttrValues> StList;
    int i;
};

/*Sharememory.cpp*/
DWORD SharedMemory()
{
                AttrValues HardCode;//Sample data which i am hard coding for testing
                HardCode[L"NAme"] = L"Test";
                HardCode[L"D.Name"] = L"SAP";
                std::list <AttrValues> HardCodedList;
                HardCodedList.push_back(HardCode);

ADstruct CheckStruct;

CheckStruct.i = 10;
        CheckStruct.StList = HardCodedList;

HANDLE hFile = INVALID_HANDLE_VALUE;// HANDLE  hFile;

    hFile = CreateFile(FileName.GetBuffer(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, 0, NULL);

    if(hFile == INVALID_HANDLE_VALUE)
    {
        printf("Error in creating a file..!");
        return 0;
    }
hMapFile = CreateFileMapping(
        hFile, // use paging file
        NULL, // default security
        PAGE_READWRITE, // read/write access
        0, // maximum object size (high-order DWORD)
        sizeof(ADstruct), // maximum object size (low-order DWORD)
        szName); // name of mapping object

    if (hMapFile == NULL)
    {
        _tprintf(TEXT("Could not create file mapping object (%d).\n"),
                                                                     GetLastError());
        return 1;
    }
ADstruct *ADobj = new ADstruct;

ADobj = (ADstruct *) MapViewOfFile(hMapFile, // handle to map object
                                  FILE_MAP_ALL_ACCESS, // read/write permission
                                  0,
                                  0,
                                sizeof(ADstruct) );

    CopyMemory( (ADstruct *) ADobj, &CheckStruct , sizeof(ADstruct) );
UnmapViewOfFile(pBuf);

    CloseHandle(hMapFile);
return 0
}

Process 2:

BOOL ReadMemoryMapping()
{
    hash_map<LPWSTR,LPWSTR> ADdata;

   HANDLE hMapFile;

   HANDLE hFile = INVALID_HANDLE_VALUE;
   hMapFile = OpenFileMapping(
                   FILE_MAP_ALL_ACCESS,   // read/write access
                   FALSE,                 // do not inherit the name
                   szName);               // name of mapping object

   if (hMapFile == NULL)
   {
      _tprintf(TEXT("Could not open file mapping object (%d).\n"),
             GetLastError());
      return 1;
   }
ADstruct * readstruct;

    readstruct = (ADstruct *) MapViewOfFile(hMapFile, // handle to map object
               FILE_MAP_ALL_ACCESS,  // read/write permission
               0,
               0,
              sizeof(ADstruct));
    _tprintf(L"\nprint data%d\n",readstruct->i);

    AttrValues At ;
    for(std::list<AttrValues>::iterator list_iter = readstruct->StList.begin();
        list_iter != readstruct->StList.end(); list_iter++)
    {
        At.clear();
         At = *list_iter; //*****Here the code crashes as there is no datas inside***
        if(At.empty() == 1)
            printf("List is empty\n");
        std::wcout<<endl<<endl<<"Attribute List In EXE : StList"<<endl;

        for(AttrValues :: iterator it1 = list_iter->begin(); it1!= list_iter->end(); it1++)
        {
            std::wcout<<it1->first<<endl;
            std::wcout<<it1->second<<endl;

        }
    }
 UnmapViewOfFile(readstruct);

   CloseHandle(hMapFile);

   return 0;
}


问:
Custom code snippet for WebStorm and PhpStorm
I use custom code snippet for Sublime Text like custom comments, function, reusable block code, CDN and more.. but I could not do that in WebStorm and PhpStorm IDE.

Here is my building block code snippet (comments) for Sublime Text:

```<code> /*============================
            comments
   ============================*/
</code>```

and this code blocks for HTML5 comments

```<code> <!-----------------------
           comments
   ----------------------->
</code>```

Moreover I'm new user for JetBrains software. Can I use custom code snippet above in JetBrains software ?

答:
Finally I get a tips !  PhpStorm allows you to create your own live templates (code snippets) to optimise your workflows.

Open the settings dialog and head into Editor | Live Templates, you can see the available live templates grouped by language. To add a new template click the + (plus) button and select Live Template. Specify the abbreviation (the short bit of text you type that will be expanded to the full code snippet) and a description.

Then provide the full code snippet in the Template text field. You can include variables in the template in the format $<variable name>$, which will allow you to provide values when the template is expanded. PhpStorm recognises $END$ as a special variable indicating the final position of the cursor after the template has been expanded and values have been provided for all variables.

Next click the Define warning text to specify which language the template is for and optionally the context it is available in.

Now the template is ready to be used. Open a file and type the abbreviation that was specified earlier, then hit Tab to expand the template. The cursor will be positioned on the first variable, provide a value then hit Tab to keep moving through all available variables. The final position of the cursor will be the location of the $END$ variable.

Further Reading

Creating & Editing Live Templates

Body:
I use custom code snippet for Sublime Text like custom comments, function, reusable block code, CDN and more.. but I could not do that in WebStorm and PhpStorm IDE.

Here is my building block code snippet (comments) for Sublime Text:

 /*============================
            comments
   ============================*/

and this code blocks for HTML5 comments

Moreover I'm new user for JetBrains software. Can I use custom code snippet above in JetBrains software ?


问:
model binder provider not being called in dotnet core 1.1.1, mvc 1.1.2
I have created a brand new .netcore project using the wizard, and added the following.

The Model Binder Provider is Never Called

Is this a bug? What am I missing? If I just throw an exception in GetBinder it's never reached.

```<code>public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc(
        _ =>
        {
            _.ModelBinderProviders.Add(new PartyModelBinderProvider());
        });
}
</code>```

The provider

```<code>public class PartyModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        if (context.Metadata.ModelType == typeof(Party))
            return new PartyModelBinder();
        return null;
    }
}
</code>```

The binder

```<code>public class PartyModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        return Task.CompletedTask;
    }
}
</code>```

My action methods are pretty simple.

```<code>[HttpGet]
public IActionResult Test()
{
    return View(new Party());
}

[HttpPost]
public IActionResult Test(Party party)
{
    return View(party);
}
</code>```

答:
Turns out that the Add method doesn't achieve the desired result, as the model binders are evaluated in order, until one is selected.

The only way to add a model binder in dotnet core is to use Insert.

```<code>services.AddMvc(
    _ =>
    {
        _.ModelBinderProviders.Insert(0, new PartyModelBinderProvider());
    });
</code>```

Body:
I have created a brand new .netcore project using the wizard, and added the following.

The Model Binder Provider is Never Called

Is this a bug? What am I missing? If I just throw an exception in GetBinder it's never reached.

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc(
        _ =>
        {
            _.ModelBinderProviders.Add(new PartyModelBinderProvider());
        });
}

The provider

public class PartyModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(ModelBinderProviderContext context)
    {
        if (context.Metadata.ModelType == typeof(Party))
            return new PartyModelBinder();
        return null;
    }
}

The binder

public class PartyModelBinder : IModelBinder
{
    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        return Task.CompletedTask;
    }
}

My action methods are pretty simple.

[HttpGet]
public IActionResult Test()
{
    return View(new Party());
}

[HttpPost]
public IActionResult Test(Party party)
{
    return View(party);
}

Body:
Turns out that the Add method doesn't achieve the desired result, as the model binders are evaluated in order, until one is selected.

The only way to add a model binder in dotnet core is to use Insert.

services.AddMvc(
    _ =>
    {
        _.ModelBinderProviders.Insert(0, new PartyModelBinderProvider());
    });


问:
Search customer by last name in database
```<code>function search_customer($search) {
       global $db;
       $query = 'SELECT * FROM customers WHERE lastName LIKE :search';

       $statement = $db->prepare($query);
       $statement->bindValue(':search', $search);
       $statement->execute();
       $results = $statement->fetchAll();
       $statement->closeCursor();
       return $results;
}
</code>```

<p>This code gives me a table of customers with the lastName that the user puts into the search field. But it obviously only works when you put in the full last name. Can anyone tell me how I have to change the code to get results too if I only enter for example the first letter of the last name ? </p>

答:
A MySQL solution

Depending on how you want the match to work, you could do something like the following:

```<code>$query = 'SELECT * FROM customers
              WHERE lastName
              LIKE CONCAT("%", :search, "%" )';
</code>```

That would return rows where lastName had :search as a substring.  CONCAT() is a variadic function which combines all of it's arguments into a single string.

```<code>CONCAT("%", "John", "%") = "%John%"
</code>```

How it works

Why are the percents useful?  MySQL's LIKE is a pattern matching keyword.  LIKE has 2 special characters "%" and "_" which are used to signify "match any group of 0 or more characters" and "match any single character" respectively.

For example:

"%john%" would match "johnson", "john", or "baker-johnson"

"joh_" would match "john", but NOT "joh"

If you just care about matching rows whose last names start with a specific string, you would remove the first "%". This would have better performance and be able to make use of indexes if you make them.

Also, as noted in another answer, this concatenation could be performed in PHP if desired.  This has the benefit of being more versatile if you wanted to let your users select the type of match to use (e.g. "Search whole string" vs. "Search from beginning of string")

Escape those wildcards!

If you do use a construct like this, be sure to escape LIKE's wildcard characters ("%" and "_") unless you want your users to be able to use the wildcard characters themselves.  If you do let them use them you should add a LIMIT clause to your statement, or you run the risk of someone entering "%" and returning every row in your table.

If you want to escape things you can use a method like that provided in this answer:
https://stackoverflow.com/a/5020292

You could easily use PHP's str_replace() combined with the linked answer to perform your escapes.  For example:

```<code>function search_customer($search) {
   global $db;
   $query = 'SELECT * FROM customers
                 WHERE lastName
                 LIKE CONCAT("%", :search, "%" ) ESCAPE "|"';

   $escapedSearch = str_replace($search, ["%","_"], ["|%","|_"]);

   $statement = $db->prepare($query);
   $statement->bindValue(':search', $escapedSearch);
   $statement->execute();
   $results = $statement->fetchAll();
   $statement->closeCursor();
   return $results;
}
</code>```

Body:
function search_customer($search) {
       global $db;
       $query = 'SELECT * FROM customers WHERE lastName LIKE :search';

       $statement = $db->prepare($query);
       $statement->bindValue(':search', $search);
       $statement->execute();
       $results = $statement->fetchAll();
       $statement->closeCursor();
       return $results;
}

This code gives me a table of customers with the lastName that the user puts into the search field. But it obviously only works when you put in the full last name. Can anyone tell me how I have to change the code to get results too if I only enter for example the first letter of the last name ?

Body:
A MySQL solution

Depending on how you want the match to work, you could do something like the following:

$query = 'SELECT * FROM customers
              WHERE lastName
              LIKE CONCAT("%", :search, "%" )';

That would return rows where lastName had :search as a substring.  CONCAT() is a variadic function which combines all of it's arguments into a single string.

CONCAT("%", "John", "%") = "%John%"

How it works

Why are the percents useful?  MySQL's LIKE is a pattern matching keyword.  LIKE has 2 special characters "%" and "_" which are used to signify "match any group of 0 or more characters" and "match any single character" respectively.

For example:

"%john%" would match "johnson", "john", or "baker-johnson"

"joh_" would match "john", but NOT "joh"

If you just care about matching rows whose last names start with a specific string, you would remove the first "%". This would have better performance and be able to make use of indexes if you make them.

Also, as noted in another answer, this concatenation could be performed in PHP if desired.  This has the benefit of being more versatile if you wanted to let your users select the type of match to use (e.g. "Search whole string" vs. "Search from beginning of string")

Escape those wildcards!

If you do use a construct like this, be sure to escape LIKE's wildcard characters ("%" and "_") unless you want your users to be able to use the wildcard characters themselves.  If you do let them use them you should add a LIMIT clause to your statement, or you run the risk of someone entering "%" and returning every row in your table.

If you want to escape things you can use a method like that provided in this answer:
https://stackoverflow.com/a/5020292

You could easily use PHP's str_replace() combined with the linked answer to perform your escapes.  For example:

function search_customer($search) {
   global $db;
   $query = 'SELECT * FROM customers
                 WHERE lastName
                 LIKE CONCAT("%", :search, "%" ) ESCAPE "|"';

   $escapedSearch = str_replace($search, ["%","_"], ["|%","|_"]);

   $statement = $db->prepare($query);
   $statement->bindValue(':search', $escapedSearch);
   $statement->execute();
   $results = $statement->fetchAll();
   $statement->closeCursor();
   return $results;
}


答:
Few days before I was facing same issue I solved this by creating below method.

```<code>public static String stripSpecialUTFChars(String string) {
    return string.replaceAll("\u0080", "");
  }
</code>```

Please pass your String to above method and use this like below

```<code>textView.setText(Html.fromHtml(stripSpecialUTFChars(yourString)));
</code>```

actually this issue is due to UTF characters.

Title: How to avoid showing characters like Ä in android keyboard

Body:
I am stuck in an issue where one of my user entering characters like Ä in an edittext and I am preparing an XML from that data. Due to encoding issue I can't prepare a valid XML from these kind of characters. Is there anyway I can stop user to enter such kind of characters or can I hide these characters from android default keyboard itself ?

Regards

Body:
Few days before I was facing same issue I solved this by creating below method.

public static String stripSpecialUTFChars(String string) {
    return string.replaceAll("\u0080", "");
  }

Please pass your String to above method and use this like below

textView.setText(Html.fromHtml(stripSpecialUTFChars(yourString)));

actually this issue is due to UTF characters.


问:
Getting an accurate count of Facebook Likes and Facebook Shares for a URL using Graph API
I am aware that there are many posts where this same question has been asked and solutions provided, however I found that the popular and the accepted answers don't seem to provide an accurate answer. This could very well be due to a Facebook Graph API bug, but since I am not really sure, hence the question.I have used the url below

```<code>https://graph.facebook.com/?fields=id,share,og_object{likes.limit(0).summary(true),comments.limit(0).summary(true)}&id=http://www.yoururl.com
</code>```

And the result I get is as follows

```<code>{
   "id": "http://www.yoururl.com",
   "share": {
  "comment_count": 0,
  "share_count": 4068
 },
   "og_object": {
  "likes": {
     "data": [

     ],
     "summary": {
        "total_count": 0
     }
  },
  "comments": {
     "data": [

     ],
     "summary": {
        "order": "chronological",
        "total_count": 0
     }
  },
  "id": "1088138987923727"
   }
}
</code>```

Which is inaccurate as the share_count is actually shares + comments + likes, in short engagement, is there a better way to achieve the same?.

答: After spending a long time researching this, I have come to conclusion that there is no better way to do this. Facebook counts all these as interactions.</p>

Body:
I am aware that there are many posts where this same question has been asked and solutions provided, however I found that the popular and the accepted answers don't seem to provide an accurate answer. This could very well be due to a Facebook Graph API bug, but since I am not really sure, hence the question.I have used the url below

https://graph.facebook.com/?fields=id,share,og_object{likes.limit(0).summary(true),comments.limit(0).summary(true)}&id=http://www.yoururl.com

And the result I get is as follows

{
   "id": "http://www.yoururl.com",
   "share": {
  "comment_count": 0,
  "share_count": 4068
 },
   "og_object": {
  "likes": {
     "data": [

     ],
     "summary": {
        "total_count": 0
     }
  },
  "comments": {
     "data": [

     ],
     "summary": {
        "order": "chronological",
        "total_count": 0
     }
  },
  "id": "1088138987923727"
   }
}

Which is inaccurate as the share_count is actually shares + comments + likes, in short engagement, is there a better way to achieve the same?.


问:
angularjs push function not working
Hi I am trying to make a single page angular js application but while adding to the list "schedulelist" only the latest record are getting pushed into the list and all the previous records are getting replaced by the latest record

This is my Html:

```<code> <table class="table1" cellspacing=2 cellpadding=5 border=0>
  <div ng-repeat="scheduleDTO in schedules">
<tr>
<td>
       <SELECT id="days" name="days" class="form-right" style="width:90%" ng-model="scheduleDTO.day_of_the_week" required>

                    <OPTION selected value="Monday">Monday</OPTION>
                    <OPTION value="Tuesday">Tuesday</OPTION>
                    <OPTION value="Wednesday">Wednesday</OPTION>
                    <OPTION value="Thursday">Thursday</OPTION>
                    <OPTION value="Friday">Friday</OPTION>
                    <OPTION value="Saturday">Saturday</OPTION>
                    <OPTION value="Sunday">Sunday</OPTION>
        </SELECT>

</td>
<td>
       <SELECT id="start_time" name="Start" class="form-right" style="width:90%" ng-model="scheduleDTO.start_time" required>
                    <OPTION value="1:00">01:00</OPTION>
                    <OPTION value="2:00">02:00</OPTION>
                    <OPTION value="3:00">03:00</OPTION>
                    <OPTION value="4:00">04:00</OPTION>
                    <OPTION value="5:00">05:00</OPTION>
                    <OPTION value="6:00">06:00</OPTION>
                    <OPTION value="7:00">07:00</OPTION>
                    <OPTION value="8:00">08:00</OPTION>
                    <OPTION selected value="9:00">09:00</OPTION>
                    <OPTION value="10:00">10:00</OPTION>
                    <OPTION value="11:00">11:00</OPTION>
                    <OPTION value="12:00">12:00</OPTION>
        </SELECT>

</td>
<td>
<SELECT id="start" name="am" class="form-right" style="width:90%" ng-model="scheduleDTO.start_time_meridiem"required>
                    <OPTION selected value="AM">AM</OPTION>
                    <OPTION value="PM">PM</OPTION>
</SELECT>

<td><SELECT  id="end_time"class="form-right" name="end" style="width:90%" ng-model="scheduleDTO.end_time" required>
                    <OPTION value="1:00">01:00</OPTION>
                    <OPTION value="2:00">02:00</OPTION>
                    <OPTION value="3:00">03:00</OPTION>
                    <OPTION value="4:00">04:00</OPTION>
                    <OPTION selected value="5:00">05:00</OPTION>
                    <OPTION value="6:00">06:00</OPTION>
                    <OPTION value="7:00">07:00</OPTION>
                    <OPTION value="8:00">08:00</OPTION>
                    <OPTION value="9:00">09:00</OPTION>
                    <OPTION value="10:00">10:00</OPTION>
                    <OPTION value="11:00">11:00</OPTION>
                    <OPTION value="12:00">12:00</OPTION>
        </SELECT>

        </td>
<td>

<SELECT id="end" name="pm" class="form-right" style="width:90%" ng-model="scheduleDTO.end_time_meridiem" required>
                    <OPTION value="AM">AM</OPTION>
                    <OPTION selected value="PM">PM</OPTION>
</SELECT>

</td>
<td><input type="button" class="addSch" ng-click="add(scheduleDTO)" value="Add Schedule" style="width:90%"> <!-- add_schedule(); -->

</td>
</tr>
</div>
</table>
<table align='center' class="table1" cellspacing=2 cellpadding=5 id="table" border=0>

<tr ng-repeat="ScheduleDTO in schedulelist">

<td>{{scheduleDTO.day_of_the_week}}</td>
<td>{{scheduleDTO.start_time}}</td>
<td>{{scheduleDTO.start_time_meridiem}}</td><td>To</td>
<td>{{scheduleDTO.end_time}}</td>
<td>{{scheduleDTO.end_time_meridiem}}</td>
<td><input type='button' value='Delete' class='delete' ng-click="remove(scheduleDTO)"></td>

</table>
</code>```

This is rthe controller:

```<code>$scope.schedulelist = [

    ];

    $scope.add = function (schedule)
            {                   schedule.volunteer_id="";
                                schedule.sid="";
                   $scope.schedulelist.push({"ScheduleDTO":schedule});
                    alert(angular.toJson($scope.schedulelist));
            };
    $scope.remove = function(schedule) {
                var index = $scope.schedulelist.indexOf(schedule);
                $scope.schedulelist.splice(index, 1);
                    alert(angular.toJson($scope.schedulelist));
            };
</code>```

答:
The problem is in this line

$scope.schedulelist.push({"ScheduleDTO":schedule});

each team a record is pushed to the ScheduleDTO property of the object and each time new entry replaces the old one.

You can do something like this

```<code>$scope.add = function (schedule)
{                   schedule.volunteer_id="";
schedule.sid="";
//Create an array of ScheduleDTO
if(  $scope.schedulelist.ScheduleDTO instanceof Array == false) {
    $scope.schedulelist.ScheduleDTO = []
}
//Push the schedule into the array
$scope.schedulelist.ScheduleDTO.push(schedule);
alert(angular.toJson($scope.schedulelist));
};
</code>```

Title: angularjs push function not working

Body:
Hi I am trying to make a single page angular js application but while adding to the list "schedulelist" only the latest record are getting pushed into the list and all the previous records are getting replaced by the latest record

This is my Html:

       <SELECT id="days" name="days" class="form-right" style="width:90%" ng-model="scheduleDTO.day_of_the_week" required>

                    <OPTION selected value="Monday">Monday</OPTION>
                    <OPTION value="Tuesday">Tuesday</OPTION>
                    <OPTION value="Wednesday">Wednesday</OPTION>
                    <OPTION value="Thursday">Thursday</OPTION>
                    <OPTION value="Friday">Friday</OPTION>
                    <OPTION value="Saturday">Saturday</OPTION>
                    <OPTION value="Sunday">Sunday</OPTION>
        </SELECT>

       <SELECT id="start_time" name="Start" class="form-right" style="width:90%" ng-model="scheduleDTO.start_time" required>
                    <OPTION value="1:00">01:00</OPTION>
                    <OPTION value="2:00">02:00</OPTION>
                    <OPTION value="3:00">03:00</OPTION>
                    <OPTION value="4:00">04:00</OPTION>
                    <OPTION value="5:00">05:00</OPTION>
                    <OPTION value="6:00">06:00</OPTION>
                    <OPTION value="7:00">07:00</OPTION>
                    <OPTION value="8:00">08:00</OPTION>
                    <OPTION selected value="9:00">09:00</OPTION>
                    <OPTION value="10:00">10:00</OPTION>
                    <OPTION value="11:00">11:00</OPTION>
                    <OPTION value="12:00">12:00</OPTION>
        </SELECT>

<SELECT id="start" name="am" class="form-right" style="width:90%" ng-model="scheduleDTO.start_time_meridiem"required>
                    <OPTION selected value="AM">AM</OPTION>
                    <OPTION value="PM">PM</OPTION>
</SELECT>

<SELECT  id="end_time"class="form-right" name="end" style="width:90%" ng-model="scheduleDTO.end_time" required>
                    <OPTION value="1:00">01:00</OPTION>
                    <OPTION value="2:00">02:00</OPTION>
                    <OPTION value="3:00">03:00</OPTION>
                    <OPTION value="4:00">04:00</OPTION>
                    <OPTION selected value="5:00">05:00</OPTION>
                    <OPTION value="6:00">06:00</OPTION>
                    <OPTION value="7:00">07:00</OPTION>
                    <OPTION value="8:00">08:00</OPTION>
                    <OPTION value="9:00">09:00</OPTION>
                    <OPTION value="10:00">10:00</OPTION>
                    <OPTION value="11:00">11:00</OPTION>
                    <OPTION value="12:00">12:00</OPTION>
        </SELECT>

<SELECT id="end" name="pm" class="form-right" style="width:90%" ng-model="scheduleDTO.end_time_meridiem" required>
                    <OPTION value="AM">AM</OPTION>
                    <OPTION selected value="PM">PM</OPTION>
</SELECT>

<input type="button" class="addSch" ng-click="add(scheduleDTO)" value="Add Schedule" style="width:90%">

{{scheduleDTO.day_of_the_week}}
{{scheduleDTO.start_time}}
{{scheduleDTO.start_time_meridiem}}	To
{{scheduleDTO.end_time}}
{{scheduleDTO.end_time_meridiem}}
<input type='button' value='Delete' class='delete' ng-click="remove(scheduleDTO)">

This is rthe controller:

$scope.schedulelist = [

    ];

    $scope.add = function (schedule)
            {                   schedule.volunteer_id="";
                                schedule.sid="";
                   $scope.schedulelist.push({"ScheduleDTO":schedule});
                    alert(angular.toJson($scope.schedulelist));
            };
    $scope.remove = function(schedule) {
                var index = $scope.schedulelist.indexOf(schedule);
                $scope.schedulelist.splice(index, 1);
                    alert(angular.toJson($scope.schedulelist));
            };

Body:
The problem is in this line

$scope.schedulelist.push({"ScheduleDTO":schedule});

each team a record is pushed to the ScheduleDTO property of the object and each time new entry replaces the old one.

You can do something like this

$scope.add = function (schedule)
{                   schedule.volunteer_id="";
schedule.sid="";
//Create an array of ScheduleDTO
if(  $scope.schedulelist.ScheduleDTO instanceof Array == false) {
    $scope.schedulelist.ScheduleDTO = []
}
//Push the schedule into the array
$scope.schedulelist.ScheduleDTO.push(schedule);
alert(angular.toJson($scope.schedulelist));
};


问:
Python: straight line, Slope k is known, one point P1 is known, length P1P2 is known, how to get P2?
For a straight line, Slope k is known, one point(x1,y1) is know, how to get the other point (x2,y2) using python?
I know the way to do calculation, but have no idea to code using python.

(y2-y1)/(x2-x1)=k

sqrt((x2-x1)^2+(y2-y1)^2)= length

if two unknown equations, both two variables with power 1, linalg-solve should work, but now the power of 2rd function is 2, how to deal with that?

I tried to simplify as following, but seems I cannot apply linalg-solve

kx2-y2-kx1+y1 = 0

(y2-y1)^2 + (x2-x1)^2 = length^2

Supplement：
thanks to all of your answer...Posh_Pumpkin's code is exactly what I want, previously I thought I need to apply linalg-solve which I usually use.

here is a test code based on his answer:suppose P1 = (1,1) p2=(x,y), p1p2= sqrt(2), k=1,then p2 must be = (2,2)

```<code>import numpy as np
import math
k = 1
d = math.sqrt(2)
p1 = (1,1)
r_sq = d**2 / (1 + k**2)
r = math.sqrt(r_sq)
p2 = (p1[0] + r, p1[1] + k*r)
print(p2)
</code>```

答:
You can solve this with basic trig.  Here is the general derivation.

```<code>let p1 = (x1,y1) & p2 = (x2 = x1+d, y2 = y1+h),
let L be the distance between p1 & p2
* note for p1 & p2 such that x1 != x2 && y1 != y2, a triangle can be formed Ldh such that tan(theta) = h/d

h/d is the slope of the line (m) connecting points p1 & p2, so tan(theta) = m
 => theta = atan(m), from the law of sines ( sin(a)/A = sin(b)/B )
 => sin(90)/L = sin(atan(theta))/y2
 => y2 = L*sin( atan(theta) )

now get x from the point slope form of a line y= y1+m(x-x1) = (y-y1)/m +x1
so x2 = (y2-y1)/m + x1
</code>```

Here is this expressed in python:

```<code>from math import sin,  atan
from random import randint

# This is the formula for (x2,y2) = p2
x = lambda y2, m, x1, y1: (y2 - y1)/float(m) + x1
y = lambda l, m, y1: l*sin( atan(m)  ) + y1

# p2 constraints ( x2 > x1, y2 > y1 or x2 > x1, y2 < y1 )
p1 =  [randint(1,1000),randint(1,1000)]
p2 =  [randint(p1[0],1001),randint(0,p1[1])]

# calculate distance between p1 & p2 (L), also calculate slope (m)
slope = lambda x1,y1,x2,y2: (y2-y1)/float(x2-x1)
dist  = lambda x1,y1,x2,y2: ( (y2-y1)**2 + (x2-x1)**2  )**(0.5)
L = dist(p1[0],p1[1],p2[0],p2[1])
m = slope(p1[0],p1[1],p2[0],p2[1])

#  now see if our functions for x & y yield p2
y2 = y(L,m,p1[1])
p_derived = [ x(y2,m,p1[0],p1[1]),y2  ]
print "p1: ",p1 , "p2 actual: ",p2, "p2 derived: ",p_derived
</code>```

So here I generate two random points p1 and p2, and verify that p2 can be calculated from the slope, distance, and p1 by comparing my derived result to the actual result.

Body:
For a straight line, Slope k is known, one point(x1,y1) is know, how to get the other point (x2,y2) using python?
I know the way to do calculation, but have no idea to code using python.

(y2-y1)/(x2-x1)=k

sqrt((x2-x1)^2+(y2-y1)^2)= length

if two unknown equations, both two variables with power 1, linalg-solve should work, but now the power of 2rd function is 2, how to deal with that?

I tried to simplify as following, but seems I cannot apply linalg-solve

kx2-y2-kx1+y1 = 0

(y2-y1)^2 + (x2-x1)^2 = length^2

Supplement：
thanks to all of your answer...Posh_Pumpkin's code is exactly what I want, previously I thought I need to apply linalg-solve which I usually use.

here is a test code based on his answer:suppose P1 = (1,1) p2=(x,y), p1p2= sqrt(2), k=1,then p2 must be = (2,2)

import numpy as np
import math
k = 1
d = math.sqrt(2)
p1 = (1,1)
r_sq = d**2 / (1 + k**2)
r = math.sqrt(r_sq)
p2 = (p1[0] + r, p1[1] + k*r)
print(p2)

Body:
You can solve this with basic trig.  Here is the general derivation.

let p1 = (x1,y1) & p2 = (x2 = x1+d, y2 = y1+h),
let L be the distance between p1 & p2
* note for p1 & p2 such that x1 != x2 && y1 != y2, a triangle can be formed Ldh such that tan(theta) = h/d

h/d is the slope of the line (m) connecting points p1 & p2, so tan(theta) = m
 => theta = atan(m), from the law of sines ( sin(a)/A = sin(b)/B )
 => sin(90)/L = sin(atan(theta))/y2
 => y2 = L*sin( atan(theta) )

now get x from the point slope form of a line y= y1+m(x-x1) = (y-y1)/m +x1
so x2 = (y2-y1)/m + x1

Here is this expressed in python:

from math import sin,  atan
from random import randint

# This is the formula for (x2,y2) = p2
x = lambda y2, m, x1, y1: (y2 - y1)/float(m) + x1
y = lambda l, m, y1: l*sin( atan(m)  ) + y1

# p2 constraints ( x2 > x1, y2 > y1 or x2 > x1, y2 < y1 )
p1 =  [randint(1,1000),randint(1,1000)]
p2 =  [randint(p1[0],1001),randint(0,p1[1])]

# calculate distance between p1 & p2 (L), also calculate slope (m)
slope = lambda x1,y1,x2,y2: (y2-y1)/float(x2-x1)
dist  = lambda x1,y1,x2,y2: ( (y2-y1)**2 + (x2-x1)**2  )**(0.5)
L = dist(p1[0],p1[1],p2[0],p2[1])
m = slope(p1[0],p1[1],p2[0],p2[1])

#  now see if our functions for x & y yield p2
y2 = y(L,m,p1[1])
p_derived = [ x(y2,m,p1[0],p1[1]),y2  ]
print "p1: ",p1 , "p2 actual: ",p2, "p2 derived: ",p_derived

So here I generate two random points p1 and p2, and verify that p2 can be calculated from the slope, distance, and p1 by comparing my derived result to the actual result.