text:
Q: JellyBean Layout Crash I have an app with a RelativeLayout that contains a ProgressBar and a WebView.  There's nothing complex to it.  However, I am getting a very strange crash where I am not even seeing the ANR dialog.  Commenting out the ProgressBar in the xml allows the app to not crash, however I'd like to use it.  Any ideas why its crashing?
The xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ProgressBar
        android:id="@+id/progress"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_gravity="center"
        android:layout_marginBottom="3dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="3dp"
        android:indeterminate="false"
        android:indeterminateOnly="false"
        android:maxHeight="2dp"
        android:minHeight="2dp"
        android:progressDrawable="@android:drawable/progress_horizontal" />

    <WebView
        android:id="@+id/webView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="8dp"
        android:background="@android:color/transparent"
        android:scrollbars="none" />

</RelativeLayout>

The log output:
09-06 16:57:41.233: I/ActivityManager(358): Displayed com.example.myapp.video/.MainActivity: +341ms
09-06 16:57:41.313: D/dalvikvm(27248): GC_FOR_ALLOC freed 3498K, 42% free 19676K/33543K, paused 47ms, total 50ms
09-06 16:57:41.423: D/dalvikvm(27248): GC_FOR_ALLOC freed 1565K, 41% free 19940K/33543K, paused 54ms, total 54ms
09-06 16:57:41.583: E/SQLiteLog(14294): (14) cannot open file at line 30174 of [00bb9c9ce4]
09-06 16:57:41.583: E/SQLiteLog(14294): (14) os_unix.c:30174: (2) open(/CachedGeoposition.db) -
09-06 16:57:41.583: D/WebKit(14294): ERROR:
09-06 16:57:41.583: D/WebKit(14294): SQLite database failed to load from /CachedGeoposition.db
09-06 16:57:41.583: D/WebKit(14294): Cause - unable to open database file
09-06 16:57:41.583: D/WebKit(14294): external/webkit/Source/WebCore/platform/sql/SQLiteDatabase.cpp(71) : bool WebCore::SQLiteDatabase::open(const WTF::String&, bool)
09-06 16:57:41.673: D/TilesManager(14294): new EGLContext from framework: 66233588
09-06 16:57:41.673: D/GLWebViewState(14294): Reinit shader
09-06 16:57:41.673: D/GLWebViewState(14294): Reinit transferQueue
09-06 16:57:44.913: A/libc(14294): Fatal signal 11 (SIGSEGV) at 0x00000008 (code=1), thread 14294 (ample.myapp.video)
09-06 16:57:45.013: I/DEBUG(122): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
09-06 16:57:45.013: I/DEBUG(122): Build fingerprint: 'google/nakasi/grouper:4.1.1/JRO03D/402395:user/release-keys'
09-06 16:57:45.013: I/DEBUG(122): pid: 14294, tid: 14294, name: ample.myapp.video  >>> com.example.myapp.video <<<
09-06 16:57:45.013: I/DEBUG(122): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 00000008
09-06 16:57:45.083: I/DEBUG(122):     r0 662b1f78  r1 00002060  r2 00000000  r3 00000004
09-06 16:57:45.083: I/DEBUG(122):     r4 00000008  r5 66323060  r6 00000008  r7 00000010
09-06 16:57:45.083: I/DEBUG(122):     r8 00000008  r9 00002060  sl 6630cee4  fp 00000004
09-06 16:57:45.083: I/DEBUG(122):     ip 00000000  sp bee12308  lr 67643fa0  pc 67643d14  cpsr 20000010
09-06 16:57:45.083: I/DEBUG(122):     d0  0000000b44921000  d1  4138000041300000
09-06 16:57:45.083: I/DEBUG(122):     d2  4445400044920000  d3  000004904491a000
09-06 16:57:45.083: I/DEBUG(122):     d4  0000048d00000315  d5  444540000000048d
09-06 16:57:45.083: I/DEBUG(122):     d6  4492000000000315  d7  3f800000000004b5
09-06 16:57:45.083: I/DEBUG(122):     d8  c0000000c0000000  d9  0000000000000000
09-06 16:57:45.083: I/DEBUG(122):     d10 0000000000000000  d11 0000000000000000
09-06 16:57:45.083: I/DEBUG(122):     d12 0000000000000000  d13 0000000000000000
09-06 16:57:45.083: I/DEBUG(122):     d14 0000000000000000  d15 0000000000000000
09-06 16:57:45.083: I/DEBUG(122):     d16 4092400000000000  d17 7e37e43c8800759c
09-06 16:57:45.083: I/DEBUG(122):     d18 0000000000000000  d19 0000000000000000
09-06 16:57:45.083: I/DEBUG(122):     d20 0000000000000000  d21 0000000000000000
09-06 16:57:45.083: I/DEBUG(122):     d22 0000000000000000  d23 0000000000000000
09-06 16:57:45.083: I/DEBUG(122):     d24 3ff26a7f0aacdd31  d25 3ff550a851800000
09-06 16:57:45.083: I/DEBUG(122):     d26 0000000000000000  d27 0000000000000000
09-06 16:57:45.083: I/DEBUG(122):     d28 4091fc0002180000  d29 0000000000000000
09-06 16:57:45.083: I/DEBUG(122):     d30 bff550a861e00000  d31 0000000000000000
09-06 16:57:45.083: I/DEBUG(122):     scr 20000012
09-06 16:57:45.093: I/DEBUG(122): backtrace:
09-06 16:57:45.093: I/DEBUG(122):     #00  pc 0003bd14  /system/lib/egl/libGLESv2_tegra.so
09-06 16:57:45.093: I/DEBUG(122):     #01  pc 0003bf9c  /system/lib/egl/libGLESv2_tegra.so
09-06 16:57:45.093: I/DEBUG(122):     #02  pc 0003c470  /system/lib/egl/libGLESv2_tegra.so
09-06 16:57:45.093: I/DEBUG(122):     #03  pc 00011f98  /system/lib/egl/libGLESv2_tegra.so (glDrawArrays+156)
09-06 16:57:45.093: I/DEBUG(122):     #04  pc 00016497  /system/lib/libhwui.so
09-06 16:57:45.093: I/DEBUG(122):     #05  pc 00016549  /system/lib/libhwui.so
09-06 16:57:45.093: I/DEBUG(122):     #06  pc 000107bb  /system/lib/libhwui.so
09-06 16:57:45.093: I/DEBUG(122):     #07  pc 00010a25  /system/lib/libhwui.so
09-06 16:57:45.093: I/DEBUG(122):     #08  pc 00010a25  /system/lib/libhwui.so
09-06 16:57:45.093: I/DEBUG(122):     #09  pc 00010a25  /system/lib/libhwui.so
09-06 16:57:45.093: I/DEBUG(122):     #10  pc 00010a25  /system/lib/libhwui.so
09-06 16:57:45.093: I/DEBUG(122):     #11  pc 00059c8f  /system/lib/libandroid_runtime.so
09-06 16:57:45.093: I/DEBUG(122):     #12  pc 0001de30  /system/lib/libdvm.so (dvmPlatformInvoke+112)
09-06 16:57:45.093: I/DEBUG(122):     #13  pc 0004d083  /system/lib/libdvm.so (dvmCallJNIMethod(unsigned int const*, JValue*, Method const*, Thread*)+394)
09-06 16:57:45.093: I/DEBUG(122):     #14  pc 00027260  /system/lib/libdvm.so
09-06 16:57:45.093: I/DEBUG(122):     #15  pc 0002bb68  /system/lib/libdvm.so (dvmInterpret(Thread*, Method const*, JValue*)+180)
09-06 16:57:45.093: I/DEBUG(122):     #16  pc 0005fab7  /system/lib/libdvm.so (dvmInvokeMethod(Object*, Method const*, ArrayObject*, ArrayObject*, ClassObject*, bool)+374)
09-06 16:57:45.093: I/DEBUG(122):     #17  pc 0006700d  /system/lib/libdvm.so
09-06 16:57:45.093: I/DEBUG(122):     #18  pc 00027260  /system/lib/libdvm.so
09-06 16:57:45.093: I/DEBUG(122):     #19  pc 0002bb68  /system/lib/libdvm.so (dvmInterpret(Thread*, Method const*, JValue*)+180)
09-06 16:57:45.093: I/DEBUG(122):     #20  pc 0005f7f1  /system/lib/libdvm.so (dvmCallMethodV(Thread*, Method const*, Object*, bool, JValue*, std::__va_list)+272)
09-06 16:57:45.093: I/DEBUG(122):     #21  pc 00049673  /system/lib/libdvm.so
09-06 16:57:45.093: I/DEBUG(122):     #22  pc 0004698d  /system/lib/libandroid_runtime.so
09-06 16:57:45.093: I/DEBUG(122):     #23  pc 0004746f  /system/lib/libandroid_runtime.so (android::AndroidRuntime::start(char const*, char const*)+390)
09-06 16:57:45.093: I/DEBUG(122):     #24  pc 00000dcf  /system/bin/app_process
09-06 16:57:45.093: I/DEBUG(122): stack:
09-06 16:57:45.093: I/DEBUG(122):          bee122c8  0000002a
09-06 16:57:45.093: I/DEBUG(122):          bee122cc  0000000c
09-06 16:57:45.093: I/DEBUG(122):          bee122d0  67070d30
09-06 16:57:45.093: I/DEBUG(122):          bee122d4  662b21f8
09-06 16:57:45.093: I/DEBUG(122):          bee122d8  00000610
09-06 16:57:45.093: I/DEBUG(122):          bee122dc  00000048
09-06 16:57:45.093: I/DEBUG(122):          bee122e0  00000000
09-06 16:57:45.093: I/DEBUG(122):          bee122e4  66227561  /system/lib/libardrv_dynamic.so (NvArdShaderWriteFlags+152)
09-06 16:57:45.093: I/DEBUG(122):          bee122e8  00000000
09-06 16:57:45.093: I/DEBUG(122):          bee122ec  6630cce8
09-06 16:57:45.093: I/DEBUG(122):          bee122f0  00000000
09-06 16:57:45.093: I/DEBUG(122):          bee122f4  00000024
09-06 16:57:45.093: I/DEBUG(122):          bee122f8  00000009
09-06 16:57:45.093: I/DEBUG(122):          bee122fc  6622a7fd  /system/lib/libardrv_dynamic.so (NvArdLoadVertexConstants_CPU_PIO+32)
09-06 16:57:45.093: I/DEBUG(122):          bee12300  df0027ad
09-06 16:57:45.093: I/DEBUG(122):          bee12304  00000000
09-06 16:57:45.093: I/DEBUG(122):     #00  bee12308  662b8470
09-06 16:57:45.093: I/DEBUG(122):          bee1230c  6624d1b8
09-06 16:57:45.093: I/DEBUG(122):          bee12310  6630caf8
09-06 16:57:45.093: I/DEBUG(122):          bee12314  00000001
09-06 16:57:45.093: I/DEBUG(122):          bee12318  0000082d
09-06 16:57:45.093: I/DEBUG(122):          bee1231c  662b21fc
09-06 16:57:45.093: I/DEBUG(122):          bee12320  d5942160
09-06 16:57:45.093: I/DEBUG(122):          bee12324  6630ceec
09-06 16:57:45.093: I/DEBUG(122):          bee12328  6624d1b8
09-06 16:57:45.093: I/DEBUG(122):          bee1232c  00000010
09-06 16:57:45.093: I/DEBUG(122):          bee12330  00000008
09-06 16:57:45.093: I/DEBUG(122):          bee12334  00000008
09-06 16:57:45.093: I/DEBUG(122):          bee12338  00000001
09-06 16:57:45.093: I/DEBUG(122):          bee1233c  6630cee4
09-06 16:57:45.093: I/DEBUG(122):          bee12340  00000003
09-06 16:57:45.093: I/DEBUG(122):          bee12344  67643fa0  /system/lib/egl/libGLESv2_tegra.so
09-06 16:57:45.093: I/DEBUG(122):     #01  bee12348  00000000
09-06 16:57:45.093: I/DEBUG(122):          bee1234c  00000000
09-06 16:57:45.093: I/DEBUG(122):          bee12350  00000010
09-06 16:57:45.093: I/DEBUG(122):          bee12354  00000008
09-06 16:57:45.093: I/DEBUG(122):          bee12358  00000004
09-06 16:57:45.093: I/DEBUG(122):          bee1235c  6764aa7c  /system/lib/egl/libGLESv2_tegra.so
09-06 16:57:45.093: I/DEBUG(122):          bee12360  662b21f8
09-06 16:57:45.093: I/DEBUG(122):          bee12364  6630ceec
09-06 16:57:45.093: I/DEBUG(122):          bee12368  662b1f30
09-06 16:57:45.093: I/DEBUG(122):          bee1236c  00000000
09-06 16:57:45.093: I/DEBUG(122):          bee12370  00000010
09-06 16:57:45.093: I/DEBUG(122):          bee12374  662b1f78
09-06 16:57:45.093: I/DEBUG(122):          bee12378  67687464  /system/lib/egl/libGLESv2_tegra.so
09-06 16:57:45.093: I/DEBUG(122):          bee1237c  00000000
09-06 16:57:45.093: I/DEBUG(122):          bee12380  6624d1b8
09-06 16:57:45.093: I/DEBUG(122):          bee12384  6624d1b8
09-06 16:57:45.093: I/DEBUG(122):          ........  ........
09-06 16:57:45.093: I/DEBUG(122):     #02  bee123a8  00000000
09-06 16:57:45.093: I/DEBUG(122):          bee123ac  00000000
09-06 16:57:45.093: I/DEBUG(122):          bee123b0  00000000
09-06 16:57:45.093: I/DEBUG(122):          bee123b4  00000004
09-06 16:57:45.093: I/DEBUG(122):          bee123b8  00000010
09-06 16:57:45.093: I/DEBUG(122):          bee123bc  000003fc
09-06 16:57:45.093: I/DEBUG(122):          bee123c0  00000000
09-06 16:57:45.093: I/DEBUG(122):          bee123c4  662b1f30
09-06 16:57:45.093: I/DEBUG(122):          bee123c8  00000000
09-06 16:57:45.093: I/DEBUG(122):          bee123cc  00000005
09-06 16:57:45.093: I/DEBUG(122):          bee123d0  00000006
09-06 16:57:45.093: I/DEBUG(122):          bee123d4  00000000
09-06 16:57:45.093: I/DEBUG(122):          bee123d8  00000000
09-06 16:57:45.093: I/DEBUG(122):          bee123dc  00000000
09-06 16:57:45.093: I/DEBUG(122):          bee123e0  00000004
09-06 16:57:45.093: I/DEBUG(122):          bee123e4  6624d1b8
09-06 16:57:45.093: I/DEBUG(122):          ........  ........
09-06 16:57:45.103: I/DEBUG(122): memory near r0:
09-06 16:57:45.103: I/DEBUG(122):     662b1f58 00000000 00000000 00000000 00000000  ................
09-06 16:57:45.103: I/DEBUG(122):     662b1f68 00000000 00000000 00000000 00000000  ................
09-06 16:57:45.103: I/DEBUG(122):     662b1f78 c48300e0 66321000 0000c000 00004000  ......2f.....@..
09-06 16:57:45.103: I/DEBUG(122):     662b1f88 00000048 00000100 00002088 00002040  H........ ..@ ..
09-06 16:57:45.103: I/DEBUG(122):     662b1f98 00002040 00000000 00000000 00000020  @ .......... ...
09-06 16:57:45.103: I/DEBUG(122): memory near r1:
09-06 16:57:45.103: I/DEBUG(122):     00002040 ffffffff ffffffff ffffffff ffffffff  ................
09-06 16:57:45.103: I/DEBUG(122):     00002050 ffffffff ffffffff ffffffff ffffffff  ................
09-06 16:57:45.103: I/DEBUG(122):     00002060 ffffffff ffffffff ffffffff ffffffff  ................
09-06 16:57:45.103: I/DEBUG(122):     00002070 ffffffff ffffffff ffffffff ffffffff  ................
09-06 16:57:45.103: I/DEBUG(122):     00002080 ffffffff ffffffff ffffffff ffffffff  ................
09-06 16:57:45.103: I/DEBUG(122): memory near r5:
09-06 16:57:45.103: I/DEBUG(122):     66323040 ffffffff ffffffff ffffffff ffffffff  ................
09-06 16:57:45.103: I/DEBUG(122):     66323050 ffffffff ffffffff ffffffff ffffffff  ................
09-06 16:57:45.103: I/DEBUG(122):     66323060 ffffffff ffffffff ffffffff ffffffff  ................
09-06 16:57:45.103: I/DEBUG(122):     66323070 ffffffff ffffffff ffffffff ffffffff  ................
09-06 16:57:45.103: I/DEBUG(122):     66323080 ffffffff ffffffff ffffffff ffffffff  ................
09-06 16:57:45.103: I/DEBUG(122): memory near r9:
09-06 16:57:45.103: I/DEBUG(122):     00002040 ffffffff ffffffff ffffffff ffffffff  ................
09-06 16:57:45.103: I/DEBUG(122):     00002050 ffffffff ffffffff ffffffff ffffffff  ................
09-06 16:57:45.103: I/DEBUG(122):     00002060 ffffffff ffffffff ffffffff ffffffff  ................
09-06 16:57:45.103: I/DEBUG(122):     00002070 ffffffff ffffffff ffffffff ffffffff  ................
09-06 16:57:45.103: I/DEBUG(122):     00002080 ffffffff ffffffff ffffffff ffffffff  ................
09-06 16:57:45.103: I/DEBUG(122): memory near sl:
09-06 16:57:45.103: I/DEBUG(122):     6630cec4 00000002 00000003 00000000 00000001  ................
09-06 16:57:45.103: I/DEBUG(122):     6630ced4 00000000 00000001 00fe0002 00dc0001  ................
09-06 16:57:45.103: I/DEBUG(122):     6630cee4 00000000 00008b52 00000101 00008b50  ....R.......P...
09-06 16:57:45.103: I/DEBUG(122):     6630cef4 0000ffff 00008b52 00000313 662ba630  ....R.......0.+f
09-06 16:57:45.103: I/DEBUG(122):     6630cf04 6630c410 6630d0d8 00000002 00000002  ..0f..0f........
09-06 16:57:45.103: I/DEBUG(122): memory near sp:
09-06 16:57:45.103: I/DEBUG(122):     bee122e8 00000000 6630cce8 00000000 00000024  ......0f....$...
09-06 16:57:45.103: I/DEBUG(122):     bee122f8 00000009 6622a7fd df0027ad 00000000  ......"f.'......
09-06 16:57:45.103: I/DEBUG(122):     bee12308 662b8470 6624d1b8 6630caf8 00000001  p.+f..$f..0f....
09-06 16:57:45.103: I/DEBUG(122):     bee12318 0000082d 662b21fc d5942160 6630ceec  -....!+f`!....0f
09-06 16:57:45.103: I/DEBUG(122):     bee12328 6624d1b8 00000010 00000008 00000008  ..$f............
09-06 16:57:45.103: I/DEBUG(122): code around pc:
09-06 16:57:45.103: I/DEBUG(122):     67643cf4 eaffffa3 e3540008 13a03000 02033001  ......T..0...0..
09-06 16:57:45.103: I/DEBUG(122):     67643d04 e3530000 01a0800b 0a000007 e1a0300b  ..S..........0..
09-06 16:57:45.103: I/DEBUG(122):     67643d14 e8960003 e2533001 e0866007 e8850003  .....0S..`......
09-06 16:57:45.103: I/DEBUG(122):     67643d24 e2855008 1afffff9 eaffff95 e1a00005  .P..............
09-06 16:57:45.103: I/DEBUG(122):     67643d34 e1a01006 e1a02004 e0855004 ebff2932  ..... ...P..2)..
09-06 16:57:45.103: I/DEBUG(122): code around lr:
09-06 16:57:45.103: I/DEBUG(122):     67643f80 e59de06c e59d002c e59d3068 e58dc004  l...,...h0......
09-06 16:57:45.103: I/DEBUG(122):     67643f90 e58d6008 e58d700c e58de010 ebfffedd  .`...p..........
09-06 16:57:45.103: I/DEBUG(122):     67643fa0 e59d2024 e3520002 e1a01000 0a000050  $ ....R.....P...
09-06 16:57:45.103: I/DEBUG(122):     67643fb0 e2817003 e3c76003 e59d301c e06a1004  .p...`...0....j.
09-06 16:57:45.103: I/DEBUG(122):     67643fc0 e2844008 e19370d1 e3570000 aaffff9c  .@...p....W.....
09-06 16:57:45.263: I/BootReceiver(358): Copying /data/tombstones/tombstone_07 to DropBox (SYSTEM_TOMBSTONE)
09-06 16:57:45.283: I/WindowState(358): WIN DEATH: Window{4181ebd0 com.example.myapp.video/com.example.myapp.video.MainActivity paused=false}
09-06 16:57:45.283: I/ActivityManager(358): Process com.example.myapp.video (pid 14294) has died.
09-06 16:57:45.283: W/ActivityManager(358): Force removing ActivityRecord{415c9a88 com.example.myapp.video/.MainActivity}: app died, no saved state
09-06 16:57:45.333: D/Zygote(124): Process 14294 terminated by signal (11)

A: That sort of crash indicates either a bug in your JNI code (if you have any) or a bug in the firmware. A SIGSEGV should be impossible from normal SDK work, even if there are bugs in your code.
If this is on a Nexus device with stock firmware, or if this is on the emulator, or if this reproducible on multiple devices with stock firmware, post an issue to http://b.android.com. Include everything you posted here, including that SIGSEGV dump.
If this is on a device with a ROM mod, contact the ROM maintainers first.


text:
Q: Why does NPM ask for peer dep's when it's clearly installed? Im working with AWS-Amplify and just updated it's CLI to the latest version, and now NPM complains that there are unmet dependencies, though graphql is clearly installed at the right version. What am missing here? Thanks for any clarification!
$ npm list -g --depth 0
/usr/local/lib
├── @aws-amplify/cli@4.12.0
├── @vue/cli@4.0.5
├── browser-sync@2.26.7
├── firebase-tools@7.10.0
├── graphql@14.5.8
├── nodemon@2.0.2
├── npm@6.13.6
└── parcel-bundler@1.12.4

npm ERR! peer dep missing: graphql@^14.5.8, required by @graphql-toolkit/file-loading@0.9.0
npm ERR! peer dep missing: graphql@^14.2.0, required by relay-compiler@6.0.0

A: This happens when your node version is not latest or when the dependencies require a certain version of other npm. Just check if all the npm packages and node is of latest version.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript clears a variable after there is no further reference it It is said, javascript clears a variable from memory after its being referenced last.
just for the sake of this question  i created a JS file for DEMO with only one variable;
//file start

//variable defined
var a=["Hello"]

//refenence to that variable
alert(a[0]);

//
//file end

no further reference to that variable, so i expect javascript to clear varaible 'a'
Now i just ran this page and then opened firebug and ran this code
alert(a[0]);

Now this alerts the value of variable, If the statement "Javascript clears a variable after  there is no further reference it" is true how come alert() shows its value.
Is it because all variable defined in global context become properties of window object, and since even after the execution file window objects exist so does it properties.

A: Of course the variable HAS to be kept around in this example - after all, you keep the ENVIRONMENT it has been defined in around. As long as you COULD still access it is has to be kept, so if you can make this test and it ever fails - the JS interpreter is "kaputt".
Do this instead:
(function () {
  var a = 1;
}());

// and NOW, at THIS point there is nothing any more referencing "a"

Of course, from out "here" you cannot test that - you'd have to look at the internal memory structures of the JS interpreter/compiler (today in the days of V8 it's more like a "interpiler" or "compreter" aynway).
In addition though, like all garbage collecting (GC) languages, the memory is not freed immediately but depending on GC strategy used by the particular implementation of Javascript, which also takes current memory usage and demand into account. GC is a costly operation and is delayed, if possible, and/or run when it does not take away CPU resources from the real app.
By the way, slight variation:
(function () {
  var a = 1;
  //empty function assigned to global namespace,
  //in browsers "window" is the global object
  window.example_function = function () {};
}());

In THIS example the result is the same as in yours: as long as you view that page the memory for "a" is NEVER released: the function assigned to property example_function of the global object still exists, so all of the environment is was defined in has to be kept! Only after
delete window.example_function

which deletes that property - which in the end is a pointer to the (empty) function expression - from the global object, could variable "a" be released. Also note that "a" is not even used by that function, see Google and search for "lexical scoping", one of the most defining properties of the Javascript language.
And even more fun:
Had I written
//define a variable in global namespace
var example_function;

(function () {
  var a = 1;
  //empty function assigned to global namespace,
  //in browsers "window" is the global object
  example_function = function () {};
}());

I could not use "delete" to remove it, in fact I could not ever release it. That's because in the first example example_function becomes a new property of the global object (emphasis), while in this last example it is a variable, and "delete" works with object properties only. (I used "windows.example_function" in the earlier example, but without the "window." it would have been just the same, example_function would have been created as property in the global object. Only the "var" statement creates variables.)

A:
Is it because all variable defined in global context become properties of window object, and since even after the execution file window objects exist so does it properties.

Yes. You would either have to close the window, or explicitly remove a from the window properties.

A: A side effect of your script is that there's a property name "a" defined in the global object ( window ), so there is actually still a global reference to a.
(function()
{
  var a = 12;
  alert(a);
})();

If we wrap the declaration of a in self-executing function like here, a will be inaccessible after the function has exited.

A: Yes, although you can mitigate this behavior by declaring and acting on your variables within the scope of a function:
( function myfunc(a){
  var b = 100;
  alert(a); // 200
  alert(b); // 100
}(200));

alert(a); // undefined
alert(b); // undefined

A: Referencing a variable does not mean using it in some manner. As long as there is at least one reference to the variable which can still be accessed, it has to be kept in memory.
Looking at your example, the following line has no effect on whether the variable gets cleared or not. Even if a wasn't being used anywhere, it would still have been kept intact.
//refenence to that variable
alert(a[0]);

Although an object may be created inside a function, its lifetime may extend beyond the function itself. The only thing to remember is whether there are still any valid references to the object in question. Consider this example,
(function() {
    var a = ["Hello"];
    var copy = a;
    a = null;

    setTimeout(function() {
        // a: null, copy: ["Hello"]
        console.log("a: %o, copy: %o", a, copy);
    }, 2000);
})();

The variable a is created inside an anonymous function, and another variable copy is referencing it. a is set to null right after, but we still have 1 reference to it from copy. Then we create a timeout which makes another reference to the same variable. Now even though this anonymous function will go out of scope after it executes the setTimeout, we still left 1 reference to it in the timeout function. So this copy variable will still be intact when the timeout function is run.


text:
Q: Use Joi library with react-native typescript I am trying to use Joi (https://joi.dev/api/?v=17.6.1) library with react-native for json format data validation.
It gives the error ReferenceError: Property 'TextEncoder' doesn't exist, js engine: hermes and says defined Joi schemas are undefined.
Could anyone please help on this to resolve ?


text:
Q: Virtual Path Issue Hello Code Experts,
I am uploading some files to a virtual directory. For the virtual directory I am giving the path like
"/Uploads/" + DatabaseName + "/" + REOID + "/" + "ExternalDocument" + "/";

It works fine in my local but not in live server. It is not uploading files in live server.
If I change it to
"~/Uploads/" + DatabaseName + "/" + REOID + "/" + "ExternalDocument" + "/";

Then will it work? If not then how shall I map it to virtual directory?

A: use the Server.MapPath function
http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath.aspx
Server.MapPath("~/Uploads/" + DatabaseName + "/" + REOID + "/" + "ExternalDocument" + "/");

A: Read the documentation on waht the ~ means. You willfind ou tthe second approach is always valid, the first one not. Te first assuems the folder is /Uploads (at the web server root).

A: +1 to @MarkisT. Would suggest you also let the Framework do the combination for you:
http://msdn.microsoft.com/en-us/library/dd782933.aspx
using System.IO;
using System.Web;

var path = Path.Combine("~/Uploads", DataBaseName, REOID, "ExternalDocument");
var fullPath = Server.MapPath(path);

If you are still having issues; would suggest you inspect fullPath on local and server to understand what is happening as relates to virtual and absolute paths. You may also have security issues on the server, especially if you happen to be writing outside the application directory. Of course, would expect exceptions in that case.


text:
Q: Color.FromNonPremultiplied different tinting with BlendState.NonPremultiplied In my XNA project I use non-processed images and draw them with BlendState.NonPremultiplied so they look normal around the edges. But when I use non-white color (Color.FromNonPremultiplied(12, 34, 56, 78)) in SpriteBatch.Draw method, it doesn't tint the sprite as it would if the BlendState was set to default.
How do I achieve the same tinting as default blendstate allows without switching to it?

A: The documentation says about Color.FromNonPremultiplied Method: Converts a non-premultipled alpha color to a color that contains premultiplied alpha.
Based on this you should use either
BlendState.NonPremultipliedand Color(12, 34, 56, 78)
OR
BlendState.AlphaBlend and Color.FromNonPremultiplied(12, 34, 56, 78)
together.


text:
Q: System.ObjectDisposedException while sending email using smtpclient (fluent-email) I am getting a System.ObjectDisposedException when i try to send an e-mail in a .NET core 6.0 project using the fluent-email library:
System.ObjectDisposedException: Cannot access a disposed object.
Object name: 'System.Net.Mail.SmtpClient'.
   at System.Net.Mail.SmtpClient.SendAsync(MailMessage message, Object userToken)
   at FluentEmail.Smtp.SendMailEx.SendMailExImplAsync(SmtpClient client, MailMessage message, CancellationToken token)

I have tried to inject the smtpclient transient, scoped and as a singleton but neither one of the options fixed this issue.
DI code:
  var smtpClient = new SmtpClient(smtpSenderOptions.Host, smtpSenderOptions.Port)
                {
                    EnableSsl = smtpSenderOptions.EnableSsl
                };

                services.AddSingleton(instance => smtpClient);

Usage (from the fluent-email library (https://github.com/lukencode/FluentEmail)):

    // Taken from https://stackoverflow.com/questions/28333396/smtpclient-sendmailasync-causes-deadlock-when-throwing-a-specific-exception/28445791#28445791
    // SmtpClient causes deadlock when throwing exceptions. This fixes that.
    public static class SendMailEx
    {
        public static Task SendMailExAsync(
            this SmtpClient @this,
            MailMessage message,
            CancellationToken token = default(CancellationToken))
        {
            // use Task.Run to negate SynchronizationContext
            return Task.Run(() => SendMailExImplAsync(@this, message, token));
        }

        private static async Task SendMailExImplAsync(
            SmtpClient client,
            MailMessage message,
            CancellationToken token)
        {
            token.ThrowIfCancellationRequested();

            var tcs = new TaskCompletionSource<bool>();
            SendCompletedEventHandler handler = null;
            Action unsubscribe = () => client.SendCompleted -= handler;

            handler = async (_, e) =>
            {
                unsubscribe();

                // a hack to complete the handler asynchronously
                await Task.Yield();

                if (e.UserState != tcs)
                    tcs.TrySetException(new InvalidOperationException("Unexpected UserState"));
                else if (e.Cancelled)
                    tcs.TrySetCanceled();
                else if (e.Error != null)
                    tcs.TrySetException(e.Error);
                else
                    tcs.TrySetResult(true);
            };

            client.SendCompleted += handler;
            try
            {
                client.SendAsync(message, tcs);
                using (token.Register(() =>
                {
                    client.SendAsyncCancel();
                }, useSynchronizationContext: false))
                {
                    await tcs.Task;
                }
            }
            finally
            {
                unsubscribe();
            }
        }
    }

My code calling the library:
  var response = await _fluentEmail
                .Subject(emailContents.Subject)
                .To(emailContents.To)
                .Attach(attachments)
                .UsingTemplate(template, emailContents)
                .SendAsync(cancellationToken);

A: The extensions provided by fluent-email did inject these classes as singleton and I did use another lifetime and therefore this issue occured.
So I forgot to also override the dependency injection container configuration for all dependencies using the System.ObjectDisposedException to use singleton, since I was using a custom implementation of FluentEmail.Smtp.SendMailEx.SendMailExImplAsync.
After overridding the other dependencies in the DI extension, it worked.


text:
Q: How can I for example list five largest files in /usr/lib -directory? How can I for example list five largest files in /usr/lib directory?
Please also add some minor explanation for each bit of code that you are using.

A: The easiest would be to simply sort by size and print the last 5 lines:
ls -Sr /usr/lib | tail -n 5

From man ls:
   -r, --reverse
          reverse order while sorting
   -S     sort by file size

tail just prints the last N lines of a file:
   -n, --lines=K
          output the last K lines, instead of the last 10; or use -n +K to
          output lines starting with the Kth

If you also want to check for files in subdirectories, you could do this:
find /usr/lib -type f -ls | sort -gk7 | tail -n 5

The find command looks for files, from man find:
   -type c
          File is of type c:
          [ ... ]
          f      regular file
   -ls    True;  list  current file in ls -dils format on standard output.
          The block counts are of 1K blocks, unless the environment  vari‐
          able  POSIXLY_CORRECT  is set, in which case 512-byte blocks are
          used.  See the UNUSUAL FILENAMES section for  information  about
          how unusual characters in filenames are handled.

sort does what you would expect, it sorts its input. From man sort:
   -g, --general-numeric-sort
          compare according to general numerical value
   -k, --key=KEYDEF
          sort via a key; KEYDEF gives location and type

So, sort -g makes it sort in numerical order and -k7 makes it sort on the 7th field which, in the case of find -ls, is the size of the file.
This should be relatively robust and have no problems with file names with spaces or weird characters. In any case, since you are searching through /usr/lib it is unlikely that you will have strange file names.

A: ls -lSr | tail -5
This will work
-r for reverse
-l for long listing
-S is the option to sort file size wise.


text:
Q: Confusing interactions between constructors and copy/move semantics in C++ Original post edited to provide more minimal reproduction.
Long-time C programmer here, relearning C++ for first time since about 2010, so I'm quite new to all the modern C++11 and beyond stuff. I think I understand the intent behind copy and move constructors and why one would explicitly define/default/delete them. However, I'm pretty lost on the interactions between the different constructor types in my own practice program:
TerritoryUSA.hpp
#ifndef TERRITORYUSA_HPP
#define TERRITORYUSA_HPP

namespace TerritoryUSA {
    enum class Identifier {
        Alabama,
        Alaska,
        American_Samoa
    };

    class Territory {
    private:
        Identifier identifier;
    public:
        // Construct.
        Territory(Identifier identifier);
        //Territory(Territory& other) = delete;         // 1
        //Territory(Territory&& other) = delete;        // 2

        // Move.
        //Territory& operator=(Territory& other) = delete;  // 3
        //Territory& operator=(Territory&& other) = delete; // 4

        // Destruct.
        ~Territory() = default;

        // Methods.
        Identifier getIdentifier();
    };
}

#endif /* TERRITORYUSA_HPP */

TerritoryUSA.cpp
#include "TerritoryUSA.hpp"

using namespace TerritoryUSA;

// Construct.
Territory::Territory(Identifier identifier) : identifier{identifier} {}

// Methods.
Identifier Territory::getIdentifier() {
    return identifier;
}

main.cpp
#include <cstdio>
#include "TerritoryUSA.hpp"

using namespace TerritoryUSA;

int main() {
    Territory territories[]{
        Territory(Identifier::Alabama),
        Territory(Identifier::Alaska),
        Territory(Identifier::American_Samoa)
    };

    for (Territory territory : territories) {
        printf("%d\n", static_cast<int>(territory.getIdentifier()));
    }
}

output
0
1
2
Program ended with exit code: 0

Note that this is done in Xcode on MacOS, which I'm also in the throes of figuring out as I mostly work with vim/make on Linux when writing C. I have't figured out where to find the compiler version yet, but this is a brand new updated Macbook with freshly installed Xcode, so it can't be very old. All I did was start a new Xcode "command line tool" application and put the 3 files in the project directory using the right click menu, so the build system should be correct (and it does build and run successfully when the marked lines are commented).
The part that's confusing the heck out of me is when I selectively uncomment the lines marked 1-4 in the header file, I get varying errors related to the construction of Territory objects. Here are the results I get when uncommenting single lines:
Line 1:
Lines 8-10 of main.cpp (where I try to instantiate the Territory objects) I get this red error:
No matching constructor for initialization of 'TerritoryUSA::Territory'

It also highlights in gray line 17 of the hpp (the constructor that takes an identifier argument) with this message:
1. Candidate constructor not viable: no known conversion from 'TerritoryUSA::Territory' to 'TerritoryUSA::Identifier' for 1st argument

It also highlights the uncommented Line 1 in gray with this message:
2. Candidate constructor not viable: expects an l-value for 1st argument

Line 2:
Lines 8-10 of main.cpp (where I try to instantiate the Territory objects) I get this red error:
Call to deleted constructor of 'TerritoryUSA::Territory'

It also highlights the uncommented Line 2 in gray with this message:
1. 'Territory' has been explicitly marked deleted here

Line 3:
No errors
Line 4:
Lines 8-10 of main.cpp (where I try to instantiate the Territory objects) I get this red error:
Call to implicitly-deleted copy constructor of 'TerritoryUSA::Territory'

It also highlights the uncommented Line 4 in gray with this message:
1. Copy constructor is implicitly deleted because 'Territory' has a user-declared move assignment operator

Questions
For Line 1, why is it trying to use a no-argument constructor and/or make any implicit assumptions? Haven't I provided a perfectly valid explicit constructor for the signature with 1 Identifier argument? I intentionally do not want to allow users to instantiate Territory objects without any arguments (quite frankly, I don't want them to instantiate them at all, but one step at a time). And also, what does deleting a copy constructor have to do with this? I'm not trying to copy anything.
For Line 2, again, I understand that I deleted the default constructor, but I'm not trying to use it, I'm trying to use the one that takes an identifier. Why am I getting tripped up? And also, what does deleting a move constructor have to do with this? I'm not trying to move anything.
For Line 4, why am I getting an error related to a deleted copy constructor if I'm deleting a move operator? I'm totally lost on this one, especially because Line 3 didn't have any errors.

A: I believe I've solved my problem, although it unfortunately doesn't really clarify why I was having issues in the first place. But alas, I am not in the business of figuring out why new code doesn't compile on old compilers, so the show must go on.
After some discussion in the comments and someone being able to build and run the code without issue, I dug around in my Xcode project settings and found that it was compiling for C++14. I changed that to C++17, uncommented all 4 lines, and the bulk of the errors went away.
There was 1 remaining error on my for loop line in main.cpp:
Call to deleted constructor of 'TerritoryUSA::Territory'

It also highlights the uncommented Line 1 in gray with this message:
1. 'Territory' has been explicitly marked deleted here

That line is the copy constructor, so I took a wild guess that the range-based for loop was implemented using copy constructors. I quickly added a reference modifier to the line to make it look like this:
    for (Territory& territory : territories) {

and voila, it builds and runs again. I don't even think range-based for loops existed in C++ back when I used the language more regularly, so I didn't know if the reference modifier would work as intended there, but it seems to. Pretty nifty, almost like a lower-level Python without copying.


text:
Q: Newton's law of Cooling, no initial temperature I'm stuck on this apparently difficult problem.
An object is placed in a a room with a temp of 20 C. the temp of the object drops by 5 C in 4 min and by 7 C in 8 min. What was the initial temp of the object when it was placed in the room?
$T(t) = Ce^{kt} + 20$
(4, Ce + 15) (8, Ce + 13)
$Ce + 15 = Ce^{4k} +20$
$Ce + 13 = Ce^{8k} +20$
$e^{8k} + 2 = e^{4k}$
$k = \frac{ln2}{-4}$
I probably misunderstood the problem.
I'd greatly appreciate any help.

A: The law may indeed be written $T(t)=20 + C \exp(-kt)$ (I choose $k>0$, $t$ in minutes).
Letting $\gamma= \exp(- 4k )$, $\gamma^2=\exp(-8k)$
 we have $T(0)-T(4) = C (1-\gamma) = 5$ and $T(0)-T(8)=C(1-\gamma^2)=7$ (if I have understood correctly your statement about temperature drops, if not you should adjust).
From this
$$ \frac{7}{5} = \frac{T(0)-T(8)}{T(0)-T(4) }=\frac{1-\gamma^2}{1-\gamma}=1+\gamma$$
yielding $\gamma=2/5$. Substituting back $C=25/3$ and $T(0)=20+25/3=28.33$

A: Newton's Law of Cooling: $\frac{dT}{dt}=k(T_e-T)$
Has the solution $T(t)=T_e+(T_0-T_e)e^{-kt}$
where $T_0=T(0)$ is the object's initial temperature we are going to find
and $T_e$ is the environment temperature
In this case $T_e=20^{\circ}C$; then we can write
$T(t)=20+(T_0-20)e^{-kt}$
Now, we know that
$T(4)=T_0-5=20+(T_0-20)e^{-k(4)}$
$T(8)=T_0-7=20+(T_0-20)e^{-k(8)}$
$T_0-25=(T_0-20)e^{-k(4)}$
$T_0-27=(T_0-20)e^{-k(8)}$
$e^{-4k}=\frac{T_0-25}{T_0-20}$;$\hspace{10 mm}$
$e^{-8k}=\frac{T_0-27}{T_0-20}$
$-4k=ln\frac{T_0-25}{T_0-20}$;$\hspace{10 mm}$
$-8k=ln\frac{T_0-27}{T_0-20}$
$2ln\frac{T_0-25}{T_0-20}=ln\frac{T_0-27}{T_0-20}$
$(\frac{T_0-25}{T_0-20})^2=\frac{T_0-27}{T_0-20}$
$(T_0-25)^2=(T_0-27)(T_0-20)$
Working on this equation we are left with $ 3T_0=85$ and $T_0=28.33^{\circ}C$
With this value we can find $k=0.25ln(2.50)$


text:
Q: Angular 2 app not working in production Mode i'm new in angular 2 , i create my first app with three components and it works fine in NodeJs. i generate the dist folder using ng build in order to run my app out of nodeJs , i moved all the js files(main.bundle,vendor.bundle..) to a new folder called angular2-test, but when i call angular2-test/index.html the app not working and i get the following error in the web browser  console :
GET file:///C:/inline.bundle.js net::ERR_FILE_NOT_FOUND        index.html:14
GET file:///C:/polyfills.bundle.js net::ERR_FILE_NOT_FOUND     index.html:15
GET file:///C:/styles.bundle.js net::ERR_FILE_NOT_FOUND        index.html:16
GET file:///C:/vendor.bundle.js net::ERR_FILE_NOT_FOUND        index.html:17
GET file:///C:/main.bundle.js net::ERR_FILE_NOT_FOUND          index.html:18
GET file:///C:/favicon.ico net::ERR_FILE_NOT_FOUND

this is my index.html code :
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Bangular</title>
  <base href="/angular2-test">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root>Loading...</app-root>
<script type="text/javascript" src="inline.bundle.js"></script>
<script type="text/javascript" src="polyfills.bundle.js"></script>
<script type="text/javascript" src="styles.bundle.js"></script>
<script type="text/javascript" src="vendor.bundle.js"></script>
<script type="text/javascript" src="main.bundle.js"></script>
</body>
</html>

also i changed my <base href to :
<base href="/"> and <base href="./">

but the app still not working,
please do you have any suggestion about my problem , note that i'm using Angular cli
Regards.


text:
Q: convert very big exponential to decimal in c# 5.35754303593134E+300 to 53575430359313400000000000000000000 ... 000000000
Can anyone do this because this number is very large?
I have tried:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            double s = double.Parse((System.Math.Pow(2, 999)).ToString(), System.Globalization.NumberStyles.Float);
            Console.WriteLine("value={0}", s);
            Console.ReadKey();
        }
    }
}

A: Do one of the following,
Console.WriteLine(s.ToString("N0")); //comma separated
Console.WriteLine(s.ToString("F0"));

Both works.

A: Your title and your code says different things but..
Basicly, you can't. decimal can't hold this value because it is way outside of it's range. It's range from 7.9 x 1028 to 7.9 x 1028.
You can save it on double (which Math.Pow return type and you don't even need to get it string representation and parse it to double again in such a case) or BigInteger.
double s = Math.Pow(2, 999);

or
BigInteger s = (BigInteger)Math.Pow(2, 999);

If you wanna get this value it's string representation, you can use "E" standard numeric format like;
s.ToString("E14") // 5,35754303593134E+300

Or you can use Jon Skeet's DoubleConverter class which exact representation of it's value;
DoubleConverter.ToExactString(s) // 5357543035931336604742125245300009052807024058527668037218751941851755255624680612465991894078479290637973364587765734125935726428461570217992288787349287401967283887412115492710537302531185570938977091076523237491790970633699383779582771973038531457285598238843271083830214915826312193418602834034688


text:
Q: Dual boot Windows 10 and Ubuntu First off let me say that I am somewhat inexperienced in using Linux, I do know the basics though. I currently run Windows 10 on my Acer Aspire E 15. For working with ROS kinetic I have to setup Ubuntu 16.04 on my Laptop. I downloaded the Ubuntu ISO and made a 8GB USB-stick bootable using LiLi USB creator (and win32 disk imager just to make sure the stick was indeed bootable). I made a new partition for Ubuntu (~100 GB) and installed Ubuntu from the stick. It told me it finished without problems; I restarted my Notebook and no matter what I do, it keeps booting up Windows. I tried several strategies to solve up this problem, like the boot-repair tool or chrooting into the system to overwrite boot priorities, but it just won't work. What else can I try to dual boot Ubuntu and Windows 10?

A: When Ubuntu was installed, a second boot manager (GRUB) should have been installed. From what you are describing, it would appear that the default Windows Boot Manager is being used instead of GRUB. I would try the steps suggested here:

*

*Boot to Windows.

*Open an Administrator Command Prompt window by right-clicking the Command Prompt icon and selecting the option to run it as
  Administrator

*Verify the existence of the Ubuntu boot manager: dir \EFI\ubuntu and make sure you can see "shimx64.efi"

*Type bcdedit /set {bootmgr} path \EFI\ubuntu\shimx64.efi

*Reboot

*If you boot into Ubuntu but GRUB did not give you a menu or if that menu did not include Windows, type sudo update-grub in a Terminal


text:
Q: Wrong image being cached with AFNetworking I'm using UIImageView+AFNetworking to load images from a remote server on a table view. However, in some situations, the wrong images are cached (on NSURLCache, not only AFImageCache), i.e. the cache from a URL returns a response from another one (both used on the app).
My tableView:cellForRowAtIndexPath: is pretty normal:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dict = self.sections[indexPath.section][indexPath.row];

    static NSString *CellIdentifier = @"Cell";
    MyCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    UIImage *placeholder = [[UIImage imageNamed:@"shield-flat"] tintedImageWithColor:[UIColor asbestosColor]];
    if (dict[@"first_url"] != [NSNull null]) {

        NSURLRequest *mandanteReq = [NSMutableURLRequest imageRequestWithURL:[NSURL URLWithString:dict[@"first_url"]]];
        [cell.firstImageView setImageWithURLRequest:mandanteReq placeholderImage:placeholder success:NULL failure:NULL];
    } else {
        cell.firstImageView.image = placeholder;
    }

    if (dict[@"second_url"] != [NSNull null]) {
        NSURLRequest *visitanteReq = [NSMutableURLRequest imageRequestWithURL:[NSURL URLWithString:dict[@"second_url"]]];
        [cell.secondImageView setImageWithURLRequest:visitanteReq placeholderImage:placeholder success:NULL failure:NULL];
    } else {
        cell.secondImageView.image = placeholder;
    }
    return cell;

}
Also, my category on NSMutableURLRequest that is used to create the request:
+ (NSMutableURLRequest *)imageRequestWithURL:(NSURL *)url {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    request.cachePolicy = NSURLRequestUseProtocolCachePolicy;
    request.HTTPShouldHandleCookies = NO;
    request.HTTPShouldUsePipelining = YES;
    request.timeoutInterval = 10;
    [request addValue:@"image/*" forHTTPHeaderField:@"Accept"];

    return request;
}

I know that dict is the current object and that the URLs are fine too. I also trust that the server (Amazon S3) is sending the correct image.
The problem often occurs on the first install of the app (probably because the images are cached after).
Any thoughts?


text:
Q: Flutter: background color for children of Column I can't seem to wrap my head around the myriad of layout widgets Flutter throws at me. I'm trying to create the simple widget that displays a Column with three children: a spacer with red background, an Image and another spacer with a blue background. The Image should be centered on the screen vertically, with the first and the third child sharing the space equally. I managed to achieve the layout but have no idea how to set the background colors. Here's what I got:
      Column(
        children: [
          Spacer(flex: 1),
          Image(
            image: AssetImage("assets/colorPicker.jpeg"),
          ),
          Spacer(flex: 1),
        ],
      )

I tried wrapping the Spacers with Containers with the appropriate color attribute, but I get an exception:
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown while applying parent data.:
Incorrect use of ParentDataWidget.

The ParentDataWidget Expanded(flex: 1) wants to apply ParentData of type FlexParentData to a RenderObject, which has been set up to accept ParentData of incompatible type ParentData.

Usually, this means that the Expanded widget has the wrong ancestor RenderObjectWidget. Typically, Expanded widgets are placed directly inside Flex widgets.
The offending Expanded is currently placed inside a ColoredBox widget.

The ownership chain for the RenderObject that received the incompatible parent data was:
  SizedBox.shrink ← Expanded ← Spacer ← ColoredBox ← Container ← Column ← _BodyBuilder ← MediaQuery ← LayoutId-[<_ScaffoldSlot.body>] ← CustomMultiChildLayout ← ⋯

This doesn't tell me anything useful.

A: You should wrap whichever column or row that has an Expanded child with another Expanded.
Expanded(child: Column(
        children: [
          Spacer(flex: 1),
          Image(
            image: AssetImage("assets/colorPicker.jpeg"),
          ),
          Spacer(flex: 1),
        ],
      ))

A: You can use a Flexible widget with a flex:1 and a child Container with color of your choice. Please see code below :
import 'package:flutter/material.dart';

final Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
        children: [
          Flexible(flex: 1, child:Container(color:Colors.red)),
          Image(
            image: NetworkImage("https://picsum.photos/350/200"),
          ),
          Flexible(flex: 1, child:Container(color:Colors.blue)),
        ],
    );
  }
}


text:
Q: troubles with moderncv after Miktex update I have been using moderncv to generate some cover letters and CVs recently. Everything was working fine, until I have done a Miktex update. I keep getting the error Undefined control sequence. \makelettertitle for the following MWE (Which used to worjk without any problems!):
\documentclass[12pt,a4paper,sans]{moderncv}
\moderncvstyle{classic}
\moderncvcolor{blue}
\usepackage{lipsum}

\usepackage[scale=0.82]{geometry} \geometry{textheight=25cm}
\usepackage[ngerman]{babel}
\usepackage{blindtext}
\usepackage{ragged2e}
\usepackage{pdfpages}
%%%%%%%%%%%%%%%%%%%

\makeatletter

\renewcommand*{\makelettertitle}{%
  % recompute lengths (in case we are switching from letter to resume, or vice versa)
  \recomputeletterlengths%
  % sender contact info
  %\hfill%
  \begin{minipage}{.5\textwidth}%
    \raggedright% \raggedleft
    \addressfont\textcolor{color2}{%
      \makebox[\textwidth][l]{\makebox[2\textwidth]{\bfseries\upshape\@firstname~\@lastname\hfill\normalfont\textcolor{black}{\@date}}}\@firstdetailselementfalse%
      \ifthenelse{\isundefined{\@addressstreet}}{}{\makenewline\addresssymbol\@addressstreet%
        \ifthenelse{\equal{\@addresscity}{}}{}{\makenewline\@addresscity}% if \addresstreet is defined, \addresscity and addresscountry will always be defined but could be empty
        \ifthenelse{\equal{\@addresscountry}{}}{}{\makenewline\@addresscountry}}%
      \collectionloop{phones}{% the key holds the phone type (=symbol command prefix), the item holds the number
        \makenewline\csname\collectionloopkey phonesymbol\endcsname\collectionloopitem}%
      \ifthenelse{\isundefined{\@email}}{}{\makenewline\emailsymbol\emaillink{\@email}}%
      \ifthenelse{\isundefined{\@homepage}}{}{\makenewline\homepagesymbol\httplink{\@homepage}}%
      \ifthenelse{\isundefined{\@extrainfo}}{}{\makenewline\@extrainfo}}%
    \end{minipage}\\[3em]
  % recipient block
  \begin{minipage}[t]{.5\textwidth}
    \raggedright%
    \addressfont%
    {\@recipientname}\\%
    \@recipientaddress%
  \end{minipage} \\[2em]
  % date
  %\hfill% US style
%  \\[1em]% UK style
  %\@date\\[2em]% US informal style: "January 1, 1900"; UK formal style: "01/01/1900"
  % opening
  \raggedright%
  \@opening\\[1.5em]%
  % ensure no extra spacing after \makelettertitle due to a possible blank line
%  \ignorespacesafterend% not working
  \hspace{0pt}\par\vspace{-\baselineskip}\vspace{-\parskip}}

\setlength{\makecvtitlenamewidth}{12cm}
\renewcommand*{\namefont}{\fontsize{24}{29}\mdseries\upshape}

\makeatother

%\patchcmd{\makeletterclosing}{[2em]}{[1em]}{}{}
\firstname{XXXXXX} % Your first name
\familyname{XXXXXX}
\title{CV}
\address{XXXXXX,12}{12345,XXXXXX}
\email{XXXXXXXXXXXXXX@XXXX.XXX}
\begin{document}
\recipient{XXXX}{XXXX\\XXXXXXXXXXXX\\1234 XXXXXX\\XXXXXX}
\date{\today} % Letter date
\opening{blablabla,} % Opening greeting
\closing{blablabla} % Closing phrase
\enclosure[Im Anhang]{CV} % List of enclosed documents

\makelettertitle % Print letter title
\blindtext[3]
\makeletterclosing % Print letter signature
\clearpage

%%%%%%%%%%%%%%%%%%%%%%%%%%%
%Lebenslauf
%%%%%%%%%%%%%%%%%%%%%%%%%%%
\clearpage

\makecvtitle % Print the CV title

\section{EDV- Kenntnisse}

\cvitem{Tool}{C, C++, VHDL}
\cvitem{Betriebssystem}{Unix, Windows}
\cvitem{Simulations-Tools}{Tool, Tool, Tool II, Tool}

%---------------------------------

\end{document}

Any help is appreciated.
Update:
Following the log file, the errors are the following:

*

*Undefined control sequence. \setlength{\makecvtitlenamewidth}{12cm}

*Missing number, treated as zero. \renewcommand

*Illegal unit of measure (pt inserted). \renewcommand
Which are respectively originating from the two commands:
 \setlength{\makecvtitlenamewidth}{12cm}
\renewcommand*{\namefont}{\fontsize{24}{29}\mdseries\upshape}

A: \makecvtitlenamewidth existed as part of moderncv 1.5.0, but was removed from moderncv 1.5.1 - the current latest version.
The current replacement seems to be \makecvheadnamewidth, which a default of 0pt (used in conditioning for an automatically set width).
The class has undergone numerous changes which makes older versions of documents incompatible with current versions. If you wish to keep the older formats, you need to maintain a temporary version of the class. Otherwise, you'll have to update your documents accordingly.


text:
Q: ColdFusion pages displayed as Raw Code I have a Tomcat 6 server running multiple application, in one of these applications the JSPs refer to links in a ColdFusion project.  In production we have Apache setup to change the DocumentRoot to the ColdFusion webroot, however as we are only running Tomcat I can't do this (i.e. our system does not have a httpd.conf or apache2.conf file).  I tried setting up a docBase in a context file to point to the ColdFusion project webroot but that didn't work so instead I set up symbolic links inside the tomcat webroot.  This linked to the pages correctly but instead of parsing the page it displays the ColdFusion code.
I don't have any experience with ColdFusion except changing the settings to point to the database I want through the Admin interface.
Tomcat webroot:
webapps/ (tomcat webroot)
    cfProject/www/ (ColdFusion webroot)
    otherProject/pages/*.jsp

Can anyone help me?  If you need more information I will update the question as we go.
UPDATE: ColdFusion version: 9
UPDATE: Context for application setup and symlinks removed however ColdFusion source is still being output and displayed on the page rather than the code being run and displaying the results.
UPDATE: I've installed apache2 and linked it up to tomcat, it is now connecting to ColdFusion correctly and loading all the .cf files from the JSP pages, however the ColdFusion pages are still being displayed in plain text.  Seems the coldFusion pages that are being redirected via a ProxyPass are working but the ones from the DocumentRoot location are not.  Will update if I figure it out.
UPDATE: Got it working in the end, I had to be careful with the order of the ProxyPass rules so once I sorted that out and gave tomcat and apache a restart the pages started coming through correctly.  Thanks for all your input Peter.
Thanks in advance,
Alexei Blue.

A: In the end I installed Apache2 and set up proxy ajp to connect to my Tomcat application listening on port 80.  Tomcat has a connector to do this automatically so I had no issues there.  Then, in the default virtual host in sites-enabled, I changed the DocumentRoot to point to the base of my ColdFusion project.  (Not sure if this is needed but it doesn't hurt).  Then, also inside the default virtual host, I added ProxyPass rules to connect different URL's to ColdFusion.  The bit that stumped me for some time was adding a rule that pointed to the root URL:
ProxyPass / /ColdFusion/www

Because the ProxyPass rules are all processed it was messing up the URL causing pages not found etc.  Once I fixed this and restarted I was sorted.
Thanks again Peter for your help on this.


text:
Q: jQuery - consuming JSON resources - some return data, others don't. Why? I'm trying to figure out how to consume json URLs in the browser and render the data in my web pages using DOM. I am not getting a consistent or predictable response.
I found a JSON URL at Google Calendar which shows the json response in my browser if I just type the URL in the address bar.
I found another JSON URL at business.gov which shows a different json response in my browser if I just type the URL in the address bar. .
I then tried to use jQuery to issue  $.ajax calls to consume and display both of these JSON resources.

Google Calendar - json only

Business.Gov

The Google Calendar JSON resource was consumed fine, but the business.gov JSON resource did not even come back in the response. (I checked with Firebug, and it returned HTTP code 200 with nothing in the response text).
How is it that both JSON URLs returned good JSON data in the browser, but only the Google Calendar URL could be consumed by jQuery.ajax while the business.gov URL could not be consumed by jQUery.ajax?
EDIT - June 19, 2010, 6:36 EST - Thanks @Juan Manuel and @TheJuice. I tried jsonp...here is what I got.
If I change the call to the following, I am able to get the browser to stop blocking the response from api.business.gov, but I can't get at the data (e.g. htmlobj2 is a nil)
  htmlobj2=$.ajax(
        {url:"http://api.business.gov/geodata/city_county_links_for_state_of/CA.json",
         async: false,
         dataType: 'jsonp',
         success: function(data, textStatus) {
            alert("Success");
            $('#myDiv').html("Your data: " );
       },
         error: function ( XMLHttpRequest, textStatus, errorThrown){
                    alert('error');
                }
    }
);

Whether I use dataType of 'jsonp' or 'script', I get the same result. htmlobj2 is nil, but the response header has the entire json data string. Furthermore, if I try to bind a callback function to the .ajax call with "data" as a parameter, that "data" parameter is also a nil object. Furthermore, neither the success or failure handler gets called.
How can I extract this JSON data from the response string and present it on my web page?
EDIT - June 22, 2010, 11:17 AM
I found a Ruby script and tweaked it to try and consume the URLs. I ran it in interactive Ruby (irb).
require 'rubygems'
require 'json'
require 'net/http'

url = "http://api.business.gov/geodata/city_county_links_for_state_of/CA.json"
resp = Net::HTTP.get_response(URI.parse(url))
data = resp.body
result = JSON.parse(data)
result.each{|entry| p entry["name"] + "," + entry["full_county_name"] }

I was able to use a similar Ruby script to consume the Google Calendar URL as well.
Bottom line? I was able to consume both JSON resources (api.business.gov and Google Calendar) using Ruby, but only the Google Calendar resource using Javascript/jQuery in my browser.
I'd appreciate any insight I can get. It doesn't seem clear from any of the documentation on the web or the API descriptions why the Google Calendar feed works in the browser no matter what, but the api.business.gov feed does not work in the browser using JSON or JSONP.

A: As Juan Manuel pointed out, this is your browser protecting you from cross site scripting.  If you take a look at your requests in Fiddler, you can see what is going on.
This is part of the response header from google:

HTTP/1.1 200 OK
Content-Type: application/json; charset=UTF-8
Access-Control-Allow-Origin: *
Rest Omitted...

This is from business.gov:

HTTP/1.1 200 OK
Date: Fri, 18 Jun 2010 21:52:10 GMT
Server: Mongrel 1.1.4
Status: 200 OK
X-Runtime: 0.36775
ETag: "172ec84fa79f748265e96d467af3d3dd"
Cache-Control: private, max-age=0, must-revalidate
Content-Type: application/json; charset=utf-8
Via: 1.1 api.business.gov
Content-Length: 229427
Proxy-Connection: Keep-Alive
Connection: Keep-Alive
Set-Cookie: .....7c5; path=/
Age: 0

[
  {"name": "Adelanto" ,
   "fips_county_cd": "71" ,
   "feat_class": "Populated Place" ,
   "county_name": "San Bernardino" ,
   "primary_latitude": "34.58" ,
   "state_name": "California" ,
..... (rest omited)

You see that your response from business.gov is actually returned, but blocked by the browser.
Update for your updates:
The Google web service is handling the JSONP for you along with jQuery.  The business.gov web service does not support JSONP apparently.  You will need to use Ruby (server side code) to act as a proxy and consume the business.gov service then return the response to the client.

A: It may be a problem with same origin policy
Can you try using JSONP?
I had the same problem (firebug showing empty data) and solved it with it, but I had control over the web service and could modify it to support it.

A: One difference between the two is the Content-Type the server is reporting for the results:
Fiddler is showing the Google Calendar call being returned as Content-Type: text/plain; charset=UTF-8 whereas business.gov is not specifying a Content-Type. application/json; charset=utf-8 (edited, my initial answer was from a Cached response).
The Content-Type essentially tells the browser what filetype the response is--it's fairly similar to a file-extension in Windows.  It's also known as a MIME-Type and has some fairly far-reaching effects (for example, it takes precedence over the DTD in a HTML/XHTML file--so if you are serving XHTML with a text/html Content-Type then the browser will actually treat the response as HTML--so lots of sites that claim they are XHTML compliant are actually serving invalid HTML.

TheJuice seems to have seen different results in Fiddler, so for the sake of comparison here's the headers I saw in testing:
Google Calendar
HTTP/1.1 200 OK
Content-Type: text/plain; charset=UTF-8
Expires: Tue, 22 Jun 2010 15:25:41 GMT
Date: Tue, 22 Jun 2010 15:25:41 GMT
Cache-Control: private, max-age=0, must-revalidate, no-transform
Vary: Accept, X-GData-Authorization, GData-Version
GData-Version: 1.0
Last-Modified: Tue, 22 Jun 2010 12:19:15 GMT
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
Server: GSE
Content-Length: 49803

Business.gov:
HTTP/1.1 200 OK
Date: Tue, 22 Jun 2010 15:34:33 GMT
Server: Mongrel 1.1.4
Status: 200 OK
X-Runtime: 0.37833
ETag: "172ec84fa79f748265e96d467af3d3dd"
Cache-Control: private, max-age=0, must-revalidate
Content-Type: application/json; charset=utf-8
Content-Length: 229427
Via: 1.1 api.business.gov
Keep-Alive: timeout=15, max=100
Connection: Keep-Alive


text:
Q: Question about Crystal Reports + SQL Server stored procedure with GROUP BY I'm writing a report in Crystal Reports XI Developer that runs a stored procedure in a SQL Server 2005 database. The record set returns a summary from log table grouped by Day and Hour.
Currently my query looks something like this:
SELECT
    sum(colA) as "Total 1",
    day(convert(smalldatetime, convert(float, Timestamp) / 1440 - 1)) as "Date",
    datepart(hh, convert(smalldatetime, convert(float, Timestamp) / 1440 - 1)) as "Hour"
    `etc...`
GROUP BY
    Day, Hour

Ignore the date insanity, I think the system designers were drinking heavily when they worked out how to store their dates.
My problem is this: since there are not always records from each hour of the day, then I end up with gaps, which is understandable, but I'd like Crystal to be able to report on the entire 24 hours regardless of whether there is data or not.
I know I can change this by putting the entire query in a WHILE loop (within the stored procedure) and doing queries on the individual hours, but something inside me says that one query is better than 24.
I'd like to know if there's a way to have Crystal iterate through the hours of the day as opposed to iterating through the rows in the table as it normally does.
Alternatively, is there a way to format the query so that it includes the empty hour rows without killing my database server?

A: Here's how I solved this problem:

*

*Create a local table in your SQL-Server.  Call it "LU_Hours".

*This table will have 1 integer field (called "Hours") with 24 rows. Of course, the values would be 1 through 24.

*Right join this onto your existing query.

*You might need to tweak this to make sure the nulls of empty hours are handled to your satisfaction.

A: You could use a WITH clause to create the 24 hours, then OUTER JOIN it.
WITH hours AS (

  SELECT 1 AS hour
  UNION
  SELECT 2 AS hour
  ...
  SELECT 24 AS hour

)

SELECT *
FROM hours h
LEFT OUTER JOIN [your table] x ON h.hour=x.datepart(hh, convert(smalldatetime, convert(float, Timestamp) / 1440 - 1))

This SQL would need to added to a Command.
Group as necessary in the SQL or the report.


text:
Q: Laravel 5.1 MethodNotAllowedHttpException Error I'm using resource controller , when i submit form through ajax , it is showing method not allowed exception.
View
 {!! Form::open(array('route' => 'product.store','class' => 'form-horizontal','id' => 'productform','name' => 'productform','files' => true)) !!}
       {!! csrf_field() !!}

            Product name

                 {!! Form::text('productName',null, array('id'=> 'productName','class'=>'form-control','placeholder'=>'Product name'))!!}

                 {!! Form::submit('Save', array('class' => 'btn btn-primary btn-block')) !!}

 {!! Form::close() !!}

AJAX
$("#productform").submit(function () {
    var token = $('[name=_token]').val();
    $.ajax({
        type: 'POST',
        url: 'product/store',
        data: {
            id: '4',
            _token: token,
         },
        success: function (data) {
            alert('success');
            return false;
        }
    })
    return false;
});

routes.php
Route::resource('product', 'ProductController');

What is the problem here...Any help is much appreciated.

A: in jquery
var BASEURL = $("#baseURL").val()

in html

<input type="hidden" id="baseURL" value="{{ url('') }}" >

A: when you try to store data in laravel your URL must be.
url: 'product',

try to go on your CMD and type:
php artisan route:list

and check the URI of product.store Name then that will be you url in your AJAX.

A: in AJAX
try to set url in AJAX to be route
$("#productform").submit(function () {
    var token = $('[name=_token]').val();
    $.ajax({
        type: 'POST',
        url: '{{ route("product.store") }}',
        data: {
            id: '4',
            _token: token,
        },
        success: function (data) {
            alert('success');
            return false;
        }
    });
    return false;
});


text:
Q: MySQL Order By and a Limit 1 subquery to return most recent record I've noticed there are a few similar questions on StackOverflow, but nothing has worked for me so far. I'll try to keep this as short as possible.
I am building a query that needs to return a number of issues that may or may not have contracts, that may or may not be completed (completed_at would be set to a DateTime, not nil). Each row needs to include:

*

*one row containing all the issue record's fields

*the description from the budget_item

*the completed_at date from the most recent contract that was completed (one budget_item could have 0 contracts, 1 contract, or 5+ contracts and any number of them could be open (completed_at :nil) or closed (completed_at: DateTime)

This is what I have so far (which returns the correct number of rows, but it is returning the most recently created contract, not the most recent
BaseItem.issues
   .joins('LEFT JOIN budget_items
           ON issues.id = budget_items.issue_id
           LEFT JOIN contracts
           ON budget_items.id = contracts.budget_item_id')
   .select('issues.*, budget_items.description, contracts.completed_at AS resolved_at')
   .group('issues.id')
   .order('contracts.completed_at')

The code in the models is as follows:
class BaseItem < ActiveRecord::Base
    has_many :issues
    ...
end

class Issue < ActiveRecord::Base
    belongs_to :base_item
    has_many :budget_items
    ...
end

class BudgetItem < ActiveRecord::Base
    belongs_to :issue
    has_many :contracts
    ...
end

class Contract < ActiveRecord::Base
    belongs_to :budget_item
    ...
end

The end result needs to be something along the line of:
There will likely be multiple issues making up the different rows. Each issue has at least four budget_items which are used only for the budget_item.description which needs to appear in the final query and then are used to join each issue to its many contracts (each budget_item could have 2 or 3 contracts so the issue could end up having 8-12 contracts. From those contracts, the query needs to order them according to their completed_at attribute and return AS resolved_at only the most recent contract's completed_at date. If there were 4 contracts, two had completed_at: nil, the query should return the most recent of the two remaining completed_at dates as the resolved_at field of that particular issue.
Any help would be greatly appreciated and please let me know if I need to provide any additional information.
-Dave
The resulting query (from a comment):
SELECT  issues.*, budget_items.description, contracts.completed_at AS resolved_at
    FROM  issues
    LEFT JOIN  budget_items ON issues.id = budget_items.issue_id
    LEFT JOIN  contracts ON budget_items.id = contracts.budget_item_id
    WHERE  issues.base_item_id = 6
    GROUP BY  issues.id
    ORDER BY  contracts.completed_at DESC
    LIMIT  1

A: .order('contracts.completed_at DESC LIMIT 1')

(or do I not understand what is missing from your code?)

A: You don't need to show your actual data in the sample to make it useful...
This is what I mean by it. You could have put into your question the following sample data:
issues
id    base_item_id
--    ------------
10               6
20               6
30               6
99             123

budget_items
id    issue_id    description
--    --------    -----------
 1          10    'one contract, none completed'
 2          20    'one contract, one completed'
 3          30    'two contracts, one completed'
 4          30    'three contracts, two completed'

contracts
id    budget_item_id    completed_at
--    --------------    ------------
 1                 1            NULL
 2                 2      2015-01-02
 3                 3      2015-01-03
 4                 3            NULL
 5                 4      2015-01-05
 6                 4            NULL
 7                 4      2015-01-07

expected result
issues.id    contracts.completed_at    budget_item.description
---------    ----------------------    -----------------------
       10                      NULL    NULL
       20                2015-01-02    one contract, one completed
       30                2015-01-07    three contracts, two completed

Here is SQL Fiddle.
Is it what you want? Does my sample data cover all possible edge cases? If not, add more rows to it and show how it affects the result.

This is how the final query may look like. MySQL doesn't have things like CROSS APPLY or LATERAL JOINS, so it is less efficient than in other databases - the subquery will run twice.
I have no idea how to translate this SQL to Ruby - I never used Ruby.
SELECT
    issues.*
    ,(
        SELECT contracts.completed_at
        FROM
            budget_items
            INNER JOIN contracts ON contracts.budget_item_id = budget_items.id
        WHERE
            budget_items.issue_id = issues.id
            AND contracts.completed_at IS NOT NULL
        ORDER BY contracts.completed_at DESC
        LIMIT 1
    ) AS resolved_at
    ,(
        SELECT budget_items.description
        FROM
            budget_items
            INNER JOIN contracts ON contracts.budget_item_id = budget_items.id
        WHERE
            budget_items.issue_id = issues.id
            AND contracts.completed_at IS NOT NULL
        ORDER BY contracts.completed_at DESC
        LIMIT 1
    ) AS description
FROM issues
WHERE issues.base_item_id = 6

The main idea is simple. We return one row for each issue. For each issue we find one latest contract using whatever conditions you need (like contracts.completed_at IS NOT NULL to look for completed contracts only).
If there is no completed contracts at all for an issue it returns NULL for description and resolved_at. You can add extra filter in the main SELECT to remove such rows if this is what you want (WHERE issues.base_item_id = 6 AND resolved_at IS NOT NULL).


text:
Q: Use database in the Firefox web extension I want to use some database in my Firefox web extension, I already found this, but it's just a storage for key-value pairs.
So how can I use database in the Firefox web extension?

A: You can use the IndexedDB Web API: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
There's a sample extension that uses it, though it's using a library. It might be better to look at general Using IndexedDB examples.
You probably want to declare "unlimitedStorage" permission; in Chrome, it lifts the 5MB restriction on size, while on Firefox it apparently bypasses a user prompt.
Note that IndexedDB is per-origin, so your content scripts (whose origin is technically the page they are running in) won't be able to access it directly; you'll need to rely on Messaging to let the background page "proxy" the access.


text:
Q: NodeJS console.log works but response.write doesn't I'm new to NodeJS.
I am reading this book to learn it.
I am using the following code in one of the request handler modules.
Basically, When I get a request from the browser, I send a call to this function and get the contents of the "DIR" command in windows displayed on the screen.
The index.js file is the one which I run as the webapp
This is index.js
var server = require("./server.js");
var router = require("./router.js");
var requestHandlers = require("./requestHandlers");

var handle = {};
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;

server.start(router.route, handle);

This is server.js
The server file sends the requests to the router
var http = require("http");
var url = require("url");

function start(route, handle)
{
function onRequest(request, response)
{
    //console.log("Request recieved!");
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " has been recieved");
    response.writeHead(200, {"Content-Type": "text/plain"});

    route(handle, pathname, response);

    response.end();
}

http.createServer(onRequest).listen(8888);

console.log("Server started!");

}

exports.start = start;

This is router.js
This is the router which uses the handle created in index.js (used to map the request to their respective handlers).
function route(handle, pathname, response)
{
console.log("About to route the request " + pathname);
if(typeof handle[pathname] == 'function')
{
    handle[pathname](response);
}
else
{
    console.log("No request handler found for " + pathname);
    response.writeHead(404,{"Content Type": "text/plain"});
    response.write("404 not found");
    response.end();
}
}

exports.route = route;

And finally this is where the requests are being handled, in the requestHandlers.js
Over here, It looks like the console.log statement works fine, but the response.write statements don't.
var exec = require("child_process").exec;

function start(response)
{
    console.log("Request handler 'start' was called.");

    exec("dir", function(error, stdout, stderr) {
        response.writeHead(200,{"Content Type": "text/plain"});
        response.write("Hello Upload!");
        response.write(stdout);
        response.write("Hello!");
        console.log(stdout);
        response.end();
    });
}

function upload(response)
{
console.log("Request handler 'upload' was called.");
response.writeHead(200,{"Content Type": "text/plain"});
response.write("Hello Upload!");
response.end();
}

exports.start = start;
exports.upload = upload;

Any help would be greatly appreciated

A: I think the reason your request is breaking is that it looks like response.writeHead is being called twice, once in server#onRequest and once in requestHandlers#upload.
Node.js Docs - response.writeHead
Once you're feeling a little more comfortable with Node I'd probably recommend pulling any response writing/ending code out of server.js and implementing a middleware approach where each request gets passed through each requestHandler until it is matched or gets to the end.
hope that helps -- happy noding!
EDIT: +1 Andreas' comment. Not the problem on the upload route since that is all synchronous, but in requestHandlers#start once exec is called the control flow continues back to server.js where response.end() is called.


text:
Q: I need to select a data that doesn't exist on a table as zero using the COUNT() function, how do I do so using Sql For instance:
SELECT COUNT(num) AS number, Status
FROM base
WHERE Status in ('P', 'J', 'K')
GROUP BY Status;

Note: J and K doesn't exist in the Status column but I need to display the number as zero
The result should be like:
number | Status
---------------
1500   | P
0      | J
0      | K

A: You could use derived table and LEFT JOIN:
SELECT count(base.num) AS number, s.Status
FROM (SELECT 'P' AS Status UNION ALL SELECT 'J' UNION ALL SELECT 'K') s
LEFT JOIN base ON s.status = base.Status
group by s.Status;

A: If you don't mind having the results as columns, rather than rows, then we can try using conditional aggregation here:
SELECT
    COUNT(CASE WHEN Status = 'P' THEN 1 END) AS p_cnt,
    COUNT(CASE WHEN Status = 'J' THEN 1 END) AS j_cnt,
    COUNT(CASE WHEN Status = 'K' THEN 1 END) AS k_cnt
FROM base;

The derived table idea suggested by @Lukasz is a good one, and you should probably have a separate table for the stati in any case.

A: You can easily UNPIVOT your data by using UNION ALL as
SELECT COUNT(num) AS number, coalesce(Status,'P') AS Status FROM base WHERE Status = 'P'
UNION ALL
SELECT COUNT(num)          , coalesce(Status,'J')           FROM base WHERE Status = 'J'
UNION ALL
SELECT COUNT(num)          , coalesce(Status,'K')           FROM base WHERE Status = 'K';

If some rows are inserted with Status 'J' or 'K' and num > 0 in the future, you'll be able to get count values more than zero for those rows also.

A: What you should probably do is fix your data model so you have a statuses reference table:
create tables statuses (
    status char(1) primary key,
    description varchar(255),
    createdAt datetime default curent_datetime
);

You might have other information to store as well.
Populate this table:
insert into statuses (status, description)
    values ('P', 'P status'),
           ('J', 'J status'),
           ('K', 'K status');

You might find better descriptions.
Declare a proper foreign key relationship:
alter table base add constraint fk_base_status foreign key (status) references statuses(status);

Then use a left join:
select s.status, count(b.status)
from statuses s left join
     base b
     on s.status = b.status
group by s.status;


text:
Q: Stop Images colliding when resizing in bootstrap and HTML Hey so i'm a student in High School
have an assessment coming up my computer studies class the assessment really is create a responsive informative website using HTML, BOOTSTRAP and CSS. Im saying this to warn people that I am shit at html and bootstrap so if there is organisation problems or just bad code thats because of my lack of knowledge
basically my problem is I have some images colliding when I resize.
most problems the my teacher said like put it in a div, resize image file not in html etc is not working
here is my html and css code which I need to fix

        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">

        </button>

                    Home (current)

                    Link

                    Link

          Dropdown link

                        Action
                        Another action
                        Something else here

            Previous

            Next

 How did I make this website

 HTML 5

 Bootstrap 4

 CSS 3

 Welcome To My Website

 this is website designed for using bootstrap for example (image slides) and (nav bars) but by no means is this a "good" website... now here is a copy paste i got from wikipedia on what bootstrap is and other ramdom facts... Bootstrap is a free and open-source CSS framework directed at responsive, mobile-first front-end web development. It contains CSS- and (optionally) JavaScript-based design templates for typography, forms, buttons, navigation and other interface components... Life is a characteristic that distinguishes physical entities that have biological processes, such as signaling and self-sustaining processes, from those that do not, either because such functions have ceased, or because they never had such functions and are classified as inanimate.

 Welcome To My Website

 Pepe the Frog is an Internet meme. A green anthropomorphic frog with a humanoid body, Pepe originated in a comic by Matt Furie called Boy's Club. It became an Internet meme when its popularity steadily grew across Myspace, Gaia Online and 4chan in 2008.

 why look at this website

 because you decided to look at

.

 because i need to get practice and get excellence in all my com tests

.

 if you really are confused as to how you got here you might want to call your GP

Are you not board yet if not click me

 well if you are not now let me make you

 Calculus, originally called infinitesimal calculus or "the calculus of infinitesimals", is the mathematical study of continuous change, in the same way that geometry is the study of shape and algebra is the study of generalizations of arithmetic operations. It has two major branches, differential calculus and integral calculus; the former concerns instantaneous rates of change, and the slopes of curves, while integral calculus concerns accumulation of quantities, and areas under or between curves. These two branches are related to each other by the fundamental theorem of calculus, and they make use of the fundamental notions of convergence of infinite sequences and infinite series to a well-defined limit.[1] Infinitesimal calculus was developed independently in the late 17th century by Isaac Newton and Gottfried Wilhelm Leibniz.[2][3] Today, calculus has widespread uses in science, engineering, and economics.[4]In mathematics education, calculus denotes courses of elementary mathematical analysis, which are mainly devoted to the study of functions and limits. The word calculus (plural calculi) is a Latin word, meaning originally "small pebble" (this meaning is kept in medicine). Because such pebbles were used for calculation, the meaning of the word has evolved and today usually means a method of computation. It is therefore used for naming specific methods of calculation and related theories, such as propositional calculus, Ricci calculus, calculus of variations, lambda calculus, and process calculus.

 Last Updated: November 7, 2019 12:09 PM
            <! EndDate

            2019

CSS CODE
    body{
        background-image: url("https://lh3.googleusercontent.com/proxy/bH-E_bOZVvg8Tet9wNoSisRFjNCivlR-7GAY2Q6AWF4q4KU46sIgxUUGHjmb58JLVum7jviuNn40NJdWZkPVtBZOJMDrc2ORZP7mvj5f04k");

    }

    footer {
        padding: 10px 0;
        clear: both;
        text-align: center;
    }
    footer a {
        color: #00bcff:

    }

    ul {
        text-align: center;
        list-style-position: inside;
    }

    .container{
        margin: 4% auto:
        max-width: 200px;
    }

    ul
    {
    list-style-type: none;
    }

    .imgbox{
           max-width: 150px;
        display: inline-block;
        vertical-align: top;
        padding:0 10px;
    }

anybody have any idea why

A: Your image width is fixed as of now as 960
Try adding below css:
.carousel-item img {
  max-width: 100%;
}

Bonus: Use picture tag for responsive design : https://www.w3schools.com/tags/tag_picture.asp


text:
Q: FastAPI - CORS and slowapi I'm currently deploying a webapp with the backend using fastapi/heroku and the frontend react/netlify. Originally I had a CORS (CORS header 'Access-Control-Allow-Origin') issue that was resolved using CORSMiddleware.
In decided to look into rate limiting for my app and through research found slowapi to be the most recommended. The issue however is when implementing slowapi through their documentation (https://slowapi.readthedocs.io/en/latest/), I'm back to receiving the CORS errors again.
Has anyone else experienced a similar issue and had a workaround? Or is there a better way overall to rate limit my app.
Sample code:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded

limiter = Limiter(key_func=get_remote_address)
origins = [example_origin]

app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=origins)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

@app.get("/home")
@limiter.limit("5/minute")
def homepage(request: Request):
    return {"test": "words"}

A: Update: The issue was resolved by including importing "Request", something which isn't noted in the slowapi docs, and request: Request in the end point (which is included in the docs)
from fastapi import FastAPI, Request

@app.get("/home")
def homepage(request: Request):
    return {"test": "words"}


text:
Q: What is hops in HttpClient? I'm learning about HttpClient, I can't understand hops, is it a proxy?

HttpClient is capable of establishing connections to the target host either directly or via a route that may involve multiple intermediate connections - also referred to as hops.

A: This refers to using multiple proxies. It is even explained in the same paragraph, two sentences later:

The use of multiple intermediate proxies to tunnel connections to the target host is referred to as proxy chaining.

A: In general, the direct route shall have one hop. There shall be two hops if the route is through a proxy. There shall be n+1 hops if the route is through a chain of n proxies.
The getHopCount shall return the number of hops in a route which shall help in giving further understanding of the same .


text:
Q: Import Django settings from several files There are lots of hints, why one cannot pull settings from multiple files easily, like so:
import base
import app1
import app2
import local

neither of them sees the settings from the files before and cannot modify them.
One solution is to import all the file in chain:
local.py:
import app2
app2.py:
import app1
app1.py:
import base
It's clumsy.
====
Another solution was to merge all the files into a single one.
I actually like this one. I would like to search multiple directories (OK, at least one) for *.py files, sort them by filename and import/merge them, so:
base.py -> 000_base.py
local.py -> zzz_local.py

ensure that base is first, local is last, the order of the other ones do not matter.
Is there some Django tool / framework / model, that implements this already or, at least, helps?
Thanks

A: Python's imports are not C or PHP includes. import somemodule doesn't inject the names defined in somemodule in the current scope, it loads the module (if it hasn't been already) and bind it to the name somemodule - then you can access names defined in the module using the qualified path ie somemodule.SOME_NAME.
If you want to directly bind the module's top-level names in the importing namespace, you have to either do it explicitely (from some_module import SOME_NAME, SOME_OTHER_NAME etc) or use a wildcard import (from some_module import *) but this is bad practice as it leads to hard to diagnose bugs and general maintainance hell (hint: if two of your imported module defines the same name, you'll only get the last imported one).
I've tried quite a few solutions over the years, and none of them was really satisfying, so now I just write a full self-contained settings file per environment (local, preview, preprod, prod), and use my virtualenv's post_activate hook to make the DJANGO_SETTINGS_MODULE envvar point to the desired settings file.
For per-app default settings, I use an app/settings module which imports django.conf.settings and sets the default value if it's not already defined, then use this app/settings module (instead of django.conf.settings) in the app, ie:
# myapp/settings.py
from django.conf import settings

SOMETHING = getattr(settings, "MYAPP_SOMETHING", 42)
ANOTHER = getattr(settings, "MYAPP_ANOTHER", False)

then
# myapp/models.py
from . import settings

class Foo(models.Model):
    bar = models.IntegerField(default=settings.SOMETHING)

In the case of required app settings, I check for them in my app's settings file too:
# myapp/settings.py
from django.exceptions import ImproperlyConfigured
from django.conf import settings

SOMETHING = getattr(settings, "MYAPP_SOMETHING", 42)
ANOTHER = getattr(settings, "MYAPP_ANOTHER", False)

try:
    REQUIRED = getattr(settings, "MYAPP_REQUIRED")
except AttributeError:
    raise ImproperlyConfigured("you must defined settings.MYAPP_REQUIRED")

This scheme also allow to validate user-defined settings, ie if you expect an int and the user used a string:
SOMETHING = getattr(settings, "MYAPP_SOMETHING", 42)
if not isinstance(SOMETHING, int):
    raise ImproperlyConfigured("settings.MYAPP_SOMETHING must be an int")


text:
Q: Why am I getting a ParseException when using SimpleDateFormat to format a date and then parse it? I have been debugging some existing code for which unit tests are failing on my system, but not on colleagues' systems. The root cause is that SimpleDateFormat is throwing ParseExceptions when parsing dates that should be parseable. I created a unit test that demonstrates the code that is failing on my system:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import junit.framework.TestCase;

public class FormatsTest extends TestCase {

    public void testParse() throws ParseException {
        DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss.SSS Z");
        formatter.setTimeZone(TimeZone.getDefault());
        formatter.setLenient(false);

        formatter.parse(formatter.format(new Date()));
    }
}

This test throws a ParseException on my system, but runs successfully on other systems.
java.text.ParseException: Unparseable date: "20100603100243.118 -0600"
    at java.text.DateFormat.parse(DateFormat.java:352)
    at FormatsTest.testParse(FormatsTest.java:16)

I have found that I can setLenient(true) and the test will succeed. The setLenient(false) is what is used in the production code that this test mimics, so I don't want to change it.

A: --- Edited after response indicating that the developer is using IBM's J9 1.5.0 Java Virtual Machine ---
IBM's J9 JVM seems to have a few bugs and incompatibilities in the parse routine of DateFormat, which SimpleDateFormat likely inherits because it is a subclass of DateFormat.  Some evidence to support that IBM's J9 isn't functioning quite the way you might expect other JVMs (like Sun's HotSpot JVM) can be seen here.
Note that these bugs and incompatibilites are not even consistent within the J9 JVM, in other words, the IBM J9 formatting logic might actually generate formatted times that are not compatible with the IBM J9 parsing logic.
It seems that people who are tied to IBM's J9 JVM tend to work around the bug in the JVM by not using DateFormat.parse(...) (or SimpleDateFormat.parse(...)).  Instead they tend to use java.util.regex.Matcher to parse the fields out manually.
Perhaps a later release of the J9 JVM fixes the issue, perhaps not.
--- Original post follows ---
Funny, the same code modified to:
import java.util.Date;
import java.util.TimeZone;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.ParseException;

public class FormatsTest {

 public void testParse() throws ParseException {
  DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss.SSS Z");
  formatter.setTimeZone(TimeZone.getDefault());
  formatter.setLenient(false);
  System.out.println(formatter.format(new Date()));

  formatter.parse(formatter.format(new Date()));
 }

 public static void main(String[] args) throws Exception {
   FormatsTest test = new FormatsTest();
   test.testParse();
 }

}

runs fine on my system.  I would wager that it is something in your environment.  Either you are compiling the code on one JVM major release and running it on another (which can cause some issues as the libraries could be out of date) or the system you are running it on might be reporting the time zone information oddly.
Finally, you might want to consider if you are using a very early point release of the JVM.  Sometimes bugs do creep into the various versions, and they are fixed in later point releases.  Could you please modify your question to include the "java -version" information for you system?
Either way, both of these are just educated guesses.  The code should work as written.

A: That should probably be a bug in IBM's J9 VM about the SimpleDateFormat class.
This post show a similar problem, and says it should be fixed on v6.
You may find the list of changes for several releases here.
I see there's a number related to DateFormat. So, you should probably raise a bug report or something with IBM for them to give you a patch.

A: Check the LANG environment variable of your computer and of the remote computer.
The date is parsed according to the locale, so 'Jul' works as July only if your LANG is set to english, otherwise a ParseException is raised.
You can make a quick test by running export LANG="en_US.UTF-8" and then running your program.
You can also set the locale programmatically, by using the following method:
DateFormat.getDateInstance(int, java.util.Locale)


text:
Q: How to merge arrays in PHP with a same value I want to merge two arrays with the same value -> user_id to one array.
You can see I have two arrays with different objects. I want merge them by user_id to one array with all objects.
For example:
$array1 = [
    $array[0]->leads = 5643;
    $array[0]->user_id= 15;
    $array[0]->sales = 1433;

    $array[1]->leads = 3264;
    $array[1]->user_id= 9;
    $array[1]->sales = 1254;
];

$array2 = [
    $array[0]->user_id= 15;
    $array[0]->processing = 2300;
    $array[0]->deleted = 203;

    $array[1]->user_id= 9;
    $array[1]->processing = 103;
    $array[1]->deleted = 80;
];

The following array is the target.
$result = [
    $array[0]->user_id= 15;
    $array[0]->processing = 2300;
    $array[0]->leads = 5643;
    $array[0]->deleted = 203;
    $array[0]->sales = 1433;

    $array[1]->user_id= 9;
    $array[1]->processing = 103;
    $array[1]->leads = 3264;
    $array[1]->deleted = 80;
    $array[1]->sales = 1254;
];

A: How about array_merge,
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

or array_merge_recursive,
<?php
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
print_r($result);
?>

Example
$array = [
    1 => [
        'cost' => '25'
    ],

    2 => [
        'blah' => 'test'
    ]
];

$new_array = array_merge_recursive($array[1], $array[2]);

var_dump($new_array);

Output
array(2) {
  ["cost"]=>
  string(2) "25"
  ["blah"]=>
  string(4) "test"
}

Live Example
Repl

A: Iterate your array and build the combined array of objects using user_id as the key.
foreach ($array as $entry) {

    // if an entry for this user id hasn't been created in the result, add this object
    if (!isset($result[$entry->user_id])) {
        $result[$entry->user_id] = $entry;

    // otherwise, iterate this object and add the values of its keys to the existing entry
    } else {
        foreach ($entry as $key => $value) {
            $result[$entry->user_id]->$key = $value;
        }
    }
}

Given the additional info you just gave (two separate arrays) the solution is basically the same, just merge the two arrays together first.
foreach (array_merge($array1, $array2) as $entry) { ...

(Working example at https://3v4l.org/ccdQc)

A: <?php
    $array1= array("leads"=> 5643,"user_id"=>15,"sales" =>1433);
    $array2= array("user_id"=> 15,"processing" => 2300,"deleted" => 203);
        $array= (array_merge($array1,$array2));
        print_r($array);
    ?>


text:
Q: C# volatile and Nullable According to the docs: http://msdn.microsoft.com/en-us/library/x13ttww7.aspx:
The volatile keyword can be applied to reference types.
So why is it illegal to use on a Nullable<T>.. a reference type!
Please note that I do not actually need volatile semantics on a Nullable<T> field, I encountered this error accidentally and am simply curious.

A: Nullable is a value type, not a reference type.
See http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx for definition.

A: Nullable<T> isn't a reference type. It's a value type:
public struct Nullable<T>
where T : struct, new()

Note the struct part.
Just because it has a null value doesn't make it a reference type... it's a nullable value type. See section 4.1.10 of the C# 4 language spec for more details.