text:
Q: SQLCipher for android: couldn't find native method I'm trying to use the SQLCipher library but always get the same error. I have a very small class to test the library:
import android.database.Cursor;

// Uncomment to use sqlite
//import android.database.sqlite.SQLiteDatabase;
//import android.database.sqlite.SQLiteOpenHelper;

// Uncomment to use sqlcipher
import net.sqlcipher.database.SQLiteDatabase;
import net.sqlcipher.database.SQLiteOpenHelper;

import android.content.ContentValues;
import android.content.Context;
import android.util.Log;

public class DataHandler extends SQLiteOpenHelper {

  SQLiteDatabase db;
  String dbPassword;

  static final String dbName = "demo.db";
  static final String defualtDbPassword = "password";
  static final boolean ENCRYPT_DATA = false;
  static final int dbVersion = 1;

  public DataHandler(Context context){
    this(context, defualtDbPassword);
  }

  public Z41DataHandler(Context context, String password){
    super(context, dbName, null, dbVersion);

    dbPassword = password;

    // Uncomment to use sqlite
//  db = getWritableDatabase();

    // Uncomment to use sqlcipher
    SQLiteDatabase.loadLibs(context);
    db = getWritableDatabase(dbPassword);
  }

...
...
Other methods to perform queries to the database
...
...

}

As you can see, the code is prepare to work with the standard SQLite library and with SQLCipher, depending on what lines are commented.
When I test the class with SQLite, it works properly in the emulator: the database is created and I can perform INSERT, UPDATE or SELECT operations.
The problem appears when I try to use the SQLCipher library. Before I try any operation, I get the following error:
06-18 07:39:16.684: W/com.example.primerapruebadeandroid.MainActivity(2359): Starting the app
06-18 07:39:16.704: D/dalvikvm(2359): Trying to load lib /data/app-lib/com.example.primerapruebadeandroid-2/libstlport_shared.so 0xb2d93620
06-18 07:39:16.704: W/linker(2359): libstlport_shared.so has text relocations. This is wasting memory and is a security risk. Please fix.
06-18 07:39:16.714: D/dalvikvm(2359): Added shared lib /data/app-lib/com.example.primerapruebadeandroid-2/libstlport_shared.so 0xb2d93620
06-18 07:39:16.714: D/dalvikvm(2359): No JNI_OnLoad found in /data/app-lib/com.example.primerapruebadeandroid-2/libstlport_shared.so 0xb2d93620, skipping init
06-18 07:39:16.714: D/dalvikvm(2359): Trying to load lib /data/app-lib/com.example.primerapruebadeandroid-2/libsqlcipher_android.so 0xb2d93620
06-18 07:39:16.734: W/linker(2359): libsqlcipher_android.so has text relocations. This is wasting memory and is a security risk. Please fix.
06-18 07:39:16.744: D/dalvikvm(2359): Added shared lib /data/app-lib/com.example.primerapruebadeandroid-2/libsqlcipher_android.so 0xb2d93620
06-18 07:39:16.744: D/dalvikvm(2359): No JNI_OnLoad found in /data/app-lib/com.example.primerapruebadeandroid-2/libsqlcipher_android.so 0xb2d93620, skipping init
06-18 07:39:16.744: D/dalvikvm(2359): Trying to load lib /data/app-lib/com.example.primerapruebadeandroid-2/libdatabase_sqlcipher.so 0xb2d93620
06-18 07:39:16.744: W/linker(2359): libdatabase_sqlcipher.so has text relocations. This is wasting memory and is a security risk. Please fix.
06-18 07:39:16.754: D/dalvikvm(2359): Added shared lib /data/app-lib/com.example.primerapruebadeandroid-2/libdatabase_sqlcipher.so 0xb2d93620
06-18 07:39:16.754: I/Database(2359): JNI_OnLoad called
06-18 07:39:16.764: I/Database(2359): JNI_OnLoad register methods
06-18 07:39:16.764: E/dalvikvm(2359): ERROR: couldn't find native method
06-18 07:39:16.764: E/dalvikvm(2359): Requested: Lnet/sqlcipher/database/SQLiteDatabase;.native_key:([C)V
06-18 07:39:16.764: W/dalvikvm(2359): JNI WARNING: JNI function FatalError called with exception pending
06-18 07:39:16.764: W/dalvikvm(2359):              in Ljava/lang/Runtime;.nativeLoad:(Ljava/lang/String;Ljava/lang/ClassLoader;Ljava/lang/String;)Ljava/lang/String; (FatalError)
06-18 07:39:16.764: W/dalvikvm(2359): Pending exception is:
06-18 07:39:16.764: I/dalvikvm(2359): java.lang.NoSuchMethodError: no static or non-static method "Lnet/sqlcipher/database/SQLiteDatabase;.native_key([C)V"
06-18 07:39:16.764: I/dalvikvm(2359):   at java.lang.Runtime.nativeLoad(Native Method)
06-18 07:39:16.764: I/dalvikvm(2359):   at java.lang.Runtime.doLoad(Runtime.java:421)
06-18 07:39:16.764: I/dalvikvm(2359):   at java.lang.Runtime.loadLibrary(Runtime.java:362)
06-18 07:39:16.764: I/dalvikvm(2359):   at java.lang.System.loadLibrary(System.java:526)
06-18 07:39:16.764: I/dalvikvm(2359):   at net.sqlcipher.database.SQLiteDatabase.loadLibs(SQLiteDatabase.java:143)
06-18 07:39:16.764: I/dalvikvm(2359):   at net.sqlcipher.database.SQLiteDatabase.loadLibs(SQLiteDatabase.java:136)
06-18 07:39:16.764: I/dalvikvm(2359):   at com.example.primerapruebadeandroid.Persistence.DataHandler.<init>(DataHandler.java:80)
06-18 07:39:16.764: I/dalvikvm(2359):   at com.example.primerapruebadeandroid.Persistence.DataHandler.<init>(DataHandler.java:64)
06-18 07:39:16.764: I/dalvikvm(2359):   at com.example.primerapruebadeandroid.MainActivity.onCreate(MainActivity.java:37)
06-18 07:39:16.764: I/dalvikvm(2359):   at android.app.Activity.performCreate(Activity.java:5231)
06-18 07:39:16.764: I/dalvikvm(2359):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
06-18 07:39:16.764: I/dalvikvm(2359):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
06-18 07:39:16.764: I/dalvikvm(2359):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
06-18 07:39:16.764: I/dalvikvm(2359):   at android.app.ActivityThread.access$800(ActivityThread.java:135)
06-18 07:39:16.764: I/dalvikvm(2359):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
06-18 07:39:16.764: I/dalvikvm(2359):   at android.os.Handler.dispatchMessage(Handler.java:102)
06-18 07:39:16.764: I/dalvikvm(2359):   at android.os.Looper.loop(Looper.java:136)
06-18 07:39:16.764: I/dalvikvm(2359):   at android.app.ActivityThread.main(ActivityThread.java:5017)
06-18 07:39:16.764: I/dalvikvm(2359):   at java.lang.reflect.Method.invokeNative(Native Method)
06-18 07:39:16.764: I/dalvikvm(2359):   at java.lang.reflect.Method.invoke(Method.java:515)
06-18 07:39:16.764: I/dalvikvm(2359):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-18 07:39:16.764: I/dalvikvm(2359):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
06-18 07:39:16.764: I/dalvikvm(2359):   at dalvik.system.NativeStart.main(Native Method)
06-18 07:39:16.764: I/dalvikvm(2359): "main" prio=5 tid=1 NATIVE
06-18 07:39:16.764: I/dalvikvm(2359):   | group="main" sCount=0 dsCount=0 obj=0xb2ae0ca8 self=0xb88e1398
06-18 07:39:16.764: I/dalvikvm(2359):   | sysTid=2359 nice=0 sched=0/0 cgrp=apps handle=-1224953516
06-18 07:39:16.764: I/dalvikvm(2359):   | state=R schedstat=( 320000000 750000000 117 ) utm=20 stm=12 core=0
06-18 07:39:16.844: I/dalvikvm(2359):   #00  pc 0000132e  /system/lib/libcorkscrew.so (unwind_backtrace_thread+29)
06-18 07:39:16.844: I/dalvikvm(2359):   #01  pc 000603ea  /system/lib/libdvm.so (dvmDumpNativeStack(DebugOutputTarget const*, int)+33)
06-18 07:39:16.844: I/dalvikvm(2359):   #02  pc 000543e4  /system/lib/libdvm.so (dvmDumpThreadEx(DebugOutputTarget const*, Thread*, bool)+395)
06-18 07:39:16.844: I/dalvikvm(2359):   #03  pc 00054452  /system/lib/libdvm.so (dvmDumpThread(Thread*, bool)+25)
06-18 07:39:16.854: I/dalvikvm(2359):   #04  pc 0003871c  /system/lib/libdvm.so
06-18 07:39:16.854: I/dalvikvm(2359):   #05  pc 00041212  /system/lib/libdvm.so
06-18 07:39:16.854: I/dalvikvm(2359):   #06  pc 00001fd2  /system/lib/libnativehelper.so (jniRegisterNativeMethods+81)
06-18 07:39:16.854: I/dalvikvm(2359):   #07  pc 00005ba0  /data/app-lib/com.example.primerapruebadeandroid-2/libdatabase_sqlcipher.so (sqlcipher::register_android_database_SQLiteDatabase(_JNIEnv*)+59)
06-18 07:39:16.854: I/dalvikvm(2359):   #08  pc 00005c28  /data/app-lib/com.example.primerapruebadeandroid-2/libdatabase_sqlcipher.so (JNI_OnLoad+51)
06-18 07:39:16.854: I/dalvikvm(2359):   #09  pc 0004fde2  /system/lib/libdvm.so (dvmLoadNativeCode(char const*, Object*, char**)+465)
06-18 07:39:16.854: I/dalvikvm(2359):   #10  pc 0006746c  /system/lib/libdvm.so
06-18 07:39:16.854: I/dalvikvm(2359):   #11  pc 00026fe0  /system/lib/libdvm.so
06-18 07:39:16.854: I/dalvikvm(2359):   #12  pc 0002df34  /system/lib/libdvm.so (dvmMterpStd(Thread*)+76)
06-18 07:39:16.854: I/dalvikvm(2359):   #13  pc 0002b5cc  /system/lib/libdvm.so (dvmInterpret(Thread*, Method const*, JValue*)+184)
06-18 07:39:16.854: I/dalvikvm(2359):   #14  pc 000605fc  /system/lib/libdvm.so (dvmInvokeMethod(Object*, Method const*, ArrayObject*, ArrayObject*, ClassObject*, bool)+391)
06-18 07:39:16.854: I/dalvikvm(2359):   #15  pc 000684c6  /system/lib/libdvm.so
06-18 07:39:16.854: I/dalvikvm(2359):   #16  pc 00026fe0  /system/lib/libdvm.so
06-18 07:39:16.854: I/dalvikvm(2359):   #17  pc 0002df34  /system/lib/libdvm.so (dvmMterpStd(Thread*)+76)
06-18 07:39:16.854: I/dalvikvm(2359):   #18  pc 0002b5cc  /system/lib/libdvm.so (dvmInterpret(Thread*, Method const*, JValue*)+184)
06-18 07:39:16.854: I/dalvikvm(2359):   #19  pc 00060318  /system/lib/libdvm.so (dvmCallMethodV(Thread*, Method const*, Object*, bool, JValue*, std::__va_list)+335)
06-18 07:39:16.864: I/dalvikvm(2359):   #20  pc 00049b4e  /system/lib/libdvm.so
06-18 07:39:16.864: I/dalvikvm(2359):   #21  pc 0003cd02  /system/lib/libdvm.so
06-18 07:39:16.864: I/dalvikvm(2359):   #22  pc 0004cddc  /system/lib/libandroid_runtime.so
06-18 07:39:16.864: I/dalvikvm(2359):   #23  pc 0004dad6  /system/lib/libandroid_runtime.so (android::AndroidRuntime::start(char const*, char const*)+353)
06-18 07:39:16.864: I/dalvikvm(2359):   #24  pc 0000105a  /system/bin/app_process
06-18 07:39:16.864: I/dalvikvm(2359):   #25  pc 0000e238  /system/lib/libc.so (__libc_init+47)
06-18 07:39:16.864: I/dalvikvm(2359):   at java.lang.Runtime.nativeLoad(Native Method)
06-18 07:39:16.864: I/dalvikvm(2359):   at java.lang.Runtime.doLoad(Runtime.java:421)
06-18 07:39:16.864: I/dalvikvm(2359):   at java.lang.Runtime.loadLibrary(Runtime.java:362)
06-18 07:39:16.864: I/dalvikvm(2359):   at java.lang.System.loadLibrary(System.java:526)
06-18 07:39:16.864: I/dalvikvm(2359):   at net.sqlcipher.database.SQLiteDatabase.loadLibs(SQLiteDatabase.java:143)
06-18 07:39:16.864: I/dalvikvm(2359):   at net.sqlcipher.database.SQLiteDatabase.loadLibs(SQLiteDatabase.java:136)
06-18 07:39:16.864: I/dalvikvm(2359):   at com.example.primerapruebadeandroid.Persistence.DataHandler.<init>(DataHandler.java:80)
06-18 07:39:16.864: I/dalvikvm(2359):   at com.example.primerapruebadeandroid.Persistence.DataHandler.<init>(DataHandler.java:64)
06-18 07:39:16.864: I/dalvikvm(2359):   at com.example.primerapruebadeandroid.MainActivity.onCreate(MainActivity.java:37)
06-18 07:39:16.864: I/dalvikvm(2359):   at android.app.Activity.performCreate(Activity.java:5231)
06-18 07:39:16.864: I/dalvikvm(2359):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
06-18 07:39:16.864: I/dalvikvm(2359):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
06-18 07:39:16.864: I/dalvikvm(2359):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
06-18 07:39:16.864: I/dalvikvm(2359):   at android.app.ActivityThread.access$800(ActivityThread.java:135)
06-18 07:39:16.864: I/dalvikvm(2359):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
06-18 07:39:16.864: I/dalvikvm(2359):   at android.os.Handler.dispatchMessage(Handler.java:102)
06-18 07:39:16.864: I/dalvikvm(2359):   at android.os.Looper.loop(Looper.java:136)
06-18 07:39:16.864: I/dalvikvm(2359):   at android.app.ActivityThread.main(ActivityThread.java:5017)
06-18 07:39:16.864: I/dalvikvm(2359):   at java.lang.reflect.Method.invokeNative(Native Method)
06-18 07:39:16.864: I/dalvikvm(2359):   at java.lang.reflect.Method.invoke(Method.java:515)
06-18 07:39:16.864: I/dalvikvm(2359):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-18 07:39:16.864: I/dalvikvm(2359):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
06-18 07:39:16.864: I/dalvikvm(2359):   at dalvik.system.NativeStart.main(Native Method)
06-18 07:39:16.864: E/dalvikvm(2359): VM aborting
06-18 07:39:16.864: A/libc(2359): Fatal signal 6 (SIGABRT) at 0x00000937 (code=-6), thread 2359 (pruebadeandroid)
06-18 07:51:37.464: W/com.example.primerapruebadeandroid.MainActivity(2408): Starting the app
06-18 07:51:37.474: D/dalvikvm(2408): Trying to load lib /data/app-lib/com.example.primerapruebadeandroid-1/libstlport_shared.so 0xb2d945b0
06-18 07:51:37.474: W/linker(2408): libstlport_shared.so has text relocations. This is wasting memory and is a security risk. Please fix.
06-18 07:51:37.484: D/dalvikvm(2408): Added shared lib /data/app-lib/com.example.primerapruebadeandroid-1/libstlport_shared.so 0xb2d945b0
06-18 07:51:37.484: D/dalvikvm(2408): No JNI_OnLoad found in /data/app-lib/com.example.primerapruebadeandroid-1/libstlport_shared.so 0xb2d945b0, skipping init
06-18 07:51:37.484: D/dalvikvm(2408): Trying to load lib /data/app-lib/com.example.primerapruebadeandroid-1/libsqlcipher_android.so 0xb2d945b0
06-18 07:51:37.494: W/linker(2408): libsqlcipher_android.so has text relocations. This is wasting memory and is a security risk. Please fix.
06-18 07:51:37.504: D/dalvikvm(2408): Added shared lib /data/app-lib/com.example.primerapruebadeandroid-1/libsqlcipher_android.so 0xb2d945b0
06-18 07:51:37.504: D/dalvikvm(2408): No JNI_OnLoad found in /data/app-lib/com.example.primerapruebadeandroid-1/libsqlcipher_android.so 0xb2d945b0, skipping init
06-18 07:51:37.514: D/dalvikvm(2408): Trying to load lib /data/app-lib/com.example.primerapruebadeandroid-1/libdatabase_sqlcipher.so 0xb2d945b0
06-18 07:51:37.514: W/linker(2408): libdatabase_sqlcipher.so has text relocations. This is wasting memory and is a security risk. Please fix.
06-18 07:51:37.524: D/dalvikvm(2408): Added shared lib /data/app-lib/com.example.primerapruebadeandroid-1/libdatabase_sqlcipher.so 0xb2d945b0
06-18 07:51:37.524: I/Database(2408): JNI_OnLoad called
06-18 07:51:37.524: I/Database(2408): JNI_OnLoad register methods
06-18 07:51:37.534: E/dalvikvm(2408): ERROR: couldn't find native method
06-18 07:51:37.534: E/dalvikvm(2408): Requested: Lnet/sqlcipher/database/SQLiteDatabase;.native_key:([C)V
06-18 07:51:37.534: W/dalvikvm(2408): JNI WARNING: JNI function FatalError called with exception pending
06-18 07:51:37.534: W/dalvikvm(2408):              in Ljava/lang/Runtime;.nativeLoad:(Ljava/lang/String;Ljava/lang/ClassLoader;Ljava/lang/String;)Ljava/lang/String; (FatalError)
06-18 07:51:37.534: W/dalvikvm(2408): Pending exception is:
06-18 07:51:37.534: I/dalvikvm(2408): java.lang.NoSuchMethodError: no static or non-static method "Lnet/sqlcipher/database/SQLiteDatabase;.native_key([C)V"
06-18 07:51:37.534: I/dalvikvm(2408):   at java.lang.Runtime.nativeLoad(Native Method)
06-18 07:51:37.534: I/dalvikvm(2408):   at java.lang.Runtime.doLoad(Runtime.java:421)
06-18 07:51:37.534: I/dalvikvm(2408):   at java.lang.Runtime.loadLibrary(Runtime.java:362)
06-18 07:51:37.534: I/dalvikvm(2408):   at java.lang.System.loadLibrary(System.java:526)
06-18 07:51:37.534: I/dalvikvm(2408):   at net.sqlcipher.database.SQLiteDatabase.loadLibs(SQLiteDatabase.java:143)
06-18 07:51:37.534: I/dalvikvm(2408):   at net.sqlcipher.database.SQLiteDatabase.loadLibs(SQLiteDatabase.java:136)
06-18 07:51:37.534: I/dalvikvm(2408):   at com.example.primerapruebadeandroid.Persistence.DataHandler.<init>(DataHandler.java:82)
06-18 07:51:37.534: I/dalvikvm(2408):   at com.example.primerapruebadeandroid.Persistence.DataHandler.<init>(DataHandler.java:66)
06-18 07:51:37.534: I/dalvikvm(2408):   at com.example.primerapruebadeandroid.MainActivity.onCreate(MainActivity.java:37)
06-18 07:51:37.534: I/dalvikvm(2408):   at android.app.Activity.performCreate(Activity.java:5231)
06-18 07:51:37.534: I/dalvikvm(2408):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
06-18 07:51:37.534: I/dalvikvm(2408):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
06-18 07:51:37.544: I/dalvikvm(2408):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
06-18 07:51:37.544: I/dalvikvm(2408):   at android.app.ActivityThread.access$800(ActivityThread.java:135)
06-18 07:51:37.544: I/dalvikvm(2408):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
06-18 07:51:37.544: I/dalvikvm(2408):   at android.os.Handler.dispatchMessage(Handler.java:102)
06-18 07:51:37.544: I/dalvikvm(2408):   at android.os.Looper.loop(Looper.java:136)
06-18 07:51:37.544: I/dalvikvm(2408):   at android.app.ActivityThread.main(ActivityThread.java:5017)
06-18 07:51:37.544: I/dalvikvm(2408):   at java.lang.reflect.Method.invokeNative(Native Method)
06-18 07:51:37.544: I/dalvikvm(2408):   at java.lang.reflect.Method.invoke(Method.java:515)
06-18 07:51:37.544: I/dalvikvm(2408):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-18 07:51:37.544: I/dalvikvm(2408):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
06-18 07:51:37.544: I/dalvikvm(2408):   at dalvik.system.NativeStart.main(Native Method)
06-18 07:51:37.544: I/dalvikvm(2408): "main" prio=5 tid=1 NATIVE
06-18 07:51:37.544: I/dalvikvm(2408):   | group="main" sCount=0 dsCount=0 obj=0xb2ae0ca8 self=0xb88e1398
06-18 07:51:37.544: I/dalvikvm(2408):   | sysTid=2408 nice=0 sched=0/0 cgrp=apps handle=-1224953516
06-18 07:51:37.544: I/dalvikvm(2408):   | state=R schedstat=( 290000000 560000000 132 ) utm=21 stm=8 core=0
06-18 07:51:37.594: I/dalvikvm(2408):   #00  pc 0000132e  /system/lib/libcorkscrew.so (unwind_backtrace_thread+29)
06-18 07:51:37.594: I/dalvikvm(2408):   #01  pc 000603ea  /system/lib/libdvm.so (dvmDumpNativeStack(DebugOutputTarget const*, int)+33)
06-18 07:51:37.594: I/dalvikvm(2408):   #02  pc 000543e4  /system/lib/libdvm.so (dvmDumpThreadEx(DebugOutputTarget const*, Thread*, bool)+395)
06-18 07:51:37.594: I/dalvikvm(2408):   #03  pc 00054452  /system/lib/libdvm.so (dvmDumpThread(Thread*, bool)+25)
06-18 07:51:37.604: I/dalvikvm(2408):   #04  pc 0003871c  /system/lib/libdvm.so
06-18 07:51:37.604: I/dalvikvm(2408):   #05  pc 00041212  /system/lib/libdvm.so
06-18 07:51:37.604: I/dalvikvm(2408):   #06  pc 00001fd2  /system/lib/libnativehelper.so (jniRegisterNativeMethods+81)
06-18 07:51:37.604: I/dalvikvm(2408):   #07  pc 00005ba0  /data/app-lib/com.example.primerapruebadeandroid-1/libdatabase_sqlcipher.so (sqlcipher::register_android_database_SQLiteDatabase(_JNIEnv*)+59)
06-18 07:51:37.604: I/dalvikvm(2408):   #08  pc 00005c28  /data/app-lib/com.example.primerapruebadeandroid-1/libdatabase_sqlcipher.so (JNI_OnLoad+51)
06-18 07:51:37.604: I/dalvikvm(2408):   #09  pc 0004fde2  /system/lib/libdvm.so (dvmLoadNativeCode(char const*, Object*, char**)+465)
06-18 07:51:37.604: I/dalvikvm(2408):   #10  pc 0006746c  /system/lib/libdvm.so
06-18 07:51:37.604: I/dalvikvm(2408):   #11  pc 00026fe0  /system/lib/libdvm.so
06-18 07:51:37.604: I/dalvikvm(2408):   #12  pc 0002df34  /system/lib/libdvm.so (dvmMterpStd(Thread*)+76)
06-18 07:51:37.604: I/dalvikvm(2408):   #13  pc 0002b5cc  /system/lib/libdvm.so (dvmInterpret(Thread*, Method const*, JValue*)+184)
06-18 07:51:37.604: I/dalvikvm(2408):   #14  pc 000605fc  /system/lib/libdvm.so (dvmInvokeMethod(Object*, Method const*, ArrayObject*, ArrayObject*, ClassObject*, bool)+391)
06-18 07:51:37.604: I/dalvikvm(2408):   #15  pc 000684c6  /system/lib/libdvm.so
06-18 07:51:37.604: I/dalvikvm(2408):   #16  pc 00026fe0  /system/lib/libdvm.so
06-18 07:51:37.604: I/dalvikvm(2408):   #17  pc 0002df34  /system/lib/libdvm.so (dvmMterpStd(Thread*)+76)
06-18 07:51:37.604: I/dalvikvm(2408):   #18  pc 0002b5cc  /system/lib/libdvm.so (dvmInterpret(Thread*, Method const*, JValue*)+184)
06-18 07:51:37.604: I/dalvikvm(2408):   #19  pc 00060318  /system/lib/libdvm.so (dvmCallMethodV(Thread*, Method const*, Object*, bool, JValue*, std::__va_list)+335)
06-18 07:51:37.604: I/dalvikvm(2408):   #20  pc 00049b4e  /system/lib/libdvm.so
06-18 07:51:37.604: I/dalvikvm(2408):   #21  pc 0003cd02  /system/lib/libdvm.so
06-18 07:51:37.604: I/dalvikvm(2408):   #22  pc 0004cddc  /system/lib/libandroid_runtime.so
06-18 07:51:37.604: I/dalvikvm(2408):   #23  pc 0004dad6  /system/lib/libandroid_runtime.so (android::AndroidRuntime::start(char const*, char const*)+353)
06-18 07:51:37.604: I/dalvikvm(2408):   #24  pc 0000105a  /system/bin/app_process
06-18 07:51:37.614: I/dalvikvm(2408):   #25  pc 0000e238  /system/lib/libc.so (__libc_init+47)
06-18 07:51:37.614: I/dalvikvm(2408):   at java.lang.Runtime.nativeLoad(Native Method)
06-18 07:51:37.614: I/dalvikvm(2408):   at java.lang.Runtime.doLoad(Runtime.java:421)
06-18 07:51:37.614: I/dalvikvm(2408):   at java.lang.Runtime.loadLibrary(Runtime.java:362)
06-18 07:51:37.614: I/dalvikvm(2408):   at java.lang.System.loadLibrary(System.java:526)
06-18 07:51:37.614: I/dalvikvm(2408):   at net.sqlcipher.database.SQLiteDatabase.loadLibs(SQLiteDatabase.java:143)
06-18 07:51:37.614: I/dalvikvm(2408):   at net.sqlcipher.database.SQLiteDatabase.loadLibs(SQLiteDatabase.java:136)
06-18 07:51:37.614: I/dalvikvm(2408):   at com.example.primerapruebadeandroid.Persistence.DataHandler.<init>(DataHandler.java:82)
06-18 07:51:37.614: I/dalvikvm(2408):   at com.example.primerapruebadeandroid.Persistence.DataHandler.<init>(DataHandler.java:66)
06-18 07:51:37.614: I/dalvikvm(2408):   at com.example.primerapruebadeandroid.MainActivity.onCreate(MainActivity.java:37)
06-18 07:51:37.614: I/dalvikvm(2408):   at android.app.Activity.performCreate(Activity.java:5231)
06-18 07:51:37.614: I/dalvikvm(2408):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
06-18 07:51:37.614: I/dalvikvm(2408):   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
06-18 07:51:37.614: I/dalvikvm(2408):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
06-18 07:51:37.614: I/dalvikvm(2408):   at android.app.ActivityThread.access$800(ActivityThread.java:135)
06-18 07:51:37.614: I/dalvikvm(2408):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
06-18 07:51:37.614: I/dalvikvm(2408):   at android.os.Handler.dispatchMessage(Handler.java:102)
06-18 07:51:37.614: I/dalvikvm(2408):   at android.os.Looper.loop(Looper.java:136)
06-18 07:51:37.614: I/dalvikvm(2408):   at android.app.ActivityThread.main(ActivityThread.java:5017)
06-18 07:51:37.614: I/dalvikvm(2408):   at java.lang.reflect.Method.invokeNative(Native Method)
06-18 07:51:37.624: I/dalvikvm(2408):   at java.lang.reflect.Method.invoke(Method.java:515)
06-18 07:51:37.624: I/dalvikvm(2408):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-18 07:51:37.624: I/dalvikvm(2408):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
06-18 07:51:37.624: I/dalvikvm(2408):   at dalvik.system.NativeStart.main(Native Method)
06-18 07:51:37.624: E/dalvikvm(2408): VM aborting
06-18 07:51:37.624: A/libc(2408): Fatal signal 6 (SIGABRT) at 0x00000968 (code=-6), thread 2408 (pruebadeandroid)

I have tried to execute this test using the SQLCipher versions 3.1 (last available binaries for android), 2.2.2 and 2.1.1, and get always the same result. I cannot test it on a real device because the lack of it.
I have followed the instruction to include the library in my project: copy the content of the libs and assets folder and include the libraries in the build path:

If I open the adb terminal and I move to the application folder, I can see the lib folder with libdatabase_sqlcipher.so, libsqlcipher_android.so and libstlport_shared.so
By the way, I'm using the ADT v22.6.2-1085508 for mac.
Any idea about what could be happening?

A: I encountered an issue similar to this on Android Studio. Turns out I was missing the "jnilibs" folder in my "main" directory.

Once added, do a build clean and try run the project again.


text:
Q: Tablesort sort and search stops working when leave and page and return Tablesort sort and search functionality works fine when the page is first loaded but if you visit another page on the site and return to the page with tablesorter then the sort ad search functionality is completely gone.
Here is a link to the page im talking about
Click on the 'one piece' link on the page and then the back link and you'll see the sort and search functionality disappear
Would appreciate some help on how to fix this problem because i cant seem to figure out why it does it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Put a div on top of a googlemap? Is there a plugin to do this or method to do this?
See, I have this site and if you scroll to the bottom, you'll see a map. What I want to do is to place a small box on top of the map, just like an overlay that will contain contact information.
Edit: Box will be on top of the watery part. :)

A: You can try this:

test

Add a div after your section div as my above code...and position set as you want from top and left..(eg: Add this - top:"you need"; left:"you need";)
Good luck

A: Something like this (without using inline styles obviously):

Here's a link in your overlay


text:
Q: Не работает фильтр для состояний в aiogram В aiogram квиз-боте я пытаюсь создать кастомный фильтр, который возвращает True, если пользователь находится в одном из нескольких состояний. Ответы от пользователя я получаю с помощью inline клавиатуры и результаты каждого вопроса записываю в FSM (так ведь можно делать?). Вот код хендлеров, в которых начинаются проблемы:
@dp.callback_query_handler(text="choice")
async def choice_continent(callback: types.CallbackQuery):
    await callback.message.edit_text("Выберите континент, по столицам странам которого "
                                     "будет проводиться тест ")
    await callback.message.edit_reply_markup(reply_markup=choice_menu)

    await Test.first()

@dp.callback_query_handler(text_contains="choice_continent", state=Test.start)
async def start_test(callback: types.CallbackQuery, state: FSMContext):
    continent = callback.data.split(":")[-1]
    countries = data[continent]

    await callback.message.edit_text(f"Выбран континент: {continent} ⛰")
    await callback.message.edit_reply_markup(reply_markup=start_menu)

    await state.update_data(continent=continent, countries=countries)

    await Test.next()

@dp.callback_query_handler(text="back", state=Test.Q1)
async def back_to_menu(callback: types.CallbackQuery, state: FSMContext):
    await choice_continent(callback)

@dp.callback_query_handler(IsInStatesGroup(), text="start_question")
async def start_question(callback: types.CallbackQuery, state: FSMContext):
    data_test = await state.get_data()
    countries = data_test["countries"]

    country = str(random.choice(list(countries.keys())))

    await callback.message.edit_text(f"Выберите столицу страны: {country}.")
    await callback.message.edit_reply_markup(reply_markup=await create_question_menu(country, countries))

    await state.update_data(country=country, countries=countries)
    await Test.next()

Мне нужно из choice_continent переходить в start_test, при нажатии на кнопку отмены переходить в back_to_menu, а из start_test в start_question. Вот код inline-клавиатур:
choice_callback_data = CallbackData("choice_continent", "continent")
question_callback_data = CallbackData("question", "type", "capital")

continents = list(data.keys())

main_menu = InlineKeyboardMarkup()
main_menu.insert(InlineKeyboardButton(text="Выбрать континент ", callback_data="choice"))

choice_menu = InlineKeyboardMarkup()

for name in continents:
    choice_menu.insert(InlineKeyboardButton(text=name, callback_data=choice_callback_data.new(
        continent=name
    )))

start_menu = InlineKeyboardMarkup()
start_menu.insert(InlineKeyboardButton(text="Начать тест ✏", callback_data="start_question"))
start_menu.insert(InlineKeyboardButton(text="Назад ⬅", callback_data="back"))

next_menu = InlineKeyboardMarkup()
next_menu.insert(InlineKeyboardButton(text="Дальше ➡", callback_data="next_question"))

Вот класс с группой состояний:
class Test(StatesGroup):
    start = State()
    Q1 = State()
    Q2 = State()
    Q3 = State()
    Q4 = State()
    Q5 = State()
    Q6 = State()
    Q7 = State()
    Q8 = State()
    Q9 = State()
    Q10 = State()

Вот класс кастомного фильтр:
class IsInStatesGroup(BoundFilter):

    async def check(self, callback: types.CallbackQuery, state: FSMContext):
        state_name = await state.get_state()

        return state_name in Test.all_states_names[1:]

Так я его подключаю:
if __name__ == "filters":
    dp.filters_factory.bind(IsInStatesGroup)

Если что, я в loader файл при создании диспатчера передал объект MemoryStorage, а при импорте в app файле придерживался правильного порядка: filters, middlewares, handlers. Когда я просто в хендлере делаю фильтр state=Test.Q1 - всё работает. Что делать?

A: Смотри. Я не сильно уверен, но сделал то что точно работает.
class FSM_TEST(StatesGroup):
    Q1 = State()
    Q2 = State()

class Filter_(BoundFilter):
    async def check(self, message: types.Message):
        state = dp.current_state(chat=message.chat.id, user=message.from_user.id)
        cur_state = await state.get_state()
        return cur_state in FSM_TEST.all_states_names

@dp.message_handler()
async def start(message: types.Message):
    await message.answer("Приве1т.")
    await FSM_TEST.Q1.set()

@dp.message_handler(Filter_(), state="*")
async def start(message: types.Message):
    await message.answer("Приве2т.")

if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)
    dp.filters_factory.bind(Filter_)

Я не смог получить обьект state в фильтре, пришлось получать его через экземпляр диспатчера. Ты только поменяй с месседжа на колбек. Я думаю что он у тебя не забиндился, где бы он у тебя это не делал.
К слову, я не совсем понимаю зачем ради такой мелочи делать целый кастомный фильтр.


text:
Q: Is there is a way to rename a visual studio project in one step ? (Automate renaming) I have been searching for a way to rename a visual studio project (vb.net) in one easy step, all i found were a tutorials that make me rename all files in the projects.

A: I suspect that the question you want answered is actually different to the question you asked. The answer to the question you actually asked is that you right-click the project in the Solution Explorer, select Rename and then enter the new name. That's it, that's all. Project renamed.
If that doesn't answer the question you actually want answered, I suggest that you actually ask that question instead.


text:
Q: Equivalences of $n$-categories This question is an extension of my previous question last year (see [2020]) in which I asked about the (consensus of a) definition of a weak $n$-category.
Here are some background: while strict $n$-categories are easily defined, they are not sufficient for $n>2$. Therefore weak $n$-categories need to be defined. What a definition of a weak $n$-category should satisfy was proposed in [BD1995]. However, many proposals have since been given (see [Lei2001] or [2020]). And as David White pointed out in [2020], we had not reached to a consensus yet.
This question focuses on a smaller part of the problem.
Question: In order to prove that different models of $n$-categories to be equivalent, there must be a well-defined notion of a $(n+1)$-category to start with. So how is it possible to really prove the equivalence?
I guess this relates to a philosophical problem that in order to justify (anything) one needs to justify the setting in which we justify. Before entering the realm of formalized arguments, we can postulate some desired results (as in [BD1995], or called "specification" in compsci's term), but nothing can stop people from building different settings (or called "implementation" in compsci's term). How could such problem be resolute without brute-force translating results from different foundations?

*

*[2020]: Definition of a $n$-category

*[BD1995]: Higher-dimensional Algebra and Topological Quantum Field Theory-[John C. Baez and James Dolan]-[arXiv:q-alg--9503002]

*[Lei2001]: A Survey of Definitions of n-Category-[Tom Leinster]-[Theory and Applications of Categories, Vol. 10, 2002, No. 1, pp 1-70]

A: That is indeed a problem, and one could argue that this is part of the reason why these questions are difficult. But I feel that in practice that has never been a strong obstruction. I guess, one way to explain how this apparent paradox disappear is simply to say that nothing forces you to look at $n$-categories as forming an $(n+1)$-categories, especially if you don't know yet what an $(n+1)$-category even is : your $n$-categories (for a concrete definition) are generally organized in a stricter kind of structure and you can show equivalence at some stricter level than as weak $n+1$-categories.
To start with a way too nice example of this, Batanin's definition of $\infty$-category using globular operads and Grothendieck-Maltsiniotis' definition of $\infty$-category using coherator have been shown to be equivalent by Dimitri Ara in his PhD thesis by simply showing they were equivalent as ordinary $1$-category. ( to be precise, part of his results were conditional on a certain faithfulness conjecture that has been proved recently by John Bourke)
Of course, this kind of equivalence is fairly rare and you can't proceed this way very often.
In general, the idea is that one has always been able to prove something so that "for any reasonable definition of $n+1$-category that would produce the equivalence" :
I guess the most typical situation is as follows: each model of $n$-categories we have is organised as an ordinary categories $C$ (whose objects are $n$-categories and morphisms generally corresponds to a notion of strict functors) and a notion of "weak equivalence" of $n$-categories. Generally $C$ is even a Quillen model structure (or rather the full subcategory of fibrant object of such a model category) but that is not really relevant at the level of generality we are talking about. Moreover in each case we know about, the correct notion of "pseudo-functor" can be recovered as a span or cospan of a strict functor and an equivalence'
An equivalence between two such model is then generally presented as a pair of ordinary functors $F:C \to C'$ and $H:C' \to C$ sending weak equivalence to weak equivalence together with zig-zags of natural equivalences connecting $FH$ to $Id_{C'}$ and $HF$ to $Id_C$.
Where by natural equivalence I just mean natural transformation that are objectwise weak equivalence.
Very often all this is done by building Quillen equivalences between Quillen model categories.
Note that what I've described above will only prove that the underlying $(n+1,1)$ categories of $n$-categories are equivalent (i.e. it doesn't take care of comparing higher non-invertible natural transformation). For this you would need in addition that $F$ and $H$ are somehow compatible to certain additional structure on $C$ and $C'$ that encode these. For example certain monoidal closed structure, or other structure that produces the $n$-category of pseudo-functor between two $n$-categories.
But I guess what makes all these comparison results hard to prove is exactly that we have to do this : find some concrete stricter algebraic structure we can talk about and compare and work with constructions that exists at this stricter level...

A: As Marc Hoyois indicates in the comments, historically this was a major obstruction, past tense "was". My feeling is that these days, there is a nice perspective that whatever weak $n$-categories are, they are the objects of some $(\infty,1)$-category $n\mathrm{Cat}$. (Of course, weak $n$-categories are the objects of more than an $(\infty,1)$-category. But the extra $n$ dimensions in $n\mathrm{Cat}$ should be recoverable from looking at exponential objects.) It was a substantial feat to develop a theory of $(\infty,1)$-categories, but it has been more or less done.
Moreover, surely $n\mathrm{Cat}$ will be not just some weird $(\infty,1)$-category, but in fact a presentable $(\infty,1)$-category, and these can be "presented" by model categories. So the question is "just" one of finding the correct Quillen equivalence class of model categories, where "correct" means that it should match your intuition about weak $n$-categories.
Note that I am not saying that there is complete consensus about which presentable $(\infty,1)$-category deserves the name $n\mathrm{Cat}$. I certainly have opinions on the matter (namely: set $0\mathrm{Cat}:= \mathrm{Set}$, and define inductively $n\mathrm{Cat}$ to be the $(\infty,1)$-category of $(\infty,1)$-categories enriched in $(n{-}1)\mathrm{Cat}$), but I don't have the sociological data to conclude that my opinions are shared by the majority, let alone that there exists a consensus.
I should also emphasize that, although I do believe there to be a single correct answer to the question of which presentable $(\infty,1)$-category should be called "$n\mathrm{Cat}$", this answer doesn't satisfy, or at least doesn't obviously satisfy, all natural desiderata. Most notably, it is not very algebraic. I mean, it isn't very non-algebraic — it is about as algebraic as is the notion of "Kan simplicial set" — but it isn't very algebraic either. However, I counter that the search for a highly algebraic theory of $n$-categories is most likely a fool's errand. Any such theory will in particular include a highly algebraic description of homotopy $n$-types. Postnikov and Whitehead provide a "lowly algebraic" description of homotopy $n$-types, and I am pessimistic about there being anything better.


text:
Q: How can a mace penetrate armor better than a sword? So, I'm trying to comprehend, just why are weapons like maces are so good at killing opponents through armors (full-plate), that sword edges can't even hope to dent. When I skimmed through google, I couldn't find any physics-based answer, so I ask it here.

A: The center of weight for maces is pretty much exactly in line with the area of impact. If you strike something with a sword, you are likely to not hit with the center of mass, which means that you will lose kinetic energy that could go to the area of impact, to torque (i.e. the sword "rolls off").
Even if you do manage to hit with the center of gravity, it's a matter of force/Area: A mace will unload its kinetic energy into a very concentrated spot, whereas a sword will unload it over the entire area of the edge.
Also, armor is designed so that swords are deflected; maces will care less about the slope at which they hit their target.
And the last reason I can think of, is that maces of the same weight have a larger inertial torque; so it takes longer to swing a mace, but you will accumulate a higher kinetic energy during the swing.

A: The mace has a greater mass, and hence greater momentum. This means when it collides with the armour/person  there is a greater change in momentum. As $F=\frac{\Delta p}{t}$, this means the force acting on the person will be greater, resulting in more damage.
Swords use the concept of the force being concentrated on a small area to pierce, but this doesn't work on armour.


text:
Q: How to compute `ulp`when `Math.ulp` is missing? I need the ulp for a given double value, but since I am developing for Codename ONE, ulp(double) is not provided. Does anyone know an efficient algorithm to compute ulp in Java? Codename ONE provides just some of the methods in the Math class (javadoc for the CN1 version) and some of the gaps are filled in MathUtil.
As a workaround, I use this (incorrect) code until I find a working replacement:
private double ulp(double y) {
    return y/1e15;
}

EDIT: I "rolled my own" and have just posted my code for review. Just in case someone else needs this.

A: Ok, since I didn't find a working replacement (both Apache Harmony and OpenJDK end up using native methods that are not available on CN1), I wrote my own version (results tested against OpenJDK-version). Just in case anyone needs it.
As for codename One: I submitted a patch to the MathUtil class, so hopefully this will be added sooner or later.
/*
 * use a precalculated value for the ulp of Double.MAX_VALUE
 */
private static final double MAX_ULP = 1.9958403095347198E292;

/**
 * Returns the size of an ulp (units in the last place) of the argument.
 * @param d value whose ulp is to be returned
 * @return size of an ulp for the argument
 */
@Override
public double ulp(double d) {
    if (Double.isNaN(d)) {
        // If the argument is NaN, then the result is NaN.
        return Double.NaN;
    }

    if (Double.isInfinite(d)) {
        // If the argument is positive or negative infinity, then the
        // result is positive infinity.
        return Double.POSITIVE_INFINITY;
    }

    if (d == 0.0) {
        // If the argument is positive or negative zero, then the result is Double.MIN_VALUE.
        return Double.MIN_VALUE;
    }

    d = Math.abs(d);
    if (d == Double.MAX_VALUE) {
        // If the argument is Double.MAX_VALUE, then the result is equal to 2^971.
        return MAX_ULP;
    }

    return nextAfter(d, Double.MAX_VALUE) - d;
}

@Override
public double copySign(double x, double y) {
    return com.codename1.util.MathUtil.copysign(x,y);
}

private boolean isSameSign(double x, double y) {
    return copySign(x, y) == x;
}

/**
 * Returns the next representable floating point number after the first
 * argument in the direction of the second argument.
 *
 * @param start starting value
 * @param direction value indicating which of the neighboring representable
 *  floating point number to return
 * @return The floating-point number next to {@code start} in the
 * direction of {@direction}.
 */
@Override
public double nextAfter(final double start, final double direction) {
    if (Double.isNaN(start) || Double.isNaN(direction)) {
        // If either argument is a NaN, then NaN is returned.
        return Double.NaN;
    }

    if (start == direction) {
        // If both arguments compare as equal the second argument is returned.
        return direction;
    }

    final double absStart = Math.abs(start);
    final double absDir = Math.abs(direction);
    final boolean toZero = !isSameSign(start, direction) || absDir < absStart;

    if (toZero) {
        // we are reducing the magnitude, going toward zero.
        if (absStart == Double.MIN_VALUE) {
            return copySign(0.0, start);
        }
        if (Double.isInfinite(absStart)) {
            return copySign(Double.MAX_VALUE, start);
        }
        return copySign(Double.longBitsToDouble(Double.doubleToLongBits(absStart) - 1L), start);
    } else {
        // we are increasing the magnitude, toward +-Infinity
        if (start == 0.0) {
            return copySign(Double.MIN_VALUE, direction);
        }
        if (absStart == Double.MAX_VALUE) {
            return copySign(Double.POSITIVE_INFINITY, start);
        }
        return copySign(Double.longBitsToDouble(Double.doubleToLongBits(absStart) + 1L), start);
    }
}

A: I'm not sure why your implementation of ULP takes signs and other criteria into account, when ULP returns the absolute value of the difference between the given value and the next floating point number in magnitude.
Here's an example of all you need to do; it's written in C#, but it's close enough to Java to understand.
public static double ULP(double value)
{
    // This is actually a constant in the same static class as this method, but
    // we put it here for brevity of this example.
    const double MaxULP = 1.9958403095347198116563727130368E+292;

    if (Double.IsNaN(value))
    {
        return Double.NaN;
    }
    else if (Double.IsPositiveInfinity(value) || Double.IsNegativeInfinity(value))
    {
        return Double.PositiveInfinity;
    }
    else if (value == 0.0)
    {
        return Double.Epsilon;    // Equivalent of Double.MIN_VALUE in Java; Double.MinValue in C# is the actual minimum value a double can hold.
    }
    else if (Math.Abs(value) == Double.MaxValue)
    {
        return MaxULP;
    }

    // All you need to understand about DoubleInfo is that it's a helper struct
    // that provides more functionality than is used here, but in this situation,
    // we only use the `Bits` property, which is just the double converted into a
    // long.
    DoubleInfo info = new DoubleInfo(value);

    // This is safe because we already checked for value == Double.MaxValue.
    return Math.Abs(BitConverter.Int64BitsToDouble(info.Bits + 1) - value);
}


text:
Q: Appending an element to the end of a list in Scala I can't add an element of type T into a list List[T].
I tried with myList ::= myElement but it seems it creates a strange object and accessing to myList.last always returns the first element that was put inside the list. How can I solve this problem?

A: That's because you shouldn't do it (at least with an immutable list).
If you really really need to append an element to the end of a data structure and this data structure really really needs to be a list and this list really really has to be immutable then do eiher this:
(4 :: List(1,2,3).reverse).reverse

or that:
List(1,2,3) ::: List(4)

A: This is similar to one of the answers but in different way :
scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> val y = x ::: 4 :: Nil
y: List[Int] = List(1, 2, 3, 4)

A: List(1,2,3) :+ 4

Results in List[Int] = List(1, 2, 3, 4)

Note that this operation has a complexity of O(n). If you need this operation frequently, or for long lists, consider using another data type (e.g. a ListBuffer).

A: Lists in Scala are not designed to be modified. In fact, you can't add elements to a Scala List; it's an immutable data structure, like a Java String.
What you actually do when you "add an element to a list" in Scala is to create a new List from an existing List. (Source)
Instead of using lists for such use cases, I suggest to either use an ArrayBuffer or a ListBuffer. Those datastructures are designed to have new elements added.
Finally, after all your operations are done, the buffer then can be converted into a list. See the following REPL example:
scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer

scala> var fruits = new ListBuffer[String]()
fruits: scala.collection.mutable.ListBuffer[String] = ListBuffer()

scala> fruits += "Apple"
res0: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple)

scala> fruits += "Banana"
res1: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana)

scala> fruits += "Orange"
res2: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana, Orange)

scala> val fruitsList = fruits.toList
fruitsList: List[String] = List(Apple, Banana, Orange)

A: We can append or prepend two lists or list&array
Append:
var l = List(1,2,3)
l = l :+ 4
Result : 1 2 3 4
var ar = Array(4, 5, 6)
for(x <- ar)
{ l = l :+ x }
  l.foreach(println)

Result:1 2 3 4 5 6

Prepending:
var l = List[Int]()
   for(x <- ar)
    { l= x :: l } //prepending
     l.foreach(println)

Result:6 5 4 1 2 3

A: List is immutable in Scala
You can use MutableList
var l = scala.collection.mutable.MutableList(1,2,3)
l += 4


text:
Q: Variable reference from external script in jsdom Below is the minimal example of jsdom code which uses the script parameter. Despite of all the attempts trying to find out a way to refer to the external JSs, I keep getting this

ReferenceError: exVar is not defined

Does anyone know what is the problem here and how to fix it?
stackOverTest.js
var jsdom = require("jsdom");

jsdom.env({
    "html": "",
    scripts: [__dirname + "exScript.js"],
    done: function(er, win) {
    console.log("exVar: ", exVar);
    }
});

exScript.js
var exVar = "test";

A: You need use win scope: console.log("exVar: ", win.exVar); and __dirname + "/exScript.js"


text:
Q: Netlogo Cyle using turtle_index I am using a turtle_index code to create a cycle in Netlogo. The cycle works but it is only using one turtle at a time. Each turtle completes the cycle before the next turtle starts the cycle. I would like all turtles to involved in the cycle at the same time. Is there a faster way to make this happen than using:
to go
  ask turtle 1 [cycle-forward]
  wait 0.5
  ask turtle 2 [cycle-forward]
  wait 0.5
  ask turtle 3[cycle-forward]
end

A: Okay from your comment I think I understand. One way to tackle this is to have turtles-own variables such that turtles know what step they have done and whether they have acted on the current tick. That way, they won't do a step out of turn. You can then break your cycle down into steps and use logical operators so that turtles don't take a step if they do not fulfill some criteria that you set. For example:
turtles-own [
  step1?
  step2?
  step3?
  acted?
]
to setup

  ca
  reset-ticks
  crt 10 [
    set step1? false
    set step2? false
    set step3? false
    set acted? false
  ]

end

to go
  ask turtles [
    set acted? false
  ]
  cycle
  tick

end

to cycle
  let step1t one-of turtles with [ step1? = false ]
  if step1t != nobody [
    ask step1t [
      set step1? true
      set acted? true
      ;;; example step 1
      set color red
      set heading 45
      fd 3
    ]
  ]

  let step2t one-of turtles with [step1? = true and step2? = false and acted? = false]
  if step2t != nobody [
    ask step2t [
      set step2? true
      set acted? true
      ;;; example step 2
      set size 1.5
      set heading 90
      fd 3
    ]
  ]

  let step3t one-of turtles with [step2? = true and step3? = false and acted? = false]
  if step3t != nobody [
    ask step3t [
      set step3? true
      set acted? true
      ;;; example step 3
      set color color + 2
      set heading 135
      fd 3
    ]
  ]
end


text:
Q: How to display a number close to zero in c#? I have a problem. I have a double number like 0.00000001. Then I should convert it into String and put it in textbox (Convert.ToString(0.00000001)). But that number displayed like 1E-08. Math.Round is not working here. I should display that number like 0.00000 (at least), not just 0.

A: You can use The numeric ("N") format specifier for that;
(0.00000001).ToString("N5").Dump(); // 0,00000
(0.00000001).ToString("N6").Dump(); // 0,000000
(0.00000001).ToString("N8").Dump(); // 0,00000001

Since my CurrentCulture's NumberDecimalSeparator is ,, it represents it as 0,0 not 0.0. If it is the same for you, you can use InvariantCulture as a second parameter in your .ToString() method.


text:
Q: Spacing Problem In txt file Created Using C Language I'm a beginner for programming still a student. I tried to create a .txt file in C to write data, save it and after to read what I have written. And I did, it running smoothly in integer format, but when I tried to use characters (sentences), when I use spaces in my input eg:- Hi, My Name is Dilan.... It's only print Hi
I tried to using different variables in both input and output codes but still getting same result.
This Is Data Writing Code
#include <stdio.h>
#include <stdlib.h>
int main()
{
      char txt[400];
      FILE *fptr;
      fptr = fopen("D:\\program.txt","w");
      if(fptr == NULL)
      {
      printf("Error!");
      exit(1);
      }
     printf(" Start Typing : ");
     scanf("%s",&txt);
     fprintf(fptr,"%s",&txt);
     fclose(fptr);
     return 0;
}

This Is Data Reading Code
#include <stdio.h>
#include <stdlib.h>
int main()
{
   char txt[400];
   FILE *fptr;
   if ((fptr = fopen("D:\\program.txt","r")) == NULL){
       printf("Error! opening file");
       exit(1);
   }
   fscanf(fptr,"%s", &txt);
   printf("You Have Entered :- %s", txt);`enter code here`
   fclose(fptr);

   return 0;
}

I need when I type "Hi, My Name is Dilan ...." instead of just "Hi" I need full sentence like "Hi, My Name is Dilan ...."

A: Try to use fgets(txt, 400, stdin)
instead of scanf("%s", &txt)

A: What are you tiping in console or something else input stream is saved in a buffer("string") in operation system, your C program acces this buffer, so when you call scanf it read from that buffer, your problem is because you use %s data specificator, which read a string while the character readed is different of blank space(space, newline or tab), up to blank spaces.
After "Hi," is a space so the read will stop. You can use a different functions, one for string pourpouses, like fgets which read up to a newline character ('/n') or up to end of stream, or something else, you can search the best choice for your problem on internet.
One other solution is to use scanf repetitive to read all string, but you have to put the spaces between words in your output file.
Very important what you should have in mind all time, the functions which read from stdin stream use this buffer of OS,  after one read(one execution of function) when you call again the function it will continue where it stoped in last execution, same for other streams (a file is a stream too).
In your example after you typed "Hi, my name is Xtx." In OS's buffer will be store all string. The first call o scanf will get only "Hi," the second call will get "my" and same the following calls.
The problem is when you type something else in stream, like a new sentence, it will be store in buffer at end of it. So maybe your calls are still read from old string while remained unread characters in buffer from last sentence.
This problem is solved with fflush(), which clean this buffer.


text:
Q: Add a rug representation to plot This question came to me when I read How convert list of numbers to list of points on x-axis?
@Mr.W suggested Interlacing a single number into a long list for the question. @Artes provides a very fast way to generate the coordinates for plotting. All these remind me a widely used graph in R, which is called rug representation. I find Mathematica seems do not provide an equivalent command.
Following are three rug plots generated in R. The basic idea of rug is that project the data points onto an axes and represent it as thin lines beside the axes. Usually, the points will be jittered a bit off the position to avoid tiles. Using function like Line or ListLinePlot can somehow implement this function, but I do not know what is the fastest way to implement this function. Is Line with @Artes's solution the best choice?

More info about rug representation
Sorry for replying messages so late! Here is more information about rug representation.
rug representation is not a density plot, it projects each point to the axes with a thin line. Thus, there is not bandwidth in rug representation. For dataset with tiles, the lines will be overlapped. There are two methods to get rid of this problem. One is using opacity to show how many lines are overlap; the other is jitter the coordinate a bit off the original position, then all lines are visible. The second option are used more widely. The jitter of coordinate can be set to RandomReal[{Min[x], Max[x]},Length@x]/50.
For the sample data, two well-known datasets from R: mtcars and iris can be used. The sample figure are plot of wt vs mpg in mtcars.
The start codes for the figure can be
mtcars = Import["mtcars.csv"];
x = Drop[mtcars[[All, 7]], 1];
y = Drop[mtcars[[All, 2]], 1];
ListPlot[Thread[List[x, y]]]

A: "DistributionAxes" -> "Lines"
You can use DensityHistogram with suboption "DistributionAxes" -> "Lines" and ListPlot of the data as Epilog:
SeedRandom[1]
dt = RandomReal[1, {50, 2}];

DensityHistogram[dt, Method -> {"DistributionAxes" -> "Lines"},
 BaseStyle -> FaceForm[],
 Epilog -> ListPlot[dt, PlotStyle -> {Red, PointSize[Large]}][[1]]]

Alternatively, with sufficiently many equal-sized bins or sufficiently small bin widths, we can use ChartElementFunction -> "Point" in DensityHistogram to get a ListPlot of data without using Epilog:
DensityHistogram[dt, {100, 100},
 Method -> {"DistributionAxes" -> "Lines"}, ColorFunction -> (Red &),
 ChartBaseStyle -> PointSize[Large], ChartElementFunction -> "Point"]

Another example:
dist1 = BinormalDistribution[{1, 1}, {1, 1}, 1/2];
dist2 = BinormalDistribution[{5, 5}, {1, 1}, -1/2]; dt2 =
 RandomVariate[MixtureDistribution[{3, 2}, {dist1, dist2}], 300];
DensityHistogram[dt2, Method -> {"DistributionAxes" -> "Lines"},
 BaseStyle -> FaceForm[],
 Epilog -> ListPlot[dt2, PlotStyle -> {Red, PointSize[Large]}][[1]]]

UnivariateDataRug
Statistics`DataDistributionUtilities`UnivariateDataRug[dt[[All, 1]]]

With some processing (to remove arrows and to change orientation), the output of Statistics`DataDistributionUtilities`UnivariateDataRug can be used to construct data rugs for the vertical and horizontal axes.
ClearAll[rugF]
rugF[dir : ("horizontal" | "vertical") : "horizontal"] :=
  Module[{rule = If[dir === "horizontal",
       Thread[{{x_, 0}, {x_, 1}} :> {{x, -.025}, {x, -.075}}],
       Thread[{{x_, 0}, {x_, 1}} :> {{-.025, x}, {-.075, x}}]]},
    Statistics`DataDistributionUtilities`UnivariateDataRug[#] /.
      Arrow[x_] :> {CapForm["Butt"], Line[x]} /. rule ] &;

Show[ListPlot[dt, PlotStyle -> PointSize[Large]],
 rugF["vertical"][dt[[All, 2]]], rugF[][dt[[All, 1]]],
 AspectRatio -> 1, Frame -> True, AxesOrigin -> {0, 0},
 PlotRangePadding -> {{.1, Scaled[.02]}, {.1, Scaled[.02]}}]

A: Here is a possible implementation of rug representation using ListPlot. Maybe implementation from @MarcoB is more efficient.
jitter function
Here is a implementation of jitter function:
jitter[x_] := Module[{r, z, xx, d}, r = {Min[x], Max[x]};
  z = First@Differences[r];
  z = If[z == 0, Abs[r], z];
  z = If[z == 0, 1, z];
  xx = DeleteDuplicates@Sort@Round[x, 10^(-3 + Floor@Log10[z])];
  d = Differences[xx];
  d = If[Length@d > 0, Min@d, If[xx != 0, xx/10, z/10]];
  x + RandomReal[{-Abs[d]/5, Abs[d]/5}, Length@x]
  ]

Based on this, rug plot can be implemented as
ListPlot[{Thread@{x, y}, Tuples@{jitter@x, {1.5}}},
 PlotMarkers -> {{}, {"|", 6}}, PlotStyle -> Black]

Density plot vs. rug
@Jens thinks density plot is more informative. I agree with the idea that density plot are easy to read, but rug provides more details of the data than density estimation. Most of the time, this is a bad thing, because we do not want to represent to much information in one graph. However, I think there are cases, rug is more suitable. Following is density estimation and is rug representation of wt in mtcars dataset. I think it is not so bad to have a rug representation near the axes.
Show[{SmoothHistogram[x],
  ListPlot[Tuples@{jitter@x, {0.02}}, PlotMarkers -> {"|", 8}]}]

A: The solutions above don't really achieve the idea of a rug plot as it is commonly used by statisticians.  Clearly there are cases when it is not appropriate (such as on scatter plots with lots of overlapping data points), but then there are other cases (esp histograms and smooth histograms) where it is insightful (and expected by journal publishers).  But "whether to use" and "how to make" are different questions.
A standard rug plot can be achieved by using Line with Scaled offset coordinates in an Epilog, and setting your PlotRangePadding accordingly.

First, here are two random datasets.
Data1 = RandomVariate[NormalDistribution[0.35, 0.05], 200];
Data2 = RandomVariate[NormalDistribution[0.55, 0.05], 60];
DataPoints = Flatten[{Data1, Data2}];

To get the rug plot you just add some extra padding to the bottom of the histogram and draw your lines in the extra space using Epilog.
Histogram[DataPoints,PlotRangePadding->{Scaled[0.02],{Scaled[0.06],Scaled[0.03]}},
Epilog->{AbsoluteThickness[0.01],Line[Table[{Scaled[{0,-0.01},{i,0}],Scaled[{0,-0.03},{i,0}]},{i,DataPoints}]]}]

Using this method will scale the location and heights of the plot and lines regardless of the y-scale (e.g., whether it is a PDF or a histogram of counts).  It is also easy to stack multiple sets of lines of different colors to represent multiple distributions.  You can also easily adjust the line appearance according to your preferences.

A: Just to illustrate the point I made in the comment, let's take a data set where the points stack up vertically, and verify what it looks like if we visualize their density by means of a color gradient as in the question One-dimensional heatmap. You first have to copy the definition of heatMap from the second code block in my answer, and then execute this:
iris = ExampleData[{"Statistics", "FisherIris"}][[All, 1 ;; 2]];

h = Show[heatMap[Map[{#, 0} &, iris[[All, 1]]],
    "Points" -> 2 Length[iris], "Radius" -> {1, .01},
    PlotRange -> {{4, 8}, {0, .1}}, PlotRangePadding -> 0,
    FrameLabel -> None,
    ColorFunction -> (ColorData["SiennaTones"][1 - #] &)],
   Frame -> None, PlotRangePadding -> None, ImagePadding -> None,
   AspectRatio -> Full];

ListPlot[iris, Prolog -> Inset[h, {4, 0}, {4, 0}, 4],
 PlotRange -> {{4, 8}, {0, 4.5}}, Frame -> True]

This replacement rug is made with a color gradient (SiennaTones) that indicates clustering of data points by darker shading. I didn't automate the choice of plot parameters yet, but it could be done if you think it's useful. The example shows that bandwidth is not a problem because I use a Gaussian filter where the radius can simply be chosen to be as small as needed to achieve the maximal resolution.
Edit
Here is another example, where the data are distributed more irregularly:
mtcars = Import["mtcars.csv"];
x = Drop[mtcars[[All, 7]], 1];
y = Drop[mtcars[[All, 2]], 1];

h2 = Show[
   heatMap[Map[{#, 0} &, x], "Points" -> 10 Length[x],
    "Radius" -> {1, .01}, PlotRange -> {{1.5, 4.5}, {0, .1}},
    PlotRangePadding -> 0, FrameLabel -> None,
    ColorFunction -> (ColorData["SiennaTones"][1 - #] &)],
   Frame -> None, PlotRangePadding -> None, ImagePadding -> None,
   AspectRatio -> Full];

ListPlot[Thread[List[x, y]],
 Prolog -> Inset[h2, {1.5, 0}, {1.5, 0}, 3],
 PlotRange -> {{1.5, 4.5}, {0, 40}}, Frame -> True]

Here, I had to use more sampling points (option "Points") because the data are more closely spaced in some places.

A: Let's generate some data to play with:
SeedRandom[5]
Round@RandomVariate[UniformDistribution[{0, 20}], 35];
data = {#, 50 - 3 # + RandomReal[{-10, 10}]} & /@ %;
ListPlot[data, PlotRange -> All]

Here is a function that calculates the size and position of the plot "piles" and constructs the plot explicitly from graphics primitives:
Clear[rugplot]
rugplot[data_] := Module[
  {plotpoints, piles, listplot, plotrange, padding, ystart, yend},
  plotpoints = {PointSize[0.015], Point[data]};
  plotrange = {Min[#], Max[#]} & /@ Transpose[data];
  ystart = plotrange[[2, 1]];
  yend = (plotrange[[2, 2]] - plotrange[[2, 1]])/15 + ystart;
  piles = {
      Thickness[#2/400], CapForm["Butt"],
      Line[{{#1, ystart}, {#1, yend}}]
      } & @@@ Tally[data[[All, 1]]];
  Graphics[
   {plotpoints, piles},
   PlotRange -> plotrange, PlotRangePadding -> None,
   AspectRatio -> 0.8, Frame -> True, Axes -> False
   ]
 ]

We can try this out with the sample data generated above:
rugplot[data]

This is almost there, but it still needs some cosmetic adjustments to the final plot range to add some padding and more space for the bars at the bottom. Unfortunately I have to go now, so I won't be able to make the adjustments straight away, but hopefully this will help for now.


text:
Q: Integer comparison, 10 and 128 I found an interesting fact, but I don't know how it happened.
Integer x = 10;
Integer y = 10;
System.out.print(x==y);    // true

Integer x = 128;
Integer y = 128;
System.out.print(x==y);    // false

A: Integer comparison using == works only for numbers between -128 and 127.
Because Integer is an Object, use equals that will work for all values.


text:
Q: Call Vuex Getters from another javascript file In /store/user/getters.js:
function getLoggedIn (state) {
  return state.loggedIn
}

In another file: router-auth.js, I try to get the getters.getLoggedIn's value (true or false) like this:
import user from '../store/user'
const loggedIn = user.getters.getLoggedIn
console.log(user.getters.getLoggedIn)

Oddly, it returns the source code of the function instead of the state's value! When I print the log of user.getters, it does list the functions.

A: You need to access the instance of the store.
const myStore = new Vuex.store({...});

Here myStore is the instance.
Assuming your store looks something like
store.js
import Vue from "vue";
import Vuex from "vuex";
import user from "./user";

Vue.use(Vuex);

const store = new Vuex.Store({
  modules: {
    user
  }
});

export default store;

You can access the instance by importing store from store.js.
router-auth.js
import store from './store.js';

function someAuthFunction() {
    console.log(store.getters.getLoggedIn);
}

A simple demo on CodeSandbox


text:
Q: How do I add router-link to a button click function on Angular 8? I am trying to add a routing function to a button on angular . I have added a (click) function to the button but how do I implement the function to navigate on the home.ts component ?
<button class="navbut" (click)="redirect()"> INVEST NOW</button >

A: I have fixed , I declared a router and imported it from @Angular/router then write the redirect() function in my ts file :
import {Router, ActivatedRoute } from '@angular/router';

export class HomeComponent implements OnInit {
constructor( private router: Router, private route: ActivatedRoute) { }
}

redirect() {
    this.router.navigate (['/investment']);
  }


text:
Q: Remote Control Program for ATMEGA168P circuit Hello I will make maybe a fool questions. I have this diagram:

This diagram is to turn on/off led lights, make blink via remote control.
Now the questions are:
1.-What kind of remote control I can buy or what characteristics to buy for remote for this circuit? Link maybe?
2.-If depending of the remote control, how this circuit will know what brand I´m using, in other words how can I program the remote buttons to apply for each function on each pin of the ATMEGA like you see. Is this defined in the on the code you prgoramr into the ATMEGA?
Thank you

A: Here's some popular IR codec code for AVR/Arduino:
http://www.righto.com/2009/08/multi-protocol-infrared-remote-library.html
https://github.com/shirriff/Arduino-IRremote
You will need to choose a remote-control, and then program the AVR to do whatever it is you want the car lights to do when you push various remote buttons.


text:
Q: Why 'dokku plugins-install' doesn't work as expected? I'm trying to use simple dokku plugins-install command, but my system replies me with:

plugins-install is not a dokku command.
See dokku help for a list of available commands.

What might be the problem here?

A: That is only a command on the 0.3.x line. The latest line or releases, 0.4.x. You can see how to install a plugin here


text:
Q: How to rewrite a query without using subquery First, some background on what I'm trying to do:
I have a table called Invoices and if I run this two SELECT I get the following:
SELECT AID, PPID, Amount, Type, Invoice FROM Invoices WHERE Type > 3 AND PPID = 2250

AID
PPID
Amount
Type
Invoice

443
2250
4500
5
0

SELECT AID, PPID, Amount, Type, Invoice FROM Invoices WHERE Type > 3 AND PPID = 1442

AID
PPID
Amount
Type
Invoice

77
1442
4500
5
0

225
1442
4500
5
0

So when PPID = 2250 it returns only 1 row and when PPID = 1442 it returns 2 rows(and that's fine)
Now I have a query here that only brings me the records that returns only one row (PPID = 2250) and if it returns more than one row(PPID = 1442) it won't bring anything.
SELECT
(SELECT TOP 1 I2.AID FROM cgpaccounts.dbo.Invoices I2 WHERE I2.Invoice = I1.Invoice AND I2.Type > 3 AND I2.PPID = I1.PPID) AS PaymentID,
I1.AID AS ChargeID,
CAST(I1.Amount AS FLOAT)/100 AS Amount,
I1.Invoice
FROM Invoices I1
WHERE I1.type <> 2 AND I1.type < 4 AND I1.Amount > 0 AND I1.PPID = 1442--added for tests only
AND (SELECT COUNT(I3.AID) FROM Invoices I3 WHERE I3.Invoice = I1.Invoice AND I3.Type > 3 AND I3.PPID = I1.PPID) = 1

So I want to rewrite that query not using subqueries (I'm running it in a AccessDB and it's taking a huge amount of time, I rewrote other queries and by removing the subqueries it improved, but I'm stuck on this one now).
I've got this far already, but to be honest, I'm not sure if I'm on the right way of thinking here.
SELECT
I2.AID AS PaymentID,
I1.AID AS ChangeID,
I1.Amount / 100 AS Amount,
I1.Invoice
FROM Invoices I1
INNER JOIN Invoices I2
ON I2.PPID = I1.PPID AND I2.Invoice = I1.Invoice
WHERE I2.Type > 3 AND I1.type <> 2 AND I1.type < 4 AND I1.Amount > 0 AND I1.PPID = 1442--added for tests only

When I run it with PPID = 2250 I get the following result: (this is what I expect)

PaymentID
ChargeID
Amount
Invoice

443
83
45
0

When I run it with PPID = 1442 I get the following result: (not what I'm expecting, I think there's something wrong in my logic there, and I'm getting duplicated results)

PaymentID
ChargeID
Amount
Invoice

77
76
45
0

225
76
45
0

77
224
45
0

225
224
45
0

In summary, what I'm trying to do is to rewrite that query without the subqueries and also add the condition to bring only the results where only 1 row is returned.
I know this is quite a long question, but I tried to give as much information as possible.
I hope someone can help me, or guide me in the right direction.

A: Try the script below adding the DISTINCT:
SELECT DISTINCT
I2.AID AS PaymentID,
I1.AID AS ChangeID,
I1.Amount / 100 AS Amount,
I1.Invoice
FROM Invoices I1, Invoices I2
WHERE I2.PPID = I1.PPID
  AND I2.Invoice = I1.Invoice
  AND I2.Type > 3
  AND I1.type <> 2
  AND I1.type < 4
  AND I1.Amount > 0
  AND I1.PPID = 1442


text:
Q: Python subprocess.Popen erroring with OSError: [Errno 12] Cannot allocate memory after period of time Note: This question has been re-asked with a summary of all debugging attempts here.

I have a Python script that is running as a background process executing every 60 seconds. Part of that is a call to subprocess.Popen to get the output of ps.
ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]

After running for a few days, the call is erroring with:

File "/home/admin/sd-agent/checks.py", line 436, in getProcesses
File "/usr/lib/python2.4/subprocess.py", line 533, in __init__
File "/usr/lib/python2.4/subprocess.py", line 835, in _get_handles
OSError: [Errno 12] Cannot allocate memory

However the output of free on the server is:

$ free -m
                  total       used       free     shared     buffers    cached
Mem:                894        345        549          0          0          0
-/+ buffers/cache:  345        549
Swap:                 0          0          0

I have searched around for the problem and found this article which says:
Solution is to add more swap space to your server. When the kernel is forking to start the modeler or discovery process, it first ensures there's enough space available on the swap store the new process if needed.
I note that there is no available swap from the free output above. Is this likely to be the problem and/or what other solutions might there be?
Update 13th Aug 09 The code above is called every 60 seconds as part of a series of monitoring functions. The process is daemonized and the check is scheduled using sched. The specific code for the above function is:
def getProcesses(self):
    self.checksLogger.debug('getProcesses: start')

    # Memory logging (case 27152)
    if self.agentConfig['debugMode'] and sys.platform == 'linux2':
        mem = subprocess.Popen(['free', '-m'], stdout=subprocess.PIPE).communicate()[0]
        self.checksLogger.debug('getProcesses: memory before Popen - ' + str(mem))

    # Get output from ps
    try:
        self.checksLogger.debug('getProcesses: attempting Popen')

        ps = subprocess.Popen(['ps', 'aux'], stdout=subprocess.PIPE).communicate()[0]

    except Exception, e:
        import traceback
        self.checksLogger.error('getProcesses: exception = ' + traceback.format_exc())
        return False

    self.checksLogger.debug('getProcesses: Popen success, parsing')

    # Memory logging (case 27152)
    if self.agentConfig['debugMode'] and sys.platform == 'linux2':
        mem = subprocess.Popen(['free', '-m'], stdout=subprocess.PIPE).communicate()[0]
        self.checksLogger.debug('getProcesses: memory after Popen - ' + str(mem))

    # Split out each process
    processLines = ps.split('\n')

    del processLines[0] # Removes the headers
    processLines.pop() # Removes a trailing empty line

    processes = []

    self.checksLogger.debug('getProcesses: Popen success, parsing, looping')

    for line in processLines:
        line = line.split(None, 10)
        processes.append(line)

    self.checksLogger.debug('getProcesses: completed, returning')

    return processes

This is part of a bigger class called checks which is initialised once when the daemon is started.
The entire checks class can be found at http://github.com/dmytton/sd-agent/blob/82f5ff9203e54d2adeee8cfed704d09e3f00e8eb/checks.py with the getProcesses function defined from line 442. This is called by doChecks() starting at line 520.

A: You've perhaps got a memory leak bounded by some resource limit (RLIMIT_DATA, RLIMIT_AS?) inherited by your python script.  Check your *ulimit(1)*s before you run your script, and profile the script's memory usage, as others have suggested.
What do you do with the variable ps after the code snippet you show us?  Do you keep a reference to it, never to be freed?  Quoting the subprocess module docs:

Note: The data read is buffered in memory, so do not use this
  method if the data size is large or unlimited.

... and ps aux can be verbose on a busy system...
Update
You can check rlimits from with your python script using the resource module:
import resource
print resource.getrlimit(resource.RLIMIT_DATA) # => (soft_lim, hard_lim)
print resource.getrlimit(resource.RLIMIT_AS)

If these return "unlimited" -- (-1, -1) -- then my hypothesis is incorrect and you may move on!
See also resource.getrusage, esp. the ru_??rss fields, which can help you to instrument for memory consumption from with the python script, without shelling out to an external program.

A: That swap space answer is bogus. Historically Unix systems wanted swap space available like that, but they don't work that way anymore (and Linux never worked that way). You're not even close to running out of memory, so that's not likely the actual problem - you're running out of some other limited resource.
Given where the error is occuring (_get_handles calls os.pipe() to create pipes to the child), the only real problem you could be running into is not enough free file descriptors. I would instead look for unclosed files (lsof -p on the PID of the process doing the popen). If your program really needs to keep a lot of files open at one time, then increase the user limit and/or the system limit for open file descriptors.

A: when you use popen you need to hand in close_fds=True if you want it to close extra file descriptors.
creating a new pipe, which occurs in the _get_handles function from the back trace, creates 2 file descriptors, but your current code never closes them and your eventually hitting your systems max fd limit.
Not sure why the error you're getting indicates an out of memory condition: it should be a file descriptor error as the return value of pipe() has an error code for this problem.

A: If you're running a background process, chances are that you've redirected your processes stdin/stdout/stderr.
In that case, append the option "close_fds=True" to your Popen call, which will prevent the child process from inheriting your redirected output.  This may be the limit you're bumping into.

A: You might want to actually wait for all of those PS processes to finish before adding swap space.
It's not at all clear what "running as a background process executing every 60 seconds" means.
But your call to subprocess.Popen is forking a new process each time.
Update.
I'd guess that you're somehow leaving all those processes running or hung in a zombie state.  However, the communicate method should clean up the spawned subprocesses.

A: Have you watched your process over time?

*

*lsof

*ps -aux | grep -i pname

*top

All should give interesting information. I am thinking that the process is tying up resources that should be freed up. Is there a chance that it is tying up resource handles (memory blocks, streams, file handles, thread or process handles)? stdin, stdout, stderr from the spawned "ps". Memory handles, ... from many small incremental allocations. I would be very interested in seeing what the above commands display for your process when it has just finished launching and running for the first time and after 24 hours of "sitting" there launching the sub-process regularly.
Since it dies after a few days, you could have it run for only a few loops, and then restart it once a day as a workaround. That would help you in the meantime.
Jacob

A: I don't think that the circumstances given in the Zenoss article you linked to is the only cause of this message, so it's not clear yet that swap space is definitely the problem. I would advise logging some more information even around successful calls, so that you can see the state of free memory every time just before you do the ps call.
One more thing - if you specify shell=True in the Popen call, do you see different behaviour?
Update: If not memory, the next possible culprit is indeed file handles. I would advise running the failing command under strace to see exactly which system calls are failing.

A: You need to
ps = subprocess.Popen(["sleep", "1000"])
os.waitpid(ps.pid, 0)

to free resources.
Note: this does not work on Windows.

A: Virtual Memory matters!!!
I encountered the same issue before I add swap to my OS. The formula for virtual memory is usually like: SwapSize + 50% * PhysicalMemorySize. I finally get this resolved by either adding more physical memory or adding a Swap disk. close_fds won't work in my case.


text:
Q: Logical OR operator result as rvalue This code I found while doing code review. Is there any hidden problem in this code or is it just fine?
myBool = myBoolA || ( oldState == AS_PLAYING );   //code #1

Edit: One typing mistake (myBoolA in place of myBool) by me created some nasty confusion; I am really sorry for that.
Actually the code to be reviewed is :
myBool = myBool || ( oldState == AS_PLAYING );   //code #1, not myBoolA

and my suggested code is:
if( oldState == AS_PLAYING ) myBool = true;   //code #2

Advantages with code#2 IMO :

*

*better readability

*if myBool is unintialized to begin with, there won't be Undefined behaviour.

A: myBool = myBoolA || ( oldState == AS_PLAYING ); is absolutely fine.
|| is a sequencing point in C++, so even if the expression on the right hand side depends on the left hand side (perhaps oldState is a reference to myBool or myBoolA), the behaviour will be defined.
Your recommendation in changing this to
if( oldState == AS_PLAYING )  myBool = true;
is actually functionally different (the assignment to myBool is different for example), so don't change it to that.
Finally, note that the short-circuiting nature of || is obviated if || is overloaded. So always check that when refactoring code.

A: As per your comments later,
You can refactor as follows:
if(!myBool)
    myBool =  (oldState == AS_PLAYING);

this will save one extra assignment operation. when myBool is true before if

A: myBool = myBoolA || ( oldState == AS_PLAYING );   //code #1
 seems to be correct version.
Your version is not equivalent to this. How? See
if myBoolA  is true and ( oldState == AS_PLAYING ) is false. myBool will still be true, but in your version, it will not be set.
After EDIT
if( oldState != AS_PLAYING )  myBool = false;    //code #2 more readable IMO

This will be fine only if, myBool is initialized with true.


text:
Q: Node server transmits empty/invalid PDFKit document I am attempting to take some input data from a front-end React app and pass it to an Express Node server, which will process the input data and return a PDF created with PDFKit. Right now, the Node server creates a perfectly readable and accurate PDF in the local filesystem, but when the http response arrives at the front-end the file is not readable, and all pages are blank.
The return data seems to be a properly formatted PDF string, though with lots of those "question marks inside a diamond" (screenshots attached).
Server-side code:
router.post("/testPDF", function(req, res, next) {
    try {

      const doc = new pdfkit()

      //create a unique name for the file
      const docName = createDocName(JSON.stringify(req.body))

      const fileWrite = fs.createWriteStream(`./pdfs/${docName}.pdf`)
      doc.pipe(fileWrite)

      //functions to create pdf based on passed data
      documentHeader(doc)
      documentBody(doc, req.body.data)

      doc.end()

      fileWrite.on('finish', function () {
        fs.readFile(`./pdfs/${docName}.pdf`, function(err, data) {
          res.writeHead(200, {'Content-Type': 'application/pdf'});
          res.write(data);
          return res.end();
        });
      })

    } catch (e) {
      console.log(e)
    }
  })

Front-end code:
axios.post("http://localhost:3001/testPDF", {data: selectedData})
    .then((res) => {
        var base64doc = Base64.encode(res.data)
        var out = []
        for (let i = 0; i < base64doc.length; i++) {
            out.push(base64doc.charAt(i))
        }
        var newBlob = new Blob(out, {type: "application/pdf;base64"})
        var url = URL.createObjectURL(newBlob)
        var newWindow = window.open()
        newWindow.location.href = url
    })
    .catch((err) => {
        console.log(err)
    })

excerpt of PDF that won't open
excerpt of (seemingly) the same PDF that will open
I've tried implementing this code using the blob-stream npm package as advised by the PDFKit website, with a similar set-up as seen above, to no avail. I've also tried piping directly to the res object instead of creating the file and then reading the file into res (as shown above), but the result is the same.


text:
Q: Methods to compute the Green's function for the 1D wave equation with nonsmooth coefficient? I am seeking advice on the best available numerical methods to compute the Green's function for a 1D wave equation with rough coefficient.
Suppose that the coefficient $c(x)$ in the 1D wave equation $u_{tt}-c(x)^2u_{xx}=0$ has constant values $c_0$ and $c_1$ to the left and right respectively of a bounded interval $I=(x_0,x_1)$, but is variable and nonsmooth on $I$. More precisely, suppose that $c$ is piecewise $C^1$ on $I$ (so that it may have a finite number of jump discontinuities, for example). Consider initial conditions corresponding to a left or right-moving unit impulse at a source point $x_s$:  $u(x,0)=\delta(x-x_s)$, $u_t(x,0)=\pm\delta^\prime(x-x_s)$. One wants to compute the (distributional) solution $u(x_r,t)$ for $0<t<T$ at some other point $x_r$. (It may be assumed that $x_s$ is a point of continuity of $c$.)
1) What established numerical techniques are applicable to this problem?
2) What would qualify as the "gold standard" against which new methods should be judged?

A: As a benchmark for comparison, one can use an explicit variable step size finite difference scheme.  This is a well established numerical technique for 1D PDE problems even with unbounded domains.
I will focus on the spatial discretization of the term $c(x) \partial_{xx} f(x)$, because the temporal discretization is standard.   Even though $c(x)$ may have jump discontinuities, this term is benign because $c(x)$ is not differentiated.  Note that numerical stability may require that the local time step size is adjusted in order to ensure that the discrete cone of influence emanating backwards from a given point always contains the continuous one (aka a CFL condition).  This is the main point of introducing a variable step size approximation.
Let $S = \{ x_i \}$ be a collection of grid points on $\mathbb{R}$ with forward, backward, and average spatial grid sizes given by:
$$
\delta x_i^+ = x_{i+1} - x_i \;, \quad \delta x_i^- = x_i - x_{i-1}\;, \quad \delta x_i = \frac{\delta x_i^+ + \delta x_i^-}{2}
$$
Note that we don't assume that $S$ contains the jump discontinuities of $c(x)$. It might be advantageous to include these points in order to satisfy the above mentioned CFL condition.  Also, in order to accurately resolve the effect of the jumps in $c(x)$, one needs to pick the local grid size sufficiently small.
At any grid point (including a jump discontinuity of $c(x)$) use a standard variable grid size, central scheme
$$
(c(x) \partial_{xx} f(x))_i \approx \frac{c_i}{ \delta x_i} \left(  \frac{f_{i+1} - f_i}{\delta x_i^+} -   \frac{f_{i} - f_{i-1}}{\delta x_i^-} \right)
$$
If $f$ is $C^4$ (in space), then it is straightforward to verify that this approximation is locally second-order accurate at every grid point.  My guess is that the overall accuracy of this scheme in the $\ell_1$ norm is also second-order. To prove this, one needs to understand the properties of the exact solution in a neighborhood of the jump discontinuities of $c(x)$.


text:
Q: Null exception on array I'm very new to Java and programming and working on a class project, we're learning about i/o, arrays and objects and we have some pretty specific guidelines to follow.  When the compiler gets to "countryInfo[count].setName(name);" , it gives me
Exception in thread "main" java.lang.NullPointerException
    at Main.main(Main.java:53)
If I comment it out, the next line gives me the same error.
I'm sure there's much more efficient ways to re write this code, but since we're newbies we aren't allowed to do that.  I read quite a bit about Null exception before I asked... if I missed it somewhere I apologize. I'm lost :(
public class Main {

/**
 * @param args the command line arguments
 */
private static Country[] countryInfo = new Country[43];

public static void main(String[] args) throws IOException {
    String name = "";
    String capital = "";
    String region = "";
    int region_Nbr = 0;
    int capital_population = 0;

    // TODO code application logic here
    String filename = "Countries.txt";
    String inputString;

    FileInputStream fis1 = new FileInputStream(filename);
    BufferedReader br1 = new BufferedReader(new InputStreamReader(fis1));
    inputString = br1.readLine();

    while (inputString != null) {
        int count = 0;
        System.out.print(inputString + "\n");

        name = inputString.substring(0, 13).trim();
        //System.out.print(name + ", "); //echo

        capital = inputString.substring(24, 36).trim();
        //System.out.print(capital + ", ");//echo

        region = inputString.substring(40, 56).trim();
        //System.out.print(region + ", "); //echo

        region_Nbr = Integer.parseInt(inputString.substring(64, 66).trim());
        //System.out.print(region_Nbr + ", ");//echo

        capital_population = Integer.parseInt(inputString.substring(72, inputString.length()).trim());
        //System.out.print(capital_population + "\n");

        countryInfo[count].setName(name);
        countryInfo[count].setCapital(capital);
        countryInfo[count].setRegion(region);
        countryInfo[count].setRegionNum(region_Nbr);
        countryInfo[count].setPopulation(capital_population);
        inputString = br1.readLine();

        count++;
    } //end while

}

}
public class Country {

private String name;
private String capital;
private String region;
private int region_Nbr;
private int capital_population;

public void setName(String w) {
    this.name = w;

} //end get name

A: You never fill your array with objects. currently you have an array but it is empty and filled with just nulls. The solution is to create objects to fill it with before using. Think of an array as being similar to an egg crate. You can't cook with eggs from the crate til you fill it with eggs first.
    countryInfo[count] = new Country(); // **** add
    countryInfo[count].setName(name);
    countryInfo[count].setCapital(capital);
    countryInfo[count].setRegion(region);
    countryInfo[count].setRegionNum(region_Nbr);
    countryInfo[count].setPopulation(capital_population);
    inputString = br1.readLine();

Edit, you state:

I'm not sure I understand why I needed to add that line, I thought that private static Country[] countryInfo = new Country[43];

When you create the array objects, also known as an array of reference type, you create a collection of empty variables, variables that are given the default value for any reference variable, null. This is different from creating an array of primitive type which will initialize the array to the default of the primitive (0 for ints, false for booleans, etc...).
Again, this is akin to creating an empty egg carton or a parking lot. In order for the array to be filled with objects, you must put the objects into the array yourself. You need to fill a parking lot with cars before you can select one and drive one off. Just having a parking lot with empty spots will not be useful to you.

A: You should add:
countryInfo[count] = new Country();

before
countryInfo[count].setName(name);


text:
Q: Update SnackBar content in Flutter I have a button that displays a SnackBar (or toast) before moving to the next page. I have a countdown and after 5 seconds I push Page2.
RaisedButton(
                    onPressed: () {
                      _startTimer();
                      final snackBar = SnackBar(
                        behavior: SnackBarBehavior.floating,
                        content: Text(
                            'Prepare yourself to start in ${widget._current.toString()}!'), // doesn't work here
                        duration: new Duration(seconds: widget._start),
                        action: SnackBarAction(
                          label: widget._current.toString(), // and neither does here
                          onPressed: () {
                            // Some code to undo the change.
                          },
                        ),
                      );
                      Scaffold.of(context).showSnackBar(snackBar);
                    },
                    child: Text(
                      "I'm ready",
                      style: TextStyle(fontSize: 20),
                    ),
                  ),

Nothing to see on the countdown but I'll paste it just in case:
void _startTimer() {
    CountdownTimer countDownTimer = new CountdownTimer(
      new Duration(seconds: widget._start),
      new Duration(seconds: 1),
    );

    var sub = countDownTimer.listen(null);
    sub.onData((duration) {
      setState(() {
        widget._current = widget._start - duration.elapsed.inSeconds;
      });
    });

    sub.onDone(() {
      print("Done");
      sub.cancel();
    });
  }

So if I display the countdown somewhere else (inside a Text for example) it works but it seems that the SnackBar doesn't change its contain, it always get the max number of the countdown.

A: you need to implement a custom widget with countdown logic in side for the content field of snackbar, like this:
class TextWithCountdown extends StatefulWidget {
  final String text;
  final int countValue;
  final VoidCallback? onCountDown;

  const TextWithCountdown({
    Key? key,
    required this.text,
    required this.countValue,
    this.onCountDown,
  }) : super(key: key);

  @override
  _TextWithCountdownState createState() => _TextWithCountdownState();
}

class _TextWithCountdownState extends State<TextWithCountdown> {
  late int count = widget.countValue;
  late Timer timer;
  @override
  void initState() {
    super.initState();
    timer = Timer.periodic(Duration(seconds: 1), _timerHandle);
  }

  @override
  void dispose() {
    timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text("[$count] " + widget.text),
    );
  }

  void _timerHandle(Timer timer) {
    setState(() {
      count -= 1;
    });
    if (count <= 0) {
      timer.cancel();
      widget.onCountDown?.call();
    }
  }
}

A: That is because the snack bar is built once, when the button is clicked. When the state updates, it rebuilds the widget tree according to the changes. The snack bar initially isn't in the widget tree, so it doesn't update.
Try to use stack and show a snack bar, and then you should be able to manipulate it however you need.
Hope it helps.

A: Update SnackBar Content
SnackBar content can be updated/rebuilt while it's visible by making its content: widget dynamic.
In the code sample below we're using a ValueNotifier and ValueListenableBuilder to dynamically rebuild the content of the SnackBar whenever ValueNotifier is given a new value.
(There are many ways to to maintain state values & rebuild widgets when it changes, such as RiverPod, GetX, StreamBuilder, etc.  This example uses the Flutter native ValueListenableBuilder.)
When running this Flutter page, click the FAB to show the SnackBar, then click on the center text to update the SnackBar's content (multiple times if you like).
Example
Use SnackBarUpdateExample() widget in your MaterialApp home: argument to try this example in an emulator or device.
class SimpleCount {
  int count = 0;
}

class SnackBarUpdateExample extends StatelessWidget {
  static const _initText = 'Initial text here';

  /// This can be "listened" for changes to trigger rebuilds
  final ValueNotifier<String> snackMsg = ValueNotifier(_initText);

  final SimpleCount sc = SimpleCount();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SnackBar Update'),
      ),
      /// ↓ Nested Scaffold not necessary, just prevents FAB being pushed up by SnackBar
      body: Scaffold(
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text('Click FAB to show SnackBar'),
              SizedBox(height: 20,),
              Text('Then...'),
              SizedBox(height: 20,),
              InkWell(
                child: Text('Click → here ← to update SnackBar'),
                onTap: () {
                  sc.count++;
                  snackMsg.value = "Hey! It changed! ${sc.count}";
                },
              ), /// When snackMsg.value changes, the ValueListenableBuilder
              /// watching this value, will call its builder function again,
              /// and update its SnackBar content widget
            ],
          ),
        ),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.play_arrow),
          onPressed: () => _showSnackBar(context),
        ),
      ),
    );
  }

  void _showSnackBar(BuildContext context) {
    var _controller = ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: SnackContent(snackMsg))
    );

    /// This resets the snackBar content when it's dismissed
    _controller.closed.whenComplete(() {
      snackMsg.value = _initText;
      sc.count = 0;
    });
  }
}

/// The ValueListenableBuilder rebuilds whenever [snackMsg] changes.
class SnackContent extends StatelessWidget {
  final ValueNotifier<String> snackMsg;

  SnackContent(this.snackMsg);

  @override
  Widget build(BuildContext context) {
    /// ValueListenableBuilder rebuilds whenever snackMsg value changes.
    /// i.e. this "listens" to changes of ValueNotifier "snackMsg".
    /// "msg" in builder below is the value of "snackMsg" ValueNotifier.
    /// We don't use the other builder args for this example so they are
    /// set to _ & __ just for readability.
    return ValueListenableBuilder<String>(
        valueListenable: snackMsg,
        builder: (_, msg, __) => Text(msg));
  }
}


text:
Q: Can we use http.sys to run application on linux container? The reason for asking this is , my application has .net framework with Aspnet core2.2 and runs using dotnet run. It also uses windows authentication.
I want to know if this application can be self contained and run on a Linux container.

A: No, it cannot. HTTP.sys only runs on Windows.
Source: HttpSys, learn.microsoft.com


text:
Q: Не работает window.onunload в некоторых браузерах В chrome window.onunload  отлично работает, но в Firefox и Opera оно не работает.Почему?Как мне это исправить?Вот код:
window.onunload = function(){
    let elems = document.getElementsByClassName("take");
    let dict = {};
    for (var i = 0; i < elems.length; i++) {
        dict[String(elems[i].src)] = elems[i].tagName;
    }
    let json = JSON.stringify(dict);
    console.log(json)
    fetch('/delete',{
        method: 'POST',
        body: json
    });
};