问:
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
I have read various on site about this issue but I am not able to figure this out. I am using pre-build database for this app.  I am using jellybean for this app.

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.quotes"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="17" />

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.example.quotes.MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>

    </manifest>
</code>```

Logcat Output

according to logcat it's caused by SQLiteCantOpenDatabaseException

```<code>06-10 23:07:01.831: E/Trace(4419): error opening trace file: No such file or directory (2)
06-10 23:07:03.611: E/SQLiteLog(4419): (14) cannot open file at line 30176 of [00bb9c9ce4]
06-10 23:07:03.621: E/SQLiteLog(4419): (14) os_unix.c:30176: (2) open(/data/data/com.example.quotes/databasesQuotesdb) -
06-10 23:07:03.641: E/SQLiteDatabase(4419): Failed to open database '/data/data/com.example.quotes/databasesQuotesdb'.
06-10 23:07:03.641: E/SQLiteDatabase(4419): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at com.example.quotes.DataBaseHelper.checkDataBase(DataBaseHelper.java:94)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at com.example.quotes.DataBaseHelper.createDataBase(DataBaseHelper.java:58)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at com.example.quotes.MainActivity.onCreate(MainActivity.java:34)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.app.Activity.performCreate(Activity.java:5104)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.os.Looper.loop(Looper.java:137)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.app.ActivityThread.main(ActivityThread.java:5041)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at java.lang.reflect.Method.invokeNative(Native Method)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at java.lang.reflect.Method.invoke(Method.java:511)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at dalvik.system.NativeStart.main(Native Method)
06-10 23:07:03.731: E/SQLiteLog(4419): (14) cannot open file at line 30176 of [00bb9c9ce4]
06-10 23:07:03.731: E/SQLiteLog(4419): (14) os_unix.c:30176: (2) open(/data/data/com.example.quotes/databasesQuotesdb) -
06-10 23:07:03.781: E/SQLiteDatabase(4419): Failed to open database '/data/data/com.example.quotes/databasesQuotesdb'.
06-10 23:07:03.781: E/SQLiteDatabase(4419): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at com.example.quotes.DataBaseHelper.openDataBase(DataBaseHelper.java:145)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at com.example.quotes.MainActivity.onCreate(MainActivity.java:44)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.app.Activity.performCreate(Activity.java:5104)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.os.Looper.loop(Looper.java:137)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.app.ActivityThread.main(ActivityThread.java:5041)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at java.lang.reflect.Method.invokeNative(Native Method)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at java.lang.reflect.Method.invoke(Method.java:511)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at dalvik.system.NativeStart.main(Native Method)
06-10 23:07:03.791: D/AndroidRuntime(4419): Shutting down VM
06-10 23:07:03.791: W/dalvikvm(4419): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-10 23:07:03.831: E/AndroidRuntime(4419): FATAL EXCEPTION: main
06-10 23:07:03.831: E/AndroidRuntime(4419): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.quotes/com.example.quotes.MainActivity}: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.os.Looper.loop(Looper.java:137)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.app.ActivityThread.main(ActivityThread.java:5041)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at java.lang.reflect.Method.invokeNative(Native Method)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at java.lang.reflect.Method.invoke(Method.java:511)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at dalvik.system.NativeStart.main(Native Method)
06-10 23:07:03.831: E/AndroidRuntime(4419): Caused by: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at com.example.quotes.DataBaseHelper.openDataBase(DataBaseHelper.java:145)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at com.example.quotes.MainActivity.onCreate(MainActivity.java:44)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.app.Activity.performCreate(Activity.java:5104)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
06-10 23:07:03.831: E/AndroidRuntime(4419):     ... 11 more
06-10 23:07:04.083: D/dalvikvm(4419): GC_CONCURRENT freed 203K, 11% free 2676K/3000K, paused 25ms+18ms, total 306ms
06-10 23:07:07.811: I/Process(4419): Sending signal. PID: 4419 SIG: 9
</code>```

DataBaseHelper.java

```<code>public class DataBaseHelper extends SQLiteOpenHelper{

    //The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/com.example.quotes/databases";

    private static String DB_NAME = "Quotesdb";

    // Table Names of Data Base.
    static final String TABLE_Name = "Quotes";

    // Contacts Table Columns names
    //private static final String _Id = "_Id";
    //private static final String quotes = "quotes";
    //private static final String author = "author";

    private SQLiteDatabase myDataBase;

    private final Context myContext;

    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     */
    public DataBaseHelper(Context context) {
        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }

    /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase() throws IOException{

        boolean dbExist = checkDataBase();
        SQLiteDatabase db_Read = null;

        if(dbExist){
            //do nothing - database already exist
        }else{
            //By calling this method and empty database will be created into the default system path
            //of your application so we are gonna be able to overwrite that database with our database.
            db_Read = this.getReadableDatabase();
            db_Read.close();

            try {
                copyDataBase();
            } catch (IOException e) {
                //throw new Error("Error copying database");
                e.toString();
            }
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){

        SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        }catch(SQLiteException e){
            //database does't exist yet.
        }

        if(checkDB != null){
            checkDB.close();
        }

        return checkDB != null ? true : false;
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException{

        //Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        //transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

    public void openDataBase() throws SQLException{
        //Open the database
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }

    @Override
    public synchronized void close() {
        if(myDataBase != null)
            myDataBase.close();

        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
    }

    /*// Getting single contact
    public List<Quotes> getQuote(int id) {
        ArrayList<Quotes>();
        getReadableDatabase();

        Cursor cursor = db.query(TABLE_Name, new String[] { _Id,
                qotes,author }, _Id + "=?", new String[] { String.valueOf(id) },
                null, null, null, null);

        //String query = "SELECT _Id, qotes, author From "+TABLE_Name;
        //String query = "SELECT * From Quotes";

        //Cursor cursor = db.rawQuery(query, null);

        if (cursor != null)
            cursor.moveToFirst();
        Quotes quotes = new Quotes(Integer.parseInt(cursor.getString(0)),
        cursor.getString(1),cursor.getString(2));
        QuoteList.add(quotes);
        return QuoteList;
    }
    */
}
</code>```

答:
Another thing to note is Environment.getExternalStorageDirectory() has been deprecated in API 29, so change this if you're using this to get the database path:

https://developer.android.com/reference/android/os/Environment#getExternalStorageDirectory()

This method was deprecated in API level 29.

To improve user privacy, direct access to shared/external storage devices is deprecated. When an app targets Build.VERSION_CODES.Q, the path returned from this method is no longer directly accessible to apps. Apps can continue to access content stored on shared/external storage by migrating to alternatives such as Context#getExternalFilesDir(String), MediaStore, or Intent#ACTION_OPEN_DOCUMENT.

Body:
I have read various on site about this issue but I am not able to figure this out. I am using pre-build database for this app.  I am using jellybean for this app.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.quotes"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="17" />

        <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.example.quotes.MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>

    </manifest>

Logcat Output

according to logcat it's caused by SQLiteCantOpenDatabaseException

06-10 23:07:01.831: E/Trace(4419): error opening trace file: No such file or directory (2)
06-10 23:07:03.611: E/SQLiteLog(4419): (14) cannot open file at line 30176 of [00bb9c9ce4]
06-10 23:07:03.621: E/SQLiteLog(4419): (14) os_unix.c:30176: (2) open(/data/data/com.example.quotes/databasesQuotesdb) -
06-10 23:07:03.641: E/SQLiteDatabase(4419): Failed to open database '/data/data/com.example.quotes/databasesQuotesdb'.
06-10 23:07:03.641: E/SQLiteDatabase(4419): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at com.example.quotes.DataBaseHelper.checkDataBase(DataBaseHelper.java:94)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at com.example.quotes.DataBaseHelper.createDataBase(DataBaseHelper.java:58)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at com.example.quotes.MainActivity.onCreate(MainActivity.java:34)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.app.Activity.performCreate(Activity.java:5104)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.os.Looper.loop(Looper.java:137)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at android.app.ActivityThread.main(ActivityThread.java:5041)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at java.lang.reflect.Method.invokeNative(Native Method)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at java.lang.reflect.Method.invoke(Method.java:511)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-10 23:07:03.641: E/SQLiteDatabase(4419):     at dalvik.system.NativeStart.main(Native Method)
06-10 23:07:03.731: E/SQLiteLog(4419): (14) cannot open file at line 30176 of [00bb9c9ce4]
06-10 23:07:03.731: E/SQLiteLog(4419): (14) os_unix.c:30176: (2) open(/data/data/com.example.quotes/databasesQuotesdb) -
06-10 23:07:03.781: E/SQLiteDatabase(4419): Failed to open database '/data/data/com.example.quotes/databasesQuotesdb'.
06-10 23:07:03.781: E/SQLiteDatabase(4419): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at com.example.quotes.DataBaseHelper.openDataBase(DataBaseHelper.java:145)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at com.example.quotes.MainActivity.onCreate(MainActivity.java:44)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.app.Activity.performCreate(Activity.java:5104)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.os.Looper.loop(Looper.java:137)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at android.app.ActivityThread.main(ActivityThread.java:5041)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at java.lang.reflect.Method.invokeNative(Native Method)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at java.lang.reflect.Method.invoke(Method.java:511)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-10 23:07:03.781: E/SQLiteDatabase(4419):     at dalvik.system.NativeStart.main(Native Method)
06-10 23:07:03.791: D/AndroidRuntime(4419): Shutting down VM
06-10 23:07:03.791: W/dalvikvm(4419): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-10 23:07:03.831: E/AndroidRuntime(4419): FATAL EXCEPTION: main
06-10 23:07:03.831: E/AndroidRuntime(4419): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.quotes/com.example.quotes.MainActivity}: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.os.Looper.loop(Looper.java:137)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.app.ActivityThread.main(ActivityThread.java:5041)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at java.lang.reflect.Method.invokeNative(Native Method)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at java.lang.reflect.Method.invoke(Method.java:511)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at dalvik.system.NativeStart.main(Native Method)
06-10 23:07:03.831: E/AndroidRuntime(4419): Caused by: android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at com.example.quotes.DataBaseHelper.openDataBase(DataBaseHelper.java:145)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at com.example.quotes.MainActivity.onCreate(MainActivity.java:44)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.app.Activity.performCreate(Activity.java:5104)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-10 23:07:03.831: E/AndroidRuntime(4419):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
06-10 23:07:03.831: E/AndroidRuntime(4419):     ... 11 more
06-10 23:07:04.083: D/dalvikvm(4419): GC_CONCURRENT freed 203K, 11% free 2676K/3000K, paused 25ms+18ms, total 306ms
06-10 23:07:07.811: I/Process(4419): Sending signal. PID: 4419 SIG: 9

DataBaseHelper.java

public class DataBaseHelper extends SQLiteOpenHelper{

    //The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/com.example.quotes/databases";

    private static String DB_NAME = "Quotesdb";

    // Table Names of Data Base.
    static final String TABLE_Name = "Quotes";

    // Contacts Table Columns names
    //private static final String _Id = "_Id";
    //private static final String quotes = "quotes";
    //private static final String author = "author";

    private SQLiteDatabase myDataBase;

    private final Context myContext;

    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     */
    public DataBaseHelper(Context context) {
        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }

    /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase() throws IOException{

        boolean dbExist = checkDataBase();
        SQLiteDatabase db_Read = null;

        if(dbExist){
            //do nothing - database already exist
        }else{
            //By calling this method and empty database will be created into the default system path
            //of your application so we are gonna be able to overwrite that database with our database.
            db_Read = this.getReadableDatabase();
            db_Read.close();

            try {
                copyDataBase();
            } catch (IOException e) {
                //throw new Error("Error copying database");
                e.toString();
            }
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase(){

        SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        }catch(SQLiteException e){
            //database does't exist yet.
        }

        if(checkDB != null){
            checkDB.close();
        }

        return checkDB != null ? true : false;
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase() throws IOException{

        //Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);

        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;

        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);

        //transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0){
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

    public void openDataBase() throws SQLException{
        //Open the database
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

    }

    @Override
    public synchronized void close() {
        if(myDataBase != null)
            myDataBase.close();

        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub
    }

    /*// Getting single contact
    public List<Quotes> getQuote(int id) {
        ArrayList<Quotes>();
        getReadableDatabase();

        Cursor cursor = db.query(TABLE_Name, new String[] { _Id,
                qotes,author }, _Id + "=?", new String[] { String.valueOf(id) },
                null, null, null, null);

        //String query = "SELECT _Id, qotes, author From "+TABLE_Name;
        //String query = "SELECT * From Quotes";

        //Cursor cursor = db.rawQuery(query, null);

        if (cursor != null)
            cursor.moveToFirst();
        Quotes quotes = new Quotes(Integer.parseInt(cursor.getString(0)),
        cursor.getString(1),cursor.getString(2));
        QuoteList.add(quotes);
        return QuoteList;
    }
    */
}


来源: stackexchange

问:
Stack class in java.util a violation of Liskov substitution principle?
From the documentation of https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html

```<code>public class Stack<E> extends Vector<E>
</code>```

Isn't this a violation of the Liskov substitution principle? The LSP in simple terms states that objects of the same superclass should be able to be swapped with each other without breaking anything.

For example: Let us say that I have a function that takes a Vector as an input. If while calling a function I start passing it a Stack then it might break because Stack prevents random access of elements.

```<code>import java.util.*;

class Book {}

class TextBook extends Book {}

public class Sample {
    public static void process(Vector<Book> books) {
        # This should not be allowed for Stack, Stack is FILO
        System.out.println(books.get(1));
    }

    public static void main(String[] args) {
        Vector<Book> books = new Vector<>();
        books.add(new Book());
        books.add(new Book());
        books.add(new Book());
        process(books);
        System.out.println("ok");

        Stack<Book> bookz = new Stack();
        bookz.add(new Book());
        bookz.add(new Book());
        bookz.add(new Book());
        process(bookz);
        System.out.println("ok");
    }
}
</code>```

答:
The JDK's implementation of Stack is strictly additive: it only adds a handful of methods to Vector's implementation without taking anything away. For this reason, it is always possible to assign (substitute) a Stack to a variable of type Vector without restricting what the client code can do. It is thus not a violation of the Liskov Substitution principle.

However, its design is acknowledged to be flawed, but according to a different principle: Inheritance is appropriate only in circumstances where the subclass really is a subtype of the superclass.. From Effective Java:

There are a number of obvious violations of this principle in the Java platform libraries. For example, a stack is not a vector, so Stack should not extend Vector.

ContentLicense: CC BY-SA 4.0

Body:
From the documentation of https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html

public class Stack<E> extends Vector<E>

Isn't this a violation of the Liskov substitution principle? The LSP in simple terms states that objects of the same superclass should be able to be swapped with each other without breaking anything.

For example: Let us say that I have a function that takes a Vector as an input. If while calling a function I start passing it a Stack then it might break because Stack prevents random access of elements.

import java.util.*;

class Book {}

class TextBook extends Book {}

public class Sample {
    public static void process(Vector<Book> books) {
        # This should not be allowed for Stack, Stack is FILO
        System.out.println(books.get(1));
    }

    public static void main(String[] args) {
        Vector<Book> books = new Vector<>();
        books.add(new Book());
        books.add(new Book());
        books.add(new Book());
        process(books);
        System.out.println("ok");

        Stack<Book> bookz = new Stack();
        bookz.add(new Book());
        bookz.add(new Book());
        bookz.add(new Book());
        process(bookz);
        System.out.println("ok");
    }
}


问:
How does one end a function in dart similar to in JS typing return
In Javascript when I want to end a function I usually write return, but in the dart, if I do that then the function asks for a return statement at the end of each branch which is messy.

```<code>Function createCategory(File image) {
    String title = _categoryTitle.value;
    if(image == null || title == null || title.length == 0) {
      return null;
    }
    CategoryModel newCategory = new CategoryModel();
    if(_categories.value == null) {
      _categories.sink.add([newCategory]);
    }
    return null;
  }
</code>```

What is the correct way to do this in dart?

答:
you can do that like this:</p>

```<code>void createCategory(File image) {
    String title = _categoryTitle.value;

    if (image != null && title.isNotEmpty && _categories.value == null) {
        _categories.sink.add([CategoryModel()]);
    }
}
</code>```

Body:
In Javascript when I want to end a function I usually write return, but in the dart, if I do that then the function asks for a return statement at the end of each branch which is messy.

Function createCategory(File image) {
    String title = _categoryTitle.value;
    if(image == null || title == null || title.length == 0) {
      return null;
    }
    CategoryModel newCategory = new CategoryModel();
    if(_categories.value == null) {
      _categories.sink.add([newCategory]);
    }
    return null;
  }

What is the correct way to do this in dart?

Body:
you can do that like this:

void createCategory(File image) {
    String title = _categoryTitle.value;

    if (image != null && title.isNotEmpty && _categories.value == null) {
        _categories.sink.add([CategoryModel()]);
    }
}


问:
std::list<const SomeClass> can not be defined
I'm trying to define a constant list of constant objects and I can't seem to get it done.
Here is my example that compiles fine:

```<code>#include <string>
#include <list>

class Person { public:
    std::string name;
    Person(const std::string &in_name){name=in_name;}
};

class MyClass { public:
    const std::list</* const */Person> l;
    MyClass(const std::list</* const */Person> &in_l):l(in_l){}
};

int main(int argc, char **argv) {
    Person dave("dave");
    MyClass c(std::list<const Person>(dave));
    return 0;
}
</code>```

When I remove the comments from const in those 2 places,
I get the following errors:

```<code>In file included from /usr/include/x86_64-linux-gnu/c++/7/bits/c++allocator.h:33:0,
                 from /usr/include/c++/7/bits/allocator.h:46,
                 from /usr/include/c++/7/string:41,
                 from main66.cpp:1:
/usr/include/c++/7/ext/new_allocator.h: In instantiation of ‘class __gnu_cxx::new_allocator<const Person>’:
/usr/include/c++/7/bits/allocator.h:108:11:   required from ‘class std::allocator<const Person>’
main66.cpp:11:53:   required from here
/usr/include/c++/7/ext/new_allocator.h:93:7: error: ‘const _Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::const_reference) const [with _Tp = const Person; __gnu_cxx::new_allocator<_Tp>::const_pointer = const Person*; __gnu_cxx::new_allocator<_Tp>::const_reference = const Person&]’ cannot be overloaded
       address(const_reference __x) const _GLIBCXX_NOEXCEPT
       ^~~~~~~
/usr/include/c++/7/ext/new_allocator.h:89:7: error: with ‘_Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::reference) const [with _Tp = const Person; __gnu_cxx::new_allocator<_Tp>::pointer = const Person*; __gnu_cxx::new_allocator<_Tp>::reference = const Person&]’
       address(reference __x) const _GLIBCXX_NOEXCEPT
       ^~~~~~~
</code>```

Is there any way to define a std::list of const objects?

答:
Error message seems clear enough https://gcc.godbolt.org/z/MG3Kxv:

error: static assertion failed: std::list must have a non-const,
  non-volatile value_type

Body:
I'm trying to define a constant list of constant objects and I can't seem to get it done.
Here is my example that compiles fine:

#include <string>
#include <list>

class Person { public:
    std::string name;
    Person(const std::string &in_name){name=in_name;}
};

class MyClass { public:
    const std::list</* const */Person> l;
    MyClass(const std::list</* const */Person> &in_l):l(in_l){}
};

int main(int argc, char **argv) {
    Person dave("dave");
    MyClass c(std::list<const Person>(dave));
    return 0;
}

When I remove the comments from const in those 2 places,
I get the following errors:

In file included from /usr/include/x86_64-linux-gnu/c++/7/bits/c++allocator.h:33:0,
                 from /usr/include/c++/7/bits/allocator.h:46,
                 from /usr/include/c++/7/string:41,
                 from main66.cpp:1:
/usr/include/c++/7/ext/new_allocator.h: In instantiation of ‘class __gnu_cxx::new_allocator<const Person>’:
/usr/include/c++/7/bits/allocator.h:108:11:   required from ‘class std::allocator<const Person>’
main66.cpp:11:53:   required from here
/usr/include/c++/7/ext/new_allocator.h:93:7: error: ‘const _Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::const_reference) const [with _Tp = const Person; __gnu_cxx::new_allocator<_Tp>::const_pointer = const Person*; __gnu_cxx::new_allocator<_Tp>::const_reference = const Person&]’ cannot be overloaded
       address(const_reference __x) const _GLIBCXX_NOEXCEPT
       ^~~~~~~
/usr/include/c++/7/ext/new_allocator.h:89:7: error: with ‘_Tp* __gnu_cxx::new_allocator<_Tp>::address(__gnu_cxx::new_allocator<_Tp>::reference) const [with _Tp = const Person; __gnu_cxx::new_allocator<_Tp>::pointer = const Person*; __gnu_cxx::new_allocator<_Tp>::reference = const Person&]’
       address(reference __x) const _GLIBCXX_NOEXCEPT
       ^~~~~~~

Is there any way to define a std::list of const objects?


问:
Python git package get tag and commit
I would like to print a git commit and the tag in my Python code.
How can I do this using git package?

When I am going to my Bitbucket I see

```<code>tag: 73-2-g46b9856

commit checksum: 46b9856
</code>```

How can I retrieve this info from git package?

I have done the following:

```<code>import git
repo = git.Repo(search_parent_directories=True)
sha = repo.head.object.hexsha
</code>```

答:
So I assume you already have the checksum you want in the sha variable.

At this point, there's a post for how to get the tags and looking for a specific tag associated with that sha in this link: Get tags of a commit

```<code># Example code for clarity

import git
repo = git.Repo(search_parent_directories=True)
sha = repo.head.object.hexsha
tagmap = {}
for t in repo.tags:
  tagmap.setdefault(repo.commit(t), []).append(t)
tags = tagmap[repo.commit(sha)] # Warning: Your latest commit might not have a tag associated with it so this will throw an error right now.
print(tags)
</code>```

Title: Python git package get tag and commit

Body:
I would like to print a git commit and the tag in my Python code.
How can I do this using git package?

When I am going to my Bitbucket I see

tag: 73-2-g46b9856

commit checksum: 46b9856

How can I retrieve this info from git package?

I have done the following:

import git
repo = git.Repo(search_parent_directories=True)
sha = repo.head.object.hexsha

Body:
So I assume you already have the checksum you want in the sha variable.

At this point, there's a post for how to get the tags and looking for a specific tag associated with that sha in this link: Get tags of a commit

# Example code for clarity

import git
repo = git.Repo(search_parent_directories=True)
sha = repo.head.object.hexsha
tagmap = {}
for t in repo.tags:
  tagmap.setdefault(repo.commit(t), []).append(t)
tags = tagmap[repo.commit(sha)] # Warning: Your latest commit might not have a tag associated with it so this will throw an error right now.
print(tags)


问:
Gridview columns not being set to width I enter
I have two gridviews one displaying under the other one. Both gridviews are exactly the same, the only difference with the second gridview is I am not showing the header column. I have tried setting the widths to the exact same values in both gridviews but the columns are not matching up.

I have tried setting with width on the boundfield:

```<code><asp:BoundField DataField="Code" HeaderText="A/C" SortExpression="Code" ItemStyle-Width ="120px"></asp:BoundField>
</code>```

I have tried setting the width of the column:

```<code>gridview.Columns[0].ItemStyle.Width = 120;
</code>```

I have tried setting the width of the cells:

```<code>foreach (TableRow row in gridview.Controls[0].Controls)
{
    row.Cells[0].Width = 120;
}
</code>```

None of the above have worked. The second gridview width (last row in the image) is not displaying the same as the first gridview

First Grid:

```<code><asp:GridView runat="server"
                            id="gvJobsPerMonth"
                            CssClass="tblResults"
                            OnItemDataBound="gvJobsPerMonth_OnItemDataBound"
                            AllowSorting="true"
                            OnSortCommand="gvJobsPerMonth_Sort"
                            DataKeyField="ID"
                            AutoGenerateColumns="false" >
                        <HeaderStyle CssClass="tblResultsHeader" />
                        <AlternatingRowStyle BackColor="#EEEEEE" />
</code>```

Second Grid:

```<code>    <asp:GridView runat="server"
                                    id="gvJobsPerMonthTotals"
                                    CssClass="tblResults"
OnItemDataBound="gvJobsPerMonthTotals_OnItemDataBound"
                                    AllowSorting="true"
                                    OnSortCommand="gvJobsPerMonthTotals_Sort"
                                    DataKeyField="ID"
                                    AutoGenerateColumns="false"
                                    ShowHeader="false" >
                                <HeaderStyle CssClass="tblResultsHeader" />
                                <AlternatingRowStyle BackColor="#EEEEEE" />
</code>```

Both grids are using the same CSS classes. The only difference is ShowHeader="false" on the second grid. But even if I set this to true the columns are still showing as different widths

答:
The width of a GridView is set with the ItemStyle Width property.</p>

```<code><asp:BoundField DataField="language" HeaderText="language">
  <ItemStyle Width="500px" />
</asp:BoundField>
</code>```

Body:
I have two gridviews one displaying under the other one. Both gridviews are exactly the same, the only difference with the second gridview is I am not showing the header column. I have tried setting the widths to the exact same values in both gridviews but the columns are not matching up.

I have tried setting with width on the boundfield:

<asp:BoundField DataField="Code" HeaderText="A/C" SortExpression="Code" ItemStyle-Width ="120px"></asp:BoundField>

I have tried setting the width of the column:

gridview.Columns[0].ItemStyle.Width = 120;

I have tried setting the width of the cells:

foreach (TableRow row in gridview.Controls[0].Controls)
{
    row.Cells[0].Width = 120;
}

None of the above have worked. The second gridview width (last row in the image) is not displaying the same as the first gridview

First Grid:

<asp:GridView runat="server"
                            id="gvJobsPerMonth"
                            CssClass="tblResults"
                            OnItemDataBound="gvJobsPerMonth_OnItemDataBound"
                            AllowSorting="true"
                            OnSortCommand="gvJobsPerMonth_Sort"
                            DataKeyField="ID"
                            AutoGenerateColumns="false" >
                        <HeaderStyle CssClass="tblResultsHeader" />
                        <AlternatingRowStyle BackColor="#EEEEEE" />

Second Grid:

    <asp:GridView runat="server"
                                    id="gvJobsPerMonthTotals"
                                    CssClass="tblResults"
OnItemDataBound="gvJobsPerMonthTotals_OnItemDataBound"
                                    AllowSorting="true"
                                    OnSortCommand="gvJobsPerMonthTotals_Sort"
                                    DataKeyField="ID"
                                    AutoGenerateColumns="false"
                                    ShowHeader="false" >
                                <HeaderStyle CssClass="tblResultsHeader" />
                                <AlternatingRowStyle BackColor="#EEEEEE" />

Both grids are using the same CSS classes. The only difference is ShowHeader="false" on the second grid. But even if I set this to true the columns are still showing as different widths

Body:
The width of a GridView is set with the ItemStyle Width property.

<asp:BoundField DataField="language" HeaderText="language">
  <ItemStyle Width="500px" />
</asp:BoundField>


问:
How to create a circular image using MKAnnotationView
I overrode MKAnnotationView to display a custom image on a map:

```<code>override init(annotation: MKAnnotation!, reuseIdentifier: String!) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)

        let img = UIImage(named: "annotation")
        self.image = img
        self.frame = CGRectMake(0, 0, 40, 40)
        self.layer.cornerRadius = 20
        self.contentMode = UIViewContentMode.ScaleAspectFit
        self.centerOffset = CGPointMake(0, -20)
    }
</code>```

I want to create a circular image on the map, but cornerRadius not working.

答:
clipToBounds will clip the view to match the layer.

```<code>annotationView.layer.cornerRadius = 20
annotationView.clipsToBounds = true
</code>```

Body:
I overrode MKAnnotationView to display a custom image on a map:

override init(annotation: MKAnnotation!, reuseIdentifier: String!) {
        super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)

        let img = UIImage(named: "annotation")
        self.image = img
        self.frame = CGRectMake(0, 0, 40, 40)
        self.layer.cornerRadius = 20
        self.contentMode = UIViewContentMode.ScaleAspectFit
        self.centerOffset = CGPointMake(0, -20)
    }

I want to create a circular image on the map, but cornerRadius not working.

Body:
clipToBounds will clip the view to match the layer.

annotationView.layer.cornerRadius = 20
annotationView.clipsToBounds = true


问:
Function to be used by others - how to export so that code isn't exposed
I wrote some code in java and I want to have it to be an exe file or any other form of user interface for other developers to use it

EDIT
what I have used in the end was exporting to jar as user  user85421 suggested.

答:
The default GUI classes of Java are called Swing. You should buy a book about Swing or take a look at any tutorial like this: https://www.guru99.com/java-swing-gui.html

If text-only input and output is OK, then just use the classes Scanner and System:

```<code>import java.util.Scanner;

class Main
{
    public static void main(String[] args)
    {
        Scanner scanner=new Scanner(System.in);
        System.out.println("Enter two numbers:");
        int number1=scanner.nextInt();
        int number2=scanner.nextInt();
        System.out.printf("%d + %d = %d\n", number1, number2, number1+number2);
    }
}
</code>```

Outputs:

```<code>Enter two numbers:
3
4
3 + 4 = 7
</code>```

Body:
The default GUI classes of Java are called Swing. You should buy a book about Swing or take a look at any tutorial like this: https://www.guru99.com/java-swing-gui.html

If text-only input and output is OK, then just use the classes Scanner and System:

import java.util.Scanner;

class Main
{
    public static void main(String[] args)
    {
        Scanner scanner=new Scanner(System.in);
        System.out.println("Enter two numbers:");
        int number1=scanner.nextInt();
        int number2=scanner.nextInt();
        System.out.printf("%d + %d = %d\n", number1, number2, number1+number2);
    }
}

Outputs:

Enter two numbers:
3
4
3 + 4 = 7


问:
Issue with condition in headerright
I try to add a conditional button in headerright but I get an error message that (probably) says this is not the way to go. I am sure the error is in the condition within the headerright of the stacknavbigator, since when I try with a straight button it works.

This is the stacknavigator code

```<code>const AppNavigator = createStackNavigator(
  {
    Loading: Loading,
    SignUp: SignUp,
    Login: Login,
    Main: Main,
  },
  {
    initialRouteName: 'Loading',

    defaultNavigationOptions: {
      headerLeft: null,
      headerRight:
      () => (
        if this.loggedIn: true {

          <Button
          onPress={() => alert('I know you')}
          title="Log-out"
          color="#fff"
          />
        }

        else {
          <Button
          onPress={() => alert('Please log in')}
          title="Log-in"
          color="#fff"
          />
             }
      );
      headerStyle: {
        backgroundColor: '#c6f1e7',
      },
      headerTintColor: '#59616e',
      headerTitleStyle: {
        fontFamily: 'Raleway-Regular',
        fontWeight: '400',
      },
    },
  },
);
</code>```

Where the fucntion in headerright is causing this error:

```<code>Error: TransformError SyntaxError: /Users/tim/Dropbox/co-own.it/apps/kowop/App.js: Unexpected token (33:8)

  31 |       headerLeft: null,
  32 |       headerRight: () => (
> 33 |         if this.loggedIn: true {
     |         ^
  34 |           <Button
  35 |           onPress={() => alert('I know you')}
  36 |           title="Log-out"

showCompileError
    index.bundle?platform=ios&dev=true&minify=false:34606:26
<unknown>
    index.bundle?platform=ios&dev=true&minify=false:34545:29
emit
    index.bundle?platform=ios&dev=true&minify=false:35025:35
<unknown>
    index.bundle?platform=ios&dev=true&minify=false:34872:23
dispatchEvent
    index.bundle?platform=ios&dev=true&minify=false:32343:31
<unknown>
</code>```

Can anyone point me in the good direction, since I can't really find the answer?

Thanks a lot!

Tim

答:
In header right you need to change the code:

```<code> headerRight:
      () => {
        let button = this.loggedIn? (

          <Button
          onPress={() => alert('I know you')}
          title="Log-out"
          color="#fff"
          />
        )

        : (
          <Button
          onPress={() => alert('Please log in')}
          title="Log-in"
          color="#fff"
          />
             )

return button;
      };
</code>```

hope it helps.

Title: Issue with condition in headerright

Body:
I try to add a conditional button in headerright but I get an error message that (probably) says this is not the way to go. I am sure the error is in the condition within the headerright of the stacknavbigator, since when I try with a straight button it works.

This is the stacknavigator code

const AppNavigator = createStackNavigator(
  {
    Loading: Loading,
    SignUp: SignUp,
    Login: Login,
    Main: Main,
  },
  {
    initialRouteName: 'Loading',

    defaultNavigationOptions: {
      headerLeft: null,
      headerRight:
      () => (
        if this.loggedIn: true {

          <Button
          onPress={() => alert('I know you')}
          title="Log-out"
          color="#fff"
          />
        }

        else {
          <Button
          onPress={() => alert('Please log in')}
          title="Log-in"
          color="#fff"
          />
             }
      );
      headerStyle: {
        backgroundColor: '#c6f1e7',
      },
      headerTintColor: '#59616e',
      headerTitleStyle: {
        fontFamily: 'Raleway-Regular',
        fontWeight: '400',
      },
    },
  },
);

Where the fucntion in headerright is causing this error:

Error: TransformError SyntaxError: /Users/tim/Dropbox/co-own.it/apps/kowop/App.js: Unexpected token (33:8)

  31 |       headerLeft: null,
  32 |       headerRight: () => (
> 33 |         if this.loggedIn: true {
     |         ^
  34 |           <Button
  35 |           onPress={() => alert('I know you')}
  36 |           title="Log-out"

showCompileError
    index.bundle?platform=ios&dev=true&minify=false:34606:26
<unknown>
    index.bundle?platform=ios&dev=true&minify=false:34545:29
emit
    index.bundle?platform=ios&dev=true&minify=false:35025:35
<unknown>
    index.bundle?platform=ios&dev=true&minify=false:34872:23
dispatchEvent
    index.bundle?platform=ios&dev=true&minify=false:32343:31
<unknown>

Can anyone point me in the good direction, since I can't really find the answer?

Thanks a lot!

Tim

Body:
In header right you need to change the code:

 headerRight:
      () => {
        let button = this.loggedIn? (

          <Button
          onPress={() => alert('I know you')}
          title="Log-out"
          color="#fff"
          />
        )

        : (
          <Button
          onPress={() => alert('Please log in')}
          title="Log-in"
          color="#fff"
          />
             )

return button;
      };

hope it helps.


问:
git central repository and Team
I have been playing around with GIT on my local computer.

As I have gain a bit of knowledge using GIT like add, commit, merge, branch, checkout, status.

I still have more to learn but im confuse one thing.. how does git handle team?

For example:

Developer A computer

Developer B computer

Developer C computer

Central repository (Server)

All Developers working on the same project.

From what I understood (correct me if im wrong).. A ,B and C developers push their branch (master?) to central repository via SSH remote.

But on the central repository, how do I get information or which files (or branch?) that has been pushed from the developers... What would it look like on the central repository?

On the central repository, how would handle merges developers work?

Thanks.

答: Central repo won't need to merge anything as it won't have its own commits. It's developers job to merge changes. Central repo will merely fast-forward on commit, or reject commit if other developer pushed before.</p>

ContentLicense: CC BY-SA 3.0

Title: git central repository and Team


问:
Firebase error while syncing a new project on Android Studio (ASCII Error)
The problem is that everytime I sync a project on Android Studio (after I followed all the steps on the Firebase guide), the "ASCII" error occured (Note that my google-services.json file is already in the app folder).

答: change your Project-level build.gradle: to this 'com.google.gms:google-services:4.2.0</p>


问:
No such file or directory, open 'app\build\intermediates\merged_manifests\debug\AndroidManifest.xml' in React-Native
After creating my React-Native project with the following command :

```<code>npx react-native init AwesomeProject
</code>```

When I want to run the project with the following command

```<code>npx react-native run-android
</code>```

I get the following error :

info Running jetifier to migrate libraries to AndroidX. You can
  disable it using "--no-jetifier" flag.

Jetifier found 864 file(s) to
  forward-jetify. Using 8 workers... info Starting JS server...

error
  ENOENT: no such file or directory, open
  'app\build\intermediates\merged_manifests\debug\AndroidManifest.xml'.
  Run CLI with --verbose flag for more details.

Error: ENOENT: no such
  file or directory, open
  'app\build\intermediates\merged_manifests\debug\AndroidManifest.xml'
      at Object.openSync (fs.js:456:3)
      at Object.readFileSync (fs.js:358:35)
      at getLaunchPackageName (C:\Users\Angular\Desktop\React-Native\AwesomeProject120\node_modules@react-native-community\cli-platform-android\build\commands\runAndroid\getLaunchPackageName.js:161:33)
      at buildAndRun (C:\Users\Angular\Desktop\React-Native\AwesomeProject120\node_modules@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:163:63)
      at C:\Users\Angular\Desktop\React-Native\AwesomeProject120\node_modules@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:135:12
      at processTicksAndRejections (internal/process/task_queues.js:97:5)
      at async Command.handleAction (C:\Users\Angular\Desktop\React-Native\AwesomeProject120\node_modules\react-native\node_modules@react-native-community\cli\build\index.js:182:9)

I tried uninstalling the package and reinstalling but It does not work.

EDIT:

there is a package named @react-native-community in the node_modules folder,
when I used @react-native-community package of my previous project and replace, It worked perfectly

my package.json

```<code>{
  "name": "AwesomeProject",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "react": "16.9.0",
    "react-native": "0.61.5"
  },
  "devDependencies": {
    "@babel/core": "^7.6.2",
    "@babel/runtime": "^7.6.2",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-jest": "^24.9.0",
    "eslint": "^6.5.1",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.56.0",
    "react-test-renderer": "16.9.0"
  },
  "jest": {
    "preset": "react-native"
  }
}
</code>```

答:
try to run:
 "cd android"
 "./gradlew assembleDebug"
 "cd .."
 "npx react-native run-android"</p>

Body:
After creating my React-Native project with the following command :

npx react-native init AwesomeProject

When I want to run the project with the following command

npx react-native run-android

I get the following error :

info Running jetifier to migrate libraries to AndroidX. You can
  disable it using "--no-jetifier" flag.

Jetifier found 864 file(s) to
  forward-jetify. Using 8 workers... info Starting JS server...

error
  ENOENT: no such file or directory, open
  'app\build\intermediates\merged_manifests\debug\AndroidManifest.xml'.
  Run CLI with --verbose flag for more details.

Error: ENOENT: no such
  file or directory, open
  'app\build\intermediates\merged_manifests\debug\AndroidManifest.xml'
      at Object.openSync (fs.js:456:3)
      at Object.readFileSync (fs.js:358:35)
      at getLaunchPackageName (C:\Users\Angular\Desktop\React-Native\AwesomeProject120\node_modules@react-native-community\cli-platform-android\build\commands\runAndroid\getLaunchPackageName.js:161:33)
      at buildAndRun (C:\Users\Angular\Desktop\React-Native\AwesomeProject120\node_modules@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:163:63)
      at C:\Users\Angular\Desktop\React-Native\AwesomeProject120\node_modules@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:135:12
      at processTicksAndRejections (internal/process/task_queues.js:97:5)
      at async Command.handleAction (C:\Users\Angular\Desktop\React-Native\AwesomeProject120\node_modules\react-native\node_modules@react-native-community\cli\build\index.js:182:9)

I tried uninstalling the package and reinstalling but It does not work.

EDIT:

there is a package named @react-native-community in the node_modules folder,
when I used @react-native-community package of my previous project and replace, It worked perfectly

my package.json

{
  "name": "AwesomeProject",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "react": "16.9.0",
    "react-native": "0.61.5"
  },
  "devDependencies": {
    "@babel/core": "^7.6.2",
    "@babel/runtime": "^7.6.2",
    "@react-native-community/eslint-config": "^0.0.5",
    "babel-jest": "^24.9.0",
    "eslint": "^6.5.1",
    "jest": "^24.9.0",
    "metro-react-native-babel-preset": "^0.56.0",
    "react-test-renderer": "16.9.0"
  },
  "jest": {
    "preset": "react-native"
  }
}


问:
http://localhost:8000/qconsole is not coming in MarkLogic 9 in browser
In my system MarkLogic admin and config panel is working, but console panel is not. It worked until yesterday.
Message in browser shown below:</p>
```<code>This site can't be reached
localhost refused to connect.
Did you mean http://localhost8000.com/?
Search Google for localhost 8000
ERR_CONNECTION_REFUSED
</code>```

答:
Move your .htaccess from the public folder to the root directory instead.

If you still have the problem then rename the file server.php in your root directory to index.php.

Body:
In my system MarkLogic admin and config panel is working, but console panel is not. It worked until yesterday.
Message in browser shown below:

This site can't be reached
localhost refused to connect.
Did you mean http://localhost8000.com/?
Search Google for localhost 8000
ERR_CONNECTION_REFUSED


问:
How to add values to an ArrayList referenced by jsp:useBean?
In JSP/JSTL, how can I set values for a usebean of class="java.util.ArrayList".

If I try using c:set property or value, I get the following error:
javax.servlet.jsp.JspTagException: Invalid property in :  "null"

答:
That isn't directly possible. There are the <c:set> and <jsp:setProperty> tags which allows you to set properties in a fullworthy javabean through a setter method. However, the List interface doesn't have a setter, just an add() method.

A workaround would be to wrap the list in a real javabean like so:

```<code>public class ListBean {

    private List<Object> list = new ArrayList<Object>();

    public void setChild(Object object) {
        list.add(object);
    }

    public List<Object> getList() {
        return list;
    }
}
</code>```

and set it by

```<code><jsp:useBean id="listBean" class="com.example.ListBean" scope="request" />
<jsp:setProperty name="listBean" property="child" value="foo" />
<jsp:setProperty name="listBean" property="child" value="bar" />
<jsp:setProperty name="listBean" property="child" value="waa" />
</code>```

But that makes little sense. How to solve it rightly depends on the sole functional requirement. If you want to preserve some List upon a GET request, then you should be using a preprocessing servlet. Create a servlet which does the following in doGet() method:

```<code>List<String> list = Arrays.asList("foo", "bar", "waa");
request.setAttribute("list", list);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);
</code>```

When you invoke the servlet by its URL, then the list is in the forwarded JSP available by

```<code>${list}
</code>```

without the need for old fashioned <jsp:useBean> tags. In a servlet you've all freedom to write Java code the usual way. This way you can use JSP for pure presentation only without the need to gobble/hack some preprocessing logic by <jsp:useBean> tags.

See also:

Our servlets wiki page

Body:
That isn't directly possible. There are the <c:set> and <jsp:setProperty> tags which allows you to set properties in a fullworthy javabean through a setter method. However, the List interface doesn't have a setter, just an add() method.

A workaround would be to wrap the list in a real javabean like so:

public class ListBean {

    private List<Object> list = new ArrayList<Object>();

    public void setChild(Object object) {
        list.add(object);
    }

    public List<Object> getList() {
        return list;
    }
}

and set it by

<jsp:useBean id="listBean" class="com.example.ListBean" scope="request" />
<jsp:setProperty name="listBean" property="child" value="foo" />
<jsp:setProperty name="listBean" property="child" value="bar" />
<jsp:setProperty name="listBean" property="child" value="waa" />

But that makes little sense. How to solve it rightly depends on the sole functional requirement. If you want to preserve some List upon a GET request, then you should be using a preprocessing servlet. Create a servlet which does the following in doGet() method:

List<String> list = Arrays.asList("foo", "bar", "waa");
request.setAttribute("list", list);
request.getRequestDispatcher("/WEB-INF/page.jsp").forward(request, response);

When you invoke the servlet by its URL, then the list is in the forwarded JSP available by

${list}

without the need for old fashioned <jsp:useBean> tags. In a servlet you've all freedom to write Java code the usual way. This way you can use JSP for pure presentation only without the need to gobble/hack some preprocessing logic by <jsp:useBean> tags.

See also:

Our servlets wiki page


问:
how Backslash \ joins printf strings when written on separate lines in C?
Using Dev C++ I was doing some fun with C and got this :

```<code>#include<stdio.h>
main()
{
printf("Hello
      world" );
}
</code>```

^^^^ here I thought output would be like "Hello (with spaces) World" but
Errors :

```<code>C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c In function 'main':
5   10  C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Warning] missing terminating " character
5   3   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] missing terminating " character
6   8   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Warning] missing terminating " character
6   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] missing terminating " character
6   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] 'world' undeclared (first use in this function)
6   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Note] each undeclared identifier is reported only once for each function it appears in
7   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] expected ')' before '}' token
7   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] expected ';' before '}' token
</code>```

but when i added a \ it worked :

```<code>#include<stdio.h>
main()
{
printf("Hello \
   World" );
}
</code>```

Without any warnings and errors.
What Magic of '\' is this ?
And do any other soccery exists , please let me know .

答:
The backslash has many special meanings, e.g. escape sequences to  represent special characters.

But the special meaning you found is the one of \ immediatly followed by a newline; which is "ignore me and the newline". For the compiler this solves the problem of encountering a newline in the middle of a string.

Body:
Using Dev C++ I was doing some fun with C and got this :

#include<stdio.h>
main()
{
printf("Hello
      world" );
}

^^^^ here I thought output would be like "Hello (with spaces) World" but
Errors :

C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c In function 'main':
5   10  C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Warning] missing terminating " character
5   3   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] missing terminating " character
6   8   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Warning] missing terminating " character
6   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] missing terminating " character
6   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] 'world' undeclared (first use in this function)
6   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Note] each undeclared identifier is reported only once for each function it appears in
7   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] expected ')' before '}' token
7   1   C:\Users\ASUS\Documents\Dev C++ Programs\helloWorldDk.c [Error] expected ';' before '}' token

but when i added a \ it worked :

#include<stdio.h>
main()
{
printf("Hello \
   World" );
}

Without any warnings and errors.
What Magic of '\' is this ?
And do any other soccery exists , please let me know .


问:
how to slide two listviews with one touch
image of two listviews

I am trying to build this image that I gave the link. Second listview to the right of the first listview. Both listview items are clickable separately. Along the y-axis, second listview's items must be in between first listview's items. Both of them should scroll if user scrolls one of them. I have some solutions.
 First one is to control two listview in one touch.
 Another solution approach is using one list view. But it has problems of touch events for the second listview. It seems first approach is right but I don't know how to connect two listviews. Thanks in advance.

答:
I thing it can be achieved using OnScrollListener, essentially you can scroll other list/recyclerview on scroll of it's sibling view.
Here is snippet, assuming you use Recycleview

```<code>class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val left = findViewById<RecyclerView>(R.id.left)
        val right = findViewById<RecyclerView>(R.id.right)
        left.adapter = Adapter()
        right.adapter = Adapter()

        val switcher = FocusSwitchListener(left, right)

        left.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (switcher.isLeftLastFocused) {
                    right.stopScroll()
                    right.scrollBy(dx, dy)
                }
            }
        })
        right.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (switcher.isRightLastFocused) {
                    left.stopScroll()
                    left.scrollBy(dx, dy)
                }
            }
        })
    }
}
</code>```

FocusSwitchListener

```<code>class FocusSwitchListener(left: View, right: View) {
    var isLeftLastFocused: Boolean = false
        private set
    var isRightLastFocused: Boolean = false
        private set

    init {
        left.setOnTouchListener { _, event ->
            if (event?.action == MotionEvent.ACTION_DOWN) {
                isLeftLastFocused = true
                isRightLastFocused = false
            }
            false
        }
        right.setOnTouchListener { _, event ->
            if (event?.action == MotionEvent.ACTION_DOWN) {
                isRightLastFocused = true
                isLeftLastFocused = false
            }
            false
        }
    }
}
</code>```

and activity xml

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

   <androidx.recyclerview.widget.RecyclerView
       android:layout_width="0dp"
       android:id="@+id/left"
       android:layout_weight="0.5"
       app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
       android:layout_height="match_parent"/>
    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="0dp"
        android:id="@+id/right"
        android:layout_weight="0.5"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        android:layout_height="match_parent"/>
</LinearLayout>
</code>```

Body:
I thing it can be achieved using OnScrollListener, essentially you can scroll other list/recyclerview on scroll of it's sibling view.
Here is snippet, assuming you use Recycleview

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val left = findViewById<RecyclerView>(R.id.left)
        val right = findViewById<RecyclerView>(R.id.right)
        left.adapter = Adapter()
        right.adapter = Adapter()

        val switcher = FocusSwitchListener(left, right)

        left.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (switcher.isLeftLastFocused) {
                    right.stopScroll()
                    right.scrollBy(dx, dy)
                }
            }
        })
        right.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                if (switcher.isRightLastFocused) {
                    left.stopScroll()
                    left.scrollBy(dx, dy)
                }
            }
        })
    }
}

FocusSwitchListener

class FocusSwitchListener(left: View, right: View) {
    var isLeftLastFocused: Boolean = false
        private set
    var isRightLastFocused: Boolean = false
        private set

    init {
        left.setOnTouchListener { _, event ->
            if (event?.action == MotionEvent.ACTION_DOWN) {
                isLeftLastFocused = true
                isRightLastFocused = false
            }
            false
        }
        right.setOnTouchListener { _, event ->
            if (event?.action == MotionEvent.ACTION_DOWN) {
                isRightLastFocused = true
                isLeftLastFocused = false
            }
            false
        }
    }
}

and activity xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="horizontal"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

   <androidx.recyclerview.widget.RecyclerView
       android:layout_width="0dp"
       android:id="@+id/left"
       android:layout_weight="0.5"
       app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
       android:layout_height="match_parent"/>
    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="0dp"
        android:id="@+id/right"
        android:layout_weight="0.5"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        android:layout_height="match_parent"/>
</LinearLayout>


问:
Add UILabel over UIImage inside StackView

The part of my storyboard looks like on first photo. On second photo I present constraints. What I am trying to achieve is to put UILabel at the bottom over the UIImageView (with photo "DJI_0049").

答:
i was also able to do this in a stackview by adding the label as a subview to the image view.

```<code>        cell.avatarImage.leadingAnchor.constraint(equalTo: cell.cellBodyStackView.leadingAnchor, constant: 10).isActive = true
        cell.avatarImage.topAnchor.constraint(equalTo: cell.cellBodyStackView.topAnchor).isActive = true
        cell.avatarImage.bottomAnchor.constraint(equalTo: cell.cellBodyStackView.bottomAnchor).isActive = true
        cell.avatarImage.trailingAnchor.constraint(equalTo: cell.commentLabel.leadingAnchor, constant: -10).isActive = true
        cell.avatarImage.widthAnchor.constraint(lessThanOrEqualToConstant: cellWidth * 0.25).isActive = true

        cell.avatarImage.addSubview(cell.usernameLabel)
        cell.usernameLabel.trailingAnchor.constraint(equalTo: cell.avatarImage.trailingAnchor).isActive = true
        cell.usernameLabel.leadingAnchor.constraint(equalTo: cell.avatarImage.leadingAnchor).isActive = true
        cell.usernameLabel.bottomAnchor.constraint(equalTo: cell.avatarImage.bottomAnchor).isActive = true
        cell.usernameLabel.centerXAnchor.constraint(equalTo: cell.avatarImage.centerXAnchor).isActive = true
        cell.usernameLabel.textAlignment = .center
        cell.usernameLabel.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        cell.usernameLabel.textColor = UIColor.white
</code>```

Body:
i was also able to do this in a stackview by adding the label as a subview to the image view.

        cell.avatarImage.leadingAnchor.constraint(equalTo: cell.cellBodyStackView.leadingAnchor, constant: 10).isActive = true
        cell.avatarImage.topAnchor.constraint(equalTo: cell.cellBodyStackView.topAnchor).isActive = true
        cell.avatarImage.bottomAnchor.constraint(equalTo: cell.cellBodyStackView.bottomAnchor).isActive = true
        cell.avatarImage.trailingAnchor.constraint(equalTo: cell.commentLabel.leadingAnchor, constant: -10).isActive = true
        cell.avatarImage.widthAnchor.constraint(lessThanOrEqualToConstant: cellWidth * 0.25).isActive = true

        cell.avatarImage.addSubview(cell.usernameLabel)
        cell.usernameLabel.trailingAnchor.constraint(equalTo: cell.avatarImage.trailingAnchor).isActive = true
        cell.usernameLabel.leadingAnchor.constraint(equalTo: cell.avatarImage.leadingAnchor).isActive = true
        cell.usernameLabel.bottomAnchor.constraint(equalTo: cell.avatarImage.bottomAnchor).isActive = true
        cell.usernameLabel.centerXAnchor.constraint(equalTo: cell.avatarImage.centerXAnchor).isActive = true
        cell.usernameLabel.textAlignment = .center
        cell.usernameLabel.backgroundColor = UIColor.black.withAlphaComponent(0.5)
        cell.usernameLabel.textColor = UIColor.white


问:
Is it possible for a button click to permanently change an image's source using only a XAML trigger?
I'm trying to solve the following problem on a WPF datagrid:

I've templated the DataGrid items to contain a button - when clicked, it displays the RowDetails for the grid. I'm having trouble getting that button styled the way I want. Specifically, I want it to appear as a "hyperlink" with a small plus-sign icon next to it. When clicked to display the RowDetails, that icon should change to a minus-sign.

Here's the ControlTemplate I'm attempting to apply to the Button:

```<code><ControlTemplate x:Key="linkButtonTemplate" TargetType="{x:Type Button}">
     <StackPanel Orientation="Horizontal">
          <Image x:Name="expanderIcon" Source="Images/Plus.png"/>
          <TextBlock Foreground="Blue" TextDecorations="Underline" Padding="5 0 0 0">
               <ContentPresenter />
          </TextBlock>
     </StackPanel>
</ControlTemplate>
</code>```

So, when the button is clicked, I want to change that Image's Source property. And when it's clicked again, I want to change it back. I've come across the following suggested solutions, and none seem ideal:

1. Use a Trigger on the Button.IsPressed event: It works! ...Except the image reverts once the event ends. (i.e. once the IsPressed property is no longer true). So it doesn't work.

2. Use an EventTrigger: These at least let you catch the Button's Click event... and

Unlike Trigger, EventTrigger  has no
  concept of termination of state, so
  the action will not be undone once the
  condition that raised the event is no
  longer true.

So, great! But they appear to only let you respond with Storyboard actions, not a simple property Setter. Unless I'm missing something, these are not meant for this scenario.

3. Use an Attached Behavior: I'm currently delving into this option, but I just can't help thinking there ought to be a XAML-contained means of doing this. If not, so be it - I'll learn Attached Behaviors.

But my hope is that someone has an angle on this that I haven't encountered.

For example, is there a way to hook the property of the DataRow containing the button that indicates if the RowDetails are currently viewable? Seems like you'd need to crack open the code behind to accomplish that, too... Am I wrong?

答:
I would not claim that EventTriggers are not meant for this, single frame animations are fine and can even be found in the default templates of certain controls, e.g.

```<code><VisualState Name="CalendarButtonFocused">
    <Storyboard>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="CalendarButtonFocusVisual" Storyboard.TargetProperty="Visibility" Duration="0">
            <DiscreteObjectKeyFrame KeyTime="0">
                <DiscreteObjectKeyFrame.Value>
                    <Visibility>Visible</Visibility>
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</VisualState>
</code>```

So here is an example of how to change the Source that way:

```<code><Image Name="img" Source="C:\Users\Public\1.png"/>
<Button Content="!">
    <Button.Triggers>
        <EventTrigger RoutedEvent="Button.Click">
            <EventTrigger.Actions>
                <BeginStoryboard>
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.Target="{x:Reference img}"
                                                       Storyboard.TargetProperty="Source">
                            <DiscreteObjectKeyFrame KeyTime="0:0:0">
                                <DiscreteObjectKeyFrame.Value>
                                    <BitmapImage UriSource="C:\Users\Public\2.png"/>
                                </DiscreteObjectKeyFrame.Value>
                            </DiscreteObjectKeyFrame>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger.Actions>
        </EventTrigger>
    </Button.Triggers>
</Button>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to solve the following problem on a WPF datagrid:

I've templated the DataGrid items to contain a button - when clicked, it displays the RowDetails for the grid. I'm having trouble getting that button styled the way I want. Specifically, I want it to appear as a "hyperlink" with a small plus-sign icon next to it. When clicked to display the RowDetails, that icon should change to a minus-sign.

Here's the ControlTemplate I'm attempting to apply to the Button:

<ControlTemplate x:Key="linkButtonTemplate" TargetType="{x:Type Button}">
     <StackPanel Orientation="Horizontal">
          <Image x:Name="expanderIcon" Source="Images/Plus.png"/>
          <TextBlock Foreground="Blue" TextDecorations="Underline" Padding="5 0 0 0">
               <ContentPresenter />
          </TextBlock>
     </StackPanel>
</ControlTemplate>

So, when the button is clicked, I want to change that Image's Source property. And when it's clicked again, I want to change it back. I've come across the following suggested solutions, and none seem ideal:

1. Use a Trigger on the Button.IsPressed event: It works! ...Except the image reverts once the event ends. (i.e. once the IsPressed property is no longer true). So it doesn't work.

2. Use an EventTrigger: These at least let you catch the Button's Click event... and

Unlike Trigger, EventTrigger  has no
  concept of termination of state, so
  the action will not be undone once the
  condition that raised the event is no
  longer true.

So, great! But they appear to only let you respond with Storyboard actions, not a simple property Setter. Unless I'm missing something, these are not meant for this scenario.

3. Use an Attached Behavior: I'm currently delving into this option, but I just can't help thinking there ought to be a XAML-contained means of doing this. If not, so be it - I'll learn Attached Behaviors.

But my hope is that someone has an angle on this that I haven't encountered.

For example, is there a way to hook the property of the DataRow containing the button that indicates if the RowDetails are currently viewable? Seems like you'd need to crack open the code behind to accomplish that, too... Am I wrong?

Body:
I would not claim that EventTriggers are not meant for this, single frame animations are fine and can even be found in the default templates of certain controls, e.g.

<VisualState Name="CalendarButtonFocused">
    <Storyboard>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="CalendarButtonFocusVisual" Storyboard.TargetProperty="Visibility" Duration="0">
            <DiscreteObjectKeyFrame KeyTime="0">
                <DiscreteObjectKeyFrame.Value>
                    <Visibility>Visible</Visibility>
                </DiscreteObjectKeyFrame.Value>
            </DiscreteObjectKeyFrame>
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</VisualState>

So here is an example of how to change the Source that way:

<Image Name="img" Source="C:\Users\Public\1.png"/>
<Button Content="!">
    <Button.Triggers>
        <EventTrigger RoutedEvent="Button.Click">
            <EventTrigger.Actions>
                <BeginStoryboard>
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.Target="{x:Reference img}"
                                                       Storyboard.TargetProperty="Source">
                            <DiscreteObjectKeyFrame KeyTime="0:0:0">
                                <DiscreteObjectKeyFrame.Value>
                                    <BitmapImage UriSource="C:\Users\Public\2.png"/>
                                </DiscreteObjectKeyFrame.Value>
                            </DiscreteObjectKeyFrame>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </BeginStoryboard>
            </EventTrigger.Actions>
        </EventTrigger>
    </Button.Triggers>
</Button>


问:
newtype-like operational semantics for a GADT where the type fully determines the constructor
Suppose I have a GADT like the following:

```<code>data Tag = A | B | C

data Payload (tag :: Tag) where
  PA :: Int -> Payload A
  PB :: Double -> Payload B
  PC :: Bool -> Payload C
</code>```

I want Payload to have no runtime representation on its own -- i.e. I want to have Coercible Int (Payload A), I want zero-cost pattern matching, and in general I want it to behave as if I had the following three newtype definitions instead:

```<code>newtype PayloadA = PA Int
newtype PayloadB = PB Double
newtype PayloadC = PC Bool
</code>```

Is there a way to convince GHC to give me that?

答:
You can do like:

```<code>data family Payload (tag :: Tag)
newtype instance Payload A = PA Int
newtype instance Payload B = PB Double
newtype instance Payload C = PC Bool
</code>```

This meets your requirement of actually having types distinct from Int, Double, Bool, and of having the operation semantics of a newtype. Of course, the price you pay is you won't be able to pattern-match to determine which is which. But you can recover such things with a typeclass or by explicitly passing the tag (which mostly amount to the same thing under the hood); for example:

```<code>class Foo (t :: Tag) where foo :: Payload t -> Int
instance Foo A where foo (PA i) = i
instance Foo B where foo (PB _) = 2
instance Foo C where foo (PC _) = 3
</code>```

Body:
Suppose I have a GADT like the following:

data Tag = A | B | C

data Payload (tag :: Tag) where
  PA :: Int -> Payload A
  PB :: Double -> Payload B
  PC :: Bool -> Payload C

I want Payload to have no runtime representation on its own -- i.e. I want to have Coercible Int (Payload A), I want zero-cost pattern matching, and in general I want it to behave as if I had the following three newtype definitions instead:

newtype PayloadA = PA Int
newtype PayloadB = PB Double
newtype PayloadC = PC Bool

Is there a way to convince GHC to give me that?

Body:
You can do like:

data family Payload (tag :: Tag)
newtype instance Payload A = PA Int
newtype instance Payload B = PB Double
newtype instance Payload C = PC Bool

This meets your requirement of actually having types distinct from Int, Double, Bool, and of having the operation semantics of a newtype. Of course, the price you pay is you won't be able to pattern-match to determine which is which. But you can recover such things with a typeclass or by explicitly passing the tag (which mostly amount to the same thing under the hood); for example:

class Foo (t :: Tag) where foo :: Payload t -> Int
instance Foo A where foo (PA i) = i
instance Foo B where foo (PB _) = 2
instance Foo C where foo (PC _) = 3


问:
@Input ony available in Life Cycle Hooks
The basketList objest is available in the html and in the Life Cycle Hook ngOnInit. However, when I try to access it with a function this.set() defined outside the hook then it doesn't work.

```<code>export class MenuOrderItemComponent implements OnInit, OnChanges {

  @Input() basketList: any;

  set(): void{
    setInterval(function(){
      console.log(this.basketList);
      console.log(this.basketList.length);
    },3000);
  }

  constructor() { }

  ngOnInit() {
    console.log('item');
    console.log(this.basketList);
    console.log(this.basketList.length);
    this.set();
  }
</code>```

I'm getting undefined for this.basketList and the error TypeError: Cannot read property 'length' of undefined for the second console.log in this.set()

答:
The issue is that function() {} defines a new this object, so by using this inside it you're actually acessing a different this object, not the MenuOrderItemComponent's one (and this other this object does not have a basketList property).

To solve this, you may use an arrow function, which does not have its own this, which means that it will use the parent's this (as you're expecting):

```<code>setInterval(() => {
  console.log(this.basketList);
  console.log(this.basketList.length);
},3000);
</code>```

For more info, check the Arrow functions section here

Body:
The basketList objest is available in the html and in the Life Cycle Hook ngOnInit. However, when I try to access it with a function this.set() defined outside the hook then it doesn't work.

export class MenuOrderItemComponent implements OnInit, OnChanges {

  @Input() basketList: any;

  set(): void{
    setInterval(function(){
      console.log(this.basketList);
      console.log(this.basketList.length);
    },3000);
  }

  constructor() { }

  ngOnInit() {
    console.log('item');
    console.log(this.basketList);
    console.log(this.basketList.length);
    this.set();
  }

I'm getting undefined for this.basketList and the error TypeError: Cannot read property 'length' of undefined for the second console.log in this.set()

Body:
The issue is that function() {} defines a new this object, so by using this inside it you're actually acessing a different this object, not the MenuOrderItemComponent's one (and this other this object does not have a basketList property).

To solve this, you may use an arrow function, which does not have its own this, which means that it will use the parent's this (as you're expecting):

setInterval(() => {
  console.log(this.basketList);
  console.log(this.basketList.length);
},3000);

For more info, check the Arrow functions section here