问:
EXCEPTION_ACCESS_VIOLATION (0xc0000005)
Have tried the solution from different thread from stack overflow and other community forums but didn't find the solution of the below issue. I have both JDK 1.7 - 64 bit and JDK 1.6 - 32 bit installed.</p>

```<code>        # A fatal error has been detected by the Java Runtime Environment:
        #
        #  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x7719748e, pid=12248, tid=9852
        #
        # JRE version: 6.0_45-b06
        # Java VM: Java HotSpot(TM) Client VM (20.45-b01 mixed mode windows-x86 )
        # Problematic frame:
        # C  [ntdll.dll+0x3748e]
        #
        # If you would like to submit a bug report, please visit:
        #   http://java.sun.com/webapps/bugreport/crash.jsp
        # The crash happened outside the Java Virtual Machine in native code.
        # See problematic frame for where to report the bug.
        #

        ---------------  T H R E A D  ---------------

        Current thread (0x4d2ce800):  JavaThread "COBOL_VERIFY-60" [_thread_in_native, id=9852, stack(0x4c930000,0x4c980000)]

        siginfo: ExceptionCode=0xc0000005, reading address 0xfffffff8

        Registers:
        EAX=0x00000000, EBX=0x00000000, ECX=0x00008f07, EDX=0x00100000
        ESP=0x4c97ed40, EBP=0x4c97ed6c, ESI=0x4d789bd8, EDI=0x4cd70000
        EIP=0x7719748e, EFLAGS=0x00010206

        Top of Stack: (sp=0x4c97ed40)
        0x4c97ed40:   00004640 4cd70000 4d789bd8 00008f07
        0x4c97ed50:   00100000 4d740000 000007ff 4cd700c4
        0x4c97ed60:   58585858 4cd707d0 00008f07 4c97edac
        0x4c97ed70:   7719dcc0 4cd70000 01789bd8 00008f07
        0x4c97ed80:   4cd70000 00000000 4d789bd8 00000000
        0x4c97ed90:   0a01000b 58585858 58585858 58585858
        0x4c97eda0:   58585858 58585800 58585858 4c97eea4
        0x4c97edb0:   7719436f 4d789bd8 4d789bd8 00008f07

        Instructions: (pc=0x7719748e)
        0x7719746e:   04 00 83 78 08 00 74 02 03 c9 8b 40 20 8b 04 88
        0x7719747e:   39 45 f0 74 33 8b 7d 08 85 d2 0f 84 16 12 04 00
        0x7719748e:   8b 48 f8 8b 57 4c 85 d1 74 03 33 4f 50 0f b7 c9
        0x7719749e:   0f b7 d9 0f b7 4d fc 2b cb 85 c9 0f 8e 5c 01 00

        Register to memory mapping:

        EAX=0x00000000 is an unknown value
        EBX=0x00000000 is an unknown value
        ECX=0x00008f07 is an unknown value
        EDX=0x00100000 is an unknown value
        ESP=0x4c97ed40 is pointing into the stack for thread: 0x4d2ce800
        EBP=0x4c97ed6c is pointing into the stack for thread: 0x4d2ce800
        ESI=0x4d789bd8 is an unknown value
        EDI=0x4cd70000 is an unknown value

        Stack: [0x4c930000,0x4c980000],  sp=0x4c97ed40,  free space=315k
        Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
        C  [ntdll.dll+0x3748e]  LdrUnlockLoaderLock+0x66a
        C  [ntdll.dll+0x3dcc0]  RtlIntegerToUnicodeString+0xfb
        C  [ntdll.dll+0x3436f]  RtlInitializeCriticalSection+0x11f
        C  [ntdll.dll+0x32b65]  RtlQueryPerformanceCounter+0x281
        C  [kernel32.dll+0x114bd]  HeapFree+0x14

        Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
        j  com.microfocus.cobol.RuntimeSystem.ccall(Ljava/lang/String;[Ljava/lang/Object;[I)I+0
        j  com.microfocus.cobol.RuntimeSystem.cobthreadtidy()I+4
        j  java.lang.Thread.run()V+11
        v  ~StubRoutines::call_stub

        ---------------  P R O C E S S  ---------------

        Java Threads: ( => current thread )
        =>0x4d2ce800 JavaThread "COBOL_VERIFY-60" [_thread_in_native, id=9852, stack(0x4c930000,0x4c980000)]
          0x4d2cd000 JavaThread "UCP-worker-thread-24" daemon [_thread_blocked, id=10012, stack(0x4ec90000,0x4ece0000)]
          0x4d2cdc00 JavaThread "UCP-worker-thread-23" daemon [_thread_blocked, id=9504, stack(0x4ee40000,0x4ee90000)]
          0x4d2cd800 JavaThread "UCP-worker-thread-22" daemon [_thread_blocked, id=7444, stack(0x4edb0000,0x4ee00000)]
          0x4d2cc800 JavaThread "UCP-worker-thread-21" daemon [_thread_blocked, id=11412, stack(0x4ec00000,0x4ec50000)]
          0x4d5cf800 JavaThread "UCP-worker-thread-20" daemon [_thread_blocked, id=12220, stack(0x4e930000,0x4e980000)]
          0x4d2cc400 JavaThread "UCP-worker-thread-19" daemon [_thread_blocked, id=9444, stack(0x4ea50000,0x4eaa0000)]
          0x4d2cbc00 JavaThread "UCP-worker-thread-18" daemon [_thread_blocked, id=7792, stack(0x4e9c0000,0x4ea10000)]
          0x4d5d5c00 JavaThread "UCP-worker-thread-17" daemon [_thread_blocked, id=12948, stack(0x4e8a0000,0x4e8f0000)]
          0x4d5d5800 JavaThread "UCP-worker-thread-16" daemon [_thread_blocked, id=12156, stack(0x4ed60000,0x4edb0000)]
          0x4d5d5000 JavaThread "UCP-worker-thread-15" daemon [_thread_blocked, id=7728, stack(0x4e7e0000,0x4e830000)]
          0x4d5d4c00 JavaThread "UCP-worker-thread-14" daemon [_thread_blocked, id=11384, stack(0x4e750000,0x4e7a0000)]
          0x4d5d4400 JavaThread "UCP-worker-thread-13" daemon [_thread_blocked, id=11920, stack(0x4e6c0000,0x4e710000)]
          0x4d5d3c00 JavaThread "UCP-worker-thread-12" daemon [_thread_blocked, id=7724, stack(0x4e630000,0x4e680000)]
          0x4d5d3800 JavaThread "UCP-worker-thread-11" daemon [_thread_blocked, id=12820, stack(0x4e5a0000,0x4e5f0000)]
          0x4d5d3000 JavaThread "UCP-worker-thread-10" daemon [_thread_blocked, id=624, stack(0x4e510000,0x4e560000)]
          0x4d5d2c00 JavaThread "UCP-worker-thread-9" daemon [_thread_blocked, id=11896, stack(0x4e480000,0x4e4d0000)]
          0x4d5d2400 JavaThread "UCP-worker-thread-8" daemon [_thread_blocked, id=1536, stack(0x4e3f0000,0x4e440000)]
          0x4d5d2000 JavaThread "UCP-worker-thread-7" daemon [_thread_blocked, id=9804, stack(0x4e360000,0x4e3b0000)]
          0x4d5d0c00 JavaThread "pool-1-thread-1" [_thread_blocked, id=11748, stack(0x4ca50000,0x4caa0000)]
          0x4d5d0000 JavaThread "UCP-worker-thread-6" daemon [_thread_blocked, id=11400, stack(0x4c9c0000,0x4ca10000)]
          0x4d5cf400 JavaThread "UCP-worker-thread-5" daemon [_thread_blocked, id=10300, stack(0x4c8a0000,0x4c8f0000)]
          0x4d68e000 JavaThread "UCP-worker-thread-4" daemon [_thread_blocked, id=12716, stack(0x4c810000,0x4c860000)]
          0x4d601000 JavaThread "OracleTimeoutPollingThread" daemon [_thread_blocked, id=11576, stack(0x4c780000,0x4c7d0000)]
          0x4d716000 JavaThread "UCP-worker-thread-3" daemon [_thread_blocked, id=11692, stack(0x4c6a0000,0x4c6f0000)]
          0x4d065c00 JavaThread "UCP-worker-thread-2" daemon [_thread_blocked, id=12432, stack(0x4c610000,0x4c660000)]
          0x4bd82800 JavaThread "UCP-worker-thread-1" daemon [_thread_blocked, id=10908, stack(0x4c2a0000,0x4c2f0000)]
          0x4bd84800 JavaThread "Timer-0" daemon [_thread_blocked, id=8584, stack(0x4c160000,0x4c1b0000)]
          0x026c5000 JavaThread "Low Memory Detector" daemon [_thread_blocked, id=9508, stack(0x4b920000,0x4b970000)]
          0x026bd400 JavaThread "C1 CompilerThread0" daemon [_thread_blocked, id=11812, stack(0x4b890000,0x4b8e0000)]
          0x026ba400 JavaThread "Attach Listener" daemon [_thread_blocked, id=9876, stack(0x4b800000,0x4b850000)]
          0x026b7000 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=8276, stack(0x4b770000,0x4b7c0000)]
          0x02687000 JavaThread "Finalizer" daemon [_thread_blocked, id=9532, stack(0x4b6e0000,0x4b730000)]
          0x02682400 JavaThread "Reference Handler" daemon [_thread_blocked, id=12744, stack(0x4b650000,0x4b6a0000)]
          0x02601800 JavaThread "main" [_thread_blocked, id=1888, stack(0x025b0000,0x02600000)]

        Other Threads:
          0x0267ec00 VMThread [stack: 0x4b5c0000,0x4b610000] [id=10572]
          0x026dec00 WatcherThread [stack: 0x4b9b0000,0x4ba00000] [id=8856]

        VM state:not at safepoint (normal execution)

        VM Mutex/Monitor currently owned by a thread: None

        Heap
         def new generation   total 215040K, used 1911K [0x04780000, 0x130d0000, 0x130d0000)
          eden space 191168K,   1% used [0x04780000, 0x0495dee8, 0x10230000)
          from space 23872K,   0% used [0x10230000, 0x10230000, 0x11980000)
          to   space 23872K,   0% used [0x11980000, 0x11980000, 0x130d0000)
         tenured generation   total 477888K, used 179691K [0x130d0000, 0x30380000, 0x30380000)
           the space 477888K,  37% used [0x130d0000, 0x1e04ae00, 0x1e04ae00, 0x30380000)
         compacting perm gen  total 409600K, used 107408K [0x30380000, 0x49380000, 0x49380000)
           the space 409600K,  26% used [0x30380000, 0x36c64020, 0x36c64200, 0x49380000)
        No shared spaces configured.

        Code Cache  [0x02700000, 0x02f90000, 0x04700000)
         total_blobs=4640 nmethods=4446 adapters=128 free_code_cache=24611968 largest_free_block=384

        Dynamic libraries:
        0x00400000 - 0x00425000     E:\app\Java\jre6\bin\java.exe
        0x77160000 - 0x772e0000     C:\Windows\SysWOW64\ntdll.dll
        0x759a0000 - 0x75ab0000     C:\Windows\syswow64\kernel32.dll
        0x76130000 - 0x76177000     C:\Windows\syswow64\KERNELBASE.dll
        0x75ca0000 - 0x75d40000     C:\Windows\syswow64\ADVAPI32.dll
        0x76b90000 - 0x76c3c000     C:\Windows\syswow64\msvcrt.dll
        0x75e90000 - 0x75ea9000     C:\Windows\SysWOW64\sechost.dll
        0x75da0000 - 0x75e90000     C:\Windows\syswow64\RPCRT4.dll
        0x74c70000 - 0x74cd0000     C:\Windows\syswow64\SspiCli.dll
        0x74c60000 - 0x74c6c000     C:\Windows\syswow64\CRYPTBASE.dll
        0x7c340000 - 0x7c396000     E:\app\Java\jre6\bin\msvcr71.dll
        0x6d810000 - 0x6dac0000     E:\app\Java\jre6\bin\server\jvm.dll
        0x76660000 - 0x76760000     C:\Windows\syswow64\USER32.dll
        0x75c10000 - 0x75ca0000     C:\Windows\syswow64\GDI32.dll
        0x75f60000 - 0x75f6a000     C:\Windows\syswow64\LPK.dll
        0x76420000 - 0x764bd000     C:\Windows\syswow64\USP10.dll
        0x731b0000 - 0x731e2000     C:\Windows\system32\WINMM.dll
        0x75d40000 - 0x75da0000     C:\Windows\system32\IMM32.DLL
        0x76a20000 - 0x76aec000     C:\Windows\syswow64\MSCTF.dll
        0x73e50000 - 0x73e9c000     C:\Windows\system32\apphelp.dll
        0x6d7c0000 - 0x6d7cc000     E:\app\Java\jre6\bin\verify.dll
        0x6d330000 - 0x6d34f000     E:\app\Java\jre6\bin\java.dll
        0x6d800000 - 0x6d80f000     E:\app\Java\jre6\bin\zip.dll
        0x6d560000 - 0x6d569000     E:\app\Java\jre6\bin\management.dll
        0x6d610000 - 0x6d623000     E:\app\Java\jre6\bin\net.dll
        0x76d20000 - 0x76d55000     C:\Windows\syswow64\WS2_32.dll
        0x74d40000 - 0x74d46000     C:\Windows\syswow64\NSI.dll
        0x74540000 - 0x7457c000     C:\Windows\system32\mswsock.dll
        0x72a20000 - 0x72a26000     C:\Windows\System32\wship6.dll
        0x74530000 - 0x74535000     C:\Windows\System32\wshtcpip.dll
        0x73eb0000 - 0x73ef4000     C:\Windows\system32\DNSAPI.dll
        0x73c30000 - 0x73c4c000     C:\Windows\system32\IPHLPAPI.DLL
        0x73c20000 - 0x73c27000     C:\Windows\system32\WINNSI.DLL
        0x73bd0000 - 0x73bd6000     C:\Windows\system32\rasadhlp.dll
        0x73be0000 - 0x73c18000     C:\Windows\System32\fwpuclnt.dll
        0x74300000 - 0x74317000     C:\Windows\system32\CRYPTSP.dll
        0x74010000 - 0x7404b000     C:\Windows\system32\rsaenh.dll
        0x73990000 - 0x739a7000     C:\Windows\system32\USERENV.dll
        0x73980000 - 0x7398b000     C:\Windows\system32\profapi.dll
        0x73c70000 - 0x73c80000     C:\Windows\system32\NLAapi.dll
        0x73c60000 - 0x73c70000     C:\Windows\system32\napinsp.dll
        0x73c50000 - 0x73c58000     C:\Windows\System32\winrnr.dll
        0x6d630000 - 0x6d639000     E:\app\Java\jre6\bin\nio.dll
        0x61000000 - 0x6100c000     E:\\app\MicroFocus\NetExpress5.1\Base\Bin\CBLJVM_SUN.DLL
        0x60000000 - 0x600b0000     E:\\app\MicroFocus\NetExpress5.1\Base\Bin\cblrtsm.dll
        0x4be00000 - 0x4be0c000     E:\app\MicroFocus\NetExpress5.1\Base\BIN\cbljvm_sun.dll
        0x4bf70000 - 0x4bf7d000     E:\app\MicroFocus\NetExpress5.1\Base\BIN\javaclass.dll
        0x4bf80000 - 0x4bf94000     E:\app\MicroFocus\NetExpress5.1\Base\BIN\oopsm.dll
        0x4c1b0000 - 0x4c1b7000     E:\app\MicroFocus\NetExpress5.1\Base\BIN\MFOM.DLL
        0x4c1c0000 - 0x4c1c9000     E:\app\MicroFocus\NetExpress5.1\Base\BIN\class.dll
        0x4cd80000 - 0x4ce31000     E:\app\MicroFocus\NetExpress5.1\Base\BIN\classm.dll
        0x4cd10000 - 0x4cd24000     E:\app\MicroFocus\NetExpress5.1\Base\BIN\MFJAVAM.DLL

        VM Arguments:
        jvm_args: -Xms700M -Xmx700M -XX:PermSize=400M -XX:MaxPermSize=400M
        Launcher Type: SUN_STANDARD

        Environment Variables:
        JAVA_HOME=C:\app\Java\jdk1.7.0_80
        CLASSPATH=E:\app\MicroFocus\NetExpress5.1\Base\BIN\mfcobol.jar;.;LASSPATH
        USERNAME=navhad
        SHELL=c:/mksnt/mksnt/sh.exe
        DISPLAY=:0.0
        OS=Windows_NT
        PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 62 Stepping 4, GenuineIntel

        ---------------  S Y S T E M  ---------------

        OS: Windows NT 6.1 , 64 bit Build 7601 Service Pack 1

        CPU:total 32 (12 cores per cpu, 2 threads per core) family 6 model 62 stepping 4, cmov, cx8, fxsr, mmx, sse, sse2, sse3, ssse3, sse4.1, sse4.2, popcnt, ht

        Memory: 4k page, physical 268376140k(253130084k free), swap 536750444k(519531228k free)

        vm_info: Java HotSpot(TM) Client VM (20.45-b01) for windows-x86 JRE (1.6.0_45-b06), built on Mar 26 2013 13:40:03 by "java_re" with MS VC++ 7.1 (VS2003)

        time: Wed Dec 16 11:07:59 2015
        elapsed time: 160 seconds
</code>```

答: Finally got solution after re-installing jdk. Installed JDK 1.7 on slave machine was corrupted due to which jdk was failing to invoke na. After reinstalling same JDK version it worked.Thanks all.</p>

Title: EXCEPTION_ACCESS_VIOLATION (0xc0000005)

Body:
Have tried the solution from different thread from stack overflow and other community forums but didn't find the solution of the below issue. I have both JDK 1.7 - 64 bit and JDK 1.6 - 32 bit installed.

        # A fatal error has been detected by the Java Runtime Environment:
        #
        #  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x7719748e, pid=12248, tid=9852
        #
        # JRE version: 6.0_45-b06
        # Java VM: Java HotSpot(TM) Client VM (20.45-b01 mixed mode windows-x86 )
        # Problematic frame:
        # C  [ntdll.dll+0x3748e]
        #
        # If you would like to submit a bug report, please visit:
        #   http://java.sun.com/webapps/bugreport/crash.jsp
        # The crash happened outside the Java Virtual Machine in native code.
        # See problematic frame for where to report the bug.
        #

        ---------------  T H R E A D  ---------------

        Current thread (0x4d2ce800):  JavaThread "COBOL_VERIFY-60" [_thread_in_native, id=9852, stack(0x4c930000,0x4c980000)]

        siginfo: ExceptionCode=0xc0000005, reading address 0xfffffff8

        Registers:
        EAX=0x00000000, EBX=0x00000000, ECX=0x00008f07, EDX=0x00100000
        ESP=0x4c97ed40, EBP=0x4c97ed6c, ESI=0x4d789bd8, EDI=0x4cd70000
        EIP=0x7719748e, EFLAGS=0x00010206

        Top of Stack: (sp=0x4c97ed40)
        0x4c97ed40:   00004640 4cd70000 4d789bd8 00008f07
        0x4c97ed50:   00100000 4d740000 000007ff 4cd700c4
        0x4c97ed60:   58585858 4cd707d0 00008f07 4c97edac
        0x4c97ed70:   7719dcc0 4cd70000 01789bd8 00008f07
        0x4c97ed80:   4cd70000 00000000 4d789bd8 00000000
        0x4c97ed90:   0a01000b 58585858 58585858 58585858
        0x4c97eda0:   58585858 58585800 58585858 4c97eea4
        0x4c97edb0:   7719436f 4d789bd8 4d789bd8 00008f07

        Instructions: (pc=0x7719748e)
        0x7719746e:   04 00 83 78 08 00 74 02 03 c9 8b 40 20 8b 04 88
        0x7719747e:   39 45 f0 74 33 8b 7d 08 85 d2 0f 84 16 12 04 00
        0x7719748e:   8b 48 f8 8b 57 4c 85 d1 74 03 33 4f 50 0f b7 c9
        0x7719749e:   0f b7 d9 0f b7 4d fc 2b cb 85 c9 0f 8e 5c 01 00

        Register to memory mapping:

        EAX=0x00000000 is an unknown value
        EBX=0x00000000 is an unknown value
        ECX=0x00008f07 is an unknown value
        EDX=0x00100000 is an unknown value
        ESP=0x4c97ed40 is pointing into the stack for thread: 0x4d2ce800
        EBP=0x4c97ed6c is pointing into the stack for thread: 0x4d2ce800
        ESI=0x4d789bd8 is an unknown value
        EDI=0x4cd70000 is an unknown value

        Stack: [0x4c930000,0x4c980000],  sp=0x4c97ed40,  free space=315k
        Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
        C  [ntdll.dll+0x3748e]  LdrUnlockLoaderLock+0x66a
        C  [ntdll.dll+0x3dcc0]  RtlIntegerToUnicodeString+0xfb
        C  [ntdll.dll+0x3436f]  RtlInitializeCriticalSection+0x11f
        C  [ntdll.dll+0x32b65]  RtlQueryPerformanceCounter+0x281
        C  [kernel32.dll+0x114bd]  HeapFree+0x14

        Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
        j  com.microfocus.cobol.RuntimeSystem.ccall(Ljava/lang/String;[Ljava/lang/Object;[I)I+0
        j  com.microfocus.cobol.RuntimeSystem.cobthreadtidy()I+4
        j  java.lang.Thread.run()V+11
        v  ~StubRoutines::call_stub

        ---------------  P R O C E S S  ---------------

        Java Threads: ( => current thread )
        =>0x4d2ce800 JavaThread "COBOL_VERIFY-60" [_thread_in_native, id=9852, stack(0x4c930000,0x4c980000)]
          0x4d2cd000 JavaThread "UCP-worker-thread-24" daemon [_thread_blocked, id=10012, stack(0x4ec90000,0x4ece0000)]
          0x4d2cdc00 JavaThread "UCP-worker-thread-23" daemon [_thread_blocked, id=9504, stack(0x4ee40000,0x4ee90000)]
          0x4d2cd800 JavaThread "UCP-worker-thread-22" daemon [_thread_blocked, id=7444, stack(0x4edb0000,0x4ee00000)]
          0x4d2cc800 JavaThread "UCP-worker-thread-21" daemon [_thread_blocked, id=11412, stack(0x4ec00000,0x4ec50000)]
          0x4d5cf800 JavaThread "UCP-worker-thread-20" daemon [_thread_blocked, id=12220, stack(0x4e930000,0x4e980000)]
          0x4d2cc400 JavaThread "UCP-worker-thread-19" daemon [_thread_blocked, id=9444, stack(0x4ea50000,0x4eaa0000)]
          0x4d2cbc00 JavaThread "UCP-worker-thread-18" daemon [_thread_blocked, id=7792, stack(0x4e9c0000,0x4ea10000)]
          0x4d5d5c00 JavaThread "UCP-worker-thread-17" daemon [_thread_blocked, id=12948, stack(0x4e8a0000,0x4e8f0000)]
          0x4d5d5800 JavaThread "UCP-worker-thread-16" daemon [_thread_blocked, id=12156, stack(0x4ed60000,0x4edb0000)]
          0x4d5d5000 JavaThread "UCP-worker-thread-15" daemon [_thread_blocked, id=7728, stack(0x4e7e0000,0x4e830000)]
          0x4d5d4c00 JavaThread "UCP-worker-thread-14" daemon [_thread_blocked, id=11384, stack(0x4e750000,0x4e7a0000)]
          0x4d5d4400 JavaThread "UCP-worker-thread-13" daemon [_thread_blocked, id=11920, stack(0x4e6c0000,0x4e710000)]
          0x4d5d3c00 JavaThread "UCP-worker-thread-12" daemon [_thread_blocked, id=7724, stack(0x4e630000,0x4e680000)]
          0x4d5d3800 JavaThread "UCP-worker-thread-11" daemon [_thread_blocked, id=12820, stack(0x4e5a0000,0x4e5f0000)]
          0x4d5d3000 JavaThread "UCP-worker-thread-10" daemon [_thread_blocked, id=624, stack(0x4e510000,0x4e560000)]
          0x4d5d2c00 JavaThread "UCP-worker-thread-9" daemon [_thread_blocked, id=11896, stack(0x4e480000,0x4e4d0000)]
          0x4d5d2400 JavaThread "UCP-worker-thread-8" daemon [_thread_blocked, id=1536, stack(0x4e3f0000,0x4e440000)]
          0x4d5d2000 JavaThread "UCP-worker-thread-7" daemon [_thread_blocked, id=9804, stack(0x4e360000,0x4e3b0000)]
          0x4d5d0c00 JavaThread "pool-1-thread-1" [_thread_blocked, id=11748, stack(0x4ca50000,0x4caa0000)]
          0x4d5d0000 JavaThread "UCP-worker-thread-6" daemon [_thread_blocked, id=11400, stack(0x4c9c0000,0x4ca10000)]
          0x4d5cf400 JavaThread "UCP-worker-thread-5" daemon [_thread_blocked, id=10300, stack(0x4c8a0000,0x4c8f0000)]
          0x4d68e000 JavaThread "UCP-worker-thread-4" daemon [_thread_blocked, id=12716, stack(0x4c810000,0x4c860000)]
          0x4d601000 JavaThread "OracleTimeoutPollingThread" daemon [_thread_blocked, id=11576, stack(0x4c780000,0x4c7d0000)]
          0x4d716000 JavaThread "UCP-worker-thread-3" daemon [_thread_blocked, id=11692, stack(0x4c6a0000,0x4c6f0000)]
          0x4d065c00 JavaThread "UCP-worker-thread-2" daemon [_thread_blocked, id=12432, stack(0x4c610000,0x4c660000)]
          0x4bd82800 JavaThread "UCP-worker-thread-1" daemon [_thread_blocked, id=10908, stack(0x4c2a0000,0x4c2f0000)]
          0x4bd84800 JavaThread "Timer-0" daemon [_thread_blocked, id=8584, stack(0x4c160000,0x4c1b0000)]
          0x026c5000 JavaThread "Low Memory Detector" daemon [_thread_blocked, id=9508, stack(0x4b920000,0x4b970000)]
          0x026bd400 JavaThread "C1 CompilerThread0" daemon [_thread_blocked, id=11812, stack(0x4b890000,0x4b8e0000)]
          0x026ba400 JavaThread "Attach Listener" daemon [_thread_blocked, id=9876, stack(0x4b800000,0x4b850000)]
          0x026b7000 JavaThread "Signal Dispatcher" daemon [_thread_blocked, id=8276, stack(0x4b770000,0x4b7c0000)]
          0x02687000 JavaThread "Finalizer" daemon [_thread_blocked, id=9532, stack(0x4b6e0000,0x4b730000)]
          0x02682400 JavaThread "Reference Handler" daemon [_thread_blocked, id=12744, stack(0x4b650000,0x4b6a0000)]
          0x02601800 JavaThread "main" [_thread_blocked, id=1888, stack(0x025b0000,0x02600000)]

        Other Threads:
          0x0267ec00 VMThread [stack: 0x4b5c0000,0x4b610000] [id=10572]
          0x026dec00 WatcherThread [stack: 0x4b9b0000,0x4ba00000] [id=8856]

        VM state:not at safepoint (normal execution)

        VM Mutex/Monitor currently owned by a thread: None

        Heap
         def new generation   total 215040K, used 1911K [0x04780000, 0x130d0000, 0x130d0000)
          eden space 191168K,   1% used [0x04780000, 0x0495dee8, 0x10230000)
          from space 23872K,   0% used [0x10230000, 0x10230000, 0x11980000)
          to   space 23872K,   0% used [0x11980000, 0x11980000, 0x130d0000)
         tenured generation   total 477888K, used 179691K [0x130d0000, 0x30380000, 0x30380000)
           the space 477888K,  37% used [0x130d0000, 0x1e04ae00, 0x1e04ae00, 0x30380000)
         compacting perm gen  total 409600K, used 107408K [0x30380000, 0x49380000, 0x49380000)
           the space 409600K,  26% used [0x30380000, 0x36c64020, 0x36c64200, 0x49380000)
        No shared spaces configured.

        Code Cache  [0x02700000, 0x02f90000, 0x04700000)
         total_blobs=4640 nmethods=4446 adapters=128 free_code_cache=24611968 largest_free_block=384

        Dynamic libraries:
        0x00400000 - 0x00425000     E:\app\Java\jre6\bin\java.exe
        0x77160000 - 0x772e0000     C:\Windows\SysWOW64\ntdll.dll
        0x759a0000 - 0x75ab0000     C:\Windows\syswow64\kernel32.dll
        0x76130000 - 0x76177000     C:\Windows\syswow64\KERNELBASE.dll
        0x75ca0000 - 0x75d40000     C:\Windows\syswow64\ADVAPI32.dll
        0x76b90000 - 0x76c3c000     C:\Windows\syswow64\msvcrt.dll
        0x75e90000 - 0x75ea9000     C:\Windows\SysWOW64\sechost.dll
        0x75da0000 - 0x75e90000     C:\Windows\syswow64\RPCRT4.dll
        0x74c70000 - 0x74cd0000     C:\Windows\syswow64\SspiCli.dll
        0x74c60000 - 0x74c6c000     C:\Windows\syswow64\CRYPTBASE.dll
        0x7c340000 - 0x7c396000     E:\app\Java\jre6\bin\msvcr71.dll
        0x6d810000 - 0x6dac0000     E:\app\Java\jre6\bin\server\jvm.dll
        0x76660000 - 0x76760000     C:\Windows\syswow64\USER32.dll
        0x75c10000 - 0x75ca0000     C:\Windows\syswow64\GDI32.dll
        0x75f60000 - 0x75f6a000     C:\Windows\syswow64\LPK.dll
        0x76420000 - 0x764bd000     C:\Windows\syswow64\USP10.dll
        0x731b0000 - 0x731e2000     C:\Windows\system32\WINMM.dll
        0x75d40000 - 0x75da0000     C:\Windows\system32\IMM32.DLL
        0x76a20000 - 0x76aec000     C:\Windows\syswow64\MSCTF.dll
        0x73e50000 - 0x73e9c000     C:\Windows\system32\apphelp.dll
        0x6d7c0000 - 0x6d7cc000     E:\app\Java\jre6\bin\verify.dll
        0x6d330000 - 0x6d34f000     E:\app\Java\jre6\bin\java.dll
        0x6d800000 - 0x6d80f000     E:\app\Java\jre6\bin\zip.dll
        0x6d560000 - 0x6d569000     E:\app\Java\jre6\bin\management.dll
        0x6d610000 - 0x6d623000     E:\app\Java\jre6\bin\net.dll
        0x76d20000 - 0x76d55000     C:\Windows\syswow64\WS2_32.dll
        0x74d40000 - 0x74d46000     C:\Windows\syswow64\NSI.dll
        0x74540000 - 0x7457c000     C:\Windows\system32\mswsock.dll
        0x72a20000 - 0x72a26000     C:\Windows\System32\wship6.dll
        0x74530000 - 0x74535000     C:\Windows\System32\wshtcpip.dll
        0x73eb0000 - 0x73ef4000     C:\Windows\system32\DNSAPI.dll
        0x73c30000 - 0x73c4c000     C:\Windows\system32\IPHLPAPI.DLL
        0x73c20000 - 0x73c27000     C:\Windows\system32\WINNSI.DLL
        0x73bd0000 - 0x73bd6000     C:\Windows\system32\rasadhlp.dll
        0x73be0000 - 0x73c18000     C:\Windows\System32\fwpuclnt.dll
        0x74300000 - 0x74317000     C:\Windows\system32\CRYPTSP.dll
        0x74010000 - 0x7404b000     C:\Windows\system32\rsaenh.dll
        0x73990000 - 0x739a7000     C:\Windows\system32\USERENV.dll
        0x73980000 - 0x7398b000     C:\Windows\system32\profapi.dll
        0x73c70000 - 0x73c80000     C:\Windows\system32\NLAapi.dll
        0x73c60000 - 0x73c70000     C:\Windows\system32\napinsp.dll
        0x73c50000 - 0x73c58000     C:\Windows\System32\winrnr.dll
        0x6d630000 - 0x6d639000     E:\app\Java\jre6\bin\nio.dll
        0x61000000 - 0x6100c000     E:\\app\MicroFocus\NetExpress5.1\Base\Bin\CBLJVM_SUN.DLL
        0x60000000 - 0x600b0000     E:\\app\MicroFocus\NetExpress5.1\Base\Bin\cblrtsm.dll
        0x4be00000 - 0x4be0c000     E:\app\MicroFocus\NetExpress5.1\Base\BIN\cbljvm_sun.dll
        0x4bf70000 - 0x4bf7d000     E:\app\MicroFocus\NetExpress5.1\Base\BIN\javaclass.dll
        0x4bf80000 - 0x4bf94000     E:\app\MicroFocus\NetExpress5.1\Base\BIN\oopsm.dll
        0x4c1b0000 - 0x4c1b7000     E:\app\MicroFocus\NetExpress5.1\Base\BIN\MFOM.DLL
        0x4c1c0000 - 0x4c1c9000     E:\app\MicroFocus\NetExpress5.1\Base\BIN\class.dll
        0x4cd80000 - 0x4ce31000     E:\app\MicroFocus\NetExpress5.1\Base\BIN\classm.dll
        0x4cd10000 - 0x4cd24000     E:\app\MicroFocus\NetExpress5.1\Base\BIN\MFJAVAM.DLL

        VM Arguments:
        jvm_args: -Xms700M -Xmx700M -XX:PermSize=400M -XX:MaxPermSize=400M
        Launcher Type: SUN_STANDARD

        Environment Variables:
        JAVA_HOME=C:\app\Java\jdk1.7.0_80
        CLASSPATH=E:\app\MicroFocus\NetExpress5.1\Base\BIN\mfcobol.jar;.;LASSPATH
        USERNAME=navhad
        SHELL=c:/mksnt/mksnt/sh.exe
        DISPLAY=:0.0
        OS=Windows_NT
        PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 62 Stepping 4, GenuineIntel

        ---------------  S Y S T E M  ---------------

        OS: Windows NT 6.1 , 64 bit Build 7601 Service Pack 1

        CPU:total 32 (12 cores per cpu, 2 threads per core) family 6 model 62 stepping 4, cmov, cx8, fxsr, mmx, sse, sse2, sse3, ssse3, sse4.1, sse4.2, popcnt, ht

        Memory: 4k page, physical 268376140k(253130084k free), swap 536750444k(519531228k free)

        vm_info: Java HotSpot(TM) Client VM (20.45-b01) for windows-x86 JRE (1.6.0_45-b06), built on Mar 26 2013 13:40:03 by "java_re" with MS VC++ 7.1 (VS2003)

        time: Wed Dec 16 11:07:59 2015
        elapsed time: 160 seconds


来源: stackexchange

问:
NodeJS Cannot find module 'io' ( socket.io with express 4.15.3)
I am new in NodeJS. I am trying to run simple chat application with express and socket.io module, but when I run application, on the page where I am using socket, on console I am getting this error, and can't understand the problem. on web page I am getting this (see attached image)

```<code>Error: Cannot find module 'io'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at new View (/Applications/XAMPP/xamppfiles/htdocs/NODE/express/node_modules/express/lib/view.js:80:30)
</code>```

Actually I have found this example in internet ( https://github.com/socketio/socket.io/tree/master/examples/chat ), and try to join it to my project.For view I am using EJS. All my JS and css files in public directory, I have copied socket.io.js from node_modules/socket.io-client/dist/socket.io.js to my javascript directory. Here is my code.

app.js

```<code>let express = require('express');
let bodyParser = require('body-parser');
let path = require('path');
let expressValidator = require('express-validator');
let db = require('mysql');
let sessions = require('express-session');

let session;

let app = express();

let connection = db.createConnection({
    host:"localhost",
    user:'root',
    password:'',
    database:'oulala'
});

connection.connect((error)=>{
    if(error){
        console.log('Error')
    }else{
        console.log("connected");
    }
});

//Body parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(sessions({
    secret:'$%2878asd8783yuh3b129x831726375r367*&^%$#',
    resave:false,
    saveUninitialized:true
}))

//View engine
app.set('view engine','ejs');
app.set('views',path.join(__dirname,'views'));

app.use(express.static(__dirname + '/public'));

//Global Vars

app.use((req,res,next)=>{
    res.locals.errors = null;
    res.locals.isAuthenticated = false;
    next();
});

app.use(expressValidator({
    errorFormatter: (param,msg,value)=>{
        let namespace = param.split('.')
        , root = namespace.shift()
        , formParam = root;

        while(namespace.length){
            formParam+= '['+namespace.shift()+']';
        }
        return {
            param : formParam,
            msg   : msg,
            value : value
        }

    }
}));

app.get('/logout',(req,res)=>{
    req.session.destroy((error)=>{
        res.redirect('/');
    })
})

app.post('/login',(req,res) => {
    session = req.session;
    req.checkBody('username','Username is required').notEmpty();
    req.checkBody('password','Password is required').notEmpty();
    errors = req.validationErrors();
    if ( errors ) {
        res.render('login',{
            title:"Login",
            errors:errors
        });
    }else{
        if(req.body.username == 'admin' && req.body.password == 'admin'){
            session.uniqueID = req.body.username;
            isAuthenticated = true;
        }
        res.redirect('/');
    }
})

app.get('/:page?',(req,res) => {
    //res.send('Hello first page');
    //res.json(people);

    let page = req.params.page;
    if ( page ) {
        if ( page == 'posts' ){
            connection.query("SELECT * FROM members",(error,rows,fields)=>{
                if(error){
                    connection.release();
                    console.log('Error in the query - '+error);

                }else{
                    res.render(page,{
                        title:page,
                        users:rows
                    });
                }
            });

        }else{
            res.render(page,{
                title:page,
                user:authenticate
            });
        }

    }else{

        session = req.session;
        if(session.uniqueID){
            res.render('index',{
                title:"Index",
                user:authenticate
            });
        }else{
            res.render('login',{
                title:"Login",
                user:authenticate
            });
        }
    }

});

// get form submition, post request
app.post('/users/add',(req,res) => {
    //console.log(req.body.first_name); // req.body - request object

    req.checkBody('first_name','Fisrtname is required').notEmpty();
    req.checkBody('last_name','Lastname is required').notEmpty();
    req.checkBody('email','Email is required').notEmpty();
    errors = req.validationErrors();

    if ( errors ) {
        res.render('index',{
            title:"Customers",
            users:people,
            errors:errors
        });
    }else{
        var newUser = {
            first_name:req.body.first_name,
            last_name:req.body.last_name,
            email:req.body.email
        }

        people.push(newUser);

        res.render(page,{
            title:page,
            users:people,
            user:authenticate
        });
    }

});

app.listen(3000, () => {
    console.log('server started on port 3000....');
});

var server = require('http').createServer(app);
var io = require('socket.io')(server);

// Chatroom

var numUsers = 0;

io.on('connection', function (socket) {
  var addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new message', function (data) {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new message', {
      username: socket.username,
      message: data
    });
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', function (username) {
    if (addedUser) return;

    // we store the username in the socket session for this client
    socket.username = username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // when the client emits 'typing', we broadcast it to others
  socket.on('typing', function () {
    socket.broadcast.emit('typing', {
      username: socket.username
    });
  });

  // when the client emits 'stop typing', we broadcast it to others
  socket.on('stop typing', function () {
    socket.broadcast.emit('stop typing', {
      username: socket.username
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });
});
</code>```

client.js

```<code>$(function() {
  var FADE_TIME = 150; // ms
  var TYPING_TIMER_LENGTH = 400; // ms
  var COLORS = [
    '#e21400', '#91580f', '#f8a700', '#f78b00',
    '#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
    '#3b88eb', '#3824aa', '#a700ff', '#d300e7'
  ];

  // Initialize variables
  var $window = $(window);
  var $usernameInput = $('.usernameInput'); // Input for username
  var $messages = $('.messages'); // Messages area
  var $inputMessage = $('.inputMessage'); // Input message input box

  var $loginPage = $('.login.page'); // The login page
  var $chatPage = $('.chat.page'); // The chatroom page

  // Prompt for setting a username
  var username;
  var connected = false;
  var typing = false;
  var lastTypingTime;
  var $currentInput = $usernameInput.focus();

  var socket = io();

  function addParticipantsMessage (data) {
    var message = '';
    if (data.numUsers === 1) {
      message += "there's 1 participant";
    } else {
      message += "there are " + data.numUsers + " participants";
    }
    log(message);
  }

  // Sets the client's username
  function setUsername () {
    username = cleanInput($usernameInput.val().trim());

    // If the username is valid
    if (username) {
      $loginPage.fadeOut();
      $chatPage.show();
      $loginPage.off('click');
      $currentInput = $inputMessage.focus();

      // Tell the server your username
      socket.emit('add user', username);
    }
  }

  // Sends a chat message
  function sendMessage () {
    var message = $inputMessage.val();
    // Prevent markup from being injected into the message
    message = cleanInput(message);
    // if there is a non-empty message and a socket connection
    if (message && connected) {
      $inputMessage.val('');
      addChatMessage({
        username: username,
        message: message
      });
      // tell server to execute 'new message' and send along one parameter
      socket.emit('new message', message);
    }
  }

  // Log a message
  function log (message, options) {
    var $el = $('<li>').addClass('log').text(message);
    addMessageElement($el, options);
  }

  // Adds the visual chat message to the message list
  function addChatMessage (data, options) {
    // Don't fade the message in if there is an 'X was typing'
    var $typingMessages = getTypingMessages(data);
    options = options || {};
    if ($typingMessages.length !== 0) {
      options.fade = false;
      $typingMessages.remove();
    }

    var $usernameDiv = $('<span class="username"/>')
      .text(data.username)
      .css('color', getUsernameColor(data.username));
    var $messageBodyDiv = $('<span class="messageBody">')
      .text(data.message);

    var typingClass = data.typing ? 'typing' : '';
    var $messageDiv = $('<li class="message"/>')
      .data('username', data.username)
      .addClass(typingClass)
      .append($usernameDiv, $messageBodyDiv);

    addMessageElement($messageDiv, options);
  }

  // Adds the visual chat typing message
  function addChatTyping (data) {
    data.typing = true;
    data.message = 'is typing';
    addChatMessage(data);
  }

  // Removes the visual chat typing message
  function removeChatTyping (data) {
    getTypingMessages(data).fadeOut(function () {
      $(this).remove();
    });
  }

  // Adds a message element to the messages and scrolls to the bottom
  // el - The element to add as a message
  // options.fade - If the element should fade-in (default = true)
  // options.prepend - If the element should prepend
  //   all other messages (default = false)
  function addMessageElement (el, options) {
    var $el = $(el);

    // Setup default options
    if (!options) {
      options = {};
    }
    if (typeof options.fade === 'undefined') {
      options.fade = true;
    }
    if (typeof options.prepend === 'undefined') {
      options.prepend = false;
    }

    // Apply options
    if (options.fade) {
      $el.hide().fadeIn(FADE_TIME);
    }
    if (options.prepend) {
      $messages.prepend($el);
    } else {
      $messages.append($el);
    }
    $messages[0].scrollTop = $messages[0].scrollHeight;
  }

  // Prevents input from having injected markup
  function cleanInput (input) {
    return $('<div/>').text(input).text();
  }

  // Updates the typing event
  function updateTyping () {
    if (connected) {
      if (!typing) {
        typing = true;
        socket.emit('typing');
      }
      lastTypingTime = (new Date()).getTime();

      setTimeout(function () {
        var typingTimer = (new Date()).getTime();
        var timeDiff = typingTimer - lastTypingTime;
        if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
          socket.emit('stop typing');
          typing = false;
        }
      }, TYPING_TIMER_LENGTH);
    }
  }

  // Gets the 'X is typing' messages of a user
  function getTypingMessages (data) {
    return $('.typing.message').filter(function (i) {
      return $(this).data('username') === data.username;
    });
  }

  // Gets the color of a username through our hash function
  function getUsernameColor (username) {
    // Compute hash code
    var hash = 7;
    for (var i = 0; i < username.length; i++) {
       hash = username.charCodeAt(i) + (hash << 5) - hash;
    }
    // Calculate color
    var index = Math.abs(hash % COLORS.length);
    return COLORS[index];
  }

  // Keyboard events

  $window.keydown(function (event) {
    // Auto-focus the current input when a key is typed
    if (!(event.ctrlKey || event.metaKey || event.altKey)) {
      $currentInput.focus();
    }
    // When the client hits ENTER on their keyboard
    if (event.which === 13) {
      if (username) {
        sendMessage();
        socket.emit('stop typing');
        typing = false;
      } else {
        setUsername();
      }
    }
  });

  $inputMessage.on('input', function() {
    updateTyping();
  });

  // Click events

  // Focus input when clicking anywhere on login page
  $loginPage.click(function () {
    $currentInput.focus();
  });

  // Focus input when clicking on the message input's border
  $inputMessage.click(function () {
    $inputMessage.focus();
  });

  // Socket events

  // Whenever the server emits 'login', log the login message
  socket.on('login', function (data) {
    connected = true;
    // Display the welcome message
    var message = "Welcome to Socket.IO Chat – ";
    log(message, {
      prepend: true
    });
    addParticipantsMessage(data);
  });

  // Whenever the server emits 'new message', update the chat body
  socket.on('new message', function (data) {
    addChatMessage(data);
  });

  // Whenever the server emits 'user joined', log it in the chat body
  socket.on('user joined', function (data) {
    log(data.username + ' joined');
    addParticipantsMessage(data);
  });

  // Whenever the server emits 'user left', log it in the chat body
  socket.on('user left', function (data) {
    log(data.username + ' left');
    addParticipantsMessage(data);
    removeChatTyping(data);
  });

  // Whenever the server emits 'typing', show the typing message
  socket.on('typing', function (data) {
    addChatTyping(data);
  });

  // Whenever the server emits 'stop typing', kill the typing message
  socket.on('stop typing', function (data) {
    removeChatTyping(data);
  });

  socket.on('disconnect', function () {
    log('you have been disconnected');
  });

  socket.on('reconnect', function () {
    log('you have been reconnected');
    if (username) {
      socket.emit('add user', username);
    }
  });

  socket.on('reconnect_error', function () {
    log('attempt to reconnect has failed');
  });

});
</code>```

index.ejs

```<code><% include partials/header %>
    <h1><%= title %></h1>
    <ul class="pages">
    <li class="chat page">
      <div class="chatArea">
        <ul class="messages"></ul>
      </div>
      <input class="inputMessage" placeholder="Type here..."/>
    </li>
    <li class="login page">
      <div class="form">
        <h3 class="title">What's your nickname?</h3>
        <input class="usernameInput" type="text" maxlength="14" />
      </div>
    </li>
  </ul>
    <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script src="/javascript/socket.io.js"></script>
    <script src="/javascript/client.js"></script>
<% include partials/footer %>
</code>```

package.json

```<code>{
  "name": "customerapp",
  "version": "1.0.0",
  "description": "Simple customer managment app",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Anna Gabrielyan",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.17.2",
    "ejs": "^2.5.6",
    "express": "^4.15.3",
    "express-session": "^1.15.3",
    "express-validator": "^3.2.0",
    "mysql": "^3.10.10",
    "oauth2-server": "^2.4.1",
    "socket.io": "^2.0.2"
  }
}
</code>```

答:
First you need to install packages using below command

```<code>npm install
</code>```

This command will install all the packages from your package.json once done you can run this program.

ContentLicense: CC BY-SA 3.0

Body:
I am new in NodeJS. I am trying to run simple chat application with express and socket.io module, but when I run application, on the page where I am using socket, on console I am getting this error, and can't understand the problem. on web page I am getting this (see attached image)

Error: Cannot find module 'io'
    at Function.Module._resolveFilename (module.js:469:15)
    at Function.Module._load (module.js:417:25)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at new View (/Applications/XAMPP/xamppfiles/htdocs/NODE/express/node_modules/express/lib/view.js:80:30)

Actually I have found this example in internet ( https://github.com/socketio/socket.io/tree/master/examples/chat ), and try to join it to my project.For view I am using EJS. All my JS and css files in public directory, I have copied socket.io.js from node_modules/socket.io-client/dist/socket.io.js to my javascript directory. Here is my code.

app.js

let express = require('express');
let bodyParser = require('body-parser');
let path = require('path');
let expressValidator = require('express-validator');
let db = require('mysql');
let sessions = require('express-session');

let session;

let app = express();

let connection = db.createConnection({
    host:"localhost",
    user:'root',
    password:'',
    database:'oulala'
});

connection.connect((error)=>{
    if(error){
        console.log('Error')
    }else{
        console.log("connected");
    }
});

//Body parser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(sessions({
    secret:'$%2878asd8783yuh3b129x831726375r367*&^%$#',
    resave:false,
    saveUninitialized:true
}))

//View engine
app.set('view engine','ejs');
app.set('views',path.join(__dirname,'views'));

app.use(express.static(__dirname + '/public'));

//Global Vars

app.use((req,res,next)=>{
    res.locals.errors = null;
    res.locals.isAuthenticated = false;
    next();
});

app.use(expressValidator({
    errorFormatter: (param,msg,value)=>{
        let namespace = param.split('.')
        , root = namespace.shift()
        , formParam = root;

        while(namespace.length){
            formParam+= '['+namespace.shift()+']';
        }
        return {
            param : formParam,
            msg   : msg,
            value : value
        }

    }
}));

app.get('/logout',(req,res)=>{
    req.session.destroy((error)=>{
        res.redirect('/');
    })
})

app.post('/login',(req,res) => {
    session = req.session;
    req.checkBody('username','Username is required').notEmpty();
    req.checkBody('password','Password is required').notEmpty();
    errors = req.validationErrors();
    if ( errors ) {
        res.render('login',{
            title:"Login",
            errors:errors
        });
    }else{
        if(req.body.username == 'admin' && req.body.password == 'admin'){
            session.uniqueID = req.body.username;
            isAuthenticated = true;
        }
        res.redirect('/');
    }
})

app.get('/:page?',(req,res) => {
    //res.send('Hello first page');
    //res.json(people);

    let page = req.params.page;
    if ( page ) {
        if ( page == 'posts' ){
            connection.query("SELECT * FROM members",(error,rows,fields)=>{
                if(error){
                    connection.release();
                    console.log('Error in the query - '+error);

                }else{
                    res.render(page,{
                        title:page,
                        users:rows
                    });
                }
            });

        }else{
            res.render(page,{
                title:page,
                user:authenticate
            });
        }

    }else{

        session = req.session;
        if(session.uniqueID){
            res.render('index',{
                title:"Index",
                user:authenticate
            });
        }else{
            res.render('login',{
                title:"Login",
                user:authenticate
            });
        }
    }

});

// get form submition, post request
app.post('/users/add',(req,res) => {
    //console.log(req.body.first_name); // req.body - request object

    req.checkBody('first_name','Fisrtname is required').notEmpty();
    req.checkBody('last_name','Lastname is required').notEmpty();
    req.checkBody('email','Email is required').notEmpty();
    errors = req.validationErrors();

    if ( errors ) {
        res.render('index',{
            title:"Customers",
            users:people,
            errors:errors
        });
    }else{
        var newUser = {
            first_name:req.body.first_name,
            last_name:req.body.last_name,
            email:req.body.email
        }

        people.push(newUser);

        res.render(page,{
            title:page,
            users:people,
            user:authenticate
        });
    }

});

app.listen(3000, () => {
    console.log('server started on port 3000....');
});

var server = require('http').createServer(app);
var io = require('socket.io')(server);

// Chatroom

var numUsers = 0;

io.on('connection', function (socket) {
  var addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new message', function (data) {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new message', {
      username: socket.username,
      message: data
    });
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', function (username) {
    if (addedUser) return;

    // we store the username in the socket session for this client
    socket.username = username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // when the client emits 'typing', we broadcast it to others
  socket.on('typing', function () {
    socket.broadcast.emit('typing', {
      username: socket.username
    });
  });

  // when the client emits 'stop typing', we broadcast it to others
  socket.on('stop typing', function () {
    socket.broadcast.emit('stop typing', {
      username: socket.username
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });
});

client.js

$(function() {
  var FADE_TIME = 150; // ms
  var TYPING_TIMER_LENGTH = 400; // ms
  var COLORS = [
    '#e21400', '#91580f', '#f8a700', '#f78b00',
    '#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
    '#3b88eb', '#3824aa', '#a700ff', '#d300e7'
  ];

  // Initialize variables
  var $window = $(window);
  var $usernameInput = $('.usernameInput'); // Input for username
  var $messages = $('.messages'); // Messages area
  var $inputMessage = $('.inputMessage'); // Input message input box

  var $loginPage = $('.login.page'); // The login page
  var $chatPage = $('.chat.page'); // The chatroom page

  // Prompt for setting a username
  var username;
  var connected = false;
  var typing = false;
  var lastTypingTime;
  var $currentInput = $usernameInput.focus();

  var socket = io();

  function addParticipantsMessage (data) {
    var message = '';
    if (data.numUsers === 1) {
      message += "there's 1 participant";
    } else {
      message += "there are " + data.numUsers + " participants";
    }
    log(message);
  }

  // Sets the client's username
  function setUsername () {
    username = cleanInput($usernameInput.val().trim());

    // If the username is valid
    if (username) {
      $loginPage.fadeOut();
      $chatPage.show();
      $loginPage.off('click');
      $currentInput = $inputMessage.focus();

      // Tell the server your username
      socket.emit('add user', username);
    }
  }

  // Sends a chat message
  function sendMessage () {
    var message = $inputMessage.val();
    // Prevent markup from being injected into the message
    message = cleanInput(message);
    // if there is a non-empty message and a socket connection
    if (message && connected) {
      $inputMessage.val('');
      addChatMessage({
        username: username,
        message: message
      });
      // tell server to execute 'new message' and send along one parameter
      socket.emit('new message', message);
    }
  }

  // Log a message
  function log (message, options) {
    var $el = $('
').addClass('log').text(message);
    addMessageElement($el, options);
  }

  // Adds the visual chat message to the message list
  function addChatMessage (data, options) {
    // Don't fade the message in if there is an 'X was typing'
    var $typingMessages = getTypingMessages(data);
    options = options || {};
    if ($typingMessages.length !== 0) {
      options.fade = false;
      $typingMessages.remove();
    }

    var $usernameDiv = $('')
      .text(data.username)
      .css('color', getUsernameColor(data.username));
    var $messageBodyDiv = $('')
      .text(data.message);

    var typingClass = data.typing ? 'typing' : '';
    var $messageDiv = $('
')
      .data('username', data.username)
      .addClass(typingClass)
      .append($usernameDiv, $messageBodyDiv);

    addMessageElement($messageDiv, options);
  }

  // Adds the visual chat typing message
  function addChatTyping (data) {
    data.typing = true;
    data.message = 'is typing';
    addChatMessage(data);
  }

  // Removes the visual chat typing message
  function removeChatTyping (data) {
    getTypingMessages(data).fadeOut(function () {
      $(this).remove();
    });
  }

  // Adds a message element to the messages and scrolls to the bottom
  // el - The element to add as a message
  // options.fade - If the element should fade-in (default = true)
  // options.prepend - If the element should prepend
  //   all other messages (default = false)
  function addMessageElement (el, options) {
    var $el = $(el);

    // Setup default options
    if (!options) {
      options = {};
    }
    if (typeof options.fade === 'undefined') {
      options.fade = true;
    }
    if (typeof options.prepend === 'undefined') {
      options.prepend = false;
    }

    // Apply options
    if (options.fade) {
      $el.hide().fadeIn(FADE_TIME);
    }
    if (options.prepend) {
      $messages.prepend($el);
    } else {
      $messages.append($el);
    }
    $messages[0].scrollTop = $messages[0].scrollHeight;
  }

  // Prevents input from having injected markup
  function cleanInput (input) {
    return $('
').text(input).text();
  }

  // Updates the typing event
  function updateTyping () {
    if (connected) {
      if (!typing) {
        typing = true;
        socket.emit('typing');
      }
      lastTypingTime = (new Date()).getTime();

      setTimeout(function () {
        var typingTimer = (new Date()).getTime();
        var timeDiff = typingTimer - lastTypingTime;
        if (timeDiff >= TYPING_TIMER_LENGTH && typing) {
          socket.emit('stop typing');
          typing = false;
        }
      }, TYPING_TIMER_LENGTH);
    }
  }

  // Gets the 'X is typing' messages of a user
  function getTypingMessages (data) {
    return $('.typing.message').filter(function (i) {
      return $(this).data('username') === data.username;
    });
  }

  // Gets the color of a username through our hash function
  function getUsernameColor (username) {
    // Compute hash code
    var hash = 7;
    for (var i = 0; i < username.length; i++) {
       hash = username.charCodeAt(i) + (hash << 5) - hash;
    }
    // Calculate color
    var index = Math.abs(hash % COLORS.length);
    return COLORS[index];
  }

  // Keyboard events

  $window.keydown(function (event) {
    // Auto-focus the current input when a key is typed
    if (!(event.ctrlKey || event.metaKey || event.altKey)) {
      $currentInput.focus();
    }
    // When the client hits ENTER on their keyboard
    if (event.which === 13) {
      if (username) {
        sendMessage();
        socket.emit('stop typing');
        typing = false;
      } else {
        setUsername();
      }
    }
  });

  $inputMessage.on('input', function() {
    updateTyping();
  });

  // Click events

  // Focus input when clicking anywhere on login page
  $loginPage.click(function () {
    $currentInput.focus();
  });

  // Focus input when clicking on the message input's border
  $inputMessage.click(function () {
    $inputMessage.focus();
  });

  // Socket events

  // Whenever the server emits 'login', log the login message
  socket.on('login', function (data) {
    connected = true;
    // Display the welcome message
    var message = "Welcome to Socket.IO Chat – ";
    log(message, {
      prepend: true
    });
    addParticipantsMessage(data);
  });

  // Whenever the server emits 'new message', update the chat body
  socket.on('new message', function (data) {
    addChatMessage(data);
  });

  // Whenever the server emits 'user joined', log it in the chat body
  socket.on('user joined', function (data) {
    log(data.username + ' joined');
    addParticipantsMessage(data);
  });

  // Whenever the server emits 'user left', log it in the chat body
  socket.on('user left', function (data) {
    log(data.username + ' left');
    addParticipantsMessage(data);
    removeChatTyping(data);
  });

  // Whenever the server emits 'typing', show the typing message
  socket.on('typing', function (data) {
    addChatTyping(data);
  });

  // Whenever the server emits 'stop typing', kill the typing message
  socket.on('stop typing', function (data) {
    removeChatTyping(data);
  });

  socket.on('disconnect', function () {
    log('you have been disconnected');
  });

  socket.on('reconnect', function () {
    log('you have been reconnected');
    if (username) {
      socket.emit('add user', username);
    }
  });

  socket.on('reconnect_error', function () {
    log('attempt to reconnect has failed');
  });

});

index.ejs

<% include partials/header %>

<%= title %>

      <input class="inputMessage" placeholder="Type here..."/>

What's your nickname?

        <input class="usernameInput" type="text" maxlength="14" />

<% include partials/footer %>

package.json

{
  "name": "customerapp",
  "version": "1.0.0",
  "description": "Simple customer managment app",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Anna Gabrielyan",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.17.2",
    "ejs": "^2.5.6",
    "express": "^4.15.3",
    "express-session": "^1.15.3",
    "express-validator": "^3.2.0",
    "mysql": "^3.10.10",
    "oauth2-server": "^2.4.1",
    "socket.io": "^2.0.2"
  }
}

Body:
First you need to install packages using below command

npm install

This command will install all the packages from your package.json once done you can run this program.


问:
Always show service in notification bar
I want to add my app to the notification bar so that it always shows, like some apps in the Google Play store.

I want it to be like this screen shot:

I want my notification to not be cleared, and for my app to be opened when the notification is clicked.

Here's My Service Class Code:

```<code>package com.demo;

import java.util.Random;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

public class ServiceExample extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this,"Service Created",300).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this,"Service Destroy",300).show();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Toast.makeText(this,"Service LowMemory",300).show();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Toast.makeText(this,"Service start",300).show();
        Notification notification = new Notification(R.drawable.ic_launcher,
                "Rolling text on statusbar", System.currentTimeMillis());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, ServiceDemoActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setLatestEventInfo(this,
                "Notification title", "Notification description", contentIntent);

        startForeground(1, notification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Toast.makeText(this,"task perform in service",300).show();
        /*ThreadDemo td=new ThreadDemo();
        td.start();*/
        Notification notification = new Notification(R.drawable.ic_launcher,
                "Rolling text on statusbar", System.currentTimeMillis());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, ServiceDemoActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setLatestEventInfo(this,
                "Notification title", "Notification description", contentIntent);

        startForeground(1, notification);

        return super.onStartCommand(intent, flags, startId);
    }

    private class ThreadDemo extends Thread{
        @Override
        public void run() {
            super.run();
            try{
            sleep(70*1000);
            handler.sendEmptyMessage(0);
            }catch(Exception e){
                e.getMessage();
            }
        }
    }
   private Handler handler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        showAppNotification();
    }
   };

   void showAppNotification() {
       try{
        NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        // The PendingIntent to launch our activity if the user selects this
        // notification.  Note the use of FLAG_CANCEL_CURRENT so that, if there
        // is already an active matching pending intent, cancel it and replace
        // it with the new array of Intents.
//      PendingIntent contentIntent = PendingIntent.getActivities(this, 0,
//             "My service completed", PendingIntent.FLAG_CANCEL_CURRENT);

        // The ticker text, this uses a formatted string so our message could be localized
        String tickerText ="djdjsdjkd";

        // construct the Notification object.
        Notification notif = new Notification(R.drawable.ic_launcher, tickerText,
                System.currentTimeMillis());

        // Set the info for the views that show in the notification panel.
//      notif.setLatestEventInfo(this, from, message, contentIntent);

        // We'll have this notification do the default sound, vibration, and led.
        // Note that if you want any of these behaviors, you should always have
        // a preference for the user to turn them off.
        notif.defaults = Notification.DEFAULT_ALL;

        // Note that we use R.layout.incoming_message_panel as the ID for
        // the notification.  It could be any integer you want, but we use
        // the convention of using a resource id for a string related to
        // the notification.  It will always be a unique number within your
        // application.
        nm.notify(0, notif);
       }catch(Exception e){
           e.getMessage();
       }
    }
}
</code>```

And I declare my Service in my project manifest file:

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

    <uses-sdk android:minSdkVersion="8" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".ServiceDemoActivity"
            android:label="@string/app_name"  >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".ServiceExample"></service>
    </application>

</manifest>
</code>```

Here's my class for starting and stopping the Service:

```<code>package com.demo;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ReceiverCallNotAllowedException;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

public class ServiceDemoActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.start).setOnClickListener(this);
        findViewById(R.id.stop).setOnClickListener(this);
    }

    private Intent inetnt;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.start:

            inetnt=new Intent(this,ServiceExample.class);
            startService(inetnt);
            break;
        case R.id.stop:

            inetnt=new Intent(this,ServiceExample.class);
            stopService(inetnt);
            break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//
    }
}
</code>```

Here's my layout code:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="StartService"
        android:id="@+id/start"/>

        <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="StopService"
        android:id="@+id/stop" />

</LinearLayout>
</code>```

答:
Just use below code to always show notification bar.</p>

```<code>    Notification.Builder builder = new Notification.Builder(MainActivity.this);
    builder.setSmallIcon(R.mipmap.ic_launcher)
            .setContentText("Call Recorder")
            .setAutoCancel(false);
    Notification notification = builder.getNotification();

    notification.flags |= Notification.FLAG_NO_CLEAR
            | Notification.FLAG_ONGOING_EVENT;

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(1, notification);
</code>```

Title: Always show service in notification bar

Body:
I want to add my app to the notification bar so that it always shows, like some apps in the Google Play store.

I want it to be like this screen shot:

I want my notification to not be cleared, and for my app to be opened when the notification is clicked.

Here's My Service Class Code:

package com.demo;

import java.util.Random;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;

public class ServiceExample extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Toast.makeText(this,"Service Created",300).show();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this,"Service Destroy",300).show();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        Toast.makeText(this,"Service LowMemory",300).show();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Toast.makeText(this,"Service start",300).show();
        Notification notification = new Notification(R.drawable.ic_launcher,
                "Rolling text on statusbar", System.currentTimeMillis());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, ServiceDemoActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setLatestEventInfo(this,
                "Notification title", "Notification description", contentIntent);

        startForeground(1, notification);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Toast.makeText(this,"task perform in service",300).show();
        /*ThreadDemo td=new ThreadDemo();
        td.start();*/
        Notification notification = new Notification(R.drawable.ic_launcher,
                "Rolling text on statusbar", System.currentTimeMillis());

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, ServiceDemoActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setLatestEventInfo(this,
                "Notification title", "Notification description", contentIntent);

        startForeground(1, notification);

        return super.onStartCommand(intent, flags, startId);
    }

    private class ThreadDemo extends Thread{
        @Override
        public void run() {
            super.run();
            try{
            sleep(70*1000);
            handler.sendEmptyMessage(0);
            }catch(Exception e){
                e.getMessage();
            }
        }
    }
   private Handler handler=new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        showAppNotification();
    }
   };

   void showAppNotification() {
       try{
        NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        // The PendingIntent to launch our activity if the user selects this
        // notification.  Note the use of FLAG_CANCEL_CURRENT so that, if there
        // is already an active matching pending intent, cancel it and replace
        // it with the new array of Intents.
//      PendingIntent contentIntent = PendingIntent.getActivities(this, 0,
//             "My service completed", PendingIntent.FLAG_CANCEL_CURRENT);

        // The ticker text, this uses a formatted string so our message could be localized
        String tickerText ="djdjsdjkd";

        // construct the Notification object.
        Notification notif = new Notification(R.drawable.ic_launcher, tickerText,
                System.currentTimeMillis());

        // Set the info for the views that show in the notification panel.
//      notif.setLatestEventInfo(this, from, message, contentIntent);

        // We'll have this notification do the default sound, vibration, and led.
        // Note that if you want any of these behaviors, you should always have
        // a preference for the user to turn them off.
        notif.defaults = Notification.DEFAULT_ALL;

        // Note that we use R.layout.incoming_message_panel as the ID for
        // the notification.  It could be any integer you want, but we use
        // the convention of using a resource id for a string related to
        // the notification.  It will always be a unique number within your
        // application.
        nm.notify(0, notif);
       }catch(Exception e){
           e.getMessage();
       }
    }
}

And I declare my Service in my project manifest file:

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

    <uses-sdk android:minSdkVersion="8" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".ServiceDemoActivity"
            android:label="@string/app_name"  >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".ServiceExample"></service>
    </application>

</manifest>

Here's my class for starting and stopping the Service:

package com.demo;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ReceiverCallNotAllowedException;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

public class ServiceDemoActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.start).setOnClickListener(this);
        findViewById(R.id.stop).setOnClickListener(this);
    }

    private Intent inetnt;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.start:

            inetnt=new Intent(this,ServiceExample.class);
            startService(inetnt);
            break;
        case R.id.stop:

            inetnt=new Intent(this,ServiceExample.class);
            stopService(inetnt);
            break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//
    }
}

Here's my layout code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="StartService"
        android:id="@+id/start"/>

        <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="StopService"
        android:id="@+id/stop" />

</LinearLayout>

Body:
Just use below code to always show notification bar.

    Notification.Builder builder = new Notification.Builder(MainActivity.this);
    builder.setSmallIcon(R.mipmap.ic_launcher)
            .setContentText("Call Recorder")
            .setAutoCancel(false);
    Notification notification = builder.getNotification();

    notification.flags |= Notification.FLAG_NO_CLEAR
            | Notification.FLAG_ONGOING_EVENT;

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(1, notification);


问:
How to redirect in after executes the query php
Here is my code:

```<code>    $id = $_GET['id'];
$data = $_POST['name'];
$data1 = $_POST['id'];
$c = 0;

foreach ($data1 as $key => $value) {
    $sql = "UPDATE ".$table_comp." SET score = " . $data[$c][$value] . " where id = " . $value .";" ;
    mysqli_query($connect,$sql);
    $c++;
}
header('Location: http://www.csscorecard.com/admin/?id=$id');
</code>```

I have problem in my redirect there is an error:

Warning: Cannot modify header information - headers already sent by (output started at /home/csscorecard/public_html/wp-content/themes/twentyseventeen/ajax/submit.php:3) in /home/csscorecard/public_html/wp-content/themes/twentyseventeen/ajax/submit.php on line 54

答: You can add  ob_start();  top of the file

Body:
Here is my code:

    $id = $_GET['id'];
$data = $_POST['name'];
$data1 = $_POST['id'];
$c = 0;

foreach ($data1 as $key => $value) {
    $sql = "UPDATE ".$table_comp." SET score = " . $data[$c][$value] . " where id = " . $value .";" ;
    mysqli_query($connect,$sql);
    $c++;
}
header('Location: http://www.csscorecard.com/admin/?id=$id');

I have problem in my redirect there is an error:

Warning: Cannot modify header information - headers already sent by (output started at /home/csscorecard/public_html/wp-content/themes/twentyseventeen/ajax/submit.php:3) in /home/csscorecard/public_html/wp-content/themes/twentyseventeen/ajax/submit.php on line 54

Body: You can add  ob_start();  top of the file


问:
Displaying current and previous pay period in SQL (based on an imported table)
I need to display the current AND last pay periods based on an imported table for biweekly pay dates. The table looks something like this:

```<code>2017-03-23 00:00:00 2017-04-06 00:00:00
2017-04-07 00:00:00 2017-04-20 00:00:00
2017-04-21 00:00:00 2017-05-06 00:00:00
2017-05-07 00:00:00 2017-05-20 00:00:00
2017-05-21 00:00:00 2017-06-05 00:00:00
2017-06-06 00:00:00 2017-06-22 00:00:00
2017-06-23 00:00:00 2017-07-06 00:00:00
2017-07-07 00:00:00 2017-07-21 00:00:00
</code>```

This code:

```<code>     SELECT *
     FROM
       table1
     WHERE
       (start_date <= now()  AND end_date >= now())
</code>```

Displays:

```<code>2017-06-06 00:00:00 2017-06-22 00:00:00
</code>```

How can I display the previous pay period?
Such as:

```<code>2017-05-21 00:00:00 2017-06-05 00:00:00
</code>```

This code just doesn't even look right, but I tried it anyways:

```<code>SELECT start_date,
CASE
    WHEN start_date = now() THEN    start_date = now() - 1
    WHEN end_date = now() THEN start_date = now() - 1
END
FROM table1;
</code>```

I know there is a way to use CASE WHEN but for some reason, I cannot get the syntax right using now() since I want it to be dynamic and not a static date.

答:
```<code> SELECT concat(start_date,'  ',
CASE
    WHEN start_date = now() THEN start_date = now() -  INTERVAL 1 DAY
WHEN end_date = now() THEN start_date =  now() - INTERVAL 1 DAY
END) AS PeriodOfPay
FROM table1;
</code>```

Body:
I need to display the current AND last pay periods based on an imported table for biweekly pay dates. The table looks something like this:

2017-03-23 00:00:00 2017-04-06 00:00:00
2017-04-07 00:00:00 2017-04-20 00:00:00
2017-04-21 00:00:00 2017-05-06 00:00:00
2017-05-07 00:00:00 2017-05-20 00:00:00
2017-05-21 00:00:00 2017-06-05 00:00:00
2017-06-06 00:00:00 2017-06-22 00:00:00
2017-06-23 00:00:00 2017-07-06 00:00:00
2017-07-07 00:00:00 2017-07-21 00:00:00

This code:

     SELECT *
     FROM
       table1
     WHERE
       (start_date <= now()  AND end_date >= now())

Displays:

2017-06-06 00:00:00 2017-06-22 00:00:00

How can I display the previous pay period?
Such as:

2017-05-21 00:00:00 2017-06-05 00:00:00

This code just doesn't even look right, but I tried it anyways:

SELECT start_date,
CASE
    WHEN start_date = now() THEN    start_date = now() - 1
    WHEN end_date = now() THEN start_date = now() - 1
END
FROM table1;

I know there is a way to use CASE WHEN but for some reason, I cannot get the syntax right using now() since I want it to be dynamic and not a static date.


问:
Android - RoomDb - Entity inserted successfully not found on select query in another Activity
I have an Entity(Kotlin code):

```<code>@Entity(foreignKeys = arrayOf(ForeignKey(entity = Agent::class, parentColumns = arrayOf("guid"), childColumns = arrayOf("agentGuid"), onDelete = ForeignKey.CASCADE)))
data class Client (@PrimaryKey
                   var guid: String = "",
                   var name: String = "",
                   var email: String = "",
                   var phone: String = "",
                   var address: String = "",
                   var agentGuid: String = "")
</code>```

Here is respective Dao Class:

```<code>@Dao
public interface ClientDao {
    @Query("SELECT * FROM Client where guid = :clientGUID LIMIT 1")
    Client getClient(String clientGUID);

    @Query("SELECT * FROM Client where agentGuid = :agentGUID")
    List<Client> getClients(String agentGUID);

    @Insert
    void insertClient(Client client);
}
</code>```

Here is the Background Task in which I am performing insert operation:

```<code>interface UpdateClientTaskResponseHandler {
    fun clientUpdated(client: Client)
    fun clientUpdateFailed()
}
data class ClientData(var client: Client, var documents: ArrayList<Document>)

class UpdateClientDataTask(val responseHandler: UpdateClientTaskResponseHandler): AsyncTask<ClientData, Void, Client?>() {
    override fun doInBackground(vararg params: ClientData?): Client? {
        params[0]?.let {
            val clientDao = MyApp.database!!.clientDao()
            //1: Check if client exists or not
            val client = clientDao.getClient(it.client.guid)
            if (client != null) {
                //TODO: to be handled
                // Update functionality
            } else {
                //2. Insert client
                clientDao.insertClient(it.client)

                //3. Insert all documents
                if (it.documents.size > 0) {
                    val documentDao = MyApp.database!!.documentDao()
                    documentDao.insertDocuments(it.documents)
                }

                return it.client
            }

            return null
        }
        return null
    }

    override fun onPostExecute(result: Client?) {
        result?.let {
            responseHandler.clientUpdated(it)
        } ?: responseHandler.clientUpdateFailed()
    }
}
</code>```

I am using below code to insert the Entity:

```<code>public void confirmClient(View view) {
        // Creating client object
        Client client = new Client(clientGuid, name, email, phone, address, agentGuid);
        // Creating client data object
        ClientData clientData = new ClientData(client, documentsAdapter.documents);
        UpdateClientDataTask updateClientDataTask = new UpdateClientDataTask(this);
        updateClientDataTask.execute(clientData);
    }
</code>```

On Success I am invoking below code to jump back to ClientActivity:

```<code>@Override
    public void clientUpdated(@NotNull Client client) {
        Intent clientsActivity = new Intent(this,ClientActivity.class);
        clientsActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );
        clientsActivity.putExtra(IntentKeysKt.getShouldRefreshData(), true);
        startActivity(clientsActivity);
    }
</code>```

My problem is - When I fire select query in onResume() method of ClientActivity it is not returning the inserted Entity.
Below is the Code:

```<code>private void displayClients()
    {
        Intent intent = getIntent();
        boolean shouldRefreshData = intent.getBooleanExtra(IntentKeysKt.getShouldRefreshData(),false);
        Toast.makeText(this, "shouldRefreshData="+shouldRefreshData, Toast.LENGTH_SHORT).show();
        if (shouldRefreshData) {
            //Load data from clients table
            intent.putExtra(IntentKeysKt.getShouldRefreshData(), false);
            ClientsRetrievalTask clientsRetrievalTask = new ClientsRetrievalTask(this);
            clientsRetrievalTask.execute(agentGUID);
        }
    }

@Override
    public void clientsRetrieved(@NotNull List<Client> clients) {
        clientsAdapter.refresh(new ArrayList<>(clients));
        recyclerViewClients.setVisibility(View.VISIBLE);
        frameLayoutPlaceholderFragment.setVisibility(View.INVISIBLE);
    }
</code>```

Surprisingly on next time app launch it shows inserted record. I am clueless please guid me.

答:
You should use;

Database.beginTransaction() before insert operation.

Database.setTransactionSuccessful() after insert operation.

Database.endTransaction() finally.

Sample code:

```<code>private static void insertData(AppDatabase db, List<ProductEntity> products, List<CommentEntity> comments) {
    db.beginTransaction();
    try {
        db.productDao().insertAll(products);
        db.commentDao().insertAll(comments);
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}
</code>```

Sample reference

Body:
I have an Entity(Kotlin code):

@Entity(foreignKeys = arrayOf(ForeignKey(entity = Agent::class, parentColumns = arrayOf("guid"), childColumns = arrayOf("agentGuid"), onDelete = ForeignKey.CASCADE)))
data class Client (@PrimaryKey
                   var guid: String = "",
                   var name: String = "",
                   var email: String = "",
                   var phone: String = "",
                   var address: String = "",
                   var agentGuid: String = "")

Here is respective Dao Class:

@Dao
public interface ClientDao {
    @Query("SELECT * FROM Client where guid = :clientGUID LIMIT 1")
    Client getClient(String clientGUID);

    @Query("SELECT * FROM Client where agentGuid = :agentGUID")
    List<Client> getClients(String agentGUID);

    @Insert
    void insertClient(Client client);
}

Here is the Background Task in which I am performing insert operation:

interface UpdateClientTaskResponseHandler {
    fun clientUpdated(client: Client)
    fun clientUpdateFailed()
}
data class ClientData(var client: Client, var documents: ArrayList<Document>)

class UpdateClientDataTask(val responseHandler: UpdateClientTaskResponseHandler): AsyncTask<ClientData, Void, Client?>() {
    override fun doInBackground(vararg params: ClientData?): Client? {
        params[0]?.let {
            val clientDao = MyApp.database!!.clientDao()
            //1: Check if client exists or not
            val client = clientDao.getClient(it.client.guid)
            if (client != null) {
                //TODO: to be handled
                // Update functionality
            } else {
                //2. Insert client
                clientDao.insertClient(it.client)

                //3. Insert all documents
                if (it.documents.size > 0) {
                    val documentDao = MyApp.database!!.documentDao()
                    documentDao.insertDocuments(it.documents)
                }

                return it.client
            }

            return null
        }
        return null
    }

    override fun onPostExecute(result: Client?) {
        result?.let {
            responseHandler.clientUpdated(it)
        } ?: responseHandler.clientUpdateFailed()
    }
}

I am using below code to insert the Entity:

public void confirmClient(View view) {
        // Creating client object
        Client client = new Client(clientGuid, name, email, phone, address, agentGuid);
        // Creating client data object
        ClientData clientData = new ClientData(client, documentsAdapter.documents);
        UpdateClientDataTask updateClientDataTask = new UpdateClientDataTask(this);
        updateClientDataTask.execute(clientData);
    }

On Success I am invoking below code to jump back to ClientActivity:

@Override
    public void clientUpdated(@NotNull Client client) {
        Intent clientsActivity = new Intent(this,ClientActivity.class);
        clientsActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP );
        clientsActivity.putExtra(IntentKeysKt.getShouldRefreshData(), true);
        startActivity(clientsActivity);
    }

My problem is - When I fire select query in onResume() method of ClientActivity it is not returning the inserted Entity.
Below is the Code:

private void displayClients()
    {
        Intent intent = getIntent();
        boolean shouldRefreshData = intent.getBooleanExtra(IntentKeysKt.getShouldRefreshData(),false);
        Toast.makeText(this, "shouldRefreshData="+shouldRefreshData, Toast.LENGTH_SHORT).show();
        if (shouldRefreshData) {
            //Load data from clients table
            intent.putExtra(IntentKeysKt.getShouldRefreshData(), false);
            ClientsRetrievalTask clientsRetrievalTask = new ClientsRetrievalTask(this);
            clientsRetrievalTask.execute(agentGUID);
        }
    }

@Override
    public void clientsRetrieved(@NotNull List<Client> clients) {
        clientsAdapter.refresh(new ArrayList<>(clients));
        recyclerViewClients.setVisibility(View.VISIBLE);
        frameLayoutPlaceholderFragment.setVisibility(View.INVISIBLE);
    }

Surprisingly on next time app launch it shows inserted record. I am clueless please guid me.

Body:
You should use;

Database.beginTransaction() before insert operation.

Database.setTransactionSuccessful() after insert operation.

Database.endTransaction() finally.

Sample code:

private static void insertData(AppDatabase db, List<ProductEntity> products, List<CommentEntity> comments) {
    db.beginTransaction();
    try {
        db.productDao().insertAll(products);
        db.commentDao().insertAll(comments);
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}

Sample reference


问:
Spring : JPA to convert native SQL to non entity pojo
I have native SQL which returns the collection of objects and i would like to get the results as collection of objects(a pojo class which is non entity)</p>

```<code>is it possible to get the results from native SQL as collection of non entity?

I am using spring jpa 1.10
</code>```

答:
There is no way to mapping non-entity classes in JPA 1.

Since JPA 2.1, you can use ConstructorResult, Used in conjunction with the SqlResultSetMapping annotation to map the SELECT clause of a SQL query to a constructor.

Here is the example

```<code>Query q = em.createNativeQuery(
      "SELECT c.id, c.name, COUNT(o) as orderCount, AVG(o.price) AS avgOrder " +
      "FROM Customer c, Orders o " +
      "WHERE o.cid = c.id " +
      "GROUP BY c.id, c.name",
      "CustomerDetailsResult");

   @SqlResultSetMapping(
       name="CustomerDetailsResult",
       classes={
          @ConstructorResult(
               targetClass=com.acme.CustomerDetails.class,
                 columns={
                    @ColumnResult(name="id"),
                    @ColumnResult(name="name"),
                    @ColumnResult(name="orderCount"),
                    @ColumnResult(name="avgOrder", type=Double.class)
                    }
          )
       }
      )
</code>```

Body:
I have native SQL which returns the collection of objects and i would like to get the results as collection of objects(a pojo class which is non entity)

is it possible to get the results from native SQL as collection of non entity?

I am using spring jpa 1.10

Body:
There is no way to mapping non-entity classes in JPA 1.

Since JPA 2.1, you can use ConstructorResult, Used in conjunction with the SqlResultSetMapping annotation to map the SELECT clause of a SQL query to a constructor.

Here is the example

Query q = em.createNativeQuery(
      "SELECT c.id, c.name, COUNT(o) as orderCount, AVG(o.price) AS avgOrder " +
      "FROM Customer c, Orders o " +
      "WHERE o.cid = c.id " +
      "GROUP BY c.id, c.name",
      "CustomerDetailsResult");

   @SqlResultSetMapping(
       name="CustomerDetailsResult",
       classes={
          @ConstructorResult(
               targetClass=com.acme.CustomerDetails.class,
                 columns={
                    @ColumnResult(name="id"),
                    @ColumnResult(name="name"),
                    @ColumnResult(name="orderCount"),
                    @ColumnResult(name="avgOrder", type=Double.class)
                    }
          )
       }
      )


问:
Adding values for missing rows based on a column value
I have a data frame:

```<code>things <- data.frame( category = c("A","B","A","B","B","A","B"),
               things2do = c("ball","ball","bat","bat","hockey","volley ball","foos ball"),
                  number = c(12,5,4,1,2,1,1))
</code>```

now I want to add "0" in number where the particular category and things2do is missing e.g. a new row for "A", "hockey" and "0" should be added, same for volleyball, and foos ball.

I hope I can get some help here.

答:
tidyr's complete() function does this:

```<code>library(tidyr)

things %>%
    complete(category, things2do, fill = list(number = 0))
</code>```

Output:

```<code># A tibble: 10 x 3
   category   things2do number
     <fctr>      <fctr>  <dbl>
 1        A        ball     12
 2        A         bat      4
 3        A   foos ball      0
 4        A      hockey      0
 5        A volley ball      1
 6        B        ball      5
 7        B         bat      1
 8        B   foos ball      1
 9        B      hockey      2
10        B volley ball      0
</code>```

Body:
I have a data frame:

things <- data.frame( category = c("A","B","A","B","B","A","B"),
               things2do = c("ball","ball","bat","bat","hockey","volley ball","foos ball"),
                  number = c(12,5,4,1,2,1,1))

now I want to add "0" in number where the particular category and things2do is missing e.g. a new row for "A", "hockey" and "0" should be added, same for volleyball, and foos ball.

I hope I can get some help here.

Body:
tidyr's complete() function does this:

library(tidyr)

things %>%
    complete(category, things2do, fill = list(number = 0))

Output:

# A tibble: 10 x 3
   category   things2do number
     <fctr>      <fctr>  <dbl>
 1        A        ball     12
 2        A         bat      4
 3        A   foos ball      0
 4        A      hockey      0
 5        A volley ball      1
 6        B        ball      5
 7        B         bat      1
 8        B   foos ball      1
 9        B      hockey      2
10        B volley ball      0


问:
Windows XP vs Vista: NTFS Junction points
Problem: I relied heavily on NTFS Junction points in Windows XP, even though they apparently were not an "official" feature of the operating system. Now MSFT has generously made NTFS Junction points an official part of Vista, but apparently they also intentionally broke them. Now my WinXP-created junction points on portable USB drive don't work when I plug that drive into a Vista box.

Questions: Does anyone have a script that will force NTFS junctions created on XP to work correctly within BOTH Vista and XP? Is there documentation or a spec that explains what MSFT did to cause this breakage?

Update: Thanks, Ulrich and Scott, for your follow-up questions. The tool I used to create the junctions was Systinternals Junction v1.05 although I can't say for sure that all of them were created with that specific version of the now-MSFT-hosted app.

As far as how the junctions are used ... assuming an external "Q Drive" device:

1) Some items on the Q Drive are junctions that point from one place on the Q Drive to another place on the Q Drive (e.g., cases where I needed to have a folder in more than one place, and a traditional .lnk style shortcut would not work)

2) Some items are junctions that point from the C Drive directly to locations on the Q Drive. These items obviously do not work when the Q Drive is not actually connected box (XP or Vista), but when connected on Vista, the junctions do not work as on XP.

答:
Junctions and symbolic links are two different types of NTFS objects and are not exactly the same thing. Why your junctions are not recognized in Vista is a mystery, but the junction functionality still exists in Vista and it not purposefully broken.

You can use mklink (http://technet.microsoft.com/en-us/library/cc753194.aspx) to create soft links (the default), hard links (/h), or junctions (/j). The biggest improvement of sym links over junctions is sym links can reference files OR directories (junctions are directory only) and the can reference network shares as well (junctions cannot).

But the bottom line is they are different. Can't tell you why your existing junctions are not recognized by Vista though. You can still create them as described above.

There freeware utility referenced in another post (LinkMagic) is your best bet to getting your junctions working again. Or recreate them with mklink.

OwnerDisplayName: dreftymac

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: dreftymac

OwnerDisplayName: Mitch Schroeter


问:
PHP: switch() default for all?
I have this:

```<code>case true:

    echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"></textarea>';
    break;

    default:
    echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend" readonly="readonly"></textarea>';
    break;
</code>```

I am trying to ONLY if it's true, then show normal else do READONLY.

The switch is checking from a function

```<code>switch( ( check_friend_state($showU["id"], 'friend') ) )
</code>```

And I tried to echo the function, and it returned err2 and not true, so why does it run true?

I also tried if/else

```<code>if(check_friend_state($showU["id"], 'friend') == true){

echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"></textarea>';
}else{
echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend" readonly="readonly"></textarea>';
}
</code>```

But as said previously it returns "err2" and still it runs true?

My function at the return:

```<code>if($USER == $uID){ // not yourself
return "err1";
}elseif( $checkIsFriend->rowCount() == 1 ){  // already friends
return "err2";
}elseif( $checkAlready->rowCount() == 1 ){ // already send a request
return "err3";
}elseif( $checkBlock->rowCount() == 1 ){ // blocked
return "err4";
}else{
return true;
}
</code>```

答:
This gets a little sloppy, but $return ends up being the value that was returned by check_friend_state()

```<code>echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"';
    if (!($return = check_friend_state($showU["id"], 'friend')) == true) {
         echo ' READONLY';
    }
echo '></textarea>';
</code>```

if check_friend_state($showU["id"], 'friend') returns anything but false or 0 it will be true

Why be set on a switch()?  It seems like switch() is more intensive on PHP because it requires more syntax, thus if used excessively it can actually have a negative effect. Though this is a guess and based on no facts.

Title: PHP: switch() default for all?

Body:
I have this:

case true:

    echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"></textarea>';
    break;

    default:
    echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend" readonly="readonly"></textarea>';
    break;

I am trying to ONLY if it's true, then show normal else do READONLY.

The switch is checking from a function

switch( ( check_friend_state($showU["id"], 'friend') ) )

And I tried to echo the function, and it returned err2 and not true, so why does it run true?

I also tried if/else

if(check_friend_state($showU["id"], 'friend') == true){

echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"></textarea>';
}else{
echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend" readonly="readonly"></textarea>';
}

But as said previously it returns "err2" and still it runs true?

My function at the return:

if($USER == $uID){ // not yourself
return "err1";
}elseif( $checkIsFriend->rowCount() == 1 ){  // already friends
return "err2";
}elseif( $checkAlready->rowCount() == 1 ){ // already send a request
return "err3";
}elseif( $checkBlock->rowCount() == 1 ){ // blocked
return "err4";
}else{
return true;
}

Body:
This gets a little sloppy, but $return ends up being the value that was returned by check_friend_state()

echo '<textarea rows="2" cols="35" name="message_friend" id="message_friend"';
    if (!($return = check_friend_state($showU["id"], 'friend')) == true) {
         echo ' READONLY';
    }
echo '></textarea>';

if check_friend_state($showU["id"], 'friend') returns anything but false or 0 it will be true

Why be set on a switch()?  It seems like switch() is more intensive on PHP because it requires more syntax, thus if used excessively it can actually have a negative effect. Though this is a guess and based on no facts.