text:
Q: Kamene causing python3 segmentation fault I have a basic python3 script for running a ping sweep using kamene with two main issues. I'm not sure if they are related so I'll add them both in the same post.
Where in here is the main issue and what have I done wrong?
First issue...
When I import IP and ICMP from kamena.all I have an error as below...
No name 'IP' in module 'kamene.all'pylint(no-name-in-module)
No name 'ICMP' in module 'kamene.all'pylint(no-name-in-module)
Second issue...
When I run the program, I get an IPv6 error and then a segmentation fault with a warning from OSX to say that python has stopped.
python3 pingsweep.py
WARNING: No route found for IPv6 destination :: (no default route?). This affects only IPv6
Segmentation fault: 11

This is my script code...
from kamene.all import sr1,IP,ICMP

for ip in range(1, 8):
  packet = IP(dst="192.168.0." + str(ip), ttl=20) / ICMP()
  reply = sr1(packet, timeout=2)

  if not (reply is None):
    print(reply.dst)

I have installed kamene with...
pip3 install kamene

Lastly, the crash report from OSX...
Process:               Python [13831]
Path:                  /Library/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python
Identifier:            Python
Version:               3.7.1 (3.7.1)
Code Type:             X86-64 (Native)
Parent Process:        bash [10827]
Responsible:           Python [13831]
User ID:               501

Date/Time:             2019-03-29 15:45:33.205 +0000
OS Version:            Mac OS X 10.14.4 (18E226)
Report Version:        12
Anonymous UUID:        D6F17B07-49F0-ACAE-B5D6-25ABF231369D

Sleep/Wake UUID:       AAE0878E-9596-4A63-BAD9-7146B5F303F5

Time Awake Since Boot: 28000 seconds
Time Since Wake:       16000 seconds

System Integrity Protection: enabled

Crashed Thread:        0  Dispatch queue: com.apple.main-thread

Exception Type:        EXC_BAD_ACCESS (SIGSEGV)
Exception Codes:       KERN_INVALID_ADDRESS at 0x0000000000000014
Exception Note:        EXC_CORPSE_NOTIFY

Termination Signal:    Segmentation fault: 11
Termination Reason:    Namespace SIGNAL, Code 0xb
Terminating Process:   exc handler [13831]

VM Regions Near 0x14:
-->
    __TEXT                 000000010197b000-000000010197c000 [    4K] r-x/rwx SM=COW  /Library/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   libpcap.A.dylib                 0x00007fff72b9041f pcap_get_selectable_fd + 4
1   _ctypes.cpython-37m-darwin.so   0x00000001027001d7 ffi_call_unix64 + 79
2   _ctypes.cpython-37m-darwin.so   0x0000000102700a38 ffi_call + 872
3   _ctypes.cpython-37m-darwin.so   0x00000001026fb9fb _ctypes_callproc + 891
4   _ctypes.cpython-37m-darwin.so   0x00000001026f5af0 PyCFuncPtr_call + 1040
5   org.python.python               0x00000001019a08b1 _PyObject_FastCallKeywords + 433
6   org.python.python               0x0000000101a602f4 call_function + 420
7   org.python.python               0x0000000101a5d4a7 _PyEval_EvalFrameDefault + 25351
8   org.python.python               0x00000001019a0ed0 function_code_fastcall + 128
9   org.python.python               0x0000000101a60432 call_function + 738
10  org.python.python               0x0000000101a5d3ec _PyEval_EvalFrameDefault + 25164
11  org.python.python               0x0000000101a60f56 _PyEval_EvalCodeWithName + 2422
12  org.python.python               0x00000001019a063b _PyFunction_FastCallDict + 523
13  org.python.python               0x00000001019a190f _PyObject_Call_Prepend + 143
14  org.python.python               0x00000001019efe91 slot_tp_init + 145
15  org.python.python               0x00000001019eb7e9 type_call + 297
16  org.python.python               0x00000001019a08b1 _PyObject_FastCallKeywords + 433
17  org.python.python               0x0000000101a602f4 call_function + 420
18  org.python.python               0x0000000101a5d54d _PyEval_EvalFrameDefault + 25517
19  org.python.python               0x0000000101a60f56 _PyEval_EvalCodeWithName + 2422
20  org.python.python               0x00000001019a0a61 _PyFunction_FastCallKeywords + 257
21  org.python.python               0x0000000101a60432 call_function + 738
22  org.python.python               0x0000000101a5d54d _PyEval_EvalFrameDefault + 25517
23  org.python.python               0x0000000101a60f56 _PyEval_EvalCodeWithName + 2422
24  org.python.python               0x0000000101a570c4 PyEval_EvalCode + 100
25  org.python.python               0x0000000101a94591 PyRun_FileExFlags + 209
26  org.python.python               0x0000000101a93e0a PyRun_SimpleFileExFlags + 890
27  org.python.python               0x0000000101ab219b pymain_main + 6827
28  org.python.python               0x0000000101ab26ea _Py_UnixMain + 58
29  libdyld.dylib                   0x00007fff73c1b3d5 start + 1

Thread 0 crashed with X86 Thread State (64-bit):
  rax: 0x0000000000000000  rbx: 0x00007ffeee283290  rcx: 0x00000001019a0373  rdx: 0x00007ffeee283110
  rdi: 0x0000000000000000  rsi: 0x0000000000000000  rbp: 0x00007ffeee283160  rsp: 0x00007ffeee283160
   r8: 0x00007ffeee283110   r9: 0x00000001019a01e8  r10: 0x00007ffeee2830c0  r11: 0x00007fff72b9041b
  r12: 0x00007ffeee2830c0  r13: 0x0000000000000001  r14: 0x0000000102700a60  r15: 0x00007fffa6c14070
  rip: 0x00007fff72b9041f  rfl: 0x0000000000010246  cr2: 0x0000000000000014

Logical CPU:     0
Error Code:      0x00000004
Trap Number:     14

Binary Images:
       0x10197b000 -        0x10197bfff +org.python.python (3.7.1 - 3.7.1) <4B030EC4-815E-34B7-90E7-D0720C31E072> /Library/Frameworks/Python.framework/Versions/3.7/Resources/Python.app/Contents/MacOS/Python
       0x10197f000 -        0x101b57fff +org.python.python (3.7.1, [c] 2001-2018 Python Software Foundation. - 3.7.1) <977C0919-F108-3AC9-8796-F42032694A62> /Library/Frameworks/Python.framework/Versions/3.7/Python
       0x101f25000 -        0x101f2eff7 +_socket.cpython-37m-darwin.so (0) <0BA1CC79-DBFC-332D-9DEE-7A81A6654023> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_socket.cpython-37m-darwin.so
       0x101f7b000 -        0x101f7cfff +_heapq.cpython-37m-darwin.so (0) <E8B35F18-1B5A-3C9E-B1F4-0BE0432459A2> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_heapq.cpython-37m-darwin.so
       0x101f80000 -        0x101f84fff +math.cpython-37m-darwin.so (0) <E18B0A65-B44F-3F1D-96A8-C29A7F794019> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/math.cpython-37m-darwin.so
       0x101f8b000 -        0x101f8dfff +select.cpython-37m-darwin.so (0) <869F8AE3-73B4-35C4-82CA-3D954FD00F78> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/select.cpython-37m-darwin.so
       0x1021e6000 -        0x1021e8ff7 +_hashlib.cpython-37m-darwin.so (0) <13B96FDE-C671-3396-B89D-2ACB4F56A05B> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_hashlib.cpython-37m-darwin.so
       0x1021ed000 -        0x10222eff7 +libssl.1.1.dylib (0) <E00648A8-30F5-3638-8774-6EE461AB8CAC> /Library/Frameworks/Python.framework/Versions/3.7/lib/libssl.1.1.dylib
       0x10224f000 -        0x10242cc6f +libcrypto.1.1.dylib (0) <4E4019C3-04B3-3DA5-8504-57FF0E7C5600> /Library/Frameworks/Python.framework/Versions/3.7/lib/libcrypto.1.1.dylib
       0x1024ac000 -        0x1024b1ff7 +_blake2.cpython-37m-darwin.so (0) <5D4A9B1B-FE9F-34EA-BD75-7B3CDDBB7CD0> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_blake2.cpython-37m-darwin.so
       0x1024b6000 -        0x1024c6ff7 +_sha3.cpython-37m-darwin.so (0) <78945AB7-D4B8-3DCE-8496-EE83FDA05E0D> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_sha3.cpython-37m-darwin.so
       0x1024cc000 -        0x1024ccff7 +_bisect.cpython-37m-darwin.so (0) <A4FCF31A-2AA6-3EAC-AF46-2F2D10EC1AB1> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_bisect.cpython-37m-darwin.so
       0x1024cf000 -        0x1024d0ff7 +_random.cpython-37m-darwin.so (0) <CE043712-0C0E-3DA4-AAF2-35654CC67C6D> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_random.cpython-37m-darwin.so
       0x1024d4000 -        0x1024d8fff +_struct.cpython-37m-darwin.so (0) <2379780F-4AB4-394B-B5AB-55A517D6627E> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_struct.cpython-37m-darwin.so
       0x102521000 -        0x102522ff7 +_posixsubprocess.cpython-37m-darwin.so (0) <11920A4C-3AD4-3C87-95E5-418D30950610> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_posixsubprocess.cpython-37m-darwin.so
       0x102526000 -        0x102527fff +fcntl.cpython-37m-darwin.so (0) <ADADACC0-C00C-3386-9709-CCB56A7C95E0> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/fcntl.cpython-37m-darwin.so
       0x10252b000 -        0x10252eff7 +zlib.cpython-37m-darwin.so (0) <CB41B121-E928-3213-92CE-7A26C3F668BF> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/zlib.cpython-37m-darwin.so
       0x102534000 -        0x102539ff7 +array.cpython-37m-darwin.so (0) <B594CECF-180C-348D-B9DA-11275D232042> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/array.cpython-37m-darwin.so
       0x102654000 -        0x102667fff +_pickle.cpython-37m-darwin.so (0) <2F30BDA6-A35E-38F0-9096-72DDCA1030B6> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_pickle.cpython-37m-darwin.so
       0x1026f3000 -        0x102703ff7 +_ctypes.cpython-37m-darwin.so (0) <78FCD5A2-0B47-331E-A406-2876C1289C15> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_ctypes.cpython-37m-darwin.so
       0x102755000 -        0x102756ff7 +_bz2.cpython-37m-darwin.so (0) <732D55D3-F86E-31E0-95B9-DB921419F7B2> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_bz2.cpython-37m-darwin.so
       0x10275a000 -        0x10278aff7 +_lzma.cpython-37m-darwin.so (0) <91D1CDE2-5956-3869-87A0-29726C9D4C60> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_lzma.cpython-37m-darwin.so
       0x102794000 -        0x102794fff +grp.cpython-37m-darwin.so (0) <9C889B5E-65A3-339F-8F34-E10FF20A6ED9> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/grp.cpython-37m-darwin.so
       0x102797000 -        0x10279cff7 +libdnet.dylib (0) <BD67BA1C-F58B-3ABF-89DE-35B09579779F> /usr/local/lib/libdnet.dylib
       0x1027e1000 -        0x1027e3ffb +netifaces.cpython-37m-darwin.so (0) <0DCF0A83-6515-3E4E-902C-2E0E7FF24E13> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/netifaces.cpython-37m-darwin.so
       0x102d04000 -        0x102d48ff7 +_decimal.cpython-37m-darwin.so (0) <C94BD9E0-CEBA-3930-AB10-15E1FEFAA244> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_decimal.cpython-37m-darwin.so
       0x102db0000 -        0x102db1ff7 +_queue.cpython-37m-darwin.so (0) <C457E118-139B-352D-A6F9-DA76389AE74E> /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload/_queue.cpython-37m-darwin.so
       0x103b9f000 -        0x103c096ef  dyld (655.1.1) <F217F7F8-A795-3109-B77F-B1E2277F3E3B> /usr/lib/dyld
    0x7fff47769000 -     0x7fff47bacfff  com.apple.CoreFoundation (6.9 - 1570.16) <F3DFF269-6705-35AD-9F01-66D77DD1B518> /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation
    0x7fff705a0000 -     0x7fff705a1ffb  libDiagnosticMessagesClient.dylib (107) <B5675E8C-2F34-3E0A-B7E8-6F2373589038> /usr/lib/libDiagnosticMessagesClient.dylib
    0x7fff709df000 -     0x7fff709e0ffb  libSystem.B.dylib (1252.250.1) <72841192-B0C9-36A0-8E55-ED651EADEF08> /usr/lib/libSystem.B.dylib
    0x7fff70c14000 -     0x7fff70c21fff  libbz2.1.0.dylib (38.200.3) <62019AC3-20C9-3DDC-9C83-189C1F258073> /usr/lib/libbz2.1.0.dylib
    0x7fff70c22000 -     0x7fff70c75ff7  libc++.1.dylib (400.9.4) <446DAE5E-4E97-3E4B-B2A3-AC0A74C0E453> /usr/lib/libc++.1.dylib
    0x7fff70c76000 -     0x7fff70c8bff7  libc++abi.dylib (400.17) <A2D1FDAD-E10F-3E53-958F-CB6BC8485767> /usr/lib/libc++abi.dylib
    0x7fff71898000 -     0x7fff71af8ff3  libicucore.A.dylib (62123.0.1) <3936C798-1978-3C6C-9050-3BBD57CDA53E> /usr/lib/libicucore.A.dylib
    0x7fff723d9000 -     0x7fff72b5efdf  libobjc.A.dylib (756.2) <4F86FC7C-496B-3E68-8A74-1EA2BA22FBCC> /usr/lib/libobjc.A.dylib
    0x7fff72b77000 -     0x7fff72bacfff  libpcap.A.dylib (79.250.1) <FA490ABF-6C15-336A-818F-0C14A8C090DB> /usr/lib/libpcap.A.dylib
    0x7fff732af000 -     0x7fff732c1ff7  libz.1.dylib (70.200.4) <FDF169F3-F992-3E8E-B3F7-D4134FEBAE41> /usr/lib/libz.1.dylib
    0x7fff73a9e000 -     0x7fff73aa2ff3  libcache.dylib (81) <9A8C27B0-49C9-337F-8BE2-37171ED2D8EE> /usr/lib/system/libcache.dylib
    0x7fff73aa3000 -     0x7fff73aadff3  libcommonCrypto.dylib (60118.250.2) <17C4F395-9FF0-331F-8167-5E85AA3588E9> /usr/lib/system/libcommonCrypto.dylib
    0x7fff73aae000 -     0x7fff73ab5ff7  libcompiler_rt.dylib (63.4) <8CB2B2B6-2C55-3733-9842-0E037AE3F46A> /usr/lib/system/libcompiler_rt.dylib
    0x7fff73ab6000 -     0x7fff73abfff7  libcopyfile.dylib (146.250.1) <24905E41-9E2F-3DD1-A255-5A17F9FCDAD7> /usr/lib/system/libcopyfile.dylib
    0x7fff73ac0000 -     0x7fff73b44fc7  libcorecrypto.dylib (602.250.23) <3A6CBD41-AFFE-3E06-B1EC-3E95BC79BAC5> /usr/lib/system/libcorecrypto.dylib
    0x7fff73bcb000 -     0x7fff73c04ff7  libdispatch.dylib (1008.250.7) <50235FCE-B399-3319-90DC-88F530D4FC5C> /usr/lib/system/libdispatch.dylib
    0x7fff73c05000 -     0x7fff73c31ff7  libdyld.dylib (655.1.1) <54C6B494-4A3D-3EEC-B083-636A76AAD649> /usr/lib/system/libdyld.dylib
    0x7fff73c32000 -     0x7fff73c32ffb  libkeymgr.dylib (30) <BEA04E04-FCF1-3A70-810F-08D0FF54CA36> /usr/lib/system/libkeymgr.dylib
    0x7fff73c40000 -     0x7fff73c40ff7  liblaunch.dylib (1336.251.2) <30E6424E-4640-3DBA-9B64-D5F725263C6E> /usr/lib/system/liblaunch.dylib
    0x7fff73c41000 -     0x7fff73c46fff  libmacho.dylib (927.0.2) <D8515A20-ED7B-3B13-9ADA-4BD7E19E38C4> /usr/lib/system/libmacho.dylib
    0x7fff73c47000 -     0x7fff73c49ffb  libquarantine.dylib (86.220.1) <8A9BF971-DB7D-311A-B131-6C5025E82F8F> /usr/lib/system/libquarantine.dylib
    0x7fff73c4a000 -     0x7fff73c4bff7  libremovefile.dylib (45.200.2) <950036B7-B91E-3B5D-853C-8C551E5B6A32> /usr/lib/system/libremovefile.dylib
    0x7fff73c4c000 -     0x7fff73c63ff3  libsystem_asl.dylib (356.200.4) <16F632AD-FADA-3DE9-85E8-EBC7D619A1DA> /usr/lib/system/libsystem_asl.dylib
    0x7fff73c64000 -     0x7fff73c64ff7  libsystem_blocks.dylib (73) <0CD6861B-EC5F-3345-9C24-B21EEB85E44F> /usr/lib/system/libsystem_blocks.dylib
    0x7fff73c65000 -     0x7fff73cecfff  libsystem_c.dylib (1272.250.1) <F3AA9047-EEDD-3D80-8CC1-023FB312EC8B> /usr/lib/system/libsystem_c.dylib
    0x7fff73ced000 -     0x7fff73cf0ffb  libsystem_configuration.dylib (963.250.1) <02C7A973-014A-31D7-B7D2-247D384CB0D2> /usr/lib/system/libsystem_configuration.dylib
    0x7fff73cf1000 -     0x7fff73cf4ff7  libsystem_coreservices.dylib (66) <4CF1C89B-FA6C-3DF3-B1F8-79F549849534> /usr/lib/system/libsystem_coreservices.dylib
    0x7fff73cf5000 -     0x7fff73cfbfff  libsystem_darwin.dylib (1272.250.1) <6983A268-20F4-3F98-A3F5-D63848933B02> /usr/lib/system/libsystem_darwin.dylib
    0x7fff73cfc000 -     0x7fff73d02ff7  libsystem_dnssd.dylib (878.250.4) <9FC5724C-DD03-3E14-A6E1-2DD009D79E0A> /usr/lib/system/libsystem_dnssd.dylib
    0x7fff73d03000 -     0x7fff73d4effb  libsystem_info.dylib (517.200.9) <F617D3CF-5A4A-36D0-8CBB-4A7C7CDB67AF> /usr/lib/system/libsystem_info.dylib
    0x7fff73d4f000 -     0x7fff73d77ff7  libsystem_kernel.dylib (4903.251.3) <84EF0290-6CB5-36E5-A273-692A7E437B36> /usr/lib/system/libsystem_kernel.dylib
    0x7fff73d78000 -     0x7fff73dc3ff7  libsystem_m.dylib (3158.200.7) <33105665-CCC3-36D5-82C9-9B21730CB3DF> /usr/lib/system/libsystem_m.dylib
    0x7fff73dc4000 -     0x7fff73de8fff  libsystem_malloc.dylib (166.251.2) <90DA09E3-1276-3FCF-8F5F-C9AA61AB9B6D> /usr/lib/system/libsystem_malloc.dylib
    0x7fff73de9000 -     0x7fff73df3ff7  libsystem_networkextension.dylib (767.250.2) <4575D797-B793-3D18-9E93-8696CF0B133B> /usr/lib/system/libsystem_networkextension.dylib
    0x7fff73df4000 -     0x7fff73dfbfff  libsystem_notify.dylib (172.200.21) <679E9132-1A46-326E-9A11-D3FF9C86041C> /usr/lib/system/libsystem_notify.dylib
    0x7fff73dfc000 -     0x7fff73e05fef  libsystem_platform.dylib (177.250.1) <3CC59141-5365-3848-94C3-D65E6FCA1E74> /usr/lib/system/libsystem_platform.dylib
    0x7fff73e06000 -     0x7fff73e10ff7  libsystem_pthread.dylib (330.250.2) <4344198A-A1A3-3C52-97B4-F168D56E9789> /usr/lib/system/libsystem_pthread.dylib
    0x7fff73e11000 -     0x7fff73e14ff7  libsystem_sandbox.dylib (851.250.12) <66E91015-F62A-3365-BB81-AA88707E8F12> /usr/lib/system/libsystem_sandbox.dylib
    0x7fff73e15000 -     0x7fff73e17ff3  libsystem_secinit.dylib (30.220.1) <F054DCB0-68CE-35E7-8B8C-D648C42124EC> /usr/lib/system/libsystem_secinit.dylib
    0x7fff73e18000 -     0x7fff73e1fff3  libsystem_symptoms.dylib (820.257.1) <C8517F35-E9DA-3649-B07D-2B38349C6730> /usr/lib/system/libsystem_symptoms.dylib
    0x7fff73e20000 -     0x7fff73e35fff  libsystem_trace.dylib (906.250.5) <AE77ACC7-488F-3AE1-BB0C-1ACFC7E1CE77> /usr/lib/system/libsystem_trace.dylib
    0x7fff73e37000 -     0x7fff73e3cffb  libunwind.dylib (35.4) <8F0BC197-B97C-3DDC-92B0-6A7D3CB72FD8> /usr/lib/system/libunwind.dylib
    0x7fff73e3d000 -     0x7fff73e6cff7  libxpc.dylib (1336.251.2) <49138829-09C8-355C-B558-97E070B84EC5> /usr/lib/system/libxpc.dylib

External Modification Summary:
  Calls made by other processes targeting this process:
    task_for_pid: 0
    thread_create: 0
    thread_set_state: 0
  Calls made by this process:
    task_for_pid: 0
    thread_create: 0
    thread_set_state: 0
  Calls made by all processes on this machine:
    task_for_pid: 15008
    thread_create: 0
    thread_set_state: 0

VM Region Summary:
ReadOnly portion of Libraries: Total=246.6M resident=0K(0%) swapped_out_or_unallocated=246.6M(100%)
Writable regions: Total=65.1M written=0K(0%) resident=0K(0%) swapped_out=0K(0%) unallocated=65.1M(100%)

                                VIRTUAL   REGION
REGION TYPE                        SIZE    COUNT (non-coalesced)
===========                     =======  =======
Kernel Alloc Once                    8K        1
MALLOC                            48.3M       22
MALLOC guard page                   16K        4
MALLOC_LARGE (reserved)            384K        2         reserved VM address space (unallocated)
STACK GUARD                          4K        1
Stack                             16.0M        1
VM_ALLOCATE                          4K        1
__DATA                            5684K       74
__LINKEDIT                       223.1M       29
__TEXT                            23.5M       71
__UNICODE                          564K        1
shared memory                       12K        3
===========                     =======  =======
TOTAL                            317.5M      210
TOTAL, minus reserved VM space   317.1M      210

Model: MacBookPro11,1, BootROM 151.0.0.0.0, 2 processors, Intel Core i5, 2.6 GHz, 8 GB, SMC 2.16f68
Graphics: kHW_IntelIrisItem, Intel Iris, spdisplays_builtin
Memory Module: BANK 0/DIMM0, 4 GB, DDR3, 1600 MHz, 0x02FE, -
Memory Module: BANK 1/DIMM0, 4 GB, DDR3, 1600 MHz, 0x02FE, -
AirPort: spairport_wireless_card_type_airport_extreme (0x14E4, 0x112), Broadcom BCM43xx 1.0 (7.77.61.2 AirPortDriverBrcmNIC-1305.8)
Bluetooth: Version 6.0.11f4, 3 services, 18 devices, 1 incoming serial ports
Network Service: Wi-Fi, AirPort, en0
Serial ATA Device: APPLE SSD SM0256F, 251 GB
USB Device: USB 3.0 Bus
USB Device: Apple Internal Keyboard / Trackpad
USB Device: BRCM20702 Hub
USB Device: Bluetooth USB Host Controller
USB Device: USB Optical Mouse
Thunderbolt Bus: MacBook Pro, Apple Inc., 17.2

A: I cannot reproduce your issues with Scapy, so I'll assume that's only related to Kamene (I have edited your question to reflect that).
You can either try using the "real" Scapy (https://github.com/secdev/scapy), or report this issue to the Kamene project.

A: This happens due to permissions issue with mac. The python program is not able to get write to the packet on to network. I had a similar issue and using sudo resolved the issue.


text:
Q: Python Post Requests using Requests library giving broken pipe error I am running a API developed in GOLang which accepts post requests over LAN. My client is using Python to send some data (size 350KB) to the server. The python code is multithreaded and may be performing simultaneous post requests, 1 per each thread. Expected average requests per second between client and server is around 3. The requests are not getting timeout as the error gets raised much earlier.
I can not seem to find the source of the error. The network should be robust as both server and client are on a single switch having 1 Gbps. Please help.
HTTPConnectionPool(host='192.168.1.105', port=8080): Max retries exceeded with url: /match (Caused by <class 'socket.error'>: [Errno 32] Broken pipe)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problem starting Ubuntu 12.04 I have an Acer Aspire 7730 laptop (Acer Aspire 7730). After a power failure it shows me only the GNU GRUB menu with these options:

*

*Ubuntu, with Linux 3.2.0.24 - generic

*Ubuntu, with Linux 3.2.0.24 - generic (safe mode)

*Memory test (memtest86+)

*Memory test (memtest86+, serial console 115200)

If I choose either of the the first options it starts the busybox menu. Can I fix this from this console or must I use a live CD (which at the moment I don't have)?

A: If it's dropping you to busybox, using a Live CD/USB is the faster and more practical option.
You generally get dropped to busybox when grub cannot find the files on /boot -- or the /boot partition itself. The power failure may have affected your filesystem or the partition table, so you're best off with the Live CD rather than risk messing anything up from within busybox.


text:
Q: Remove "The field must be a number" default validation text on decimal property I have .cshtml file with code below:
@Html.TextBoxFor(m => m.Level)
@Html.ValidationMessageFor(m => m.Level)

And property in model:
[RegularExpression(@"^\d+.\d{0,2}$", ErrorMessage="Only two places after comma")]
public decimal? Level {get; set;}

If I put the comma in the form it shows me info "The field Level must be a number". When I write the number after a comma then these communicate disappoint. How can I remove this default validation message?

A: This is actually expected behaviour but if you still don't want that default number validation message, there are two options.
You can just remove number validation on client side,
$("#Level").rules("remove", 'number');

Or you can change property type to String on server side.
[RegularExpression(@"^\d+.\d{0,2}$", ErrorMessage="Only two places after comma")]
public string Level {get; set;}


text:
Q: SOLR how to manage combined company data in single docbase I am developing a Saas and I was wondering if there was a way I could store say 5 companies documents (say 1000 docs each) in a unified docbase using a field (companyId) and then adding that to my query.
I believe this cannot work because it will not force that one field to match perfectly.
so are there any other strategies people have to do this?  It might be a bit costly to spool up a full SOLR instance for each customer as we many have many small trial customers.

A: Keeping multiple customers in a single collection will work fine, as long as you make sure you're keeping, and sending, in a companyId each time. The companyId field would be an indexed string field (so that it's not analyzed in any way) and can be used for only exact matches. You'd then use a filter query (fq) to limit the result set to only documents that match this term:
&fq=companyId:123

To make this approach more secure (i.e. so that you don't end up in a situation where you forget to include a companyId filter query), you can set a default value that doesn't match any documents in your request handler.
<lst name="defaults">
  <str name="fq">companyId:0</str>
</lst>

There is a few downsides with keeping everything in a single collection / core, and that is scoring for documents for a single customer will be affected by what the other customers have indexed. Since the number of terms present will be across the entire collection, this might give slightly weird results for terms that isn't common with one customer, but very common with another customer.
The alternative is to create a separate collection for each customer (saas_123) - since you use a configSet when creating the collection, the configuration will be shared for all the customers. You can then also use Solr's built-in authentication and authorization to have user accounts that can only access a single collection (and store this user information together with the user in your main application). This will add an additional level of security.
I'd recommend extending the Solr client (or creating your own API internally instead of using the Solr client directly) to make sure you're setting everything up as expected (with a required companyId for example).


text:
Q: Subsonic 3 Sql Join using SimpleRepository can't join on columns with same name? I'm trying to using the Subsonic Fluent query interface to create a simple inner join between two tables:
[SearchJobResults]
PK SearchJobResultId int
Name string
Desc string
[ParseResults]
PK ParseResultId int
Name string
SearchJobResultId int
There is a 1 to 1 relationship between these tables.
Keep in mind, I'm not using ActiveRecord. I have classes for ParseResult and SearchJobResult that work fine.
 IDataProvider p  = ProviderFactory.GetProvider("DemacDB");
 SqlQuery query = new SqlQuery(p);

 var q = new Select(p).From("ParseResults")
         .InnerJoin<SearchJobResult>("SearchJobResultId","SearchJobResultId").GetRecordCount();

This code throws an exception:
Test method Models.SearchTests.TestSubsonicQueryMethods threw exception:  System.InvalidOperationException: Don't know which column to join to - can't find column SearchJobResultId in table ParseResults.
I've looked at the source code for SubSonic to see where this execption is coming from:
 private void CreateJoin<T>(string fromColumnName, string toColumnName, Join.JoinType type)
    {
        //see if we can find the table
        var toTable = _provider.FindOrCreateTable(typeof(T));

        //the assumption here is that the FromTable[0] is the table to join from
        if(FromTables.Count == 0)
            throw new InvalidOperationException("Can't join if there's no table to join to - make sure to use From() before InnerJoin");

        if(toTable == null)
            throw new InvalidOperationException("Can't find the table for this type. Try using the Column instead");

        var fromColumn = FromTables[0].GetColumn(fromColumnName);
        if(fromColumn == null)
            throw new InvalidOperationException("Don't know which column to join to - can't find column " + fromColumnName + " in table " + FromTables[0].Name);

        var toColumn = toTable.GetColumn(toColumnName);
        if(toColumn == null)
            throw new InvalidOperationException("Don't know which column to join to - can't find column " + toColumnName + " in table " + toTable.Name);

        CreateJoin(fromColumn, toColumn, Join.JoinType.Inner);
    }

I've tried using Aliases but that fails.  Additionally, if I just do a simple query like this it works fine:
var d = new Select(p).From("ParseResults").GetRecordCount();

A: Turns out you need to use the Typed T overloads of From/Join to get this working.
 var b = new Select(p).From<ParseResult>().InnerJoin<SearchJobResult>("SearchJobResultId", "SearchJobResultId").GetRecordCount();

Works as the FromTables collection in Subsonic now correctly gets enumerated because it's reading the type from the actual object and not the DB.


text:
Q: regex find and replace file path I need to find and replace a file path. The first part through "...uploads/" is consistent and need to be replaced. The year and month folder change and in the end need to go away. Then the image name.
For example this:
http://www.example.com/wp-content/uploads/2013/05/images-7.jpeg
Becomes this:
http://info.newsite.com/images/house/images-7.jpeg
Thank you in advance.

A: Just replace:
http://www.example.com/wp-content/uploads/\d+/\d+/

with
http://info.newsite.com/images/house/

The \d+ will match the varying year and month values.


text:
Q: Generate MQsql query to get records I am having the following table say "A"
"column1"   "column2"
   1         arafath@gmail.com
   2         ram@gmail.com;arafath@gmail.com
   3         tom@gmail.com

I want to get the records with the following condition.
Condition1:
      If the column value exist in the any of the row, it will retrieve the matched rows
Condition2:
      If the column value doesn't match with any of the row, it wants to retrieve all the rows
  Eg: column2 = "ram@gmail.com"
  Output should be "row 2"

  Eg: column2 = "arafath@gmail.com"
  Output should be "row 1, row 2"

  Eg: column2 = "xxx@gmail.com" (Unmatched column)
  Output should be all the rows (row 1, row 2, row 3)

Please help me out to solve the problem.
Thanks in advance.

A: We can try using a union here:
SELECT col1, col2
FROM yourTable
WHERE col2 REGEXP '[[:<:]]ram@gmail.com[[:>:]]'
UNION ALL
SELECT col1, col2
FROM yourTable
WHERE col2 NOT REGEXP '[[:<:]]ram@gmail.com[[:>:]]' AND
    NOT EXISTS (SELECT 1 FROM yourTable WHERE col2 REGEXP '[[:<:]]ram@gmail.com[[:>:]]');

Demo
The above strategy is that the first half of the union returns the matching record, if it exists.  The second half of the union then returns all other records, but only if on match were found in the first half of the union.  If a match were found, then the WHERE clause in the second half of the union would fail, and would return nothing.
Also, please note that storing comma separated (or semicolon separated) data in your MySQL tables is generally bad practice.  I had to use REGEXP to get around this problem, but ideally if each email had a separate row, we would only need to use = equality.

A: Please try the below one.
SELECT col1, col2
FROM yourTable
where ( not exists (Select col2
FROM yourTable where col2 like 'xxx@gmail.com')
or col2 like 'xxx@gmail.com');


text:
Q: running a django webapp in python 3 I am using python 3.3 in a virtualenv in a macosx machine, when I installed django 1.5 alpha release after untarring django 1.5 and running following command
pip install -e Django-1.5a1

it looks like django is installed, when I run
    pip freeze
following is the output
Django==1.5a1
Pygments==1.5
South==0.7.6
bpython==0.11
distribute==0.6.28
django-debug-toolbar==0.9.4
django-extensions==1.0.0
ipython==0.13.1
logilab-astng==0.24.1
logilab-common==0.58.1
pylint==0.26.0

clearly django is installed however import django doesn't seem to be working when I run the following
import django

in python shell inside virtualenv, the output is
No module named import django

what can be the problem with this setup

A: looks like pip does not work for installing this version, I used setup.py and everything seems to be working now.


text:
Q: How to sort the indices of Slice> using vDSP? I'm using buffer in many other vDSP operations before the code below. To those operations it is naturally a contiguous piece of memory, and that's handy as there are vastly reduced number of calls to vDSP.

// […] many operations with buffer here

var buffer = UnsafeMutableBufferPointer<Double>.allocate(capacity: 10000000)

var sortedIndices: UnsafeMutablePointer<UInt> = UnsafeMutablePointer<UInt>.allocate(capacity: 10000000)

for (indexIndices, indexC) in buffer.indices.enumerated() {
    sortedIndices[indexIndices] = UInt(indexC)
}

vDSP_vsortiD(
    UnsafePointer<Double>(buffer.baseAddress)!,
    sortedIndices,
    nil,
    UInt(buffer.count),
    vDSP.SortOrder.descending.rawValue
)

I need to sort buffer sliced up. Also, I'd like not to copy its contents before every sort into smaller buffers as this is performance critical (as many times as possible per second).
vDSP_vsortiD() and vDSP_vsorti() do not support Slice.
For example this code is not possible since .baseAddress doesn't exist on a Slice and I guess UnsafePointer doesn't understand Slice either.
var sliceOfBuffer: Slice<UnsafeMutableBufferPointer<Double>> = buffer[0...30000]

vDSP_vsortiD(
    UnsafePointer<Double>(sliceOfBuffer.baseAddress)!, // This fails
    sortedIndices[0...30000], // This also fails
    nil,
    UInt(30000),
    vDSP.SortOrder.descending.rawValue
)

// Is there another sort indices function which accepts those types as params?

Many operations under vDSP accept Slice, however the above sort functions don't.
Swift v5.6

A: Given that it's a C API, it's less error prone to just think a little more in C terms.  Forget slices, just use pointers.
In C it would look something like this:
    double *buffer = (double *)calloc(size(double), 10000000);
    vDSP_Length *sortedIndices = (vDSP_Length*) calloc(size(vDSP_Length), 10000000);

    vDSP_vsortiD(
        buffer,
        sortedIndices,
        NULL,
        (vDSP_Length)30000,
        vDSP_SortOrder_descending // Probably a different name in reality
    );

And for sorting in the middle of the buffer it would look like this:
    const vDSP_Length sortOffset = 4000;
    const vDSP_Length sortCount  = 10000;

    vDSP_vsortiD(
        buffer + sortOffset,
        sortedIndices + sortOffset,
        NULL,
        sortCount,
        vDSP_SortOrder_descending // Probably a different name in reality
    );

In Swift the spelling of how you do that is a little different, but you do exactly the same thing.  You have an UnsafeMutableBufferPointer, so you're on the right track that you need to use its baseAddress, but you don't need to do anything else to it.  UnsafeMutablePointer types can be passed to UnsafePointer parameters for C calls (but not the other way around).  sortedIndices is already a pointer rather than a buffer pointer, so you can just use it directly.
    vDSP_vsortiD(
        buffer.baseAddress!,
        sortedIndices,
        nil,
        vDSP_Length(30000),
        vDSP.SortOrder.descending.rawValue
    )

If instead, you want to sort somewhere in the middle of your buffer:
    // index range of 4000..<14_000
    let startOfSlice = 4000
    let lengthOfSlice = 10_000

    vDSP_vsortiD(
        buffer.baseAddress!.advanced(by: startOfSlice),
        sortedIndices.advanced(by: startOfSlice),
        nil,
        vDSP_Length(lengthOfSlice),
        vDSP.SortOrder.descending.rawValue
    )

A: You can use withUnsafeBufferPointer() to pass the address of the slice's element storage to the vDSP function:
sliceOfBuffer.withUnsafeBufferPointer { bp in
    vDSP_vsortiD(
        bp.baseAddress!,
        sortedIndices,
        nil,
        UInt(sliceOfBuffer.count),
        vDSP.SortOrder.descending.rawValue
    )
}

With respect to slicing the indices: It seems that one can pass sortedIndices + sliceOfBuffer.startIndex to the vDSP function. However, the documentation states that the indices must be initialized starting at zero, so I would not rely on that.


text:
Q: Find which servlet a web request will hit Inside a servlet Filter, is there a way to figure out which Servlet a particular request would eventually hit? I need to do Role based security checks based upon Servlets (not URL patterns) , in a filter (due to legacy reasons).
thanks

A: This information is not available by HttpServletRequest.
If you're already on Servlet 3.0 (Tomcat 7, Glassfish 3, JBoss AS 6, etc), then you can get information of all servlet registrations and mappings by ServletContext#getServletRegistrations():
for (Entry<String, ? extends ServletRegistration> entry = servletContext.getServletRegistrations().entrySet()) {
    String servletClassName = entry.getKey();
    Collection<String> urlPatterns = entry.getValue().getMappings();
    // ...
}

You could do the URL matching yourself based on the servlet mappings and the information as obtained by among others HttpServletRequest#getServletPath()
If you're not already on Servlet 3.0, then you need to parse the web.xml and collect all servlets and their URL patterns yourself, or to have a copy of it elsewhere. For manually parsing web.xml, the JAXB may come handy.

A: The  HttpServletRequest.getServletPath() returns the part of the request URI that resulted in the servlet being invoked.


text:
Q: Forgot my password for secure database I created a database structure in which a user gets a public and a private key to access information, the public key is uploaded to the database and the private key is encrypted with the users password so I let he can access it. To implement a "Forgot my Password" in this structure an email would have to be sent to the Unser, which provides the option to encrypt the private key with a new password. I thought about storing all private keys somewhere else but that would compromise the entire security, because I don't want the private key or the password stored anywhere in the database. So the problem that I'm having now is that I don't have access to the private key without the original password, so how would I be able to let the user re encrypt it with a new password.

A: You don't need the original password to add the option for the user change the password. And is very dangerous create a way to recover the original passoword of the user. If I was you, I would use some hash algorithm, like SHA-256, and store the result as the password of the user.
Well, returning for the question, one way to accomplish this password user change is create a UUID in your User table. When the user try to change his password, you redirect him to a page with this UUID in the link. This UUID works as a temporary key that permit the user change his password.
Per example.
Table: User
id | name | UUID
1  | John | f39a33c3-e7f5-455a-afad-dcf845eb04a1

When the user wants to change the password, you send a link for his e-mail:
http://yoursite.com/recover-password?UUID=f39a33c3-e7f5-455a-afad-dcf845eb04a1

So, when the user enter the new password in the page and submit the informations, you get this UUID and validate if it's really the UUID generated for the user. So, the password change can happen.

A: The simplest way to achieve this is to decrypt the private key with current password and re-encrypt it with new password and then update the new password in the database.


text:
Q: FPDF - PHP While loop only returns first value I have this code:
  while ($row = mysql_fetch_array($result)) {
  $pdf=new PDF();
  $pdf->AliasNbPages();
  $pdf->AddPage();
  $pdf->SetFont('Times','',12);

  $pdf->SetFont('Arial','B',16);
  $pdf->Cell(42,10, "".$row["firstname"].$row["lastname"]);
  $pdf->Output();
  }

It only generates the first value of the result (1 pdf page). There are supposed to be 9 results or pdf pages. In this case where the first and last name of all the players appear in 9 seperate pdf pages.
I tried the following PHP way but it did not work either.
while () {

 } echo "":

Any ideas?

A: This should be what you are after
  $pdf = new PDF();
  $pdf->AliasNbPages();
  $pdf->SetFont('Arial','B',16);

  while ($row = mysql_fetch_array($result)) {
      $pdf->AddPage();
      $pdf->Cell(42, 10, $row["firstname"] . " " . $row["lastname"]);
  }

  $pdf->Output();


text:
Q: How to splice onto socketfd? The manual mentioned splice() can transfer data between two arbitrary filedescriptors, also onto a socketfd. This works if the file is send at once. Therefore the filesize has to be lower than PIPE_BUF_SZ (=65536).
But, how to handle bigger files? I want to understand the difference to sendfile() syscall. How would you rewrite the sendfile() syscall?
The second splice returns with Invalid argument. I guess it is because the socketfd is not seekable.
size_t len = 800000; //e.g.
static int do_copy(int in_fd, int out_fd)
{
    loff_t in_off = 0, out_off = 0;
    static int buf_size = 65536;
    off_t len;
    int filedes[2];
    int err = -1;

    if(pipe(filedes) < 0) {
        perror("pipe:");
        goto out;
    }

    while(len > 0) {
        if(buf_size > len) buf_size = len;
        /* move to pipe buffer. */
        err = splice(in_fd, &in_off, filedes[1], NULL, buf_size, SPLICE_F_MOVE | SPLICE_F_MORE);
        if(err < 0) {
            perror("splice:");
            goto out_close;
        }
        /* move from pipe buffer to out_fd */
        err = splice(filedes[0], NULL, out_fd, &out_off, buf_size, SPLICE_F_MOVE | SPLICE_F_MORE);
        if(err < 0) {
            perror("splice2:");
            goto out_close;
        }
        len -= buf_size;
    }
    err = 0;
    out_close:
    close(filedes[0]);
    close(filedes[1]);

    out:
    return err;
}

A: sendfile() systemcall does not check if the filedescriptor is seekable. The only check onto that fd is, if you can read (FMODE_READ) onto the fd.
splice() does some more checks. Among others, if the fd is seekable (FMODE_PREAD) / (FMODE_PWRITE).
That's why sendfile works, but splice won't.


text:
Q: PHP: Update value start from 0 and not 1 I have a table where I drag and drop, when I drop the row I want to update order values, it works but start updating from value 0 and I want start from 1.
Example before drag and drop:

After:

My code looks like here:
public function updateOrder(Request $request)
   {

       $queryParams = [];

       $ids = $request->ids;
       //el query será definido en su totalidad de forma manual
       $query = 'UPDATE projects SET `order` = CASE id ';
       //agregamos cada parámetro de orden y de id al array para respetar las convenciones de PDO
       foreach ($ids as $order => $id) {
           $query .= 'WHEN ? THEN ? ';
           $queryParams[] = (int) $id;
           $queryParams[] = (int) $order;
       }

       //por último agregamos los ids implicados en el update
       $queryParams = array_merge($queryParams, $ids);

       //generamos los ? necesarios para el array de ids en el query PDO
       $whereInArray = array_fill(0, count($ids), '?');
       $whereInString = implode(", ", $whereInArray);

       //agregamos dicho string generado al query final
       $query .= "END WHERE id IN ($whereInString)";

       //realizamos el update
       DB::update($query, $queryParams);
   }

¿What I need to update in code?

A: Please try $queryParams[] = (int) $order+1;


text:
Q: Removing _dc parameter in Ext Using Ext, default Ext.Ajax add to GET-request _dc parameter. For example
GET /ConnViewProcessing/?_dc=1263286227619

How to remove this parameter?
PS: it's necessary to manually cache response to ETag and If-None-Match.

A: I am using ExtJS 4.2, but this should work for Ext JS 4.1 and on.  In the proxy there is a property called noCache you should set this to false.
Ext4.define('Server',{
    extend: 'Ext4.data.Model',
    fields: [
            {name: 'id'},
            {name: 'key'},
            {name: 'value'}
    ],
    proxy: {
            type: 'rest',
            url : 'yaddayaddayadda',
            noCache: false,
            reader : {
                    type: 'json'
            }

    }
});

The reason my code says Ext4.  is because I am using the sandbox mode as I move old Ext JS 3x code into 4.2

A: This should work with extjs 4.0.7:
Ext.Loader.config.disableCaching = false;

A: Setting the flag disableCaching to false (double negation - yay!) on the Ext.data.Connection should do the trick.
For more, look at the disableCaching-documentation.
(Please note that quite a few classes in Ext seem to have the option available, so you might have to muck around a bit.)

A: Set disableCaching option to false:
Ext.Ajax.disableCaching = false;

A: Using Ext JS 4.1, and after adding the following code to app.js, the _dc parameter disappears:
// Disable _dc parameter

Ext.Loader.setConfig({
    disableCaching: false
});

// My App

Ext.application({

A: For those that want to set "disableCaching: false" in Sencha Architect 3+, here is how..:

*

*In the project inspector window, select the top node,
"Application"

*Then in the "Config" window below that where you
set the object properties, etc, select "Loader Config"..  in my case
I had to click the "+" to the right of this as I hadn't set any
items yet.  This will create a new "LoaderXX" object in the "Project
Inspector" window above; Loader25 in my case.

*Now either select the new object in the
"Project Inspector" window, or click on the right arrow beside the
new "LoaderXX" (Loader25 in my case).  This will take you to the
properties for the object.

*Untick the "disableCaching" item.
Save the project and refresh the browser window, and enjoy persistent breakpoints, etc, etc in Chrome.

A: The proper way to accomplish that with Sencha Cmd 6.x is to set a (global) switch in app.json (because all of those hacks and overrides might interfere unnecessarily with the functionality):
"loader": {
    "cache": true
},

Then run sencha app refresh, in order to update the application's bootstrap.json.
Alternatively,  one can configure Ext.Loader (at run-time):
Ext.Loader.setConfig({disableCaching: false});

When scrolling upwards and reading the actual question, concerning Ext.Ajax (per request):
Ext.Ajax.request({url: '/ConnViewProcessing', disableCaching: false});

The result: no more _dc parameters on scripted requests.
@see Sencha Cmd 6.x - The Microloader.

A: Note that the use of Ext.Loader has changed in ExtJS 5.
In ExtJS 5, caching can be disabled:

*

*temporarily by adding "?cache" to the end of the URL

*by setting a cookie called 'ext-cache' with the value of 1

*or by editing the file .sencha/app/Boot.js and setting the '_config.disableCaching' property to be true (overwriting the dynamic lookup).

A: The only way I was able to disable _dc in ExtJS 4.2.x globally on my project:
Ext.define('Ext.data.Connection', {override:'Ext.data.Connection', disableCaching:false });
Ext.define('Ext.data.proxy.Server', {override:'Ext.data.proxy.Server', noCache:false });
Ext.define('Ext.data.JsonP', {override:'Ext.data.JsonP', disableCaching:false });

This is ugly, but any other ideas?

A: This is how I did this:
Ext.Ajax.request({
    url: url,
    disableCaching:false
});

A: I decided that I wanted the cache to be destroyed client side, but server side I was using my own caching mechanism (PHP's APC).
I left the _dc in the Ext ajax request, but then removed it from the REQUEST_URI, and then use the REQUEST_URI as the basis for the cache key
I found this useful: Regular expression to remove one parameter from query string

A: If you develop under Sencha CMD you can do like this
http://localhost:1841/?disableCacheBuster

or just
http://localhost:1841/?cache

A: For all who are looking for a way to disable it in a newer version:
proxy: {
    type: 'ajax',
    noCace: false
}

A: I use Ext.NET on top of Ext.JS. It adds some more voodoo to Ext.js...
I tried to get rid of the dc= parameter, but all mentioned configurations did not work. So, this is my uber-effective, uber-dirty solution:
Ext.Date.now = function () { return ""; }

As far as I can see, Ext.Date.now() is only used for the caching logic. So it should be relativity save.


text:
Q: Integrability of a sequence of iid random variables I'd really appreciate some hints on the first part of the following question:
Let $f_n, n\in \mathbb{N}$ be a sequence of iid random variables over $(\Omega, A,P)$. That is,
$P(\{f_1 \in A\})=P(\{f_2 \in A\})= ···$ for all $A \in \mathbb{B}$.
Show that, if there is a $c \in \Re$ such that
$P\Bigg(\Bigg\{\lim_{n \to \infty}\frac{1}{n}\sum\limits_{i=1}^n f_i=c\Bigg\}\Bigg) >0,$ then
$P(\{|f_n|>n$ for infinitely many $n\})=0.$
Then conclude that $f_1$ (and therefore also $f_2,f_3,..$ because of the identical distribution) is integrable.

A: *

*Borel-Cantelli Lemma

You want to show that
$$P(\limsup A_n) = 0$$
where $A_n = \{|f_n| > n\} = \{\frac{|f_n|}{n} > 1\}$
Perhaps we might try Borel-Cantelli Lemma?
If we can show the following
$$\sum_{n=1}^{\infty} P(A_n) = \sum_{n=1}^{\infty} P(\frac{|f_n|}{n} > 1) < \infty$$
Note that $P(A_n^C) = 1 - P(\frac{|f_n|}{n} \le 1) $
then we would get what we want.

*Kolmogorov 0-1 Law

Denote
$$\overline{f_n} := \frac{1}{n}\sum\limits_{i=1}^n f_i$$
to have:
$$P(\lim \overline{f_n}=c) >0$$
Observe that
$$\{\lim \overline{f_n}=c \} \in \bigcap_{n=1}^{\infty} \sigma(f_n, f_{n+1}, ...)$$
By the Kolmogorov 0-1 Law,
$$P(\lim \overline{f_n}=c) = 0 \ \text{or} \ 1$$
Since
$$P(\lim \overline{f_n}=c) >0$$
we have that
$$P(\lim [\overline{f_n}]=c) = 1$$
which is equivalent to either:
$$P(\liminf [\overline{f_n}]=c) = 1$$
$$P(\limsup [\overline{f_n}]=c) = 1$$
Try using one of those with one of the inequalities below.

*Important inequalities

Williams - Probability with Martingales

Deduced similarly:
(iii) If $\liminf x_n > z$, then
$ \ \ \ \ \ \ \ (x_n > z)$ eventually (that is, for infinitely many n)
(iv) If $\liminf x_n < z $, then
$ \ \ \ \ \ \ \ (x_n < z)$ infinitely often (that is, for infinitely many n)


text:
Q: How to use methods to pass information between classes I am currently taking my first Java course and am having a hard time understanding methods and how you can you them to pass information between classes.
I have written code for an assignment i have but i can not figure out for the life of me how to pass taxableIncome and tax from one class to another.
Could you please look at my code and point me in the right direct or tell me what i am doing wrong? I have been trying to get this to work all week but have not had luck. Please make your responses understandable to someone who has little knowledge of Java currently enter code here.
My first class code is following:
/**
 * This program will ask the user for their taxable income, and display that number based on calculations done in the TaxCalculator Class.
 */

import java.util.*;

public class TaxCalculatorTester{
    public static void main(String [] args){

        double taxableIncome = 0; //declare and initialize taxable income
        double tax = 0;
        Scanner input = new Scanner(System.in);

        System.out.println("This program will calculate how much you owe in taxes based on your income.");
        System.out.println("Please enter your taxable income for this year.");
        taxableIncome = input.nextDouble( );

        TaxCalculator taxObject = new TaxCalculator();
        taxObject.CalculateTax(tax);

        System.out.println("You owe " + tax + " in taxes.");
        System.out.println("Please note this is just a estimate and acutal amount due may differ.");
    }
}

The second class code that actual calculates everything is as follows:
/**
 * This program will calculate how much tax a user owes based on the user input taxable income which is pulled from the TaxCalculatorTester class.
 */

import java.util.*;

class TaxCalculator{

    static double CalculateTax (double taxableIncome){
        double tax = 0.0;

        if (taxableIncome < 9526)
          tax = taxableIncome * .10;
        else if (taxableIncome <= 38700.99)
          tax = taxableIncome * .12;
        else if (taxableIncome <= 82500.99)
          tax = taxableIncome * .22;
        else if (taxableIncome <= 157500.99)
          tax = (taxableIncome * .24);
        else if (taxableIncome <= 200000.99)
          tax = taxableIncome * .32;
        else if (taxableIncome <= 500000.99)
          tax = taxableIncome * .35;
        else
          tax = taxableIncome * .37;
     return tax;
    }
}

A: You have to change your:
TaxCalculator taxObject = new TaxCalculator();
taxObject.CalculateTax(tax);

in to:
tax = TaxCalculator.CalculateTax(taxableIncome);

Method CalculateTax (which name should start from lower case) is static so you can call it without creating object of containing class (CalculateTax in your case).
In your code you are passing tax as argument of CalculateTax method, but tax is 0. You have to pass value typed by user so taxableIncome.
Also, you have to remember to assign somewhere value returned by method CalculateTax, because in your code you are passing data, method is doing some calculation and you don't care about result (returned value).


text:
Q: How do I put timer on session destroy codeigniter? How can I put a timer on my $this->session->sess_destroy() from my model without using the $config['sess_expiration'] = 0; on config?

A: By default it expires 7200 i think. and from what I know, dynamically setting it doesn't work. Why do you want it anyway? Maybe we can suggest, but the answer would be you can't.
http://forum.codeigniter.com/thread-31039.html

A: Use this
//set session expire time, after that user should login again
$this->session->sess_expiration = '1800'; //30 Minutes
$this->session->sess_expire_on_close = 'true';


text:
Q: Speed up Apache Commons FTPClient transfer I am using Apache Commons FTPClient to upload large files, but the transfer speed is only a fraction of transfer speed using WinSCP via FTP. How can I speed up my transfer?
    public boolean upload(String host, String user, String password, String directory,
        String sourcePath, String filename) throws IOException{

    FTPClient client = new FTPClient();
    FileInputStream fis = null;

    try {
        client.connect(host);
        client.login(user, password);
        client.setControlKeepAliveTimeout(500);

        logger.info("Uploading " + sourcePath);
        fis = new FileInputStream(sourcePath);

        //
        // Store file to server
        //
        client.changeWorkingDirectory(directory);
        client.setFileType(FTP.BINARY_FILE_TYPE);
        client.storeFile(filename, fis);
        client.logout();
        return true;
    } catch (IOException e) {
        logger.error( "Error uploading " + filename, e );
        throw e;
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            client.disconnect();

        } catch (IOException e) {
            logger.error("Error!", e);
        }
    }
}

A: Increase the buffer size:
client.setBufferSize(1024000);

A: use the outputStream method, and transfer with a buffer.
InputStream inputStream = new FileInputStream(myFile);
OutputStream outputStream = ftpclient.storeFileStream(remoteFile);

byte[] bytesIn = new byte[4096];
int read = 0;

while((read = inputStream.read(bytesIn)) != -1) {
    outputStream.write(bytesIn, 0, read);
}

inputStream.close();
outputStream.close();

A: There is a known issued with Java 1.7 and Commons Net 3.2, the bug is https://issues.apache.org/jira/browse/NET-493
If running these versions I'd suggest the upgrade to Commons Net 3.3 as the first step. Apparently 3.4 fixes more performance issues too.

A: It would be better if you use
ftp.setbuffersize(0);
if you use 0 as your buffersize , it will take as infinite buffer size.
obviously ur transaction will get speeded up... I personally experienced it..
all the best... :)


text:
Q: Why do I keep receiving Google Chrome Errors? For a very long time now I have had various problems when using Google Chrome and other browsers when trying to reach Social Networking sites. I get various messages such as:

Besides this error sometimes the page will just say "IT WORKS" and nothing else. Other times it will have me redirect to places like mediaplex. In particular when I go to Facebook. There is normally an easy fix to this. I have to empty my cache and other site plug-in data. However, I use applications that use this data particularly the flash data that is deleted when I choose to clear this. My question is how do I stop these errors from happening? I already know how to fix them, but I want to know how to make them stop!

A: It looks like you have a virus. I would scan for viruses, malware, spyware, and other baddies. This looks to be a case of DNS cache poisoning or host file hijacking. Basically, you have a virus that is trying to redirect you to other malicious sites by hijacking domain names and pointing them at the wrong servers when your computer tries to resolve them into IP addresses.
The first "This is probably not the site you're looking for!" problem is a very good example of SSL certificates doing it's job. the server that you were sent to was unable to prove to your computer that it was "Buy.com", and since it knows that the real Buy.com can prove that, Chrome was able to know that something fishy was going on.
The "It works!" is the default homepage for a server that has just been set up; basically, a blank website. This is another indicator of something fishy going on with your DNS if you're visiting a website and see that when you don't expect it.
Other redirects are further hints that something is maliciously trying to redirect your browsing.


text:
Q: Inner product of two continuous maps is continuous Let f,g be continuous maps of S in $\mathbb{R}^n$, to $\mathbb{R}^m$. Show the inner product h(x) = $\langle f(x), g(x)\rangle$ is continuous.
My attempt:
Since f,g are continuous, their product is a continuous mapping, so for $\epsilon \gt 0\: t.e\:  \delta \gt 0$ such that $\parallel x - a\parallel \lt \delta $ implies $\parallel \langle f(x),g(x)\rangle - \langle f(a)g(a)\rangle \parallel \le\parallel f(x)g(x) - f(a)g(a)\parallel \lt \epsilon$ by schwartz inequality.

A: (Adjust $n$, $m$ as appropriate, the question is a little ambiguous.)
The map $\phi: \mathbb{R}^n \times \mathbb{R}^n \to \mathbb{R}$ (or complex, if it suits) defined by $\phi(x,y) = \langle x , y \rangle $ is continuous since
\begin{eqnarray}
|\phi(x,y) - \phi(x',y')| &=& |\phi(x,y) - \phi(x,y') + \phi(x,y') - \phi(x',y')| \\
& \leq & |\phi(x,y) - \phi(x,y')| + |\phi(x,y') - \phi(x',y')| \\
& \leq & \|x\| \|y-y'\| + \|y'\| \|x-x'\|
\end{eqnarray}
Hence if $\max(\|x-x'\|,\|y-y'\|) \leq 1$, then $|\phi(x,y) - \phi(x',y')| \leq \max(\|x\|,\|y\|+1)(\|y-y'\| + \|x-x'\|)$. Now choose $\epsilon>0$, then if $\max(\|x-x'\|,\|y-y'\|) < \frac{1}{2\max(\|x\|,\|y\|+1)}\epsilon$ (and $\leq 1$, of course), you have $|\phi(x,y) - \phi(x',y')| < \epsilon$.
Since $\phi$ is continuous, and the map $\eta:S \to \mathbb{R}^n \times \mathbb{R}^n$ defined by $\eta(x) = (f(x),g(x))$ is continuous, it follows that the composition $\phi \circ \eta$ is continuous.


text:
Q: mvc should everything be async We currently are building an MVC 5 application, the application makes calls to a Business Layer which calls the database, there is no WCF or Web Api service.  All of our controllers are currently not async, i've been looking into task/async and wanted to know if it's becoming common to make all Actions in a Controller async?  For us, all actions are requesting the business layer to read data via Entity Framework, so would it make sense to change them all to asnyc?  Or it is really only helpful when there is a middle layer, like a WCF or Web API service which might involve network latency that it's worth it?

A: All async does is allow a thread that is in a wait-state be returned to the thread pool to field other operations. When whatever operation the original thread was waiting on finishes, a thread is requested back from the thread pool to finish the overarching task. Because the thread must be waiting, certain operations like making a request over HTTP to an API are ideal candidates for async while other operations like complex calculations and other CPU-bound work are completely inappropriate for async.
Now, since your question is regarding database queries, the answer is it depends. For example, if your database happened to be on the same server as your website (which is totally not a good idea BTW) async wouldn't do much for you. There may be some waiting, but it's going to be miniscule to the point where it would probably take longer to pass the threads around than it would to just hold the thread until the database finishes its work. Now, if you're doing things right and your database is on a remote server, network latency starts to come into play. A database on an internal network may still not benefit much from async, since the latency would still probably be very low, but async could still potentially help some. If your database is on an external network, though, then async would definitely be warranted as latency would be much higher.
Still, it's probably better err on the side of using async than not. Even if latency is low, that may not always be the case. And if your network is getting hammered, having everything set up as async will give your web server some valuable leeway to field requests where it otherwise might deadlock under the load.


text:
Q: Show that $x \sin x$ is not uniformly continuous
I have seen a lot of posts that have solved this already by taking two sequences $(a_n), (b_n)$, then showing $\lim(a_n - b_n) = 0$ but $|f(a_n) - f(b_n)| > \epsilon$, but I would like to show nonuniform continuity with a different approach.

My question is how would you pick two points (not sequences), $x_{\delta}$ and $u_{\delta}$ such that $|x_{\delta} - u_{\delta}| < \delta$ FOR ALL $\delta > 0$?
In particular using this criteria for nonuniform continuity to show that xsinx is not uniform continuous:

ii) There exists an $\epsilon_0 > 0$ such that for every $\delta > 0$ there are points $x_{\delta}, u_{\delta}$ in $A$ such that $|x_{\delta} - u_{\delta}| < \delta$ and $|f(x_{\delta}) - f(u_{\delta})| \geq \epsilon_0$ for all $n \in \mathbb{N}$.

A: You don't need $$|x_\delta-u_\delta|<\delta$$ for all $\delta>0$. According to the $\varepsilon-\delta$ definition, what you need is to find $\varepsilon_0$ such that for any $\delta$ such a pair of points $x_\delta,u_\delta$ exists, but the values can change with $\delta$.
You may choose for instance $\varepsilon_0=1$. Then for any $\delta>0$ take $x_\delta=2k\pi$ for some integer $k=k(\delta)$ sufficiently large thanks to the oscillation of the cosine there will exist some
$$u_\delta\in(2k\pi-\delta,2k\pi+\delta)$$
such that
$$
|u_\delta|\geq1
$$
as desired.
Hope this helps.
PS: the result is not true if you stay within a compact set.


text:
Q: ggmap's get_map returns 'Error in gzfile(file, "rb") : cannot open the connection' I have some R code to plot data on maps with ggmap. It was working fine last week. However, now when I run the line to get the map:
emap <- get_map(c(-2.503704,43.18735),zoom=9,maptype="roadmap",color="bw")

I get the following error:
Error in gzfile(file, "rb") : cannot open the connection
In addition: Warning message:
In gzfile(file, "rb") :
  cannot open compressed file '/var/folders/2w/2wSOAL2LFUC+2QkRaR1wI++++TI/-Tmp-//Rtmpj0TMx5/ggmap/index.rds', probable reason 'No such file or directory'

I have searched this forum and the web but can't find any other threads discussing this error.
Any help is much appreciated.
Regards,
Noelia
PS: sessionInfo() returns the following:
R version 3.1.2 (2014-10-31)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] mapproj_1.2-2  maps_2.3-9     ggmap_2.4      dplyr_0.4.1        xtable_1.7-4   ggplot2_1.0.1  reshape2_1.4.1

loaded via a namespace (and not attached):
[1] assertthat_0.1      colorspace_1.2-6    DBI_0.3.1           digest_0.6.8        geosphere_1.3-13    grid_3.1.2
[7] gtable_0.1.2        jpeg_0.1-8          labeling_0.3        lattice_0.20-31     lazyeval_0.1.10     magrittr_1.5
[13] MASS_7.3-40         munsell_0.4.2       parallel_3.1.2      plyr_1.8.1          png_0.1-7           proto_0.3-10
[19] Rcpp_0.11.5         RgoogleMaps_1.2.0.7 rjson_0.2.15        RJSONIO_1.3-0       scales_0.2.4        sp_1.0-17
[25] stringr_0.6.2       tools_3.1.2

A: I've experienced the same error, with code that had also previously worked. You may have already tried this, but I resolved it by simply ending the R session and restarting it.
If this does not work, try uninstalling/reinstalling R(Studio), or at least the packages involved.

A: if you save your files as RData, even you can open it in R but sometimes it is corrupted, you have to run all those variable in formula again and then you can run your code properly. its because in your formula you have a variable that is not accessible by the computer.

A: Same issue was happening to me. I use R version 3.4.2, and RStudio Version 1.1.383. I restarted RStudio, and it fixed the issue.


text:
Q: Trouble casting shadows in three.js Fiddle:
http://jsfiddle.net/8Lhz0kpc/2/
I've tried to get shadows by following what I've seen in tutorials, but none of the settings seem to work.
My objects are set to cast & receive Shadow
@cube.castShadow = true
@cube.receiveShadow = true

The floor is set to receiveShadow
@floor.castShadow = false
@floor.receiveShadow = true

And on the light I have
@spotLight.castShadow = true

@spotLight.shadowMapWidth = 1024
@spotLight.shadowMapHeight = 1024

@spotLight.shadowCameraNear = 50
@spotLight.shadowCameraFar = 800
@spotLight.shadowCameraFov = 30
@spotLight.shadowDarkness = 0.5

@spotLight.shadowCameraVisible = true

Not sure where to go from here, might be something simple I've missed?

A: You wrote sphere.recieveShadow :)


text:
Q: How to use concurrent.future.wait? I'm studying python, here I got some problem on the concurrent.futures.wait() -- Here's the details--
I want to make the main process hold until all the child processes completed. So I used wait() to block the main process. But I always got error , please kind help.
def child_process(args):
    pid=os.getpid();
    while (args.len() > 0 ):
        task=args.pop(0)
        time.sleep(1+ random.random()*5)   #simulate the worker time
    print("Process "+str(pid)+" : "+task[0]+"  "+task[1])
    return

if (__name__  ==  "__main__") :

   mgr = multiprocessing.Manager()
   tasks=mgr.list()
   tasks=[[1,10],[2,20],[3,30],[4,40],[5,50],[6,60]]

    #executor=ProcessPoolExecutor(max_workers=3)
    f=[]
    with concurrent.futures.ProcessPoolExecutor(max_workers=3) as executor:
        f.append(executor.submit(child_process,tasks))
        f.append(executor.submit(child_process,tasks))
        f.append(executor.submit(child_process,tasks))

#        wait(future,timeout=0,return_when=concurrent.futures.ALL_COMPLETED)

        concurrent.futures.wait(f[0])
        concurrent.futures.wait(f[1])
        concurrent.futures.wait(f[2])

        executor.shutdown()

The error is --
C:\Work\python\src\test>python test.py
Traceback (most recent call last):
  File "C:\Work\python\src\test\test.py", line 70, in <module>
    concurrent.futures.wait(f[0])
  File "C:\tools\Python310\lib\concurrent\futures\_base.py", line 290, in wait
    fs = set(fs)
TypeError: 'Future' object is not iterable

This puzzles me most -- is that f[0] not a future object returned by submit()?
Then I tried with --
wait(f,timeout=0,return_when=concurrent.futures.ALL_COMPLETED)

the new error is --
C:\Work\python\src\test>python test.py
C:\Work\python\src\test\test.py:68: RuntimeWarning: coroutine 'wait' was never awaited
  wait(f,timeout=0,return_when=concurrent.futures.ALL_COMPLETED)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

I really don't know how to fix it. Please kidn advise. Thanks
Regards
Eisen

A: Few things to point out:

*

*Wrapping expression with parenthesis in while statement is redundant.

>>> a = 0
>>> while a < 10:
...     a += 1

*

*Error message is saying "Future object is not iterable" - which means, f[0] you passed is indeed Future Object which is not wait method was expecting.

>>> from concurrent import futures
>>> help(futures.wait)
Help on function wait in module concurrent.futures._base:

wait(fs, timeout=None, return_when='ALL_COMPLETED')
    Wait for the futures in the given sequence to complete.

    Args:
        fs: The sequence of Futures (possibly created by different Executors) to
            wait upon.
# ...

Here we can see argument fs actually expect you the Sequence of Futures.
So instead of this:
concurrent.futures.wait(f[0])
concurrent.futures.wait(f[1])
concurrent.futures.wait(f[2])

You probably want this:
concurrent.futures.wait(f)

Which is still not required since with block wait until all processes stops.

Here's demonstration:
"""
Demo codes for https://stackoverflow.com/q/71458088/10909029

Waiting for child process to complete
"""

import os
import math
import queue
import multiprocessing as mp
from concurrent import futures

def child_process(task_queue: mp.Queue):
    # If this doesn't work, save this function in other file. REPL or jupyter especially.
    pid = os.getpid()

    print(f"[{pid}] Started!")
    processed_count = 0

    while True:
        try:
            item = task_queue.get_nowait()
        except queue.Empty:
            # task done
            break

        # else continue on
        # some workload
        try:
            print(f"[{pid}] {item}! = {math.factorial(item)}")

        finally:
            # tell queue we processed the item.
            task_queue.task_done()
            processed_count += 1

    print(f"[{pid}] Task done!")

def main():
    # just merely rapping codes in function namespace makes codes tiny bit faster

    mp_manager = mp.Manager()
    task_queue = mp_manager.Queue()

    # populate queue
    for n in range(100):
        task_queue.put_nowait(n)

    # start pool
    with futures.ProcessPoolExecutor() as executor:
        future_list = [executor.submit(child_process, task_queue) for _ in range(5)]

        # can use executor.shutdown(wait=True) instead
        # not required since all executor wait for all process to stop when exiting `with` block.
        # hence, also no need to manually call executor.shutdown().
        futures.wait(future_list)

if __name__ == '__main__':
    main()

Output:
[18412] Started!
[18412] 0! = 1
[4680] Started!
[18412] 1! = 1
[2664] Started!
[18412] 2! = 2
[18412] 3! = 6
[17900] Started!
[18412] 4! = 24
[18412] 5! = 120
[4680] 6! = 720
[4680] 7! = 5040
[18412] 8! = 40320
[17900] 9! = 362880
[4680] 10! = 3628800
[18412] 11! = 39916800

...

[17900] 21! = 51090942171709440000
[4680] 22! = 1124000727777607680000
[2664] 23! = 25852016738884976640000
[16792] Started!
[18412] 24! = 620448401733239439360000
[17900] 25! = 15511210043330985984000000

...

[17900] 99! = 933262154439441526816992388562667004907159682643816214685929638952175999932299156089414639761565182862536979208272237582511852109168640000000000000000000000
[18412] Task done!
[17900] Task done!
[16792] Task done!
[2664] Task done!
[4680] Task done!


text:
Q: How to get an ObservableCollection list item which inside another ObservableCollection list? I have a class PlayerVM.cs, that has a property:
public ObservableCollection<PlaylistVM> PlayLists
        {
            get { return _playLists; }
            set { _playLists = value; }
        }

PlaylistVM.cs also has its own collection:
public ObservableCollection<CompositionVM> Songs
        {
            get
            {
                return _songs;
            }
            set
            {
                _songs = value;
            }
        }

By that, my PlayerVM has a list of playlists, and each that playlist has its own list of songs.
I need to display list of songs being sorted alphabetically. But I don't want to change their order in ObservableCollections, I want change their order only in GUI (only display them alphabetically, not to change real order).
I am new in wpf (and xaml), and today I've learned only how to display PLAYLISTS  NAMES ordered alphabetically. I am doing it by code:
<Window x:Class="Player_beta.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:Player_beta">
    <Window.Resources>
        <CollectionViewSource Source="{Binding PlayLists}"  x:Key="plView"><!--here I would like to get access to PlayLists.Songs-->
            <CollectionViewSource.SortDescriptions>
                <scm:SortDescription PropertyName="plNAME"/> <!--and here I would like to get NAME(that property of 'Songs' which contains songtitle) instead of plNAME - name of playlist)-->
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>
 </Window.Resources>
<!-- etc...-->
            <TreeView Name="treeCategories" ItemsSource="{Binding Source={StaticResource plView}}" >
<TreeView.ItemTemplate>
                    <HierarchicalDataTemplate ItemsSource="{Binding Songs}">
                                <TextBlock Text="{Binding plNAME}"/> <!-- <-- here is where the name of PLAYLIST shows-->
                        <HierarchicalDataTemplate.ItemTemplate >
                            <DataTemplate >
                                    <TextBlock Text="{Binding NAME}"/> <!-- <-- here is where the name of song shows-->
                                </Grid>
                            </DataTemplate>
                        </HierarchicalDataTemplate.ItemTemplate>
                    </HierarchicalDataTemplate>
                </TreeView.ItemTemplate>
            </TreeView>

A: You can add the ICollectionView instance in PlaylistVM.cs class and bind with it. This way original list will remain unaffected as well.
private ICollectionView songsView;
public ICollectionView SongsView
{
    get
    {
        if (songsView== null)
        {
            songsView= CollectionViewSource.GetDefaultView(Songs);
            songsView.SortDescriptions.Add(new SortDescription("Name",
                                               ListSortDirection.Ascending));
        }
        return songsView;
    }
}

and in XAML:
<HierarchicalDataTemplate ItemsSource="{Binding SongsView}">

A: What you can do is, you can add a CollectionView property to the PlaylistVM class:
public CollectionView songsCollectionView;
public CollectionView SongsCollectionView
{
    get
    {
        if (songsCollectionView == null)
        {
            songsCollectionView  = new CollectionView(Songs);
            songsCollectionView.SortDescriptions.Add(new SortDescription("plNAME", ListSortDirection.Ascending));
        }

        return songsCollectionView;
    }
}

and then you can bind your xaml like this:
<HierarchicalDataTemplate ItemsSource="{Binding SongsCollectionView}">

This should fulfill your requirement of showing sorted songs in GUI without changing the original collection.

A: This is not the most efficient, but will get the job done. Note that it does NOT detect if the name of any of the songs has changed. It also will rebuild the entire list in the UI everytime a song is added or removed.
public class PlaylistVM: System.ComponentModel.INotifyPropertyChanged
{
    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

    private ObservableCollection<CompositionVM> _songs;
    public ObservableCollection<CompositionVM> Songs
    {
        get
        {
            return _songs;
        }
        set
        {
            if(_songs != value)
            {
                //if old value not null, unhook event
                if (_songs != null)
                {
                    _songs.CollectionChanged -= FireSongsChanged;
                }
                //change the value
                _songs = value;

                //if new value !=null, then attach handlers.
                if (_songs != null)
                {
                    _songs.CollectionChanged += FireSongsChanged;
                }

                //this will fire the
                FireSongsChanged(null, null);
            }

        }
    }

    void FireSongsChanged(object sender, EventArgs e)
    {
        //the collection of songs has changed, tell UI that it needs to requery the list of ordered songs.
        var ev = this.PropertyChanged;
        if (ev != null)
        {
            ev(this, new System.ComponentModel.PropertyChangedEventArgs("OrderedSongs"));
        }
    }

    //set the UI to bind to the following list of the songs. ordered by name.
    public IEnumerable<CompositionVM> OrderedSongs
    {
        get
        {
            return Songs.OrderBy(song => song.Name);
        }
    }

}


text:
Q: SSRS - Set different padding/margins based on view type My report is setup perfectly for print layout.  When I look at the report in my SSRS server as a webpage everything, tables/charts etc, are on the very left edge of the screen.  Is there a way I can change padding or margins based on the view I'm in?  So if I'm in the standard web view everything is bumped over half an inch, but if I'm in print preview that extra half inch is gone?
I might be missing the point though.

A: SSRS reports have 2 size types:

*

*Interactive Size - specifies the default size of pages when rendering the report in an interactive renderer.

*Page Size - specifies the width and height for the report

These sizes are set at the Report properties level. Adjusting these should give you the desired results.


text:
Q: Global variables in library that linked by multiple entities of a single process I've got static library that supplies logger services, and it's linked to several sub-components in my C/C++ project.
I'd like to set the scope of global variables that defined in logger to all those entities that are link this library (for instance, log_level), and I wonder if change the library to dynamic would do the trick... would it ?

A: Your question does not make clear what you mean by "component" and "scope".
If I understand correctly, you have a single program (i.e. single executable, and single process at runtime) which includes several libraries (what you call "components") and [some of] these libraries are linked to a common logger library. You want all these libraries to be able to set a common variable log_level defined in the logger library. Is my understanding correct ?
If you define the log_level as a global variable in the source code of the logger library (i.e. defined once outside the scope of any function), you will have access to this global variable in any other component/library linked to your program by declaring it as extern.

@MSalters, i guess you're right, but i wanted to emphasis that if i link static library to several components in my process, it will generate separate instance of this library per each such component, and not enable sharing the global variables. – Zohar81 yesterday

No, the final linking will remove any duplicate of the same library. You may link the logger library either only once to the program or several times to every components/libraries (that are finally linked together to the program), the same single variable log_level will be shared among everyone.
// logger.lib : logger.h
extern int log_level;
extern void log(const char* mesg);

// logger.lib : logger.c
int log_level;
void log(const char* mesg)    { /*...*/ }

// component1.lib : component1.c
#include "logger.h"  // declare log_level as extern
void component1()
{
    log_level = 1;   // modifies log_level defined in logger.c
    /* ... */
}

Another (and better) way to do quite the same thing is defining you log_level variable as static and provide some kind of accessor, such as:
// logger.lib : logger.h
extern void set_log_level(int log_level);
extern void log(const char* mesg);

// logger.lib : logger.c
static int s_log_level;  // only visible to logger.c
void set_log_level(int log_level) { s_log_level = log_level; }
void log(const char* mesg)        { /*...*/ }


text:
Q: Pass only the specified optional params to an underlying widget Assume I have a simple function that takes a URL to an svg image and returns a widget:
Widget loadImage(String url, { height, width }) {
  // Wrap URL in an SvgPicture and return
  return SvgPicture.network(url)
}

I'd like to apply the width and height params to SvgPicture only if they are defined. Something like this (though this obviously results in a syntax error):
Widget loadImage(String url, { height, width }) {
  // Wrap URL in an SvgPicture and return
  return SvgPicture.network(
    url,
    if(height) height : height, // <--
    if(width) width : width, // <--
  )
}

How do I do this?

A: If a parameter is optional, it means, it can be null. There for, the receiver function should ensure whether it is null or not.
So, you can simply use
Widget loadImage(String url, {double height,double width }) {
  return SvgPicture.network(
        url,
        height: height,
        width: width
      )
}

A: There is no way you can not pass the parameter conditionally. If you want the SvgPicture widget to use its default height and width (if any), then you can pass null to those parameters. In this case, passing null to height and width has exactly the same effect as not using those parameters in the SvgPicture at all.
So the most readable way of doing it would be, simply:
Widget loadImage(String url, {double height, double width}) {
  return SvgPicture.network(
        url,
        height: height,
        width: width
      )
}

As a side note, I would recommend always type-annotating parameters in functions, i.e., stating that height and width are double.


text:
Q: What does the image on the back of the LotR discs represent? Been watching the extended blu-ray version of LotR and I noticed this symbol on the back cover. Don't think I've seen this whilst watching the films, anyone know what it represents?

A: It's a depiction of the badge of the House of Elrond from the LotR films.
This art piece depicting the badge comes from Weta Workshop designer Daniel Falconer.

Image courtesy of The Lord of the Rings: The Art of The Fellowship of the Ring

ELVEN INSIGNIA - Daniel Falconer
These badges were used to represent the various Elven armies that
might appear in the Second Age sequences. Gil-galad's was a slight
reworking of the one Tolkien himself created, and similarly the Houses
of both Elrond and Galadriel borrowed elements from his concepts for
their respective fathers, Eärendil and Finarfin.
The other designs
were entirely Dan's inventions, although clearly in keeping with the
others. The designs were intended to appear on the breasts of the
Elres' armor and were also incorporated by the art  department for use
in their Elven banners.

A: They're designed after the fashion of Tolkien's Elven insignia, but the overall shapes are wrong- The badge for an Elvish house is supposed to be in the shape of a square. Personal badges are a bit different. A man's badge is in the shape of a lozenge (a square tipped 45 degrees on its side), and a woman's badge is circular. The badge they made for Galadriel is almost accurate, but as they intended for it to represent her army rather than Galadriel herself, it should be in the shape of a square.


text:
Q: Python command removed from PATH when adding PIP I started by downloading Python and adding it to the PATH variable
setx PATH c:\Python27

Next when I run the Python command it works
Next I installed pip and I had to add it to de PATH variable
setx PATH c:\Python27\scripts

Now when I run the PIP command it works, but when I try to run the Python command it does not work anymore.
So I reset de Python command to the PATH variable, but it removes the PIP command.

A: as far as i know setx will set the value and not append to it
so inorder to do what you want you should do
setx PATH %PATH%;<NEWADDITION>


text:
Q: Can I change tinymce behavior of wrapping text with semantic tags such as  or ? guys.
I need some helps about tinymce.
I'd like to do as like below with tinymce. (I want to do)
Entire words are bold.
But this is italic.
I'm still bold!

However, while I have done with tinymce, I'm getting
Entire words are bold.
But this is italic.
I'm still bold!

This would be happen when making all text bold, and then make part of text italic.
Here are what I tried to set
style_formats: [{title: 'Bold text', inline: 'strong'},
                {title: 'Italic text', inline: 'em'}]

or
formats: {
    bold: {inline: 'strong'},
    italic: {inline: 'em'}
}

and so on...
Is there any option or hack to achieve this?

A: Correct me if I'm wrong, but is this the course of action you're taking to bold/italicize your content?

*

*Highlight all text.

*Press the bold button.

*Highlight the second line.

*Press the italic button.

The default behaviour should be that each line is wrapped in its own  tag. You might want to check if you have Style Merging enabled - this may be causing what you're experiencing.


text:
Q: Why does Django need a request object in rendering a template? Why does Django need a request object in rendering a template?
 return render(request, 'polls/index.html', context)

A: As per the docs about render:

Combines a given template with a given context dictionary and returns
  an HttpResponse object with that rendered text.

Thus it's meant to be used in views, where you have a request object and need to return an HttpResponse. A typical use case is when you build the context from the request.
If you only need to render a template, you can use the shortcut function render_to_string:
from django.template.loader import render_to_string

render_to_string('your_template.html', {'some_key':'some_value'})

Or do it manually:
from django.template import Context, Template

Template('your_template.html').render(Context({'some_key':'some_value'})

A: The request argument is used if you want to use a RequestContext which is usually the case when you want to use template context processors. You can pass in None as the request argument if you want and you will get a regular Context object in your template.

A: I believe this is b/c the render() shortcut is using a RequestContext
You could also use get_template directly and call render with a normal Context


text:
Q: How to get random item in a list, and get another random item from a second list with the name of the first choose I Have a list called "Livros"
in "Livros" i have ("Lucas", "Isaias").
I have other two lists , one called "Lucas" and other called "Isaias"
in Lucas i have ("Lucas1", "Lucas2", "Lucas3")
and in Isaias ("Isaias1", "Isaias2", "Isaias3")
So, i need to choice a random one in "Livros" between both "Lucas and Isaias".
for example, if i choise ("Lucas")
i will need to raffle one more item in Lucas list.
so, now for example, if my choise is "Lucas2"
ill need to raflle the last item in a dict called "Lucas2" that i have
  Lucas2 = {
    "1" : "Text1" ,
    "2" : "Text2" ,
    "3" : "Text3" ,
    "4" : "Text4"
}

and for last i need to print the key and value in the respective dict.
i tried a thing , but i get just one letter at second print.. so i cant search in dicts..
anyone can help me?
i've been lookin for answers in google, forums and etc... no successful
#!/usr/bin/env python3
from random import *

Livros = ["Lucas", "Isaias"]

Lucas = ["Lucas1", "Lucas2"]
Isaias = ["Isaias1", "Isaias2"]

Lucas1 = {
    "1" : "Text1" ,
    "2" : "Text2" ,
    "3" : "Text3" ,
    "4" : "Text4"
}

Lucas2 = {
    "1" : "Text1" ,
    "2" : "Text2" ,
    "3" : "Text3" ,
    "4" : "Text4"
}

Isaias1 = {
    "1" : "Text1" ,
    "2" : "Text2" ,
    "3" : "Text3" ,
    "4" : "Text4"
}

Isaias2 = {
    "1" : "Text1" ,
    "2" : "Text2" ,
    "3" : "Text3" ,
    "4" : "Text4"
}

x = choice(Livros)
print(x)

xx = choice(x)
print(xx)```

A: If you need to print out the keys, then use nested dictionaries instead of lists. I'm sure there must be a fancy way to do the random choices at the end, recursively or something, but this works as required.
import random

Lucas1 = {
    "1" : "Text1" ,
    "2" : "Text2" ,
    "3" : "Text3" ,
    "4" : "Text4"
}

Lucas2 = {
    "1" : "Text1" ,
    "2" : "Text2" ,
    "3" : "Text3" ,
    "4" : "Text4"
}

Lucas = {"Lucas1": Lucas1, "Lucas2": Lucas2}
Isaias = {"Isaias1": Isaias1, "Isaias2": Isaias2}

Livros = {"Lucas": Lucas, "Isaias": Isaias}

master_key = random.choice(Livros.keys())
entity_key = random.choice(Livros[master_key].keys())
result_key = random.choice(Livros[master_key][entity_key].keys())
print(result_key, Livros[master_key][entity_key][result_key])

Otherwise, just nest the objects inside the list:
Lucas1 = {
    "1" : "Text1" ,
    "2" : "Text2" ,
    "3" : "Text3" ,
    "4" : "Text4"
}

Lucas2 = {
    "1" : "Text1" ,
    "2" : "Text2" ,
    "3" : "Text3" ,
    "4" : "Text4"
}

Lucas = [Lucas1, Lucas2, ... ]
Livros = [Lucas, Isaias]

result = random.choice(random.choice(random.choice(Livros)))

Again, probably a fancier way to use random.choice, but I'm currently cooking breakfast and need to head off.


text:
Q: LINQ to Entities chaining commands with differing results My question is more general, but I have an example to help illustrate:
db.aTable.Where(x => x.Date < someDateInThePast).OrderByDescending(x => x.Date).First()

That gives me one item, which differs from the item returned by this command:
db.aTable.Where(x => x.Date < someDateInThePast).ToList().OrderByDescending(x => x.Date).First()

(note the "ToList()" in the middle).
From what I can see, what is actually happening in the 1st example is the OrderBy is completely disregarding the filtering that is done by the .Where(). It is ordering the entire aTable.
And the 2nd query is giving the actually correct item.
The .Date parameter is a DateTime type (on SQL side it is a 'datetime').
Is this behaviour to be expected from LINQ to Entities?

A: By adding .ToList() you actually change the context in which the data is processed.
Your first query is handled by your database completely and you only return the value from .First() to your Entity-Instance.
In the second one, you basically give the command to load up the conditioned aTable by giving him the command .ToList() and THEN order it, add the second condition and pick the first Date value from that already instanced table.
Microsoft states link that a CLR change might lead to unexpected results, which is what you are doing.
One way to know exactly what is happening would be that you execute your statement on your SQL Server directly:
Select Top(1) Date
From aTable
Where Date < someDateInThePast
order by Date desc

And then create a dbset for your data up to the point where the context changes:
Select *
From aTable
Where Date < someDateInThePast
order by Date desc

And then call it separately in your c# environment. Then check whether the results still differ.
Hope this helps!

A: I can't fully explain why it works like this but I have found that the inclusion of the First() is what is causing the issue. When I view the raw SQL that is generated by the LINQ there is no reference to 'Order By' in it. I can only assume the ordering happens on the client side. But, there is reference to take 'TOP (1)' in the SQL. Meaning, because the SQL server is only returning 1 result, the order by is happening on just 1 result and doesn't do anything useful.
If I change First() to ToList() then the ordering works as expected. This doesn't solve my issue but it explains the behaviour.


text:
Q: Split SQL 2017 column apart by Carriage Return and Line feed I'm working with an Address column in SSMS 2017 that has Carriage Returns and Line Feeds.  One line in SQL is broken into three lines when pasting into Notepad.
Can someone help me break the single SQL column into multiple columns based on the Carriage Return and Line Feeds? I'm expecting to see the Address broken up into three different columns separated by CR and LF delimiter in SQL.
I've tried all the examples on the web that use CHAR(13) and Char(10) but they don't seem to be working.
Any help would be greatly appreciated.

A: You can use string_split and pivot to get the desired result.
Input text:

declare @t table (val nvarchar(1000))

insert into @t
select 'Smith, John
North Bend, 100 Bay Park, Field 2
Trever, NJ 11993
'
select * from @t

;WITH C AS
(
    SELECT value ,ROW_NUMBER() OVER(PARTITION BY val ORDER BY (SELECT NULL)) as rn
    FROM @t t
    CROSS APPLY STRING_SPLIT(REPLACE(val, CHAR(13)+CHAR(10),'~'), '~') AS SPL
)
SELECT [1] AS [Name]
      ,[2] AS Addr_1
      ,[3] AS Addr_2
FROM C
PIVOT
(
    MAX(VALUE)
    FOR RN IN([1],[2],[3])
) as PVT

Result:

A: declare @table table(
input nvarchar(255))
insert into @table
values ('Smith, John
North Bend, 100 Bay Park, Field 2
Trever, NJ 11993')

select
pvt.[1] as [name] ,
pvt.[2] as [address],
pvt.[3] as [city state & zip]
from
(
     select *
     from @table cross apply
     (select rowN = row_number() over (order by (select null)), value from string_split(input, char(10)))d)src
pivot (
     max(value)
          for src.rowN in ([1], [2], [3])
) pvt

link to fiddle uk


text:
Q: c++11 : generic type push via a std::function I am trying to build a generic push component.
I have a class store<T> which

*

*has a T t; member

*has a void push(const T & t) method called by data providers.

When push is called by a provider, I want a value computed by a std::function< T2(const T&)>  and all clients (store<T2>) are notified
with that result value of type T2. A store client has first to subscribe to store via a linker<T, T2> object.
template <class data> class store
{
    data data_;
    std::list< action<data > > m_links;
public:
    void push(const data & e)
    {
        data_ = e;
        for(action<data> a : m_links)
            a(data_);
    }

    void subscribe(action<data> d)
    {
        m_links.push_back(d);
    }
};

Linker object :
template < class data1, class data2 > class linker
{
    // source where come the push calls
    store<data1> & m_source;
    // targets to be notified after computation
    std::list<store<data2> * > m_targets;
    // computation function
    std::function< data2(const data1 &)> m_func;

public:
    linker(store<data1> & source, std::function< data2(const data1 &)> func)
    : m_source(source), m_func(func)
    {
        m_source.subscribe([this](const data1 & d){this->push(d);});
    }
    // add a client
    void add_target(store<data2> & target)
    {
        m_targets.push_back(&target);
    }
    void push(const data1 & e)
    {
        //compute result
        data2 d2 = m_func(e);
        // notify all
        for(store<data2> * s2 : m_targets)
        {
            s2->push(d2);
        }
    }
};

Use case :
int main()
{
    // function : just increment an int, return as double
    std::function<double(const int &) > f_inc = [](const int& i){ return i+1;};
    // function : display the data
    std::function<int(const double&) > f_display = [](const double& d){ std::cout << "value=" << d << std::endl ; return 0;};

    store<int> source;
    store<double> target, target2;

    linker<int, double> l(source, f_inc);
    l.add_target(target);
    l.add_target(target2);

    linker<double, int> display(target, f_display);

    source.push(1);

    return 0;
}

I want to suppress the explicit-ness of the 'linker' object. I did not succeed because I dont know how to handle the fact that when a store client subscribes to a store object, the object can not store a pointeur to store since it does not know the type T2 !
I would like to write something like that:
std::function<double(const int &) > f_inc = [](const int& i){ return i+1;};
store<int> source;
store<double> target;

source.link_to(target, f_inc);

and be able to unsubscribe :
source.unlink(target, f_inc);

or with ids:
id i = source.link_to(target, f_inc);
source.unsubscribe(i);

I am using codeblocks + mingw 4.8.1 under windows xp.
I guess a design pattern exists for this use case ...
ps: I cant use boost.

A: It seems to me that by explicitness you mean the fact that Linker has template parameters.
I would envision something like:
class Broker {
public:
    Broker(): _lastId(0) {}

    //
    // Notification
    //
    template <typename T>
    void notify(store<T> const& source, T const& event) {
        auto const it = _sources.find(&source);

        if (it == _sources.end()) { return; }

        for (size_t id: it->second) { _targets.find(id)->second->invoke(&event); }
    } // notify

    //
    // Subscription
    //
    template <typename T, typename U>
    size_t subscribe(Store<T> const& source, U&& callback) {
        _targets[++_lastId] = std::unique_ptr<Action>(new ActionT<T>(callback));

        _sources[&source].insert(_lastId);

        return _lastId;
    } // subscribe

    template <typename T, typename U>
    size_t subscribe(Store<T> const& source, U const& callback) {
        return this->subscribe(source, U{callback});
    } // subscribe

    void unsubscribe(size_t id) {
        auto const it = _targets.find(id);

        if (it == _targets.end()) { return; }

        void const* source = it->second->_source;

        auto const it2 = _sources.find(source);
        assert(it != _sources.end());

        it2->second.erase(id);

        if (it2->second.empty()) { _sources.erase(it2); }

        _targets.erase(it);
    } // unsubscribe

    template <typename T>
    void unsubscribe(store<T> const& source) {
        auto const it = _sources.find(&source);

        if (it == _sources.end()) { return; }

        for (size_t id: it->second) { _targets.erase(id); }

        _sources.erase(it);
    } // unsubscribe

private:
    //
    // Action/ActionT<T> perform Type Erasure (here, we erase T)
    //
    struct Action {
        Action(void const* source): _source(source) {}

        virtual void invoke(void const*) = 0;

        void const* _source;
    }; // struct Action

    template <typename T>
    class ActionT: Action {
    public:
        ActionT(store<T> const& source, std::function<void(T)> f):
             Action(&source),
             _callback(std::move(f))
        {}

        virtual void invoke(void const* event) {
           _callback(T(*static_cast<T const*>(event));
        }

    private:
        std::function<void(T)> _callback;
    }; // class ActionT

    using Targets = std::map<size_t, std::unique_ptr<Action>>;
    using Sources = std::map<void const*, std::set<size_t>>;

    size_t _lastId;
    Targets _targets;
    Sources _sources;
}; // class Broker

As you may see, fairly complicated... and the worst of it ? It is still unsafe. Specifically, there are lifetime issues:

*

*if you register a callback that has references to the external world, you must remove it before those references die

*it would be cleaner to remove the sources when they disappear (to prevent a leak)

There are some ways to work around it, you might want to look into signal/slots which help implementing this logic without tying it to a specific object.