问:
Android SQLiteException during creating Table
I am getting this error again and again.Can't figure it out how to solve.I am sharing the codes.Please help!

Codes:
addnewcontact.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.sambal.contactmanager.AddNewContact">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name:"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="79dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Mobile Number:"
        android:id="@+id/textView2"
        android:layout_below="@+id/textView"
        android:layout_alignParentStart="true"
        android:layout_marginTop="25dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Email Id:"
        android:id="@+id/textView3"
        android:layout_marginTop="26dp"
        android:layout_below="@+id/textView2"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/etName"
        android:layout_above="@+id/textView2"
        android:layout_alignParentEnd="true"
        android:layout_toEndOf="@+id/textView2" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/etMobileNumber"
        android:layout_above="@+id/textView3"
        android:layout_alignEnd="@+id/etName"
        android:layout_toEndOf="@+id/textView2" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:id="@+id/etEmail"
        android:layout_alignBottom="@+id/textView3"
        android:layout_alignParentEnd="true"
        android:layout_toEndOf="@+id/textView2" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SAVE"
        android:id="@+id/btnSave"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>
</code>```

here is DataBaseHelper.java

```<code>package com.example.sambal.contactmanager;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME="contacts.db";
    private static final String TABLE_NAME="contacts";

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

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE" + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,MOBILE_NUMBER INTEGER,E-MAIL TEXT)");

    }

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

    }
    public boolean insertData(String name,int mobile_number,String email){
        SQLiteDatabase db = this.getWritableDatabase();

            ContentValues contentValues = new ContentValues();
            contentValues.put("NAME", name);
            contentValues.put("MOBILE_NUMBER", mobile_number);
            contentValues.put("E-MAIL", email);

            long result = db.insert(TABLE_NAME, null, contentValues);
            if (result == -1)
                return false;
            else
                return true;

        }

    }
</code>```

AddNewContact.java

```<code>package com.example.sambal.contactmanager;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddNewContact extends AppCompatActivity {
    EditText name,mobile_number,email;
    Button save;

    private DatabaseHelper databaseHelper;

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

        databaseHelper=new DatabaseHelper(this);

        name= (EditText) findViewById(R.id.etName);
        mobile_number= (EditText) findViewById(R.id.etMobileNumber);
        email= (EditText) findViewById(R.id.etEmail);
        save= (Button) findViewById(R.id.btnSave);

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

                    boolean result = databaseHelper.insertData(name.getText().toString(),
                            Integer.parseInt(mobile_number.getText().toString()), email.getText().toString());
                    if (result)
                        Toast.makeText(AddNewContact.this, "Data Inserted", Toast.LENGTH_SHORT).show();
                    else
                        Toast.makeText(AddNewContact.this, "Data Not Inserted", Toast.LENGTH_SHORT).show();

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

Here is MainActivity.java

```<code>package com.example.sambal.contactmanager;

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

public class MainActivity extends AppCompatActivity {
    DatabaseHelper databaseHelper;
    Button addcontact;

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

        databaseHelper=new DatabaseHelper(this);
        addcontact= (Button) findViewById(R.id.btnAdd);
         addcontact.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 Intent intent=new Intent(MainActivity.this,AddNewContact.class);
                 startActivity(intent);
             }
         });
    }
}
</code>```

The logcat

```<code> 03-30 23:11:27.650 28750-28750/com.example.sambal.contactmanager E/SQLiteLog: (1) near "TABLEcontacts": syntax error
03-30 23:11:27.673 28750-28750/com.example.sambal.contactmanager E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.sambal.contactmanager, PID: 28750
                                                                                android.database.sqlite.SQLiteException: near "TABLEcontacts": syntax error (code 1): , while compiling: CREATE TABLEcontacts (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,MOBILE_NUMBER INTEGER,E-MAIL TEXT)
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                                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:1674)
                                                                                at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
                                                                                at com.example.sambal.contactmanager.DatabaseHelper.onCreate(DatabaseHelper.java:25)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
                                                                                at com.example.sambal.contactmanager.DatabaseHelper.insertData(DatabaseHelper.java:40)
                                                                                at com.example.sambal.contactmanager.AddNewContact$1.onClick(AddNewContact.java:33)
                                                                                at android.view.View.performClick(View.java:4790)
                                                                                at android.view.View$PerformClick.run(View.java:19883)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
03-30 23:11:54.392 29707-29707/com.example.sambal.contactmanager E/SQLiteLog: (1) near "TABLEcontacts": syntax error
03-30 23:11:54.397 29707-29707/com.example.sambal.contactmanager E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.sambal.contactmanager, PID: 29707
                                                                                android.database.sqlite.SQLiteException: near "TABLEcontacts": syntax error (code 1): , while compiling: CREATE TABLEcontacts (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,MOBILE_NUMBER INTEGER,E-MAIL TEXT)
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                                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:1674)
                                                                                at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
                                                                                at com.example.sambal.contactmanager.DatabaseHelper.onCreate(DatabaseHelper.java:25)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
                                                                                at com.example.sambal.contactmanager.DatabaseHelper.insertData(DatabaseHelper.java:40)
                                                                                at com.example.sambal.contactmanager.AddNewContact$1.onClick(AddNewContact.java:33)
                                                                                at android.view.View.performClick(View.java:4790)
                                                                                at android.view.View$PerformClick.run(View.java:19883)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
03-30 23:12:08.363 30145-30145/com.example.sambal.contactmanager E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.sambal.contactmanager, PID: 30145
                                                                                java.lang.NumberFormatException: Invalid int: "fhh"
                                                                                at java.lang.Integer.invalidInt(Integer.java:138)
                                                                                at java.lang.Integer.parse(Integer.java:410)
                                                                                at java.lang.Integer.parseInt(Integer.java:367)
                                                                                at java.lang.Integer.parseInt(Integer.java:334)
                                                                                at com.example.sambal.contactmanager.AddNewContact$1.onClick(AddNewContact.java:34)
                                                                                at android.view.View.performClick(View.java:4790)
                                                                                at android.view.View$PerformClick.run(View.java:19883)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
</code>```

答:
You need to add a space between Table keyword and Table Name:

```<code>db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,MOBILE_NUMBER INTEGER,E-MAIL TEXT)");
</code>```

Here is an example:

```<code>  String sql = "CREATE TABLE " + TABLE_NAME + " (" + TITLE
      + " text not null, " + BODY + " text not null " + ");";

  db.execSQL(sql);
</code>```

Body:
I am getting this error again and again.Can't figure it out how to solve.I am sharing the codes.Please help!

Codes:
addnewcontact.xml

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name:"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="79dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Mobile Number:"
        android:id="@+id/textView2"
        android:layout_below="@+id/textView"
        android:layout_alignParentStart="true"
        android:layout_marginTop="25dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Email Id:"
        android:id="@+id/textView3"
        android:layout_marginTop="26dp"
        android:layout_below="@+id/textView2"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/etName"
        android:layout_above="@+id/textView2"
        android:layout_alignParentEnd="true"
        android:layout_toEndOf="@+id/textView2" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/etMobileNumber"
        android:layout_above="@+id/textView3"
        android:layout_alignEnd="@+id/etName"
        android:layout_toEndOf="@+id/textView2" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:ems="10"
        android:id="@+id/etEmail"
        android:layout_alignBottom="@+id/textView3"
        android:layout_alignParentEnd="true"
        android:layout_toEndOf="@+id/textView2" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="SAVE"
        android:id="@+id/btnSave"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

here is DataBaseHelper.java

package com.example.sambal.contactmanager;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME="contacts.db";
    private static final String TABLE_NAME="contacts";

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

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE" + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,MOBILE_NUMBER INTEGER,E-MAIL TEXT)");

    }

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

    }
    public boolean insertData(String name,int mobile_number,String email){
        SQLiteDatabase db = this.getWritableDatabase();

            ContentValues contentValues = new ContentValues();
            contentValues.put("NAME", name);
            contentValues.put("MOBILE_NUMBER", mobile_number);
            contentValues.put("E-MAIL", email);

            long result = db.insert(TABLE_NAME, null, contentValues);
            if (result == -1)
                return false;
            else
                return true;

        }

    }

AddNewContact.java

package com.example.sambal.contactmanager;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AddNewContact extends AppCompatActivity {
    EditText name,mobile_number,email;
    Button save;

    private DatabaseHelper databaseHelper;

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

        databaseHelper=new DatabaseHelper(this);

        name= (EditText) findViewById(R.id.etName);
        mobile_number= (EditText) findViewById(R.id.etMobileNumber);
        email= (EditText) findViewById(R.id.etEmail);
        save= (Button) findViewById(R.id.btnSave);

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

                    boolean result = databaseHelper.insertData(name.getText().toString(),
                            Integer.parseInt(mobile_number.getText().toString()), email.getText().toString());
                    if (result)
                        Toast.makeText(AddNewContact.this, "Data Inserted", Toast.LENGTH_SHORT).show();
                    else
                        Toast.makeText(AddNewContact.this, "Data Not Inserted", Toast.LENGTH_SHORT).show();

            }
        });
    }
}

Here is MainActivity.java

package com.example.sambal.contactmanager;

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

public class MainActivity extends AppCompatActivity {
    DatabaseHelper databaseHelper;
    Button addcontact;

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

        databaseHelper=new DatabaseHelper(this);
        addcontact= (Button) findViewById(R.id.btnAdd);
         addcontact.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 Intent intent=new Intent(MainActivity.this,AddNewContact.class);
                 startActivity(intent);
             }
         });
    }
}

The logcat

 03-30 23:11:27.650 28750-28750/com.example.sambal.contactmanager E/SQLiteLog: (1) near "TABLEcontacts": syntax error
03-30 23:11:27.673 28750-28750/com.example.sambal.contactmanager E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.sambal.contactmanager, PID: 28750
                                                                                android.database.sqlite.SQLiteException: near "TABLEcontacts": syntax error (code 1): , while compiling: CREATE TABLEcontacts (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,MOBILE_NUMBER INTEGER,E-MAIL TEXT)
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                                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:1674)
                                                                                at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
                                                                                at com.example.sambal.contactmanager.DatabaseHelper.onCreate(DatabaseHelper.java:25)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
                                                                                at com.example.sambal.contactmanager.DatabaseHelper.insertData(DatabaseHelper.java:40)
                                                                                at com.example.sambal.contactmanager.AddNewContact$1.onClick(AddNewContact.java:33)
                                                                                at android.view.View.performClick(View.java:4790)
                                                                                at android.view.View$PerformClick.run(View.java:19883)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
03-30 23:11:54.392 29707-29707/com.example.sambal.contactmanager E/SQLiteLog: (1) near "TABLEcontacts": syntax error
03-30 23:11:54.397 29707-29707/com.example.sambal.contactmanager E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.sambal.contactmanager, PID: 29707
                                                                                android.database.sqlite.SQLiteException: near "TABLEcontacts": syntax error (code 1): , while compiling: CREATE TABLEcontacts (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,MOBILE_NUMBER INTEGER,E-MAIL TEXT)
                                                                                at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                                at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:889)
                                                                                at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:500)
                                                                                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:1674)
                                                                                at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
                                                                                at com.example.sambal.contactmanager.DatabaseHelper.onCreate(DatabaseHelper.java:25)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
                                                                                at com.example.sambal.contactmanager.DatabaseHelper.insertData(DatabaseHelper.java:40)
                                                                                at com.example.sambal.contactmanager.AddNewContact$1.onClick(AddNewContact.java:33)
                                                                                at android.view.View.performClick(View.java:4790)
                                                                                at android.view.View$PerformClick.run(View.java:19883)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)
03-30 23:12:08.363 30145-30145/com.example.sambal.contactmanager E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.sambal.contactmanager, PID: 30145
                                                                                java.lang.NumberFormatException: Invalid int: "fhh"
                                                                                at java.lang.Integer.invalidInt(Integer.java:138)
                                                                                at java.lang.Integer.parse(Integer.java:410)
                                                                                at java.lang.Integer.parseInt(Integer.java:367)
                                                                                at java.lang.Integer.parseInt(Integer.java:334)
                                                                                at com.example.sambal.contactmanager.AddNewContact$1.onClick(AddNewContact.java:34)
                                                                                at android.view.View.performClick(View.java:4790)
                                                                                at android.view.View$PerformClick.run(View.java:19883)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:135)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5268)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)

Body:
You need to add a space between Table keyword and Table Name:

db.execSQL("CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,MOBILE_NUMBER INTEGER,E-MAIL TEXT)");

Here is an example:

  String sql = "CREATE TABLE " + TABLE_NAME + " (" + TITLE
      + " text not null, " + BODY + " text not null " + ");";

  db.execSQL(sql);


来源: stackexchange

问:
How to fix "namespace x already contains a definition for x" error? Happened after converting to VS2010
Specifically the error occurs in the Resources.Designer.cs:

Error 2   The namespace 'ModulusFE' already contains a definition for 'StockChartX'   Resources.Designer.cs   11  21  ModulusFE.StockChartX

I've googled this and am still quite confused. Does anyone know anything I might try?

I have tried rebuilding and cleaning, as well as renaming the Resources.Designer.cs file in hopes that it would rebuild, but no luck.

The top of the code says this:

```<code>// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.225
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
</code>```

Any ideas whatsoever would be appreciated.

答:
This is not the best solve, but if you really don't care it is an easy solution.
I simply renamed my class. So I had class Card and I changed it to MyCard.</p>

ContentLicense: CC BY-SA 3.0

Body:
Specifically the error occurs in the Resources.Designer.cs:

Error 2   The namespace 'ModulusFE' already contains a definition for 'StockChartX'   Resources.Designer.cs   11  21  ModulusFE.StockChartX

I've googled this and am still quite confused. Does anyone know anything I might try?

I have tried rebuilding and cleaning, as well as renaming the Resources.Designer.cs file in hopes that it would rebuild, but no luck.

The top of the code says this:

// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.225
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>

Any ideas whatsoever would be appreciated.


问:
heroku not updating database schema
Heroku doesn't seem to update my database schema when I deploy. Here are the details:

Here is what is should look like for the User class:

```<code>create_table "users", :force => true do |t|
t.string   "username"
t.datetime "created_at"
t.datetime "updated_at"
t.string   "email"
t.string   "encrypted_password"
t.string   "salt"
t.string   "remember_token"
t.boolean  "admin",              :default => false
</code>```

end

Here is my deploy procedure:

```<code>git push heroku master
heroku rake db:migrate
heroku db:push
</code>```

Everything seems to go smoothly... except that if I check the actually User table in db...

```<code>heroku console User
</code>```

... I get an old version of User...

```<code>User(id: integer, username: string, created_at: datetime, updated_at: datetime)
</code>```

Any idea what I am doing wrong?
Thanks a lot for your help!

Simon

答:
Run heroku rake run db:migrate
Then heroku restart

Refresh your web page and it should all work.

ContentLicense: CC BY-SA 2.5

Title: heroku not updating database schema

Body:
Heroku doesn't seem to update my database schema when I deploy. Here are the details:

Here is what is should look like for the User class:

create_table "users", :force => true do |t|
t.string   "username"
t.datetime "created_at"
t.datetime "updated_at"
t.string   "email"
t.string   "encrypted_password"
t.string   "salt"
t.string   "remember_token"
t.boolean  "admin",              :default => false

end

Here is my deploy procedure:

git push heroku master
heroku rake db:migrate
heroku db:push

Everything seems to go smoothly... except that if I check the actually User table in db...

heroku console User

... I get an old version of User...

User(id: integer, username: string, created_at: datetime, updated_at: datetime)

Any idea what I am doing wrong?
Thanks a lot for your help!

Simon

ContentLicense: CC BY-SA 4.0


问:
How to downsize my scss code?
I started writing classes such as:

```<code>.small-bottom-margin { margin-bottom: $margin; }
.small-top-margin { margin-top: $margin; }
.medium-bottom-margin { margin-bottom: $margin *2; }
.medium-top-margin { margin-top: $margin *2; }
.large-bottom-margin { margin-bottom: $margin *4; }
.large-top-margin { margin-top: $margin *4; }
</code>```

Soon I wanted to be able to specify what happened on different screens, such as (for the small bottom margin example):

```<code>@media #{$small-only} { .small-bottom-margin-sm { margin-bottom: $margin; }}
@media #{$medium-only} { .small-bottom-margin-md { margin-bottom: $margin; }}
@media #{$large-only} { .small-bottom-margin-lg { margin-bottom: $margin; }}
@media #{$small-up} { .small-bottom-margin-sm-up { margin-bottom: $margin; }}
@media #{$medium-up} { .small-bottom-margin-md-up { margin-bottom: $margin; }}
@media #{$large-up} { .small-bottom-margin-lg-up { margin-bottom: $margin; }}
@media #{$medium-down} { .small-bottom-margin-sm-mp { margin-bottom: $margin; }}
</code>```

... etc for all the margin sizes (medium and large), and for the top margin too.

I find this extremely practical in terms of readability of my html + speed to add margins through my app, which is often a pain when you have a complicated layout, but it seems awfully long to write in my css.

Is it bad practice to do this?
  If not, is there some kind of css function that would allow me to automatically generate all this code?

答:
I think this is a matter of your own coding style and taste, in the first place, but for me these classes seem kind of 'unsemantic'.

What if, one day, you decide that it is more practical for those elements to have a padding instead of a margin. So you just do the following:

```<code>.small-bottom-margin {
    /* margin-bottom: $margin; */
    padding-bottom: $margin;
}
</code>```

This works, but makes your class name look stupid. Much like a class called .red-button. Naming it .alert-button would be much more future proof.

I tend to always name classes after what’s their function.

If you want to go that way anyway, you could keep that SCSS more DRY by doing something like this.

```<code>$breakpoints: (
    'sm': $small-only,
    'md': $medium-only,
    'lg': $large-only,
    'sm-up': $small-up,
    'md-up': $medium-up,
    'lg-up': $large-up,
    'sm-mp': $medium-down
);

$sizeFactors: (
    'small': 1,
    'medium: 2,
    'large: 4
);

$directions: (
    'up',
    'down',
);

@each $breakpointKey, $breakpointValue in $breakpoints {
    @media #{$breakpointValue} {
        @each $sizeFactorKey, $sizeFactorValue in $sizeFactors {
            @each $direction in $directions {
                .#{$sizeFactorKey}-#{$direction}-margin-#{$breakpointKey} {
                    margin-#{$direction}: $margin * $sizeFactorValue;
                }
            }
        }
    }
}
</code>```

Title: How to downsize my scss code?

Body:
I started writing classes such as:

.small-bottom-margin { margin-bottom: $margin; }
.small-top-margin { margin-top: $margin; }
.medium-bottom-margin { margin-bottom: $margin *2; }
.medium-top-margin { margin-top: $margin *2; }
.large-bottom-margin { margin-bottom: $margin *4; }
.large-top-margin { margin-top: $margin *4; }

Soon I wanted to be able to specify what happened on different screens, such as (for the small bottom margin example):

@media #{$small-only} { .small-bottom-margin-sm { margin-bottom: $margin; }}
@media #{$medium-only} { .small-bottom-margin-md { margin-bottom: $margin; }}
@media #{$large-only} { .small-bottom-margin-lg { margin-bottom: $margin; }}
@media #{$small-up} { .small-bottom-margin-sm-up { margin-bottom: $margin; }}
@media #{$medium-up} { .small-bottom-margin-md-up { margin-bottom: $margin; }}
@media #{$large-up} { .small-bottom-margin-lg-up { margin-bottom: $margin; }}
@media #{$medium-down} { .small-bottom-margin-sm-mp { margin-bottom: $margin; }}

... etc for all the margin sizes (medium and large), and for the top margin too.

I find this extremely practical in terms of readability of my html + speed to add margins through my app, which is often a pain when you have a complicated layout, but it seems awfully long to write in my css.

Is it bad practice to do this?
  If not, is there some kind of css function that would allow me to automatically generate all this code?

Body:
I think this is a matter of your own coding style and taste, in the first place, but for me these classes seem kind of 'unsemantic'.

What if, one day, you decide that it is more practical for those elements to have a padding instead of a margin. So you just do the following:

.small-bottom-margin {
    /* margin-bottom: $margin; */
    padding-bottom: $margin;
}

This works, but makes your class name look stupid. Much like a class called .red-button. Naming it .alert-button would be much more future proof.

I tend to always name classes after what’s their function.

If you want to go that way anyway, you could keep that SCSS more DRY by doing something like this.

$breakpoints: (
    'sm': $small-only,
    'md': $medium-only,
    'lg': $large-only,
    'sm-up': $small-up,
    'md-up': $medium-up,
    'lg-up': $large-up,
    'sm-mp': $medium-down
);

$sizeFactors: (
    'small': 1,
    'medium: 2,
    'large: 4
);

$directions: (
    'up',
    'down',
);

@each $breakpointKey, $breakpointValue in $breakpoints {
    @media #{$breakpointValue} {
        @each $sizeFactorKey, $sizeFactorValue in $sizeFactors {
            @each $direction in $directions {
                .#{$sizeFactorKey}-#{$direction}-margin-#{$breakpointKey} {
                    margin-#{$direction}: $margin * $sizeFactorValue;
                }
            }
        }
    }
}


问:
Remove items of list from another lists with criteria
i have a list of writers.

```<code>public class Writers{
    long WriterID { get;set; }
}
</code>```

Also I have two lists of type Article.

```<code>public class Article{
    long ArticleID { get; set; }
    long WriterID { get; set; }
    //and others
}
</code>```

so the code i have is:

```<code>List<Article> ArticleList = GetList(1);
List<Article> AnotherArticleList = AnotherList(2);
List<Writers> listWriters = GetAllForbiddenWriters();
</code>```

I want to remove those records from ArticleList, AnotherArticleList where WriterID matches from listWriters WriterID. How to do this in LINQ?

答:
```<code>articlesList.RemoveAll(a => listWriters.Exists(w => w.WriterID == a.WriterID));
anotherArticlesList.RemoveAll(a => listWriters.Exists(w => w.WriterID == a.WriterID));
</code>```

Body:
i have a list of writers.

public class Writers{
    long WriterID { get;set; }
}

Also I have two lists of type Article.

public class Article{
    long ArticleID { get; set; }
    long WriterID { get; set; }
    //and others
}

so the code i have is:

List
 ArticleList = GetList(1);
List
 AnotherArticleList = AnotherList(2);
List<Writers> listWriters = GetAllForbiddenWriters();

I want to remove those records from ArticleList, AnotherArticleList where WriterID matches from listWriters WriterID. How to do this in LINQ?


问:
ReactJS - cannot read property 'props' of undefined
I am practicing React native. When I compile the following program, I am getting Cannot read property 'props' of undefined error for Details.js. Kindly let me know as to what went wrong here.

Layout.js

```<code>import React, {Component} from 'react';
import Header from './Header';
import Details from './Details';

export default class Layout extends React.Component {
constructor(props){
  super(props);
    this.state = {
                     heading: "Welcome no-name guy!",
                     header: "I am your header",
                     footer: "I am your footer"
                 };
               }

render() {
   return (
           <div>
            <Header headerprop={this.state.header} />
            <Details detailprop={this.state.heading} />
          </div>
          );
         }
}
</code>```

Details.js

```<code>import React from 'react';

const Details = (detailprop) => {
 return (
  <div className="heading-style">{this.props.detailprop}</div>
 );
 };
Details.bind(this);
export default Details;
</code>```

Header.js

```<code>import React, {Component} from 'react';

export default class Header extends React.Component {
 render(){
           return(
                   <div>{this.props.headerprop}</div>
                 );
          }
 }
</code>```

答:
In functional components, the props are passed as the first parameter.  So, you only need to do this:

```<code>const Details = (props) => {
    return (
        <div className="heading-style">{props.detailprop}</div>
    );
};
</code>```

If you know the prop that you want to handle you can destructure that prop:

```<code>const Details = ({ detailProp }) => {
    return (
        <div className="heading-style">{detailprop}</div>
    );
};
</code>```

Body:
I am practicing React native. When I compile the following program, I am getting Cannot read property 'props' of undefined error for Details.js. Kindly let me know as to what went wrong here.

Layout.js

import React, {Component} from 'react';
import Header from './Header';
import Details from './Details';

export default class Layout extends React.Component {
constructor(props){
  super(props);
    this.state = {
                     heading: "Welcome no-name guy!",
                     header: "I am your header",
                     footer: "I am your footer"
                 };
               }

render() {
   return (

          );
         }
}

Details.js

import React from 'react';

const Details = (detailprop) => {
 return (

{this.props.detailprop}

 );
 };
Details.bind(this);
export default Details;

Header.js

import React, {Component} from 'react';

export default class Header extends React.Component {
 render(){
           return(

{this.props.headerprop}

                 );
          }
 }

Body:
In functional components, the props are passed as the first parameter.  So, you only need to do this:

const Details = (props) => {
    return (
        <div className="heading-style">{props.detailprop}</div>
    );
};

If you know the prop that you want to handle you can destructure that prop:

const Details = ({ detailProp }) => {
    return (
        <div className="heading-style">{detailprop}</div>
    );
};


问:
How can an array be grouped by two properties?
Ex:

```<code>const arr = [{
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 2,
  question: {
    templateId: 200
  }
}, {
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 1,
  question: {
    templateId: 300
  }
}];
</code>```

Expected Result: const result = groupBy(arr, 'group', 'question.templateId');

```<code>const result = [
  [{
    group: 1,
    question: {
      templateId: 100
    }
  }, {
    group: 1,
    question: {
      templateId: 100
    }
  }],
  [{
    group: 1,
    question: {
      templateId: 300
    }
  }],
  [{
    group: 2,
    question: {
      templateId: 200
    }
  }]
];
</code>```

So far: I am able to group the result by a single property using Array.prototype.reduce().

function groupBy(arr, key) {
  return [...arr.reduce((accumulator, currentValue) => {
    const propVal = currentValue[key],
      group = accumulator.get(propVal) || [];
    group.push(currentValue);
    return accumulator.set(propVal, group);
  }, new Map()).values()];
}

const arr = [{
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 2,
  question: {
    templateId: 200
  }
}, {
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 1,
  question: {
    templateId: 300
  }
}];

const result = groupBy(arr, 'group');

console.log(result);```

答:
I would recommend to pass a callback function instead of a property name, this allows you to do the two-level-access easily:

```<code>function groupBy(arr, key) {
  return Array.from(arr.reduce((accumulator, currentValue) => {
    const propVal = key(currentValue),
//                  ^^^^            ^
          group = accumulator.get(propVal) || [];
    group.push(currentValue);
    return accumulator.set(propVal, group);
  }, new Map()).values());
}
</code>```

Now you can do groupBy(arr, o => o.group) and groupBy(arr, o => o.question.templateId).

All you need to do for getting to your expected result is group by the first property and then group each result by the second property:

```<code>function concatMap(arr, fn) {
  return [].concat(...arr.map(fn));
}
const result = concatMap(groupBy(arr, o => o.group), res =>
  groupBy(res, o => o.question.templateId)
);
</code>```

Body:
Ex:

const arr = [{
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 2,
  question: {
    templateId: 200
  }
}, {
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 1,
  question: {
    templateId: 300
  }
}];

Expected Result: const result = groupBy(arr, 'group', 'question.templateId');

const result = [
  [{
    group: 1,
    question: {
      templateId: 100
    }
  }, {
    group: 1,
    question: {
      templateId: 100
    }
  }],
  [{
    group: 1,
    question: {
      templateId: 300
    }
  }],
  [{
    group: 2,
    question: {
      templateId: 200
    }
  }]
];

So far: I am able to group the result by a single property using Array.prototype.reduce().

function groupBy(arr, key) {
  return [...arr.reduce((accumulator, currentValue) => {
    const propVal = currentValue[key],
      group = accumulator.get(propVal) || [];
    group.push(currentValue);
    return accumulator.set(propVal, group);
  }, new Map()).values()];
}

const arr = [{
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 2,
  question: {
    templateId: 200
  }
}, {
  group: 1,
  question: {
    templateId: 100
  }
}, {
  group: 1,
  question: {
    templateId: 300
  }
}];

const result = groupBy(arr, 'group');

console.log(result);

Body:
I would recommend to pass a callback function instead of a property name, this allows you to do the two-level-access easily:

function groupBy(arr, key) {
  return Array.from(arr.reduce((accumulator, currentValue) => {
    const propVal = key(currentValue),
//                  ^^^^            ^
          group = accumulator.get(propVal) || [];
    group.push(currentValue);
    return accumulator.set(propVal, group);
  }, new Map()).values());
}

Now you can do groupBy(arr, o => o.group) and groupBy(arr, o => o.question.templateId).

All you need to do for getting to your expected result is group by the first property and then group each result by the second property:

function concatMap(arr, fn) {
  return [].concat(...arr.map(fn));
}
const result = concatMap(groupBy(arr, o => o.group), res =>
  groupBy(res, o => o.question.templateId)
);


问:
Write data to file and set custom icon
I'm currently developing a macOS cocoa application. Within one of the windows I'm gathering values from multiple arrays and building an xml file as a key/value backup. After saving the file I'm wanting to set a custom icon for the particular xml file. I've searched throughout stackoverflow and the rest of the web and haven't been able to find any solutions. Throughout the different functions within my application I'm able to pull a previously set icon from a file but haven't been able to set one for a newly created file. Any assistance would be greatly appreciated. </p>

答:
In order to change the XML file icon you should use that:

```<code>[[NSWorkspace sharedWorkspace] setIcon:iconImage forFile:path options:0];
</code>```

Where iconImage is a NSImage of the icon and path is the path of the xml file. Note that the change may not be visible until you rename the file or restart the computer. A workaround is renaming the xml file and then renaming it with the old name back again.

Also, note that macOS icons are different of Windows and Linux icons, so that icon may only be visible in macOS systems (in some cases, only in your machine).

Title: Write data to file and set custom icon

Body:
In order to change the XML file icon you should use that:

[[NSWorkspace sharedWorkspace] setIcon:iconImage forFile:path options:0];

Where iconImage is a NSImage of the icon and path is the path of the xml file. Note that the change may not be visible until you rename the file or restart the computer. A workaround is renaming the xml file and then renaming it with the old name back again.

Also, note that macOS icons are different of Windows and Linux icons, so that icon may only be visible in macOS systems (in some cases, only in your machine).


问:
All properties on nativeElement.style are empty
I am trying to create a select that will resize to the width of the selected item.

Here's the implementation in jQuery/Javascript: Drop down list width fit selected item text

The problem I'm having is that the styles are always empty. If I try to set the mainSelectElement to hiddenSelectElement, it almost disappears. The reason is that nativeElement.style.width is blank. I logged the style property to the console, and every property is blank. We also have global styles applied to select, and those are not appearing either.

Does anyone know why my styles are blank? Does this have something to do with the shadow DOM? And best of all, any solutions?

```<code>import { Component, Input, Output, EventEmitter, forwardRef, ViewChild, ElementRef, Renderer } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

const SELECT_RESIZE_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useClass: forwardRef(() => SamSelectResizableComponent),
  multi: true
}

@Component({
  selector: 'sam-select-resizable',
  template: `
    <select #mainSelectElement [ngModel]="selected" (ngModelChange)="updateSelected($event)">
      <ng-content></ng-content>
    </select>

    <select #hiddenSelectElement>
      <option >{{selected}}</option>
    </select>
  `,
  providers: [
    SELECT_RESIZE_VALUE_ACCESSOR
  ]
})
export class SamSelectResizableComponent implements ControlValueAccessor {

  @ViewChild('hiddenSelectElement') hiddenSelectElement: ElementRef;
  @ViewChild('mainSelectElement') mainSelectElement: ElementRef;

  public selected: any;

  private onChangeCallback: (_: any) => void = (_: any) => {};
  private onTouchedCallback: () => void = () => {};

  get value(): any {
    return this.selected;
  }

  set value(val: any) {
    if (val !== this.selected) {
      this.selected = val;
      this.onChangeCallback(this.selected);
    }
  }

  constructor(private renderer: Renderer) {}

  updateSelected(event) {
    this.selected = event;
    const hiddenWidth = this.hiddenSelectElement.nativeElement.style.width;
    this.renderer.setElementStyle(this.mainSelectElement.nativeElement, 'width', hiddenWidth);
  }

  writeValue(value: any) {
    if (value !== this.selected) {
      this.selected = value;
      this.onChangeCallback(this.selected);
    }
  }

  registerOnChange(fn: any) {
    this.onChangeCallback = fn;
  }

  registerOnTouched(fn: any) {
    this.onTouchedCallback = fn;
  }
}
</code>```

答:
You should be taking width from nativeElement directly, instead of taking it from style

```<code>const hiddenWidth = this.hiddenSelectElement.nativeElement.clientWidth; //.width
</code>```

Body:
I am trying to create a select that will resize to the width of the selected item.

Here's the implementation in jQuery/Javascript: Drop down list width fit selected item text

The problem I'm having is that the styles are always empty. If I try to set the mainSelectElement to hiddenSelectElement, it almost disappears. The reason is that nativeElement.style.width is blank. I logged the style property to the console, and every property is blank. We also have global styles applied to select, and those are not appearing either.

Does anyone know why my styles are blank? Does this have something to do with the shadow DOM? And best of all, any solutions?

import { Component, Input, Output, EventEmitter, forwardRef, ViewChild, ElementRef, Renderer } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

const SELECT_RESIZE_VALUE_ACCESSOR: any = {
  provide: NG_VALUE_ACCESSOR,
  useClass: forwardRef(() => SamSelectResizableComponent),
  multi: true
}

@Component({
  selector: 'sam-select-resizable',
  template: `
    <select #mainSelectElement [ngModel]="selected" (ngModelChange)="updateSelected($event)">
      <ng-content></ng-content>
    </select>

    <select #hiddenSelectElement>
      <option >{{selected}}</option>
    </select>
  `,
  providers: [
    SELECT_RESIZE_VALUE_ACCESSOR
  ]
})
export class SamSelectResizableComponent implements ControlValueAccessor {

  @ViewChild('hiddenSelectElement') hiddenSelectElement: ElementRef;
  @ViewChild('mainSelectElement') mainSelectElement: ElementRef;

  public selected: any;

  private onChangeCallback: (_: any) => void = (_: any) => {};
  private onTouchedCallback: () => void = () => {};

  get value(): any {
    return this.selected;
  }

  set value(val: any) {
    if (val !== this.selected) {
      this.selected = val;
      this.onChangeCallback(this.selected);
    }
  }

  constructor(private renderer: Renderer) {}

  updateSelected(event) {
    this.selected = event;
    const hiddenWidth = this.hiddenSelectElement.nativeElement.style.width;
    this.renderer.setElementStyle(this.mainSelectElement.nativeElement, 'width', hiddenWidth);
  }

  writeValue(value: any) {
    if (value !== this.selected) {
      this.selected = value;
      this.onChangeCallback(this.selected);
    }
  }

  registerOnChange(fn: any) {
    this.onChangeCallback = fn;
  }

  registerOnTouched(fn: any) {
    this.onTouchedCallback = fn;
  }
}

Body:
You should be taking width from nativeElement directly, instead of taking it from style

const hiddenWidth = this.hiddenSelectElement.nativeElement.clientWidth; //.width


问:
Error parsing XML: mismatched tag AND Error:Execution failed for task
```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Poids : "
    android:textStyle="bold"
    android:textColor="#FF0000"
    android:gravity="center"
    />
<EditText
    android:id="@+id/poids"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Poids"
    android:inputType="numberDecimal"
    />
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Taille : "
    android:textStyle="bold"
    android:textColor="#FF0000"
    android:gravity="center"
    />
<EditText
    android:id="@+id/taille"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Taille"
    android:inputType="numberDecimal"
    />
<RadioGroup
    android:id="@+id/group"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checkedButton="@+id/radio2"
    android:orientation="horizontal"
    >
    <RadioButton
        android:id="@+id/radio1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Mètre"
        />
    <RadioButton
        android:id="@+id/radio2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Centimètre"
        />
</RadioGroup>
<CheckBox
    android:id="@+id/mega"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Mega fonction !"
    />
<Button
    android:id="@+id/calcul"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Calculer l'IMC"
    />
<Button
    android:id="@+id/raz"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="RAZ"
    />
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Résultat:"
    />
<TextView
    android:id="@+id/result"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="Vous devez cliquer sur le bouton « Calculer l'IMC » pour obtenir un résultat."
    />
</LinearLayout>
</code>```

Hi everyone, I try to make a view interface but I have those errors when I'm executing my code:

-Error:(43) Error parsing XML: mismatched tag

-Error:Execution failed for task ':app:processDebugResources'.

com.android.ide.common.process.ProcessException: Failed to execute aapt

Can anyone help me? Please I'm a beginner

答:
add / in line number 42 and delete  in line number 55</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Poids : "
    android:textStyle="bold"
    android:textColor="#FF0000"
    android:gravity="center"
    />
<EditText
    android:id="@+id/poids"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Poids"
    android:inputType="numberDecimal"
    />
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Taille : "
    android:textStyle="bold"
    android:textColor="#FF0000"
    android:gravity="center"
    />
<EditText
    android:id="@+id/taille"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Taille"
    android:inputType="numberDecimal"
    />
<RadioGroup
    android:id="@+id/group"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checkedButton="@+id/radio2"
    android:orientation="horizontal"
    />
    <RadioButton
        android:id="@+id/radio1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Mètre"
        />
    <RadioButton
        android:id="@+id/radio2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Centimètre"
        />
<CheckBox
    android:id="@+id/mega"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Mega fonction !"
    />
<Button
    android:id="@+id/calcul"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Calculer l'IMC"
    />
<Button
    android:id="@+id/raz"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="RAZ"
    />
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Résultat:"
    />
<TextView
    android:id="@+id/result"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="Vous devez cliquer sur le bouton « Calculer l'IMC » pour obtenir un résultat."
    />
</LinearLayout>
</code>```

Body:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Poids : "
    android:textStyle="bold"
    android:textColor="#FF0000"
    android:gravity="center"
    />
<EditText
    android:id="@+id/poids"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Poids"
    android:inputType="numberDecimal"
    />
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Taille : "
    android:textStyle="bold"
    android:textColor="#FF0000"
    android:gravity="center"
    />
<EditText
    android:id="@+id/taille"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Taille"
    android:inputType="numberDecimal"
    />
<RadioGroup
    android:id="@+id/group"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checkedButton="@+id/radio2"
    android:orientation="horizontal"
    >
    <RadioButton
        android:id="@+id/radio1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Mètre"
        />
    <RadioButton
        android:id="@+id/radio2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Centimètre"
        />
</RadioGroup>
<CheckBox
    android:id="@+id/mega"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Mega fonction !"
    />
<Button
    android:id="@+id/calcul"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Calculer l'IMC"
    />
<Button
    android:id="@+id/raz"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="RAZ"
    />
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Résultat:"
    />
<TextView
    android:id="@+id/result"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="Vous devez cliquer sur le bouton « Calculer l'IMC » pour obtenir un résultat."
    />
</LinearLayout>

Hi everyone, I try to make a view interface but I have those errors when I'm executing my code:

-Error:(43) Error parsing XML: mismatched tag

-Error:Execution failed for task ':app:processDebugResources'.

com.android.ide.common.process.ProcessException: Failed to execute aapt

Can anyone help me? Please I'm a beginner

Body:
add / in line number 42 and delete  in line number 55

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Poids : "
    android:textStyle="bold"
    android:textColor="#FF0000"
    android:gravity="center"
    />
<EditText
    android:id="@+id/poids"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Poids"
    android:inputType="numberDecimal"
    />
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Taille : "
    android:textStyle="bold"
    android:textColor="#FF0000"
    android:gravity="center"
    />
<EditText
    android:id="@+id/taille"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Taille"
    android:inputType="numberDecimal"
    />
<RadioGroup
    android:id="@+id/group"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checkedButton="@+id/radio2"
    android:orientation="horizontal"
    />
    <RadioButton
        android:id="@+id/radio1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Mètre"
        />
    <RadioButton
        android:id="@+id/radio2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Centimètre"
        />
<CheckBox
    android:id="@+id/mega"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Mega fonction !"
    />
<Button
    android:id="@+id/calcul"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Calculer l'IMC"
    />
<Button
    android:id="@+id/raz"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="RAZ"
    />
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Résultat:"
    />
<TextView
    android:id="@+id/result"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:text="Vous devez cliquer sur le bouton « Calculer l'IMC » pour obtenir un résultat."
    />
</LinearLayout>


问:
Is It Possible to Make Every Instance of a Word on a Website Non-Breaking?
We have a hyphenated word that we use frequently on our website and we never want it to wrap or break - we always want the two parts of the word on the same line.

Is there a way to make every instance of this word on the site non-breaking or do I have to do it with something like "white-space: nowrap" in a span around every instance of the word?

Ideally, would love to be able to do an update where every instance of the word that exists on the site becomes non-breaking, without having to manually go and update each word.

Thanks!

答:
Like Joe mentioned, you can loop through your content and use regex to identify and replace your word with a span that applies white-space: nowrap

Here's a demo using jquery.

var keyword = 'some-word',
    re = new RegExp(keyword,"g");

$('p').each(function() {
  $(this).html($(this).html().replace(re, ''+keyword+''))
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.nowrap {
  white-space: nowrap;
}</code>```

these are words and this is some-word and here are more words these are words and this is some-word and here are more words these are words and this is some-word and here are more words

these are words and this is some-word and here are more words these are words and this is some-word and here are more words these are words and this is some-word and here are more words

these are words and this is some-word and here are more words these are words and this is some-word and here are more words these are words and this is some-word and here are more words
```

Body:
Like Joe mentioned, you can loop through your content and use regex to identify and replace your word with a span that applies white-space: nowrap

Here's a demo using jquery.

var keyword = 'some-word',
    re = new RegExp(keyword,"g");

$('p').each(function() {
  $(this).html($(this).html().replace(re, '<span class="nowrap">'+keyword+'</span>'))
});

.nowrap {
  white-space: nowrap;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>these are words and this is some-word and here are more words these are words and this is some-word and here are more words these are words and this is some-word and here are more words</p>
<p>these are words and this is some-word and here are more words these are words and this is some-word and here are more words these are words and this is some-word and here are more words</p>
<p>these are words and this is some-word and here are more words these are words and this is some-word and here are more words these are words and this is some-word and here are more words</p>


问:
Can the NOT operator work on multiple conditions present in parenthesis?
I run following query in MySQL :

```<code>SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';
</code>```

It returned me exactly the correct expected result.

After that I run following query :

```<code>SELECT * FROM Customers
WHERE NOT (Country='Germany' AND Country='USA');
</code>```

This time it returned me all the records present in the table(result-set of the query SELECT * FROM Customers;)

I'm not understanding why the NOT operator is not working in second query with parenthesis?

You can go to this link and check :

```<code>https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_where_not_and
</code>```

答:
Yes, of course it can.  But, by the rules of boolean logic, the correct formulation uses OR, not AND:

```<code>SELECT *
FROM Customers
WHERE NOT (Country = 'Germany' OR Country = 'USA');
</code>```

Your condition is:

```<code>WHERE NOT (Country = 'Germany' AND Country = 'USA');
</code>```

Obviously, a single row cannot meet both conditions at the same time, because Country has only one value.  Hence, one every row, the AND evaluates to false, and NOT turns it into true -- so not filtering occurs.

The more typical way to write this is:

```<code>SELECT *
FROM Customers
WHERE Country NOT IN ('Germany', 'USA');
</code>```

Body:
I run following query in MySQL :

SELECT * FROM Customers
WHERE NOT Country='Germany' AND NOT Country='USA';

It returned me exactly the correct expected result.

After that I run following query :

SELECT * FROM Customers
WHERE NOT (Country='Germany' AND Country='USA');

This time it returned me all the records present in the table(result-set of the query SELECT * FROM Customers;)

I'm not understanding why the NOT operator is not working in second query with parenthesis?

You can go to this link and check :

https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_where_not_and

Body:
Yes, of course it can.  But, by the rules of boolean logic, the correct formulation uses OR, not AND:

SELECT *
FROM Customers
WHERE NOT (Country = 'Germany' OR Country = 'USA');

Your condition is:

WHERE NOT (Country = 'Germany' AND Country = 'USA');

Obviously, a single row cannot meet both conditions at the same time, because Country has only one value.  Hence, one every row, the AND evaluates to false, and NOT turns it into true -- so not filtering occurs.

The more typical way to write this is:

SELECT *
FROM Customers
WHERE Country NOT IN ('Germany', 'USA');


问:
static variables definition time C++
i ran into a question i didnt know the answer to so i am posting here :)
does a static variable defined (not initialized) on the start of the program or when i enter the function it is defined in?

i know that the initialization of the static variable happens in the function it is defined, but i am not talking about initialization but definition, when it takes sapce in my stoarge.

i found out it is always in a lower address than the local variable in the main? is it related? is the variables always lower in the address if they are defined before? thanks for the answers

答:
Please consider the memory layout of a typical C/C++ program, for instance, from CS-fundamentals.com.

The place for extern variables (from other modules), global and static variables is called uninitialized data segment (or bss). Since the program can't guess what functions will be called, it is reasonable to believe that all the static variables that are local in scope will have its place defined there in the start of the program.

And local variables (the ones that disappear when you leave a function) are kept in the stack area.

That's almost everything we can know about the placement of memory variables. Anything else is largely dependent on the decision of the author of the code generation step of the compilation process.

Title: static variables definition time C++


问:
This code shows the error of: "No suitable Driver found for jdbc:mysql://localhost:3306/ab"
```<code>import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String a=t1.getText();
{try {
    String driver = "com.mysql.jdbc.Driver";
Class.forName(driver);
Connection C=DriverManager.getConnection("jdbc:mysql://localhost:3306/ab","root","root");
Statement S=C.createStatement();
String query="Insert into ab values('"+a+"');";
S.executeUpdate(query);
}
catch (Exception e)
{
    JOptionPane.showMessageDialog(this, e.getMessage());
}     }
    }
</code>```

<p>I have given the correct address but it is showing the no driver found.I'm using the mysql-connector-C-6.1. It is in my build path. I have restarted MySQL. I've also logged on from the command line with root and Password and it connected fine. I'm not currently seeing a port 3306 in STATUS. </p>

答: Are you sure you are using the connector-c? That one is, as the name suggests, for the C language and not for java. You should be using the connector-j library.</p>

Body:
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.swing.JOptionPane;

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String a=t1.getText();
{try {
    String driver = "com.mysql.jdbc.Driver";
Class.forName(driver);
Connection C=DriverManager.getConnection("jdbc:mysql://localhost:3306/ab","root","root");
Statement S=C.createStatement();
String query="Insert into ab values('"+a+"');";
S.executeUpdate(query);
}
catch (Exception e)
{
    JOptionPane.showMessageDialog(this, e.getMessage());
}     }
    }

I have given the correct address but it is showing the no driver found.I'm using the mysql-connector-C-6.1. It is in my build path. I have restarted MySQL. I've also logged on from the command line with root and Password and it connected fine. I'm not currently seeing a port 3306 in STATUS.


问:
Resizable UILabel which scrolls across the screen
Right, I'm trying to get a label with text in it (done already obviously), which scrolls across the screen.

The text that is input into the label is done by a UITextField and a UIButton. This updates fine.

But I'm trying to get the UILabel to resize accordingly to the amount of text input, so that the WHOLE lot of text scrolls across the screen.

This is the code I have at the moment for the scrolling label:

```<code>[lblMessage setText: txtEnter.text];

CABasicAnimation *scrollText;

scrollText=[CABasicAnimation animationWithKeyPath:@"position.x"];
scrollText.duration = 3.0;
scrollText.repeatCount = 10000;
scrollText.autoreverses = NO;
scrollText.fromValue = [NSNumber numberWithFloat:500];
scrollText.toValue = [NSNumber numberWithFloat:-120.0];

[[lblMessage layer] addAnimation:scrollText forKey:@"scrollTextKey"];
</code>```

The problem is, sometimes is starts scrolling in the middle of the screen, and sometimes vanishes before it has fully gone acrosss.

It also cuts of text due to the label being one size.. I don't know how to change this.

Thanks in advance.

Dom

答:
I believe something similar to the solution for this question would work for this case.

You could embed the UILabel in a UIScrollView, with the UIScrollView set to the max size of the label that you want to display on the screen at one time.  The UIScrollView would need to have its scroll indicators turned off using its showsHorizontalScrollIndicator and showsVerticalScrollIndicator properties.  On a change of text, you could do the following:

```<code>[lblMessage setText: txtEnter.text];
[lblMessage sizeToFit];
scrollView.contentSize = lblMessage.frame.size;
</code>```

followed by the panning animation code as described in the above-linked question, with the frame to be panned to being the far right of the UILabel.  This would cause the text to scroll at a constant rate across the label.  If you want the label to scroll back to the beginning, you could use the UIView setAnimationRepeatAutoreverses: and setAnimationRepeatCount: methods in the beginning of your animation block.

Body:
Right, I'm trying to get a label with text in it (done already obviously), which scrolls across the screen.

The text that is input into the label is done by a UITextField and a UIButton. This updates fine.

But I'm trying to get the UILabel to resize accordingly to the amount of text input, so that the WHOLE lot of text scrolls across the screen.

This is the code I have at the moment for the scrolling label:

[lblMessage setText: txtEnter.text];

CABasicAnimation *scrollText;

scrollText=[CABasicAnimation animationWithKeyPath:@"position.x"];
scrollText.duration = 3.0;
scrollText.repeatCount = 10000;
scrollText.autoreverses = NO;
scrollText.fromValue = [NSNumber numberWithFloat:500];
scrollText.toValue = [NSNumber numberWithFloat:-120.0];

[[lblMessage layer] addAnimation:scrollText forKey:@"scrollTextKey"];

The problem is, sometimes is starts scrolling in the middle of the screen, and sometimes vanishes before it has fully gone acrosss.

It also cuts of text due to the label being one size.. I don't know how to change this.

Thanks in advance.

Dom

LastEditorDisplayName: Chris Hanson

Body:
I believe something similar to the solution for this question would work for this case.

You could embed the UILabel in a UIScrollView, with the UIScrollView set to the max size of the label that you want to display on the screen at one time.  The UIScrollView would need to have its scroll indicators turned off using its showsHorizontalScrollIndicator and showsVerticalScrollIndicator properties.  On a change of text, you could do the following:

[lblMessage setText: txtEnter.text];
[lblMessage sizeToFit];
scrollView.contentSize = lblMessage.frame.size;

followed by the panning animation code as described in the above-linked question, with the frame to be panned to being the far right of the UILabel.  This would cause the text to scroll at a constant rate across the label.  If you want the label to scroll back to the beginning, you could use the UIView setAnimationRepeatAutoreverses: and setAnimationRepeatCount: methods in the beginning of your animation block.

OwnerDisplayName: Brad Larson


问:
TCL Thread: Tracking that a child Tcl Thread is still running
I am facing a problem with determining whether a Tcl thread is still running or not.  I have code that looks like this:

```<code>package require Thread
proc p1 {} {
    set tid [thread::create {
        #Child Thread
        proc executeCommand {} {
            #Run several command line commands
            return 1
        }
        thread::wait
    }]
    set currentProcessID [twapi::get_current_process_id]
    set var ::p1results($tid)
    set $var ""

    #Get all threads before ::thread::send
    set beforeThreads [twapi::get_process_thread_ids $currentProcessID]

    ::thread::send -async $tid [list executeCommand {}] $var

    #Get all threads after ::thread::send
    set afterThreads [twapi::get_process_thread_ids $currentProcessID]

    #set processThreadId to be the difference between before and after twapi calls
    set processThreadId {}
    foreach threadId $afterThreads {
        if {[lsearch -exact $beforeThreads $threadId] == -1} {
            set processThreadId $threadId
        }
    }

    while {[lsearch -exact [twapi::get_process_thread_ids $currentProcessID] $processThreadId] > -1} {
        #Notify a database that child thread is still running
        after 3000
    }

    vwait $var
    set result [set $var]
    unset $var
    ::thread::release $tid
    return $result
}

p1
</code>```

As you can see, I am currently tracking the child thread, that I started with ::thread::send, with the TCL twapi package.  I do not want to block the parent thread with 'vwait' or else I will not be able to notify the DB that the child thread is still running.  This has proven to be unreliable, as occasionally the thread id that I have stored 'processThreadId' will exit before my thread 'proc executeCommand {}' finishes.

So my question is this - is there a reliable way for the parent thread (main thread) to track if a child thread is still running, without blocking the parent thread with 'vwait'?

答:
If you have the id of the worker thread, you can use thread::exists to query if it is still alive. It takes just the id as an argument, and returns a boolean, which should be exactly what you need.

However, the thread could die immediately after you ask the question; no way to prevent that in a true, general async system. I prefer to arrange for the worker thread to send a message back when it is done, and once that message is received I know that everything is finished. I often like to think in terms of sending "work items" to threads, rather than just simple messages.

Body:
I am facing a problem with determining whether a Tcl thread is still running or not.  I have code that looks like this:

package require Thread
proc p1 {} {
    set tid [thread::create {
        #Child Thread
        proc executeCommand {} {
            #Run several command line commands
            return 1
        }
        thread::wait
    }]
    set currentProcessID [twapi::get_current_process_id]
    set var ::p1results($tid)
    set $var ""

    #Get all threads before ::thread::send
    set beforeThreads [twapi::get_process_thread_ids $currentProcessID]

    ::thread::send -async $tid [list executeCommand {}] $var

    #Get all threads after ::thread::send
    set afterThreads [twapi::get_process_thread_ids $currentProcessID]

    #set processThreadId to be the difference between before and after twapi calls
    set processThreadId {}
    foreach threadId $afterThreads {
        if {[lsearch -exact $beforeThreads $threadId] == -1} {
            set processThreadId $threadId
        }
    }

    while {[lsearch -exact [twapi::get_process_thread_ids $currentProcessID] $processThreadId] > -1} {
        #Notify a database that child thread is still running
        after 3000
    }

    vwait $var
    set result [set $var]
    unset $var
    ::thread::release $tid
    return $result
}

p1

As you can see, I am currently tracking the child thread, that I started with ::thread::send, with the TCL twapi package.  I do not want to block the parent thread with 'vwait' or else I will not be able to notify the DB that the child thread is still running.  This has proven to be unreliable, as occasionally the thread id that I have stored 'processThreadId' will exit before my thread 'proc executeCommand {}' finishes.

So my question is this - is there a reliable way for the parent thread (main thread) to track if a child thread is still running, without blocking the parent thread with 'vwait'?


问:
RxAndroid issue with retrofit?
I'm having a cast problem inside the subscribe method, i don't know why the new Observer is giving this issue.

```<code> Observable<GradeModel> getGrade = retrofit
                .create(GradeService.class)
                .getGrade()
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .map(model -> {
                    // transform model
                    DecimalFormat grades = (DecimalFormat) model.getGrades();
                    return grades;
                })
                .subscribe(new Subscriber<DecimalFormat>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i(TAG, "onError method of observer");
                    }

                    @Override
                    public void onNext(DecimalFormat grades) {
                        mainPresenter.setListGrades(grades);
                    }
                });
</code>```

Required:
  rx.Observable

  Found:
  rx.Subscription

答:
Up until .subscribe(...) it is an Observable. However after subscribing it returns a Subscription instance which can be used to cancel the subscription.

The exception occurs because you are casting this Subscription back into an Observable although they are completely unrelated.

Without knowing your intentions with that variable it is hard to say what the correct code would be.

Title: RxAndroid issue with retrofit?

Body:
I'm having a cast problem inside the subscribe method, i don't know why the new Observer is giving this issue.

 Observable<GradeModel> getGrade = retrofit
                .create(GradeService.class)
                .getGrade()
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .map(model -> {
                    // transform model
                    DecimalFormat grades = (DecimalFormat) model.getGrades();
                    return grades;
                })
                .subscribe(new Subscriber<DecimalFormat>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.i(TAG, "onError method of observer");
                    }

                    @Override
                    public void onNext(DecimalFormat grades) {
                        mainPresenter.setListGrades(grades);
                    }
                });

Required:
  rx.Observable

  Found:
  rx.Subscription


问:
Django: prefetch_related results ordered by a field of an intermediary table
How can I prefetch_related objects in Django and order them by a field in an intermediary table?

Here's the models I'm working with:

```<code>class Node(models.Model):
    name = models.CharField(max_length=255)
    edges = models.ManyToManyField('self', through='Edge', symmetrical=False)

class Edge(models.Model):
    from_node = models.ForeignKey(Node, related_name='from_node')
    to_node = models.ForeignKey(Node, related_name='to_node')

    weight = models.FloatField(default=0)
</code>```

Given a node, I'd like to prefetch all of the related nodes, ordered by weight.

When I use this query:

```<code>n = Node.objects.prefetch_related('to_node').order_by('edge__weight').get(name='x')
</code>```

the order_by has no effect.

Edit:

My best answer so far

```<code>n = Node.objects.get(name='x')
edges = Edge.objects.filter(from_node=n).prefetch_related('to_node').order_by('weight')
</code>```

Then instead of iterating n.edges (as I'd prefer), I iterate edges.to_node

答:
Nowadays, you can also use the Prefetch class to achieve this:

https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.Prefetch

Or, if you want to do this all the time as a default, you can look into the meta ordering on the intermediary table, something like:

```<code>class SomeThroughModel(models.Model):
    order = models.IntegerField("Order", default=0, blank=False, null=False)
    ...

    class Meta:
        ordering = ['order']  # order is the field holding the order
</code>```

Body:
How can I prefetch_related objects in Django and order them by a field in an intermediary table?

Here's the models I'm working with:

class Node(models.Model):
    name = models.CharField(max_length=255)
    edges = models.ManyToManyField('self', through='Edge', symmetrical=False)

class Edge(models.Model):
    from_node = models.ForeignKey(Node, related_name='from_node')
    to_node = models.ForeignKey(Node, related_name='to_node')

    weight = models.FloatField(default=0)

Given a node, I'd like to prefetch all of the related nodes, ordered by weight.

When I use this query:

n = Node.objects.prefetch_related('to_node').order_by('edge__weight').get(name='x')

the order_by has no effect.

Edit:

My best answer so far

n = Node.objects.get(name='x')
edges = Edge.objects.filter(from_node=n).prefetch_related('to_node').order_by('weight')

Then instead of iterating n.edges (as I'd prefer), I iterate edges.to_node

Body:
Nowadays, you can also use the Prefetch class to achieve this:

https://docs.djangoproject.com/en/1.10/ref/models/querysets/#django.db.models.Prefetch

Or, if you want to do this all the time as a default, you can look into the meta ordering on the intermediary table, something like:

class SomeThroughModel(models.Model):
    order = models.IntegerField("Order", default=0, blank=False, null=False)
    ...

    class Meta:
        ordering = ['order']  # order is the field holding the order


问:
How to get 3 days back of current date and should not be weekends
How can I get 3 days back of current date and should not fall on weekends (Sat/Sun)

Let's say if date i select date as 03/28/2017. It should display date as 03/23/2017. It should not take sat/sun.

```<code>dto.ProcessEndDate.AddDays(-3);
</code>```

答:
This code assumes that if new date falls on a weekend, it will instead return the Friday before.

```<code>public static DateTime GetDateExcludeWeekends(DateTime date, int index)
{
    var newDate = date.AddDays(-index);

    if(newDate.DayOfWeek == DayOfWeek.Sunday)
    {
        return newDate.AddDays(-2);
    }

    if(newDate.DayOfWeek == DayOfWeek.Saturday)
    {
        return newDate.AddDays(-1);
    }

    return DateTime.Now;
}
</code>```

You can tweak the logic, but the main thing is to look at the DayOfWeek enum property of the DateTime class.

Body:
How can I get 3 days back of current date and should not fall on weekends (Sat/Sun)

Let's say if date i select date as 03/28/2017. It should display date as 03/23/2017. It should not take sat/sun.

dto.ProcessEndDate.AddDays(-3);

Body:
This code assumes that if new date falls on a weekend, it will instead return the Friday before.

public static DateTime GetDateExcludeWeekends(DateTime date, int index)
{
    var newDate = date.AddDays(-index);

    if(newDate.DayOfWeek == DayOfWeek.Sunday)
    {
        return newDate.AddDays(-2);
    }

    if(newDate.DayOfWeek == DayOfWeek.Saturday)
    {
        return newDate.AddDays(-1);
    }

    return DateTime.Now;
}

You can tweak the logic, but the main thing is to look at the DayOfWeek enum property of the DateTime class.


问:
Vb 6.0 project loading error
I have recently downloaded vb6.o project file from bitbucket but unable to run project it generates following error in log files
'0' could not be loaded
Line 0: The file E:\cas\Forms\errorform.frm could not be loaded.</p>

答:
I've seen this when the line endings for the vb6 files are converted from cr\lf to just lf.

For me this was caused by checking the source code out from git with autocrlf configured wrong.

Once I had git configured correctly, I needed to execute the following to reset all the line endings in my working copy:

```<code>git rm -rf --cached .
git reset --hard HEAD
</code>```

Warning The above commands will delete all of your working copy files and recheck them out.

Credit

Title: Vb 6.0 project loading error

Body:
I've seen this when the line endings for the vb6 files are converted from cr\lf to just lf.

For me this was caused by checking the source code out from git with autocrlf configured wrong.

Once I had git configured correctly, I needed to execute the following to reset all the line endings in my working copy:

git rm -rf --cached .
git reset --hard HEAD

Warning The above commands will delete all of your working copy files and recheck them out.

Credit