text:
Q: App crashing while calling callback() to java. Getting runtime error due to detatchThread I am trying to basically create a callback from native-lib.cpp class callback() method to call some method in java. But for that, I need env variable also. I am trying to create same in native-lib.cpp but getting this error.  I think some issue because of thread being detatched. Can someone please clarify this. I am very new to callbacks creation concept. Can someone point out exactly the issue. Some issue with detachThread seems to me. Can someone clarify on the issue. Thanks in advance.
This  is the native-lib.cpp:
#include <jni.h>
#include <string>
#include "Numbers.h"

#include <android/log.h>

#define  LOG_TAG    "logs"

#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)

typedef struct number_ctx{
    JavaVM  *javaVM;
    jclass   mathsClass;
    jobject  mathsObj;
    jclass   mainActivityClass;
    jobject  mainActivityObj;
    pthread_mutex_t  lock;
} NumbersCtx;
NumbersCtx g_ctx;

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved) {
    JNIEnv* env;
    memset(&g_ctx, 0, sizeof(g_ctx));

    g_ctx.javaVM = vm;

    if (vm ->GetEnv((void **)&env, JNI_VERSION_1_6) != JNI_OK) {
        return JNI_ERR; // JNI version not supported.
    }

    jclass  clz = env->FindClass(
            "com/example/maths/Maths1");

    g_ctx.mathsClass = static_cast<jclass>(env->NewGlobalRef(clz));

    clz = env->FindClass(
            "com/example/maths/MainActivity");

    g_ctx.mainActivityClass = static_cast<jclass>(env->NewGlobalRef(clz));

    g_ctx.mathsObj = NULL;
    g_ctx.mainActivityObj = NULL;

    env->DeleteLocalRef(clz);

    return  JNI_VERSION_1_6;
}

void callback() {

    JNIEnv* env;

    LOGD("Starting finally ");

    if (g_ctx.javaVM ->GetEnv((void **)&env, JNI_VERSION_1_6) != JNI_OK) {
        LOGD("JNI Error is %d" , JNI_ERR); // JNI version not supported.
    }

    LOGD("Env variable received successfully");

    int status = g_ctx.javaVM->AttachCurrentThread(&env, NULL);

    if(status != JNI_OK) {
        LOGD("Failed to attach the thread");
    } else {

        LOGD("Thread attached successfully");

        jmethodID testMessage = env->GetMethodID(g_ctx.mathsClass, "printMessage",
                                                 "()V");
        // Call the method on the object
        env->CallVoidMethod(g_ctx.mathsObj, testMessage);

        if (env->ExceptionCheck()) {
            env->ExceptionDescribe();
        }

        LOGD("Void Method called Successfully");

        g_ctx.javaVM->DetachCurrentThread();

        LOGD("Thread detached successfully");
    }

    LOGD("This callback is called finally");
}

jfieldID getPtrFieldId(JNIEnv * env, jobject obj)
{
    static jfieldID ptrFieldId = 0;

    if (!ptrFieldId)
    {
        jclass c = env->GetObjectClass(obj);
        ptrFieldId = env->GetFieldID(c, "numberptr", "J");
        env->DeleteLocalRef(c);
    }

    return ptrFieldId;
}

extern "C"
JNIEXPORT void JNICALL
Java_com_example_maths_Maths1_createNumberInstance(JNIEnv *env, jobject thiz, jint a, jint b) {
    // TODO: implement createNumberInstance()

    g_ctx.mathsObj = env->NewGlobalRef(thiz);
    Numbers* num = new Numbers(a, b);
    callback();
    env->SetLongField(thiz, getPtrFieldId(env, thiz), (jlong) num);

}

This is error which I am getting:
2020-06-02 19:25:39.101 15965-15965/com.example.maths A/m.example.math: runtime.cc:2067] Thread[1,tid=15965,Native,Thread*=0xec991800,peer=0x71b391f0,"main"] attempting to detach while still running code
2020-06-02 19:25:39.497 15965-15965/com.example.maths A/m.example.math: runtime.cc:630] Runtime aborting...
2020-06-02 19:25:39.497 15965-15965/com.example.maths A/m.example.math: runtime.cc:630] Dumping all threads without mutator lock held
2020-06-02 19:25:39.497 15965-15965/com.example.maths A/m.example.math: runtime.cc:630] All threads:
2020-06-02 19:25:39.497 15965-15965/com.example.maths A/m.example.math: runtime.cc:630] DALVIK THREADS (17):
2020-06-02 19:25:39.497 15965-15965/com.example.maths A/m.example.math: runtime.cc:630] "main" prio=10 tid=1 Runnable
2020-06-02 19:25:39.497 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   | group="" sCount=0 dsCount=0 flags=0 obj=0x71b391f0 self=0xec991800
2020-06-02 19:25:39.497 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   | sysTid=15965 nice=-10 cgrp=default sched=0/0 handle=0xece36dc8
2020-06-02 19:25:39.497 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   | state=R schedstat=( 466154407 353144186 350 ) utm=12 stm=34 core=0 HZ=100
2020-06-02 19:25:39.497 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   | stack=0xff27a000-0xff27c000 stackSize=8192KB
2020-06-02 19:25:39.497 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   | held mutexes= "abort lock" "mutator lock"(shared held)
2020-06-02 19:25:39.497 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #00 pc 00493b43  /apex/com.android.runtime/lib/libart.so (art::DumpNativeStack(std::__1::basic_ostream<char, std::__1::char_traits<char>>&, int, BacktraceMap*, char const*, art::ArtMethod*, void*, bool)+115)
2020-06-02 19:25:39.497 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #01 pc 005b1fd2  /apex/com.android.runtime/lib/libart.so (art::Thread::DumpStack(std::__1::basic_ostream<char, std::__1::char_traits<char>>&, bool, BacktraceMap*, bool) const+994)
2020-06-02 19:25:39.497 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #02 pc 005ace61  /apex/com.android.runtime/lib/libart.so (art::Thread::Dump(std::__1::basic_ostream<char, std::__1::char_traits<char>>&, bool, BacktraceMap*, bool) const+65)
2020-06-02 19:25:39.497 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #03 pc 005d2cd1  /apex/com.android.runtime/lib/libart.so (art::DumpCheckpoint::Run(art::Thread*)+929)
2020-06-02 19:25:39.497 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #04 pc 005cac06  /apex/com.android.runtime/lib/libart.so (art::ThreadList::RunCheckpoint(art::Closure*, art::Closure*)+486)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #05 pc 005c9e6c  /apex/com.android.runtime/lib/libart.so (art::ThreadList::Dump(std::__1::basic_ostream<char, std::__1::char_traits<char>>&, bool)+2268)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #06 pc 005796f0  /apex/com.android.runtime/lib/libart.so (art::AbortState::DumpAllThreads(std::__1::basic_ostream<char, std::__1::char_traits<char>>&, art::Thread*) const+448)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #07 pc 00564d30  /apex/com.android.runtime/lib/libart.so (art::Runtime::Abort(char const*)+1536)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #08 pc 000249b3  /apex/com.android.runtime/lib/libartbase.so (_ZNSt3__110__function6__funcIPFvPKcENS_9allocatorIS5_EES4_EclEOS3_+35)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #09 pc 0000bac7  /system/lib/libbase.so (android::base::LogMessage::~LogMessage()+727)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #10 pc 005645de  /apex/com.android.runtime/lib/libart.so (art::Runtime::DetachCurrentThread()+414)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #11 pc 003ecc83  /apex/com.android.runtime/lib/libart.so (art::JII::DetachCurrentThread(_JavaVM*)+67)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #12 pc 003e3445  /apex/com.android.runtime/lib/libart.so (art::(anonymous namespace)::CheckJII::DetachCurrentThread(_JavaVM*)+117)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #13 pc 00009d6a  /data/app/com.example.maths-alZFaEzd-BAd84VC19Fvrg==/lib/x86/libnative-lib.so (_JavaVM::DetachCurrentThread()+42)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #14 pc 00009a8a  /data/app/com.example.maths-alZFaEzd-BAd84VC19Fvrg==/lib/x86/libnative-lib.so (callback()+554)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #15 pc 0000a24c  /data/app/com.example.maths-alZFaEzd-BAd84VC19Fvrg==/lib/x86/libnative-lib.so (Java_com_example_maths_Maths1_createNumberInstance+172)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #16 pc 00144f67  /apex/com.android.runtime/lib/libart.so (art_quick_generic_jni_trampoline+71)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #17 pc 0013e7d2  /apex/com.android.runtime/lib/libart.so (art_quick_invoke_stub+338)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #18 pc 00149a69  /apex/com.android.runtime/lib/libart.so (art::ArtMethod::Invoke(art::Thread*, unsigned int*, unsigned int, art::JValue*, char const*)+281)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #19 pc 00332502  /apex/com.android.runtime/lib/libart.so (art::interpreter::ArtInterpreterToCompiledCodeBridge(art::Thread*, art::ArtMethod*, art::ShadowFrame*, unsigned short, art::JValue*)+386)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #20 pc 0032c19c  /apex/com.android.runtime/lib/libart.so (bool art::interpreter::DoCall<false, false>(art::ArtMethod*, art::Thread*, art::ShadowFrame&, art::Instruction const*, unsigned short, art::JValue*)+988)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #21 pc 006818dd  /apex/com.android.runtime/lib/libart.so (MterpInvokeVirtual+989)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #22 pc 00138821  /apex/com.android.runtime/lib/libart.so (mterp_op_invoke_virtual+33)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #23 pc 0011dc02  [anon:dalvik-classes.dex extracted in memory from /data/app/com.example.maths-alZFaEzd-BAd84VC19Fvrg==/base.apk] (com.example.maths.Maths1.<init>+26)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #24 pc 0068461c  /apex/com.android.runtime/lib/libart.so (MterpInvokeDirect+1324)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #25 pc 00138921  /apex/com.android.runtime/lib/libart.so (mterp_op_invoke_direct+33)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #26 pc 0011db02  [anon:dalvik-classes.dex extracted in memory from /data/app/com.example.maths-alZFaEzd-BAd84VC19Fvrg==/base.apk] (com.example.maths.MainActivity.onCreate+26)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #27 pc 00681b4c  /apex/com.android.runtime/lib/libart.so (MterpInvokeVirtual+1612)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #28 pc 00138821  /apex/com.android.runtime/lib/libart.so (mterp_op_invoke_virtual+33)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #29 pc 0019175e  /system/framework/framework.jar (android.app.Activity.performCreate+30)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #30 pc 00681b4c  /apex/com.android.runtime/lib/libart.so (MterpInvokeVirtual+1612)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #31 pc 00138821  /apex/com.android.runtime/lib/libart.so (mterp_op_invoke_virtual+33)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #32 pc 00191726  /system/framework/framework.jar (android.app.Activity.performCreate+2)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #33 pc 00681b4c  /apex/com.android.runtime/lib/libart.so (MterpInvokeVirtual+1612)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #34 pc 00138821  /apex/com.android.runtime/lib/libart.so (mterp_op_invoke_virtual+33)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #35 pc 001eefda  /system/framework/framework.jar (android.app.Instrumentation.callActivityOnCreate+6)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #36 pc 00681b4c  /apex/com.android.runtime/lib/libart.so (MterpInvokeVirtual+1612)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #37 pc 00138821  /apex/com.android.runtime/lib/libart.so (mterp_op_invoke_virtual+33)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #38 pc 00180bb8  /system/framework/framework.jar (android.app.ActivityThread.performLaunchActivity+752)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #39 pc 0068461c  /apex/com.android.runtime/lib/libart.so (MterpInvokeDirect+1324)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #40 pc 00138921  /apex/com.android.runtime/lib/libart.so (mterp_op_invoke_direct+33)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #41 pc 00180836  /system/framework/framework.jar (android.app.ActivityThread.handleLaunchActivity+94)
2020-06-02 19:25:39.498 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #42 pc 00681b4c  /apex/com.android.runtime/lib/libart.so (MterpInvokeVirtual+1612)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #43 pc 00138821  /apex/com.android.runtime/lib/libart.so (mterp_op_invoke_virtual+33)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #44 pc 0025e28e  /system/framework/framework.jar (android.app.servertransaction.LaunchActivityItem.execute+126)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #45 pc 00681b4c  /apex/com.android.runtime/lib/libart.so (MterpInvokeVirtual+1612)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #46 pc 00138821  /apex/com.android.runtime/lib/libart.so (mterp_op_invoke_virtual+33)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #47 pc 002607da  /system/framework/framework.jar (android.app.servertransaction.TransactionExecutor.executeCallbacks+154)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #48 pc 00681b4c  /apex/com.android.runtime/lib/libart.so (MterpInvokeVirtual+1612)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #49 pc 00138821  /apex/com.android.runtime/lib/libart.so (mterp_op_invoke_virtual+33)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #50 pc 00260716  /system/framework/framework.jar (android.app.servertransaction.TransactionExecutor.execute+146)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #51 pc 00681b4c  /apex/com.android.runtime/lib/libart.so (MterpInvokeVirtual+1612)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #52 pc 00138821  /apex/com.android.runtime/lib/libart.so (mterp_op_invoke_virtual+33)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #53 pc 0017fb6e  /system/framework/framework.jar (android.app.ActivityThread$H.handleMessage+78)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #54 pc 00681b4c  /apex/com.android.runtime/lib/libart.so (MterpInvokeVirtual+1612)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #55 pc 00138821  /apex/com.android.runtime/lib/libart.so (mterp_op_invoke_virtual+33)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #56 pc 002f5846  /system/framework/framework.jar (android.os.Handler.dispatchMessage+38)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #57 pc 00681b4c  /apex/com.android.runtime/lib/libart.so (MterpInvokeVirtual+1612)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #58 pc 00138821  /apex/com.android.runtime/lib/libart.so (mterp_op_invoke_virtual+33)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #59 pc 00319ee6  /system/framework/framework.jar (android.os.Looper.loop+466)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #60 pc 00684fdc  /apex/com.android.runtime/lib/libart.so (MterpInvokeStatic+1260)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #61 pc 001389a1  /apex/com.android.runtime/lib/libart.so (mterp_op_invoke_static+33)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #62 pc 00189466  /system/framework/framework.jar (android.app.ActivityThread.main+194)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #63 pc 002f8e0a  /apex/com.android.runtime/lib/libart.so (_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_6JValueEbb.llvm.1175793267244191248+298)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #64 pc 002ffcc5  /apex/com.android.runtime/lib/libart.so (art::interpreter::EnterInterpreterFromEntryPoint(art::Thread*, art::CodeItemDataAccessor const&, art::ShadowFrame*)+181)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #65 pc 0066fc49  /apex/com.android.runtime/lib/libart.so (artQuickToInterpreterBridge+1209)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #66 pc 0014503d  /apex/com.android.runtime/lib/libart.so (art_quick_to_interpreter_bridge+77)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #67 pc 0013e9a2  /apex/com.android.runtime/lib/libart.so (art_quick_invoke_static_stub+418)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #68 pc 00149a7a  /apex/com.android.runtime/lib/libart.so (art::ArtMethod::Invoke(art::Thread*, unsigned int*, unsigned int, art::JValue*, char const*)+298)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #69 pc 0055a563  /apex/com.android.runtime/lib/libart.so (art::(anonymous namespace)::InvokeWithArgArray(art::ScopedObjectAccessAlreadyRunnable const&, art::ArtMethod*, art::(anonymous namespace)::ArgArray*, art::JValue*, char const*)+99)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #70 pc 0055c37f  /apex/com.android.runtime/lib/libart.so (art::InvokeMethod(art::ScopedObjectAccessAlreadyRunnable const&, _jobject*, _jobject*, _jobject*, unsigned int)+1327)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #71 pc 004c91a3  /apex/com.android.runtime/lib/libart.so (art::Method_invoke(_JNIEnv*, _jobject*, _jobject*, _jobjectArray*)+83)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   at com.example.maths.Maths1.createNumberInstance(Native method)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   at com.example.maths.Maths1.<init>(Maths1.java:16)
2020-06-02 19:25:39.499 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   at com.example.maths.MainActivity.onCreate(MainActivity.java:21)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630] "Runtime worker thread 0" prio=10 tid=2 Native (still starting up)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   | group="" sCount=1 dsCount=0 flags=1 obj=0x0 self=0xd9500000
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   | sysTid=15991 nice=0 cgrp=default sched=0/0 handle=0xec77fd90
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   | state=S schedstat=( 1604515 798906 8 ) utm=0 stm=0 core=1 HZ=100
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   | stack=0xec771000-0xec773000 stackSize=63KB
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   | held mutexes=
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   kernel: (couldn't read /proc/self/task/15991/stack)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #00 pc 00000b77  [vdso] (__kernel_vsyscall+7)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #01 pc 00092328  /apex/com.android.runtime/lib/bionic/libc.so (syscall+40)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #02 pc 00150802  /apex/com.android.runtime/lib/libart.so (art::ConditionVariable::WaitHoldingLocks(art::Thread*)+114)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #03 pc 00150783  /apex/com.android.runtime/lib/libart.so (art::ConditionVariable::Wait(art::Thread*)+35)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #04 pc 005d4b15  /apex/com.android.runtime/lib/libart.so (art::ThreadPool::GetTask(art::Thread*)+261)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #05 pc 005d3c43  /apex/com.android.runtime/lib/libart.so (art::ThreadPoolWorker::Run()+83)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #06 pc 005d370f  /apex/com.android.runtime/lib/libart.so (art::ThreadPoolWorker::Callback(void*)+239)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #07 pc 0011a8e5  /apex/com.android.runtime/lib/bionic/libc.so (__pthread_start(void*)+53)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #08 pc 000af6a7  /apex/com.android.runtime/lib/bionic/libc.so (__start_thread+71)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   (no managed stack frames)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630] "Jit thread pool worker thread 0" prio=10 tid=3 Native
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   | group="" sCount=1 dsCount=0 flags=1 obj=0x159c0030 self=0xec98ee00
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   | sysTid=15990 nice=0 cgrp=default sched=0/0 handle=0xd9404d90
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   | state=S schedstat=( 4160010 1789692 15 ) utm=0 stm=0 core=1 HZ=100
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   | stack=0xd9306000-0xd9308000 stackSize=1023KB
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   | held mutexes=
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   kernel: (couldn't read /proc/self/task/15990/stack)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #00 pc 00000b77  [vdso] (__kernel_vsyscall+7)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #01 pc 00092328  /apex/com.android.runtime/lib/bionic/libc.so (syscall+40)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #02 pc 00150802  /apex/com.android.runtime/lib/libart.so (art::ConditionVariable::WaitHoldingLocks(art::Thread*)+114)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #03 pc 00150783  /apex/com.android.runtime/lib/libart.so (art::ConditionVariable::Wait(art::Thread*)+35)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #04 pc 005d4b15  /apex/com.android.runtime/lib/libart.so (art::ThreadPool::GetTask(art::Thread*)+261)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #05 pc 005d3c75  /apex/com.android.runtime/lib/libart.so (art::ThreadPoolWorker::Run()+133)
2020-06-02 19:25:39.500 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #06 pc 005d370f  /apex/com.android.runtime/lib/libart.so (art::ThreadPoolWorker::Callback(void*)+239)
2020-06-02 19:25:39.501 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #07 pc 0011a8e5  /apex/com.android.runtime/lib/bionic/libc.so (__pthread_start(void*)+53)
2020-06-02 19:25:39.501 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   native: #08 pc 000af6a7  /apex/com.android.runtime/lib/bionic/libc.so (__start_thread+71)
2020-06-02 19:25:39.501 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   (no managed stack frames)
2020-06-02 19:25:39.501 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]
2020-06-02 19:25:39.501 15965-15965/com.example.maths A/m.example.math: runtime.cc:630] "Runtime worker thread 1" prio=10 tid=4 Native (still starting up)
2020-06-02 19:25:39.501 15965-15965/com.example.maths A/m.example.math: runtime.cc:630]   | group="" sCount=1 dsCount=0 flags=1 obj=0x0 self=0xd9508c00

A: If GetEnv returns JNI_OK, the current thread is already attached and you should not try to detach it.
This is why Android is screaming bloody murder at you: you are trying to detach the main thread!
You should only try to attach (and detach later) if it returned JNI_EDETACHED.


text:
Q: Why did the ajax call failed.The code below redirects to authenticate.php instead of echoeing text to login.html This is the markup

    Competitive Exams

    <form action="authenticate.php" method="get" id="login">

Login

<input type="text" name="username" placeholder="Username" >

<input type="password" name="password" placeholder="Password">

<input type="submit" value="MoveIn">

    </form>

    Copyright &copy 2013.All Rights Reserved.Created by :HACKSHAK & I-GOOGLEPLAY.

/This is the javascript code for ajax call/
window.onload = function(){
var form   = document.getElementById('login');
var output = document.getElementById('show');

form.onsubmit = function(e){
    e.preventDefault();
    var action = form.action;
    var method = form.method;
    var data   = {};
    var names =  document.querySelectorAll('#login [name]');

        for(var i=0;i<2;i++){
            var name   = names[i].name;
            var value  = names[i].value;
                data[name] = value;
        }

        var transmit = new Transmit(method,action,data,output).bind(transmit);

}

function Transmit(method,action,data,output){
    this.method = method;
    this.action = action;
    this.data   = data;
    this.output = output;

    var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    alert(xhr);
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4 && xhr.status == 200){
            this.output.innerHTML     = xhr.responseText;
            this.output.style.display = "inline-block";
        }
    }

    xhr.open(this.method,this.action?this.data,true);
    xhr.send();
}

}
when I run the code even after the default behaviour of the form is prevented it redirects to authenticate.php instead of making ajax call.

A: From the JS error console:

Uncaught SyntaxError: Unexpected token ,

You start a ternary operator here, but never finish it:
xhr.open(this.method,this.action?this.data,true);

Consequently, the function you assign to onload never gets properly parsed, so it never gets assigned, so you never assign your submit event.
It looks like you are trying to construct a query string, but getting it entirely wrong.
You need to loop over the object, encodeURIComponent all the keys and values, and then concatenate them (via +) using = and & characters before concatenating (again with +) to the action and the string "?".
Authentication should generally be done with a POST request rather than a GET request though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Integral of a function defined in the set of Surreal Numbers Given ${\{C}\}\ $ the set of all the $Surreal\  numbers$, is it possible to define the integral:
$$\int_a^b{dxf(x)}$$where
$$a\in{\{C}\},b\in{\{C}\},x\in{\{C}\}$$
Thanks

A: There is some discussion of this topic at the very end of the second edition (2000) On Numbers and Games by Conway.  He describes work by himself, Simon Norton, and Martin Kruskal to define integration. According to the description, it looked good for a while, producing workable logarithm function in terms of the integral of $x^{-1}$, but then got stuck, and finally:

For twenty years we believed that the definition was nevertheless probably "correct" in some natural sense, and that these difficulties arose merely because we did not understand exactly which genetic definitions were "legal" to use in it.

Kruskal has now made some progress of a rather sad kind by showing that this belief was false. Namely, the definition integrates $e^t$ over the range $[0, \omega]$ to the wrong answer, $e^\omega$, rather than $e^\omega-1$, independent of whatever reasonable genetic definition we give for the exponential function.

(Page 228.)
There is other discussion of the details in the same section.  I do not know whether any progress has been made since then.

A: As of yesterday, there may be a new development.
"Integration on the Surreals" (Ovidiu Costin, Philip Ehrlich):

Conway's real closed field No of surreal numbers is a sweeping generalization of the real numbers and the ordinals to which a number of elementary functions such as log and exponentiation have been shown to extend. The problems of identifying significant classes of functions that can be so extended and of defining integration for them have proven to be formidable. In this paper, we address this and related unresolved issues by showing that extensions to No, and thereby integrals, exist for most functions arising in practical applications. In particular, we show they exist for a large subclass of the resurgent functions, a subclass that contains the functions that at infinity are semi-algebraic, semi-analytic, analytic, meromorphic, and Borel summable as well as generic solutions to linear and nonlinear systems of ODEs possibly having irregular singularities. We further establish a sufficient condition for the theory to carry over to ordered exponential subfields of No more generally and illustrate the result with structures familiar from the surreal literature. We work in NBG less the Axiom of Choice (for both sets and proper classes), with the result that the extensions of functions and integrals that concern us here have a "constructive" nature in this sense. In the Appendix it is shown that the existence of such constructive extensions and integrals of substantially more general types of functions (e.g. smooth functions) is obstructed by considerations from the foundations of mathematics.

The paper has not been published or formally peer-reviewed. But even if it doesn't hold up, its bibliography will be valuable to someone interested in this topic.


text:
Q: Array becomes undefined when passed to function React js , socket.io
I'm trying to pass an array to a function and use it, somehow the array becomes undefined when passed to the function i don't know what i'm doing wrong. I'm using react js and Socket.io the code in question is below:

socket.on(PRIVATE_MESSAGE, ({reciever, sender})=>{
  if(reciever in connectedUsers){
      var users = [reciever, sender]
      console.log("users: " + users )
   const newChat = factories.createNewConversation(`${reciever}&${sender}`, users)
      }
 })

Here i'm passing the users array to the function createNewConversation, when i print the array before i pass it, it works fine.

function createNewConversation(Messages, Name, Users) {
 var conversationID = uuidv4()
 console.log("user found: " + Users)
              .
              .
              .
 }

here when i try to print the Users array it says its undefined. I've looked around but couldn't find an answer. any help would be really appreciated


text:
Q: How to include font-awesome in codeigniter i have include font-awesome but icons are show square box..
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/css/font-awesome.css') ?>">

please help me

A: You can't use base_url() or site_url() for font-awesome.css only because of:
@font-face {
font-family: 'FontAwesome';
  src: url('../fonts/fontawesome-webfont.eot?v=4.6.3');
  src: url('../font-awesome-4.6.3/fonts/fontawesome-webfont.eot?#iefix&v=4.6.3') format('embedded-opentype'), url('../font-awesome-4.6.3/fonts/fontawesome-webfont.woff2?v=4.6.3') format('woff2'), url('../fonts/fontawesome-webfont.woff?v=4.6.3') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.6.3') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.6.3#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}

Solution 1. If you don't want to download font-awesome, you can use:
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
Of course this always works. Disanvantage of solution 1 is the dependence on the internet connection.
Solution 2. First of all, you must download all files of fontawesome(svg, woff, eot,...) and put them all in a folder - for example, let the name of the folder be fontawesome.
Then, you must remove the following code from the file font-awesome.css
@font-face {
    font-family: 'FontAwesome';
      src: url('../fonts/fontawesome-webfont.eot?v=4.6.3');
      src: url('../font-awesome-4.6.3/fonts/fontawesome-webfont.eot?#iefix&v=4.6.3') format('embedded-opentype'), url('../font-awesome-4.6.3/fonts/fontawesome-webfont.woff2?v=4.6.3') format('woff2'), url('../fonts/fontawesome-webfont.woff?v=4.6.3') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.6.3') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.6.3#fontawesomeregular') format('svg');
      font-weight: normal;
      font-style: normal;
    }

After that, you copy them into the <style></style> of the .html or .php file, which you want to implement font-awesome. But you must change the src as follow:
@font-face {
    font-family: 'FontAwesome';
      src: url('<?=site_url('fontawesome/fontawesome-webfont.eot?v=4.6.3'); ?>');
      src: url('<?=site_url('fontawesome/fontawesome-webfont.eot?#iefix&v=4.6.3') ; ?>') format('embedded-opentype'), url('<?=site_url('fontawesome/fontawesome-webfont.woff2?v=4.6.3');?>') format('woff2'), url('<?=site_url('fontawesome-webfont.woff?v=4.6.3'); ?>') format('woff'), url('<?=site_url('fontawesome/fontawesome-webfont.ttf?v=4.6.3'); ?>') format('truetype'), url('<?=site_url('fontawesome/fontawesome-webfont.svg?v=4.6.3#fontawesomeregular'); ?>') format('svg');
      font-weight: normal;
      font-style: normal;
    }

and remember to add these in your .html, .php too:
<link rel="stylesheet" type="text/css" href="<?=site_url("fontawesome/font-awesome.css"); ?>" />

And including glyphicon of bootstrap is totally similar.

A: fontawesome is not only single css file it include more file internally so if you want to do it in offline you have to put all file related to font awesome like fonts or use online link is better option
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

A: Hosting on your server
Click here to Download Font-Awesome
Extract the downloaded ZIP into your Codeigniter Directory. I assumed you have extracted FontAwesome in plugin/font-awesome/
Code to include the file in view:
<link rel="stylesheet" type="text/css" href="<?php echo base_url('plugin/font-awesome/css/font-awesome.min.css'); ?>">

Using CDN Hosted
Simply Add this code into your view
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

A: If you dont want the cdn then you can do this.
open the css file (in fontawesome/css) and change the url source of all font files.
this block
@font-face {

font-family: 'FontAwesome';
  src: url('../fonts/fontawesome-webfont.eot?v=4.6.3');
  src: url('../font-awesome-4.6.3/fonts/fontawesome-webfont.eot?#iefix&v=4.6.3') format('embedded-opentype'), url('../font-awesome-4.6.3/fonts/fontawesome-webfont.woff2?v=4.6.3') format('woff2'), url('../fonts/fontawesome-webfont.woff?v=4.6.3') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.6.3') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.6.3#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}

to
@font-face {
  font-family: 'FontAwesome';
  src: url('domainName/fonts/fontawesome-webfont.eot?v=4.6.3');
  src: url('domainName/fonts/fontawesome-webfont.eot?#iefix&v=4.6.3') format('embedded-opentype'), url('domainName/fonts/fontawesome-webfont.woff2?v=4.6.3') format('woff2'), url('domainName/fonts/fontawesome-webfont.woff?v=4.6.3') format('woff'), url('domainName/fonts/fontawesome-webfont.ttf?v=4.6.3') format('truetype'), url('http://localhost/khloe/assets/font-awesome-4.6.3/fonts/fontawesome-webfont.svg?v=4.6.3#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}

A: There is not a difference, you are still able to use the following code:
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

You can also include it via the CSS file by adding:
@import url("https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css");

A: Try this..
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/css/font-awesome.css">

and set your base_url in your config file like this
$config['base_url'] = 'http://domain.com/websiteroot/';

A: Firstly I would recommend that you inspect your browser if there are any errors by pressing F12 on Chrome.

Make sure that the URL corresponds to the place you have put your font awesome folder: e.g.
Project
--Application
--Assets
----CSS
------font awesome
--------CSS
----------fontawesome.css
--system
If the path is correct then go to font awesome website to check the code of the icon you want, every icon you choose will have an example of how to use it.
https://fontawesome.com/icons?d=gallery
Hope that helps


text:
Q: Customize Laravel error reporting to remove stack trace How can you turn off or remove the stack traces from Laravel's error reports. They're annoying if you want to read them in your console. I know you can add a custom handler in app/Exceptions/Handler.php, but I have no idea how to do that.

A: For those who don't like "add this, remove that" kind of instructions, here's what app/Exceptions/Handler.php should look like, based on Laravel 5.7, and sticking to a message format like PHP's native one:
<?php

namespace App\Exceptions;

use Log;
use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Auth\AuthenticationException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Report or log an exception.
     *
     * @param  \Exception  $exception
     * @return void
     */
    public function report(Exception $exception)
    {
        Log::error(sprintf(
            "Uncaught exception '%s' with message '%s' in %s:%d",
            get_class($exception),
            $exception->getMessage(),
            $exception->getTrace()[0]['file'],
            $exception->getTrace()[0]['line']
        ));
        // parent::report($exception);
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Exception  $exception
     * @return \Illuminate\Http\Response
     */
    public function render($request, Exception $exception)
    {
        return parent::render($request, $exception);
    }
}

Note that you can replace Log::error() with a simple call to error_log() to write to PHP's standard error log. If you do that, you don't have to remove the call to parent::report(). That way you can keep the traces in the Laravel log for further debugging, but keep your main PHP log for quick checks.

A: Setting APP_DEBUG=false in your .env file works fine for the frontend.
If you don't want the stack trace lines to be outputted in the log files only, try this.
In /app/Exceptions/Handler.php add use Log; at the top, then add this in the report function:
Log::error('['.$e->getCode().'] "'.$e->getMessage().'" on line '.$e->getTrace()[0]['line'].' of file '.$e->getTrace()[0]['file']);

And remove:
parent::report($e);

More info: https://laracasts.com/discuss/channels/laravel/remove-stacktrace-from-log-files

A: Since I can not comment on or edit @Harold answer, here is a improved sollution:

*

*In /app/Exceptions/Handler.php add use Log; at the top,

*Then modify the report function:

    public function report(Exception $e)
    {
        if (!config('app.debug')) {
            Log::error('['.$e->getCode().'] "'.$e->getMessage().'" on line '.$e->getTrace()[0]['line'].' of file '.$e->getTrace()[0]['file']);
        } else {
            parent::report($e);
        }
    }

A: Another way is to edit the log format in your logging config file. This means you don't have to override the default report function which would mean missing out on other logic within the parent function.
I set mine to this:
 'daily' => [
        'driver' => 'daily',
        'formatter' =>LineFormatter::class,
        'formatter_with' => [
            'format' => "[%datetime%] %channel%.%level_name%: %message%\n %context%\n",
            'dateFormat' => "Y-m-d H:i:s"
        ],
        'path' => storage_path('logs/laravel.log'),
        'level' => env('LOG_LEVEL', 'debug'),
        'days' => 14,
    ],

A: Harold and Jani's answers are correct.
However the log line is less detailed than the default one.
The best solution would be to edit the file:

vendor/laravel/frameworks/src/Illuminate/Log/LogManager.php

and add false argument when the includeStacktraces method is called.
add false to

$formatter->includeStacktraces();

so:

$formatter->includeStacktraces(false);

This will simply disable the stacktrace. Everything else remains the same.

A: simplely set your APP_DEBUG=false in your env file.


text:
Q: Angular: How to change/set current page of jw-pagination? I'm having a problem with jw-angular-pagination. I was adding custom sort function when I found that I have no control over the page of pagination. I wonder how to change selected page to first after sorting?
My code (simplified):
HTML:
<div *ngFor="let result of pageOfItems">
  // ...
</div>
<jw-pagination class="fadeIn" [items]="affiliates" (changePage)="onChangePage($event)" [pageSize]="pageSize"></jw-pagination>

TS:
affiliates: any[]; // Let's say there are data already
pageOfItemsAffiliates: any;
pageSize = 10;
currentPage = 1;

constructor() {}

onChangePageAffiliates(pageOfItems: Array<any>) {
  this.pageOfItemsAffiliates = pageOfItems;
}

onClickSort(by: string) {
  this.affiliates = this.affiliates.sort((a, b) => {
    return a.totalBalance > b.totalBalance ? -1 : 1;
  });

  this.pageOfItemsAffiliates = this.affiliates.slice(0, this.pageSize);
  this.currentPage = 1;
}

So when I click page 2, then sort, it will show first 10 elements sorted but jw-pagination widget will still be showing page 2 as active (while the truth is it's showing the first page). How to make it work properly?

A: For now I have achieved it with kind of workaround. Simulating click on first page button. This button is disabled while first page is selected but it doesn't seem to be an issue.
  changeSelectedPageToFirst() {
    let firstElement: HTMLElement = document.getElementsByClassName('first-item')[0] as HTMLElement;
    let clickFirst = firstElement.children[0] as HTMLElement;
    clickFirst.click();
  }

Anyways, still I belive there's some better way to do this?


text:
Q: Adding recursive functionality to a json merge script in php How do I recursively access all json files?
The below code finds all the json files in a single directory and merges them into a single file.
I now have a hierarchical folder structure, how do I adapt the following to cycle through all the directories under the root directory json/bones?
<?php
    $files = glob("json/bones/*.json");
    //Create an empty new array
    $newDataArray = [];
    //Get the contents of each file
    foreach($files as $file){
        $thisData = file_get_contents($file);
        //Decode the json
        $thisDataArray = json_decode($thisData);
        //Add $thisData to the new array
        $newDataArray[] = $thisDataArray;
    }
    //Encode the array to JSON
    $newDataJSON = json_encode($newDataArray);
    file_put_contents("json/data.json",$newDataJSON);
?>

edit - new code:
<?php
    $directory = ("json/data/")
    $scan_dir = scandir ( string $directory [, int $sorting_order = SCANDIR_SORT_ASCENDING [, resource $context ]] ) : array;
      //Create an empty new array

    $newDataArray = [];
    //Get the contents of each file
    // foreach($files as $file){
    foreach($scan_dir as $file){
       $thisData = file_get_contents($file);
        //Decode the json
        $thisDataArray = json_decode($thisData);
        //Add $thisData to the new array
        $newDataArray[] = $thisDataArray;
    }
    //Encode the array to JSON
    $newDataJSON = json_encode($newDataArray);
    file_put_contents("json/data.json",$newDataJSON);
?>

Further edit:
This now presents a permissions error file_get_contents(.): failed to open stream: Permission denied it had no issues before.
<?php
  $dir = "../../json/data/";
  echo "
directory: ".$dir."
";
  $files = scandir($dir);
  //Create an empty new array
  $newDataArray = [];
  //Get the contents of each file
  // foreach($files as $file){
  foreach($files as $file){
      $thisData = file_get_contents($file);
      //Decode the json
      $thisDataArray = json_decode($thisData);
      //Add $thisData to the new array
      $newDataArray[] = $thisDataArray;
  }
  //Encode the array to JSON
  $newDataJSON = json_encode($newDataArray);
  file_put_contents("data.json",$newDataJSON);
?>

A: This did the trick
$rii = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('../../json/data/'));

$files = array();

foreach ($rii as $file) {
    if ($file->isDir()){
        continue;
    }
    $files[] = $file->getPathname();
}

var_dump($files);

  // $dir = "../../json/data/";
  // echo "
directory: ".$dir."
";
  // $files = scandir($dir);
  //Create an empty new array
  $newDataArray = [];
  //Get the contents of each file
  // foreach($files as $file){
  foreach($files as $file){
      $thisData = file_get_contents($file);
      //Decode the json
      $thisDataArray = json_decode($thisData);
      //Add $thisData to the new array
      $newDataArray[] = $thisDataArray;
  }
  //Encode the array to JSON
  $newDataJSON = json_encode($newDataArray);
  file_put_contents("gfgdata.json",$newDataJSON);


text:
Q: How to run a jl file (julia) in R I know that the  JuliaCall package allows to us use the Julia language in R. But I have a jl script with complex instructions and I would like to run in the R language!
For example, suposse that my jl file is "myscript.jl" return a certain array A.
#install.packages("JuliaCall")
library(JuliaCall)

Is there some function to run the jl file?
A <- somefunction("myscript.jl")

some help?

A: It is indeed quite simple if you have Julia on path.
First create a file juliaScripts.jl with content:
function getAnElement(array,n)
    return array[n]
end

Then in R you just do:
> install.packages("JuliaCall")
> library(JuliaCall)
> julia_setup() # on every new R session !
> julia_source("juliaScript.jl")
> out <- julia_call("getAnElement",c(10,20,30),2)
> out
[1] 20

Note that the R vector has been automatically converted to a Julia Array.
Not to make advertising, but more details on interfacing R <-> Julia are on my Apress(2019) book "Julia Quick Syntax reference" on Chapter 7 "Interfacing Julia with other languages" (I shouldn't say it, but you can easily find the pdf online in well-known sites...)


text: Q: What does it mean to say two matrices are conjugate? I was asked to find two 2 x 2 matrices over $R$ which have the same characteristic polynomial but which are not conjugate. What does it mean to say two matrices are conjugate in this context?


text:
Q: What unit types can enter bunkers in SC2? I know that in melee, SCVs, marines, marauders, ghosts and reapers can enter a bunker (and I assume so can medics, firebats and spectres in the single-player). Can any other unit types enter a bunker? In particular, can any non-Terran unit enter it? (assuming it somehow got under your control in the first place)
And if any other unit can enter a bunker, how much space does it take? Same as with transports?

A: Any Terran Infantry unit can enter a bunker. Bunkers are restricted to Terran units exclusively, so you'll have to find another secret place if you want to cuddle zerglings in private.

None of the units in the above picture could join the bunker party.


text:
Q: Access copyright info on Wikimedia Commons via api I would like to use the MediaWiki API to get the copyright info for an image.
When you click on an image in Wikipedia, the page with the image is opened containing a button "more details". Clicking this button you come to a page which contains a "Use this file on the web" link. Clicking this link (runs the script "stockPhoto.call_web();" which) shows a window with the information I would like to get via a MediaWiki API call.
I have been looking at "action=query" and all kinds of properties, but couldn't find the desired information. Any idea?

A: You can combine action=query with prop=imageinfo and iiprop=extmetadata to get the information. Perhaps also combine it with iiextmetadatafilter=LicenseShortName to get it more readable, example: https://en.wikipedia.org/w/api.php?format=jsonfm&action=query&titles=File:30C3_Commons_Machinery_2.jpg&prop=imageinfo&iiprop=extmetadata%7Curl&iiextmetadatafilter=LicenseShortName
However, not all image files have data like this yet but probably a large enough amount to be useful. Do prepare to find images with no answer.


text:
Q: how to transfert informations from one view to another i have this view in my app
http://hpics.li/ce94f6c
the user should put the fly number and he will get informations taht i got from a web service in the table view .
But this table view is small and i want to make one at the height and width of the vie .
Should i hide the label and button and then show the large table view ?
Or should i make a new xib and load it when the user click the button ?
or should i create a new tableviewcontroller with .xib and send to him the json to parase and put in the table view ?
help please

A: What you can do is to go with your second option.

*

*You can firstly create a ViewController where you have a label and a button field. (You should also put some image is this case as having only a button and a label on complete screen will seem to be odd).

*Once you click the button you can call the web service and then navigate to a new viewController where you can display web results in a tableView.


text:
Q: How to append keys which are not previously in dataframe 1 but are in dataframe 2 against each name I have a Dataframe df1 like this
    id  name  day  marks  mean_marks
0   1  John  Wed     28          28
1   1  John  Fri     30          30
2   2  Alex  Fri     40          50
3   2  Alex  Fri     60          50

and another dataframe df2 as:
    day  we
 0  Mon  29
 1  Wed  21
 2  Fri  31

now when i do :
z = pd.merge(df1, df2, how='outer', on=['day']).fillna(0)

i got:
    id  name  day  marks  mean_marks    we
0  1.0  John  Wed   28.0        28.0    21
1  1.0  John  Fri   30.0        30.0    31
2  2.0  Alex  Fri   40.0        50.0    31
3  2.0  Alex  Fri   60.0        50.0    31
4  0.0     0  Mon    0.0         0.0    29

but i wanted something which would look like :
    id  name  day  marks  mean_marks    we
0  1.0  John  Wed   28.0        28.0    21
1  1.0  John  Mon   0.0         0.0     29
2  1.0  John  Fri   30.0        30.0    31
3  2.0  Alex  Mon   0.0         0.0     29
4  2.0  Alex  Wed   0.0         0.0     21
5  2.0  Alex  Fri   40.0        50.0    31
6  2.0  Alex  Fri   60.0        50.0    31

that is 'day' which are not previously in df1 but are in df2 should be appended to day against each name.
Can someone please help me with this.

A: You might need a cross join to create all combinations of days per id and name , then merge should work:
u = df1[['id','name']].drop_duplicates().assign(k=1).merge(df2.assign(k=1),on='k')
out = df1.merge(u.drop('k',1),on=['day','name','id'],how='outer').fillna(0)

print(out.sort_values(['id','name']))

   id  name  day  marks  mean_marks  we
0   1  John  Wed   28.0        28.0  21
1   1  John  Fri   30.0        30.0  31
4   1  John  Mon    0.0         0.0  29
2   2  Alex  Fri   40.0        50.0  31
3   2  Alex  Fri   60.0         5.0  31
5   2  Alex  Mon    0.0         0.0  29
6   2  Alex  Wed    0.0         0.0  21

A: The following code should do it:
z = df1.groupby(['name']).apply(lambda grp: grp.merge(df2, how='outer', on='day').
                                fillna({'name': grp.name, 'id': grp.id})).reset_index(drop=True).fillna(0)

It gives the following output:
    id  name  day marks mean_marks  we
0  2.0  Alex  Fri    40         50  31
1  2.0  Alex  Fri    60         50  31
2  2.0  Alex  Mon     0          0  29
3  2.0  Alex  Wed     0          0  21
4  1.0  John  Wed    28         28  21
5  1.0  John  Fri    30         30  31
6  1.0  John  Mon     0          0  29

A: you can create df3 with all names and day combination:
df3 = pd.DataFrame([[name, day] for name in df1.name.unique() for day in df2.day.unique()], columns=['name', 'day'])

Then add id's from df1:
df3 = df3.merge(df1[['id', 'name']]).drop_duplicates()[['id', 'name', 'day']]

Then add marks and mean marks from df1:
df3 = df3.merge(df1, how='left')

Then merge:
z = df3.merge(df2, how='outer', on=['day']).fillna(0).sort_values('id')

Out:
    id  name    day marks   mean_marks  we
0   1   John    Mon 0.0     0.0         29
2   1   John    Wed 28.0    28.0        21
4   1   John    Fri 30.0    30.0        31
1   2   Alex    Mon 0.0     0.0         29
3   2   Alex    Wed 0.0     0.0         21
5   2   Alex    Fri 40.0    50.0        31
6   2   Alex    Fri 60.0    50.0        31

A: To have the result ordered by weekdays (within each group by id), we should
convert day column in both DataFrames to Categorical type.
I think, it is better than in your original concept, where you don't care
about the days order.
To  do it, run:
wDays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
days = pd.Categorical(wDays, wDays, ordered=True)
df1.day = df1.day.astype(days)
df2.day = df2.day.astype(days)

Then define the following function, performing merge within a group
by id and filling NaN values (using either ffill or fillna):
def myMerge(grp):
    res = pd.merge(grp, df2, how='right', on=['day'])
    res[['id', 'name']] = res[['id', 'name']].ffill()
    res[['marks', 'mean_marks']] = res[['marks', 'mean_marks']].fillna(0)
    return res.sort_values('day')

Then group df1 by id and apply the above function to each group:
df1.groupby('id', sort=False).apply(myMerge).reset_index(drop=True)

The final step above is reset_index, to re-create "ordinary" index.
I added also sort=False to keep your desired (original) order of groups.


text:
Q: Weird error with JAXB when unmarshalling two XML strings, one succeeds and the other fails with JAXBException: Implementation of JAXB-API not found I'm working on a project built with Spring Boot (v.2.7.5) with Java 17 that has to handle XML's. It's generating sources from a whole bunch of XSD-files and uploads XML's to a third party using an API. It has to handle both marshalling and unmarshaling of XML with namespaces etc. That isn't an issue though.
There is a part of the application where a file is fetched from disk, unmarshalled to a Java object, which is of one of the generated classes types, then some information is added to the object using one of it's setters and then the xml content is uploaded to a third party using an API.
The problem is that when the application has two files to unmarshall almost simultaneously (they are handled as separate scheduled jobs by Spring Boot so they are not handled within the same function or anything like that) one of them succeeds and the other (second one in order being processed) throws the exception:
javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
...
Caused by: java.lang.ClassNotFoundException: com.sun.xml.bind.v2.ContextFactory
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
    at javax.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:92)
    at javax.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:125)
    at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:230)

This is super weird! How can it succeed even once if a JAXB-API implementation isn't on the classpath?!
The application is built using Gradle and the build.gradle has among others the following contents:
dependencies {
    ....

    // JAXB
    implementation "javax.xml.bind:jaxb-api:2.3.1"
    runtimeOnly "com.sun.xml.bind:jaxb-impl:2.3.3"
}

So clearly an implementation of the JAXB-API is on the classpath!
I have tried all the various implementations, Glassfish, EclipseLink MOXy etc. various versions, all with the same issue.
What's even more weird is that when I run the application inside my IDE I don't get this error. I get it when the application is packaged into a Docker container (it's being run inside a Kubernetes cluster in production).
Has anyone encountered something like this?

A: It turned out to be that marshallers and unmarshallers aren't thread safe with JAXB as described here: https://javaee.github.io/jaxb-v2/doc/user-guide/ch06.html#d0e6879
I also updated to version 2.3.7 of the jaxb-impl, which probably had no real impact on the problem being resolved but I wanted to throw it out there just in case.
The solution was to create a new unmarshaller each time and have it done inside a non-static method.
Edit:
The solution above didn't fully work but making the methods that were doing the marshalling/unmarshalling synchronized did resolve the issue completely.


text:
Q: Magento2: Payment method is not showing on checkout page The payment method is not showing on the checkout page.

console error:
Uncaught Error: Script error for: Magento_Checkout/js/model/place-order
b2aee5ee1e36f296863f6f91b53a4ae9.min.js:16 Uncaught Error: Script error for: Magento_Checkout/js/model/place-order
http://requirejs.org/docs/errors.html#scripterror
    at makeError (b2aee5ee1e36f296863f6f91b53a4ae9.min.js:16)
    at HTMLScriptElement.onScriptError (b2aee5ee1e36f296863f6f91b53a4ae9.min.js:112)

Please help me.


text:
Q: How to create MongoBD Schema for typescript interface with "alternative types"? I have the following typescript interface:
interface IDataItem {
  id: string;
  value: boolean | number | string;
  temp: boolean;
}

For simplicity, let's consider a simple array of data like this:
const MyData: IDataItem[] = [
  {
    id: '1',
    value: false,
    temp: false,
  },
  {
    id: '2',
    value: 'Test',
    temp: true,
  },
  {
    id: '3',
    value: 42,
    temp: false,
  },
];

How can I save this data to a MongoDB using mongoose? I have experience creating "Schemas" with typescript interfaces with "unique types" but not "alternative types" (such as boolean | number | string).
To be more specific: What do I have to put where the question marks are?
const schema = new Schema<IData>({
  id: { type: String, required: true },
  value: ???,
  temp: {type: Boolean, required: true },
});

Any suggestion is highly appreciated! Thank you so much!

A: you can use mixed type for multiple types for a field it's like any(in Ts) probably not exactly what you want i guess but anyway:
value : {type : Schema.Types.Mixed}

also recommend to take a look at Mongoose Documentation for Mixed type


text:
Q: sc.textFile does not work in spark-shell So I am starting to pick up the habit of doing my debugging in spark-shell and I'm running into an issue with collecting from textFile.
I basically have a file with JSON strings in hdfs and when I attempt to do
val y = sc.textFile("hdfs://nameservice1/path/to/file.txt").collect()

I get the following error:
16/05/26 23:51:42 WARN storage.BlockManager: Block broadcast_0 already exists on this machine; not re-adding it
16/05/26 23:51:42 WARN storage.BlockManager: Block broadcast_0_piece0 already exists on this machine; not re-adding it
16/05/26 23:51:42 INFO spark.SparkContext: Created broadcast 0 from textFile at QueryAnalyzer.scala:50
java.lang.ClassCastException: scala.collection.immutable.HashMap$HashTrieMap cannot be cast to org.apache.spark.SerializableWritable
    at org.apache.spark.rdd.HadoopRDD.getJobConf(HadoopRDD.scala:140)
    at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:196)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:219)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:217)
    at scala.Option.getOrElse(Option.scala:120)
    at org.apache.spark.rdd.RDD.partitions(RDD.scala:217)
    at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:32)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:219)
    at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:217)

has anyone run into anything like this before?


text:
Q: [Vue warn]: Failed to mount component: template or render function not defined in Webpack 4 I started getting this error once I upgraded to Webpack and related dependencies to v4: [Vue warn]: Failed to mount component: template or render function not defined.
Here's the relevant snippets of my package.json and webpack.config.js before and after:
Before upgrade:
package.json
{
  "dependencies": {
    "vue": "^2.5.0",
    "vue-template-compiler": "^2.5.0"
  },
  "devDependencies": {
    "babel-core": "^6.9.0",
    "babel-loader": "^6.2.4",
    "babel-plugin-external-helpers": "^6.22.0",
    "babel-plugin-transform-es2015-block-scoping": "^6.26.0",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-es2015": "^6.9.0",
    "babel-preset-es2015-without-strict": "^0.0.4",
    "babel-preset-es2017": "^6.24.1",
    "babel-preset-latest": "^6.24.1",
    "css-loader": "^0.26.0",
    "eslint": "^4.3.0",
    "husky": "^0.14.3",
    "lint-staged": "^4.0.2",
    "resolve-url-loader": "^1.6.0",
    "sass-loader": "^4.0.1",
    "stats-webpack-plugin": "^0.2.1",
    "style-loader": "^0.13.1",
    "uglifyjs-webpack-plugin": "^1.1.6",
    "vue-loader": "^12.1.0",
    "webpack": "3.10.0",
    "webpack-dev-server": "^2.3.0",
    "webpack-monitor": "^1.0.13"
  }
}

webpack.config.js
 {
  resolve: {
    modules: [
      path.join(__dirname, '..', 'webpack'),
      'node_modules/'
    ],
    alias: {
      vue: process.env.NODE_ENV === 'production' ? 'vue/dist/vue.min.js' : 'vue/dist/vue.js',
      libs: 'libs/'
    }
  },

  plugins: [
    new StatsPlugin('manifest.json', {
      chunkModules: false,
      source: false,
      chunks: false,
      modules: false,
      assets: true
    })],
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true,
              presets: ['es2015']
            }
          }
        ]
      }, {
        test: /\.vue$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'vue-loader'
          }
        ]
      },
      {
        test: /\.js$/,
        include: [
          path.resolve(process.cwd(), 'node_modules/')
        ],
        use: [
          {
            loader: 'babel-loader',
            options: {
              plugins: ['transform-es2015-block-scoping'],
              cacheDirectory: true
            }
          }
        ],
      },
    ]
  }
};

After upgrade:
package.json
{
  "dependencies": {
    "vue": "^2.5.13",
    "vue-template-compiler": "^2.5.13"
  },
  "devDependencies": {
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.3",
    "babel-plugin-external-helpers": "^6.22.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-latest": "^6.24.1",
    "css-loader": "^0.26.0",
    "eslint": "^4.3.0",
    "husky": "^0.14.3",
    "lint-staged": "^4.0.2",
    "resolve-url-loader": "^1.6.0",
    "sass-loader": "^4.0.1",
    "stats-webpack-plugin": "^0.2.1",
    "style-loader": "^0.13.1",
    "uglifyjs-webpack-plugin": "^1.1.6",
    "vue-loader": "^14.1.1",
    "webpack": "^4.0.1",
    "webpack-cli": "^2.0.9",
    "webpack-dev-server": "^3.0.0",
    "webpack-monitor": "^1.0.13"
  }
}

webpack.config.js
{
  resolve: {
    modules: [
      path.join(__dirname, '..', 'webpack'),
      'node_modules/'
    ],
    alias: {
      vue: process.env.NODE_ENV === 'production' ? 'vue/dist/vue.min.js' : 'vue/dist/vue.js',
      libs: 'libs/'
    }
  },

  plugins: [
    new StatsPlugin('manifest.json', {
      chunkModules: false,
      source: false,
      chunks: false,
      modules: false,
      assets: true
    })],
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true
            }
          }
        ]
      }, {
        test: /\.vue$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'vue-loader'
          }
        ]
      },
      {
        test: /\.js$/,
        include: [
          path.resolve(process.cwd(), 'node_modules/')
        ],
        use: [
          {
            loader: 'babel-loader',
            options: {
              cacheDirectory: true
            }
          }
        ],
      },
    ]
  }
};

What is expected?
Vue components work without errors after upgrading
What is actually happening?
Most Vue components show an error and fail to load: [Vue warn]: Failed to mount component: template or render function not defined.

A: Figured this out (h/t @skribe). Basically I was declaring components like this:
Vue.component('thing', require('libs/components/thing.vue'));
I had to change that to:
Vue.component('thing', require('libs/components/thing.vue').default);


text:
Q: Pandas pivot columns and rows assistance Really new to python, and trying to solve what might be really simple for you guys but would help me wrap my head around this.
I have the following data.
Date         Time          Delta
01/02/2020   9:30:00 AM    .05
01/02/2020   9:30:01 AM    .029
01/02/2020   9:30:02 AM    .033
...

I'm trying to get that into this form

Date        9:30:00 AM   9:30:01: AM   9:30:02 AM
01/02/2020 .05           .029          .033
...

I've tried:
df = pd.read_csv('C:\\Data\\test.csv')
newDF = df[['Date', 'Time', 'Delta']]

res = newDF.pivot(index='Date', columns='Time', values='Delta')

But that doesn't work at all. In-fact gives an error ValueError: Index contains duplicate entries, cannot reshape.
Is this possible only with Pandas?


text:
Q: How to get all the subviews of a window or view in latest SwiftUI App? Is there any way to get all the subviews of an UIView, like [view subviews] in SwiftUI app ?
When I try to query, Its giving me "_TtCOCV7SwiftUI11DisplayList11ViewUpdater8Platform13CGDrawingView....". I am trying to get all textfields, labels etc.

A: In most cases, you should prefer not thinking about "getting" the views in SwiftUI. In SwiftUI your views are structs, and you should structure your data model to "drive" changes to the views.
For example, if you were thinking about disabling all text fields, you should consider having a bool value in your data model that "drives" your SwiftUI views to become disabled or enabled. If you were thinking about styling all text fields a certain way, you should consider storing that styling information in your data model, and use different view modifiers on the text fields when the data model's value changes.
With that said, you can use UIKit methods to get all the views in your SwiftUI hierarchy, by wrapping your top-most SwiftUI view in a UIHostingController. This way, you can query some UIKit views rendered under the hood. You might not always get the views you you want, because only some views in SwiftUI are rendered using native views like UIView and NSView, and some others are not. You can use the View Debugger to inspect your view hierarchy in more details to see which views you can query.


text:
Q: Adding splashscreen to iphone app in AppDelegate I'm running xcode-4.2 and the project is based for ios5 using storyboards.
I've created a single view application , using the template provided by Apple.
In the storyboard I the removed the viewcontroller created for me and added a UITabBarController.
Next I added a new class MyTabBarController which is a subclass of UITabBarController.
Now I want to show a splashscreen before the TabBar appears. So I can do some loading and calculation in the background.
I thought AppDelegate.m would be a good place for this. Since that's the place where my rootview get's loaded not ? Or should a show the splashscreen from the rootviewcontroller which is MyTabBarController in my case ?
So I created a xib file. I'm surprised you can add .xib files to ios5 storyboard projects. The xib file is called SplashView.xib it has a single view with an image on it.
Code in AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
_splashScreen = [[UIViewController alloc] initWithNibName:@"SplashView" bundle:nil];
//_splashScreen is defined as:@property (strong, nonatomic) UIViewController *splashScreen;

[_window.rootViewController presentModalViewController:_splashScreen animated:NO];

[self performSelector:@selector(hideSplash) withObject:nil afterDelay:2];
return YES;

}
The problem is nothing happens. Even if I change the value from 2 to 200. The application starts up as if there is no splashscreen.
As you might have noticed I'm still struggling with the design of objective-c and iphone application. I hope a decent answer to my question will bring some clarity to the subject.
Thanks in advance!

A: Splash screens are built into iOS apps. All you need to do is create a file called Default.png and Default@2x.png (for retina displays) and it will work as a splash screen for when the app launches.
You can also set what these images will be in your apps info.plist.

A: I've dealt with a few clients who wanted to use an animated splash.
Though I'm totally against this, following Apple's HIG,
those clients just don't understand...
Anyway, since - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions; has to return boolean,
it's very important not to halt it for anything.
Also, since launch time is measured by iOS, if it's taking too long, the app will be terminated by iOS!
For this reason, I often use - (void)applicationDidBecomeActive:(UIApplication *)application;
with some kind of flag to indicate if it happened at launch or at returning from background mode.
Or, you should use a NSTimer or - (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay;
so, didFinishLaunchingWithOptions can return without being blocked for processing your animated splash.
This delayed performSelector should be implemented not only for hiding action (like the way you intended it), but also for starting the animation.

A: If you are using storyboard, you can just add the splash UIImageView to your window.rootViewController.view like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    UIImage *splashImage = [UIImage autoAdjustImageNamed:@"Default.png"];
    UIImageView *splashImageView = [[UIImageView alloc] initWithImage:splashImage];
    [self.window.rootViewController.view addSubview:splashImageView];
    [self.window.rootViewController.view bringSubviewToFront:splashImageView];
    [UIView animateWithDuration:1.5f
                          delay:2.0f
                        options:UIViewAnimationOptionCurveEaseInOut
                     animations:^{
                         splashImageView.alpha = .0f;
                         CGFloat x = -60.0f;
                         CGFloat y = -120.0f;
                         splashImageView.frame = CGRectMake(x,
                                                            y,
                                                            splashImageView.frame.size.width-2*x,
                                                            splashImageView.frame.size.height-2*y);
                     } completion:^(BOOL finished){
                         if (finished) {
                             [splashImageView removeFromSuperview];
                         }
                     }];

    return YES;
}

I think the reason why directly just add the UIImageView to window is because iOS will bring the rootViewController.view to front when the default splash will hide. And this will overlap the animation. This means the animation does happen but it's behind the rootViewController.

A: I just add an identical image to the launch image to my first view controller and then fade it (or whatever animation you require) - this avoids pausing the app load in the AppDelegate.
You need to ensure that the image has the same size and origin as your launch image e.g. to set the image to display on my first view controller which is a tableViewController:
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.tableView.bounds];
imageView.image = [UIImage imageNamed:@"[imagename]"];
[self.tableView addSubview:imageView];
[self.tableView bringSubviewToFront:imageView];
// Fade the image
 [self fadeView:imageView];

-(void)fadeView:(UIView*)viewToFade
{
    [UIView animateWithDuration:FADE_DURATION
                     animations:^ {
                         viewToFade.alpha = 0.0;
                    }
     ];

}


text:
Q: What does leveling Jack up actually do? In Mary Skelter: Nightmares, you technically play as Jack. Incidentally, Jack is the one party member who does not participate in combat and instead is the only one who can use items or spend his turn acting as a human shield for the other party members. However, after battle, he receives experience and levels up like everyone else, though, unlike the rest of the party members, Jack shows no stat gains (he doesn't even appear to have stats) or ability unlocks.
That said, does leveling Jack up actually do anything or is it just there for consistency's sake?


text:
Q: Concept of mass In classical mechanics, there seems to be a need to distinguish between inertial and gravitational mass. Some texts show how the concept of mass may be defined with some mathematical rigor. There is also an equivalence principle.
I would like to know if the concept of mass in Newton's "Principia" is not expressed in a much simpler manner.
edit:Newton on Mass and Force.
By Ed Dellian, Bogenstr. 5, D-14169 Berlin.

What does Newton say about "mass"? Let us read the "Definitio 1" which opens the Prin-
  cipia:
  "Quantitas materiae est mensura eiusdem orta ex illius densitate et magnitudine
  conjunctim." That is: The quantity of matter is that measure of it which arises from its
  density and volume conjointly.

So Newton's mass is simply "quantity of matter" obtained through density x volume (density => weight concept).
Had we defined our unit mass with a fixed volume of water, then any object's mass could easily be measured using a scale against a certain volume of water - the volume of water would give the mass. This manner of definition could be taken as a fundamental definition of mass; it may seem to be just gravitational mass.
With a definition of mass done, then force is defined as simply: mass x acceleration. We may not need any discussion of "inertial mass".

A: I am a freshman in physics so i had the same confusion a some time ago. What i understood is the following.
There are four interactions in nature that are fundamental. In physics we don't care so much for pointing out the source of the interaction as to describe the very interaction itself. Therefore we describe them by giving to space specific properties with wich we can detrmine the forces that are acted upon particles/bodies that enter it. That space of course is called a force field. In order for a particle/body to interact with this force field, it has to have a specific property according to the kind of the interaction.
For example: In order to interact with an electromagnetic field, the particle has to have a property that we call charge.
Accordingly, a particle that enters a gravitational field has to have a specific property that we call gravitational mass.
Now as for the inertial mass, there is a phenomenon in nature that is called inertia and that is the tendency of bodies/particles to resist to any change of their kinetic state.
So inertial mass is the a numerical value of the enertia that a body has, meaning that the more inertial mass a body has the "harder" it changes its kinetic state and vice versa. Of course with the word harder we mean that the force that has to act upon it has to be larger. This definition occurs from the second axiom of Newton.
$$\vec{F}=\frac{\mathrm d\vec{p}}{\mathrm dt}$$
Let's examine an isolated system of tow particles.
According to the third axiom of Newton, the forces that are acted upon them are opposite.
$$\vec{F_1}=-\vec{F_2}$$
So the net force of the system, since it is isolated it is zero.
$$
\sum\vec{F}=0 \quad\Longrightarrow\quad \frac{\mathrm d\vec{p}}{\mathrm dt}=0
$$
Therefore the momentum of the system is conserved.
$$
m_1 \vec{v}_\mathrm{initial} + m_2 \vec{u}_\mathrm{initial}= m_1 \vec{v}_\mathrm{final} + m_2 \vec{u}_\mathrm{final}
$$
$$
m_1 \Delta \vec{v} = -m_2\Delta \vec{u} \quad\Longrightarrow\quad \frac{m_2}{m_1}= \frac{\left|\Delta \vec{v}\right|}{\left|\Delta \vec{u}\right|}
$$
If we define $m_1$ as standard inertial mass then
$$
m_2= \frac{\left|\Delta \vec{v}\right|}{\left|\Delta \vec{u}\right|}
$$
So $m_2$ is inversly proporional to the change of kinetic state of the body. Which means that the greater the inertial mass is, the "harder" the velocity changes.
As all experiments show till today, inertial and gravitational mass have the same value.

A: General relativity showed that there is no such thing as gravitational mass, only inertial mass.
Force is something that can be measured with a spring or transducer.  Inertial mass can then be measured as the (constant) ratio of the net force on an object to its acceleration.


text:
Q: RestKit CoreData and UIImage I'm using Rest Kit with Core Data, one of the Core Data entities has an attribute 'image' that has a binary type.
I'm still in mockup stage so the image is populated with this code:
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://lorempixel.com/60/60/people"]]];
entry.image = UIImagePNGRepresentation(image);

Another tab has a collection view that uses fetchedResultsController.
After creating a new entity, if I only save the context the image works fine.
But if I push the entity to the web server using 'postObject:' the image is corrupted when it comes back from the server. I've confirmed the server receives the same string representation of the image "<2f396a2f 34414151 536b5a4a 52674142 ... 6a6e502f 32513d3d>" and stores it directly into a MySQL column of type long blob and at all points the string representation is the same.
But when the collection view is populated using a server call via RestKit the entities image is invalid. I'm think the issue is the data is being converted into the data representation of the description of the data.
Does anyone have a working example with images. The only thing I can think of is that I need to add a custom transformation, but the documentation and examples are lacking as far as how to actually implement one.

A: RestKit is storing the plain NSData for the image in Core Data - it has no idea what else you might want to do with it. Generally you don't want to manage images directly in Core Data or using RestKit.
Generally, store the path of the image in Core Data and the file on disk. Download them asynchronously (from the URL's which would also be in Core Data).
For uploading, you could make RestKit upload the data, but you probably actually want to file upload or convert to base64. You will need to write some code for this (which you could have RestKit pick up by using the key of the method name that returns the appropriate data). A similar process will work for mapping the data in.
RestKit data transformers are hard to make work in this situation as you are converting between data and strings and they are too general to be able to intercept accurately.


text:
Q: Apache + PHP not showing any formating What I am going to ask is probably a simple problem but I can't figure out solution. I have installed apache2 on Debian server and updated php to version 7.3. I think that I have made a mistake when disabling/enabling some modules but I am not sure.
Since that moment, text formatting/styles are not shown at all. See the image please, it is a result of pure phpinfo()
What do I do?
Error log shows nothing

[Tue May 25 23:33:51.759710 2021] [mpm_prefork:notice] [pid 27142] AH00163: Apache/2.4.38 (Debian) OpenSSL/1.1.1d configured -- resuming normal operations
[Tue May 25 23:33:51.759811 2021] [core:notice] [pid 27142] AH00094: Command line: '/usr/sbin/apache2'

apache2.conf
#ServerRoot "/etc/apache2"

#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
#Mutex file:${APACHE_LOCK_DIR} default

#
# The directory where shm and other runtime files will be stored.
#

DefaultRuntimeDir ${APACHE_RUN_DIR}

#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}

#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300

#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On

#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100

#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5

# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

HostnameLookups Off

ErrorLog ${APACHE_LOG_DIR}/error.log

LogLevel warn

# Include module configuration:
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf

Include ports.conf

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Require all denied
</Directory>

<Directory /usr/share>
    AllowOverride None
    Require all granted
</Directory>

<Directory /var/www/>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

AccessFileName .htaccess

<FilesMatch "^\.ht">
    Require all denied
</FilesMatch>

LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

IncludeOptional conf-enabled/*.conf

# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf

<IfModule mod_ssl.c>
SSLStaplingCache shmcb:/var/run/apache2/stapling_cache(128000)
<VirtualHost *:443>

    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

Header always set X-Content-Type-Options "nosniff"
Header always set X-Xss-Protection "1; mode=block"
Header always set X-Frame-Options "sameorigin"
Header always set Referrer-Policy "same-origin"
Header set Content-Security-Policy "default-src 'self';"
Header always set Permissions-Policy "geolocation=(),midi=(),sync-xhr=(),microphone=(),camera=(),magnetometer=(),gyroscope=(),fullscreen=(self),payment=()"
ServerName CENSORED
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/CENSORED/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/CENSORED/privkey.pem
Header always set Strict-Transport-Security "max-age=31536000"
SSLUseStapling on
</VirtualHost>
</IfModule>

Modules:
    Loaded Modules:
     core_module (static)
     so_module (static)
     watchdog_module (static)
     http_module (static)
     log_config_module (static)
     logio_module (static)
     version_module (static)
     unixd_module (static)
     access_compat_module (shared)
     alias_module (shared)
     auth_basic_module (shared)
     authn_core_module (shared)
     authn_file_module (shared)
     authz_core_module (shared)
     authz_host_module (shared)
     authz_user_module (shared)
     autoindex_module (shared)
     deflate_module (shared)
     dir_module (shared)
     env_module (shared)
     filter_module (shared)
     headers_module (shared)
     mime_module (shared)
     mpm_prefork_module (shared)
     negotiation_module (shared)
     php7_module (shared)
     proxy_module (shared)
     proxy_fcgi_module (shared)
     proxy_http_module (shared)
     reqtimeout_module (shared)
     rewrite_module (shared)
     setenvif_module (shared)
     slotmem_shm_module (shared)
     socache_shmcb_module (shared)
     ssl_module (shared)
     status_module (shared)

If it comes to the modules there might be actually some mistakes; i tried to install php7.3 fpm bud ended up using the "not fpm" version.
Thank you so much for your time.

A: Ok so I resolved the problem. The only thing I had to do was removing the CSP header from SSL apache config file. Since then it works normally.
TIP for everyone: Check developers console


text:
Q: List of Minimum Size with Default Values This should be a simple one.
I have a string with comma-separated values that I need to split:
String[] values = input.split(",");

However, I need the values to be 5 elements long, no more, no less. So, if split() only provides three values, I need the result padded to values with a default provided (null). Output can be a List or an array.
I've hunted and googled and haven't found what I need. I'm hoping that someone will see this and know an existing utility so I don't have to write my own.

A: You've confused a programming language with an almanac.
There is no such function; there probably will never be such a function in any major library. It's 2 lines of code to write it yourself:
String[] splitInto5(String in) {
    String[] out = in.split("\\s*,\\s*", 5);
    return out.length < 5 ? Arrays.copyOf(out, 5) : out;
}

The general idea behind programming languages is that you can program more complex components as needed. This is how you do such a thing - now you have a utility method that splits into precisely 5 elements.


text:
Q: Rails - Using checkboxes to select multiple objects and having a choice of actions to perform Id like to be able to create checkboxes for a list of objects. Then offer the user a number of actions to perform on the objects selected. I.e. delete, archive etc.
I know of ryan's screencasts but it doesnt explain how to create links to multiple actions for the selected objects. It just showed him create a form_tag with a url to one action and a submit button.

A: I think you can do it in two ways.
First: you can add as many buttons to one form as you want:
<%= f.submit "Action 1" %>
<%= f.submit "Action 2" %>
<%= f.submit "Action 3" %>

And all of them are submitted to one action in which you can check:
if params[:commit] == "Action 1"
  do some stuff for action 1
elsif params[:commit] == "Action 2"
  do other stuff
... and so on
end

Another way is to use some js. On example when user clicks on button "Action 2" it changes "action" parameter in form and submits data to this action.
EDIT:
In case of translated websites, you can do it like this:
<%= f.submit (I18n.t :action_1) %>

and in controller:
if params[:commit] == I18n.t :action_1
...
end

And in en.yml add:
action_1: Action 1

In pl.yml add:
action_1: Akcja 1

and so on.

A: You can always change the name of the submit button.  Just look for the params[:button_name] instead of params[:commit].
You'll need some sort of method in the controller to handle the ability to update_many objects.  Maybe a before filter to dispatch...


text:
Q: How can I observe API call based on user submit button and at same time getValue from edit text which is necessary for submit action? The problem is if I'll write observe statement in onCreate, it won't observe based on user click event. Because I want to only call repository API when user fill value in edit text and submit button, then only I can get value which I have to pass in repository to make API call and pass that value to API.
repository
public MutableLiveData<License> getLicenseData(String licenseKey, String macAddress, int productId) {
        final MutableLiveData<License> licenseData = new MutableLiveData<>();
        apiCall.getLicenseData(licenseKey, macAddress, productId).enqueue(new Callback<License>() {
            @Override
            public void onResponse(Call<License> call, Response<License> response) {
                licenseData.setValue(response.body());
            }

            @Override
            public void onFailure(Call<License> call, Throwable t) {
                licenseData.setValue(null);
            }
        });
        return licenseData;
    }

ViewModel class
 private void getLicenseData(String licenseKey, String macAddress, int productId) {
            mutableLiveData = manualLicenseRepository.getLicenseData(licenseKey, macAddress, productId);
        }

public void onClick(View view) {
    switch (view.getId()) {
        case R.id.btn_submit:
            try {
                getLicenseData(key.getValue(), "null", FIXED_PRODUCT_ID);
            } catch (NullPointerException e) {
                e.printStackTrace();
            }
            break;

    }
}

Activity - onCreate:
 protected void init() {
        manualLicenseKeyViewModel.init();
        manualLicenseKeyViewModel.getLicenseRepository().observe(this, this);
    }

A: First I will suggest you to Add data binding in your App
now in your Activity XML do something like this
<!--here it is 2 way binding-->
<EditText
    ...
    android:text="@={viewmodel.key}
    ... />

<!--here it is single way binding-->
<Button
    ...
    android:onClick="@{() -> viewmodel.doneClicked()}"
    ... />

Now in your ViewModel
//value in key will be same as value in the EditText as it is bidirectional data binding
public MutableLiveData<String> key = new MutableLiveData<>();

//update this MutableLiveData accordingly
private MutableLiveData<Boolean> isDataAvailable = new MutableLiveData<>();

//observe this LiveData
LiveData<Boolean> isDataAvailable(){
    return isDataAvailable;
}

public void doneClicked(){
    //here you can get value of your "key"
    //this method will call when clicking on the button
    //you can call your custom method from here,
    //also update data in "isDataAvailable"
}

In your Activity
viewModel.isDataAvailable().observe(this, aBoolean -> {
    //here you will receive change in value of isDataAvailable
}

PS
Your question is not clear at all, and your code is not helpful
Do you want to observe change in mutableLiveData of getLicenseData(...) inside your viewModel?

mutableLiveData = manualLicenseRepository.getLicenseData(licenseKey, macAddress, productId);

Please also change the name of this variable to something related the data it is getting, mutableLiveData is not a good variable name
Edit 1
try this to observe changes in the data, it is recommended to observe LiveData but you can observer MutableLiveData as you have not provided sufficient information I m using your mutableLiveData variable
In your Activity try this
viewModel.mutableLiveData.observe(this, license -> {
    //here you can observe changes in your mutableLiveData when It receives data from Repo
    //here license is the object of data inserted into mutableLiveData from repo
});

Please explain more.
Hope this will help!

A: I assume the methods you posted are from your Activity. Merely adding a method named onClick doesn't do anything at all; you need to attach a click listener to your button. For example, something like this in your onCreate method:
findViewById(R.id.btn_submit).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        try {
            getLicenseData(key.getValue(), "null", FIXED_PRODUCT_ID);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }
});

A: You have LiveData defined inside the method which is wrong. LiveData is something that's constantly observed by View(Activity) and therefore it needs to be held in ViewModel/Repository in a member variable.
Also, your repository looks redundant (does not do anything). I suggest redefining LiveData as a member variable of your ViewModel, making the request inside the ViewModel and posting the value to LiveData.
If you just need to send request and receive result then you don't need to even use LiveData, just use some Listener/Callback interface instead.


text:
Q: Something went wrong with PHP and Ajax I have this ajax code. data consists of login credentials.
$.ajax({
        url: "app/php/login.php",
        type: "GET",
        data: data,
        dataType: 'json',
        async: true,
        success: function(response){
            blah blah
        }
})

and here is my login.php. Everytime i sent a request, an alert pops up with the message Something Went Wrong. Am i doing this right? Forgive me for using GET method in a login
header('Content-Type: application/json');

$dbconn = mysqli_connect("localhost","root","","alumni_tracker") or die("Could not connect to database!"); //host, username, password, db
mysqli_select_db($dbconn,"alumni_tracker");
$student_no = $_GET["student_no"];
$password = $_GET["password"];
$query = "SELECT * FROM user WHERE student_no= '$student_no' AND password=MD5('$password')";
$res = mysqli_query($dbconn, $query);

if(empty($res)){
    $data = "1";
}
else if(!empty($res) && $student_no == "111111111"){
    $data = "2";
}
else{
    while($row = mysqli_fetch_array($res)){
        $data = array('student_no'=>$row['student_no'],'password'=>$row['password']);
    }
}
return json_encode($data);
exit();

A: disregarding the security issues, the fix was to use echo instead of return in json_encode($data)