content
stringlengths
85
101k
title
stringlengths
0
150
question
stringlengths
15
48k
answers
list
answers_scores
list
non_answers
list
non_answers_scores
list
tags
list
name
stringlengths
35
137
Q: in mechanize, is there anyway of rewriting the url to POST to in a form? I'm running a python script and I'm using mechanize. The form i'm trying to submit normally uses javascript to rewrite the url to POST to, so to correctly submit the form i need to manually do the same. is there anyway of doing this? A: Mechanize doesn't process Javascript. The best way usually is to use browser to process Javascript - if you prefer do it in Python use PythonExt. Also you can try Selenium - seleniumhq.org. It's used for web-site testing but can send forms too. A: you may test zope http://pypi.python.org/pypi?:action=display&name=zope.testbrowser
in mechanize, is there anyway of rewriting the url to POST to in a form?
I'm running a python script and I'm using mechanize. The form i'm trying to submit normally uses javascript to rewrite the url to POST to, so to correctly submit the form i need to manually do the same. is there anyway of doing this?
[ "Mechanize doesn't process Javascript. The best way usually is to use browser to process Javascript - if you prefer do it in Python use PythonExt.\nAlso you can try Selenium - seleniumhq.org. It's used for web-site testing but can send forms too.\n", "you may test zope http://pypi.python.org/pypi?:action=display&...
[ 1, 1 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0003656117_mechanize_python.txt
Q: Mac OS X python 'import vigra' error I want to use vigra under Mac OS X 10.6.4. So I installed all dependencies with Macpotrs. Everything compiled and I could install vigra too. But when I try to import vigra, then I get a 'Segmentation fault'. Do someone know how to solve this problem? Here the Mac OS X error report: Process: Python [784] Path: /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python Identifier: Python Version: ??? (???) Code Type: X86-64 (Native) Parent Process: bash [779] Date/Time: 2010-10-02 14:21:08.522 +0200 OS Version: Mac OS X 10.6.4 (10F569) Report Version: 6 Interval Since Last Report: 3444718 sec Crashes Since Last Report: 91 Per-App Crashes Since Last Report: 12 Anonymous UUID: D1732CEB-3906-4947-832C-99C1C260905E Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000000 Crashed Thread: 0 Dispatch queue: com.apple.main-thread Thread 0 Crashed: Dispatch queue: com.apple.main-thread 0 ??? 000000000000000000 0 + 0 1 org.python.python 0x00000001010977f2 PyImport_Import + 139 2 org.python.python 0x000000010109799f PyImport_ImportModule + 40 3 vigranumpycore.so 0x0000000100557b33 init_module_vigranumpycore() + 19 4 libboost_python-mt.dylib 0x000000010071f511 boost::python::handle_exception_impl(boost::function0) + 273 5 libboost_python-mt.dylib 0x0000000100720676 bool boost::python::handle_exception(void (*)()) + 54 6 libboost_python-mt.dylib 0x000000010072041b boost::python::detail::init_module(char const*, void (*)()) + 91 7 org.python.python 0x00000001000d3911 _PyImport_LoadDynamicModule + 177 8 org.python.python 0x00000001000d1bcf import_submodule + 383 9 org.python.python 0x00000001000d20ea load_next + 234 10 org.python.python 0x00000001000d23fb PyImport_ImportModuleLevel + 363 11 org.python.python 0x00000001000af973 builtin_import + 131 12 org.python.python 0x000000010000b902 PyObject_Call + 98 13 org.python.python 0x00000001000b0bb7 PyEval_CallObjectWithKeywords + 87 14 org.python.python 0x00000001000b4e7e PyEval_EvalFrameEx + 12622 15 org.python.python 0x00000001000b9af5 PyEval_EvalCodeEx + 2197 16 org.python.python 0x00000001000b9c16 PyEval_EvalCode + 54 17 org.python.python 0x00000001000ceac0 PyImport_ExecCodeModuleEx + 208 18 org.python.python 0x00000001000cfd22 load_source_module + 722 19 org.python.python 0x00000001000d12df load_package + 463 20 org.python.python 0x00000001000d1bcf import_submodule + 383 21 org.python.python 0x00000001000d20ea load_next + 234 22 org.python.python 0x00000001000d23fb PyImport_ImportModuleLevel + 363 23 org.python.python 0x00000001000af973 builtin_import + 131 24 org.python.python 0x000000010000b902 PyObject_Call + 98 25 org.python.python 0x00000001000b0bb7 PyEval_CallObjectWithKeywords + 87 26 org.python.python 0x00000001000b4e7e PyEval_EvalFrameEx + 12622 27 org.python.python 0x00000001000b9af5 PyEval_EvalCodeEx + 2197 28 org.python.python 0x00000001000b9c16 PyEval_EvalCode + 54 29 org.python.python 0x00000001000de50c PyRun_InteractiveOneFlags + 380 30 org.python.python 0x00000001000de76e PyRun_InteractiveLoopFlags + 78 31 org.python.python 0x00000001000defe1 PyRun_AnyFileExFlags + 161 32 org.python.python 0x00000001000ee40c Py_Main + 2764 33 org.python.python 0x0000000100000f14 0x100000000 + 3860 Thread 0 crashed with X86 Thread State (64-bit): rax: 0x000000010113ed88 rbx: 0x000000010058f030 rcx: 0x0000000000000000 rdx: 0x0000000100592030 rdi: 0x0000000000000000 rsi: 0x0000000000000000 rbp: 0x00007fff5fbfccf0 rsp: 0x00007fff5fbfcce8 r8: 0x0000000000000100 r9: 0x0000000010035468 r10: 0x000000000000002a r11: 0x0000000100592054 r12: 0x0000000000000000 r13: 0x0000000000000000 r14: 0x000000010058f030 r15: 0x00007fff5fbfcf20 rip: 0x0000000000000000 rfl: 0x0000000000010206 cr2: 0x0000000000000000 Binary Images: 0x100000000 - 0x100000fff +org.python.python 2.6.6 (2.6.6) <9D90DD3B-6C94-741D-4900-0FDD4139E880> /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python 0x100003000 - 0x10014fff7 +org.python.python 2.6.6, (c) 2004-2008 Python Software Foundation. (2.6.6) /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python 0x1002e3000 - 0x1002e5ff7 +readline.so ??? (???) /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/readline.so 0x100440000 - 0x100468ff7 +libreadline.6.1.dylib 6.1.0 (compatibility 6.0.0) /opt/local/lib/libreadline.6.1.dylib 0x10047e000 - 0x1004c3fef +libncursesw.5.dylib 5.0.0 (compatibility 5.0.0) /opt/local/lib/libncursesw.5.dylib 0x1004d2000 - 0x1004fcff7 +libncurses.5.dylib 5.0.0 (compatibility 5.0.0) <9829BCEB-0A54-5FA7-788E-0F0593301164> /opt/local/lib/libncurses.5.dylib 0x100555000 - 0x10056efff +vigranumpycore.so ??? (???) <9B417A36-C0B4-47FC-0D7C-C24E9AFC1A42> /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/vigra/vigranumpycore.so 0x100700000 - 0x10073fff7 +libboost_python-mt.dylib ??? (???) <1D14BD86-A204-EBD7-59EE-A733E09C1A96> /opt/local/lib/libboost_python-mt.dylib 0x101000000 - 0x101110ff7 org.python.python 2.6.1 (2.6.1) /System/Library/Frameworks/Python.framework/Versions/2.6/Python 0x7fff5fc00000 - 0x7fff5fc3bdef dyld 132.1 (???) /usr/lib/dyld 0x7fff803e9000 - 0x7fff8049ffff libobjc.A.dylib 227.0.0 (compatibility 1.0.0) /usr/lib/libobjc.A.dylib 0x7fff8293e000 - 0x7fff82942ff7 libmathCommon.A.dylib 315.0.0 (compatibility 1.0.0) <95718673-FEEE-B6ED-B127-BCDBDB60D4E5> /usr/lib/system/libmathCommon.A.dylib 0x7fff82c46000 - 0x7fff82e04fff libicucore.A.dylib 40.0.0 (compatibility 1.0.0) <0E53A4A6-AC06-1B61-2285-248F534EE356> /usr/lib/libicucore.A.dylib 0x7fff83b44000 - 0x7fff83cb9ff7 com.apple.CoreFoundation 6.6.3 (550.29) <48810602-63C3-994D-E563-DD02B16E76E1> /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation 0x7fff86454000 - 0x7fff864a0fff libauto.dylib ??? (???) <205CE82B-3DE0-4A9D-CEB9-F6A3DDA22ED4> /usr/lib/libauto.dylib 0x7fff86b03000 - 0x7fff86b80fef libstdc++.6.dylib 7.9.0 (compatibility 7.0.0) <35ECA411-2C08-FD7D-11B1-1B7A04921A5C> /usr/lib/libstdc++.6.dylib 0x7fff8752e000 - 0x7fff876eefef libSystem.B.dylib 125.2.0 (compatibility 1.0.0) <95E02DD0-ADEA-745B-E7FA-ABA064E4658C> /usr/lib/libSystem.B.dylib 0x7fff88245000 - 0x7fff88256ff7 libz.1.dylib 1.2.3 (compatibility 1.0.0) /usr/lib/libz.1.dylib 0x7fffffe00000 - 0x7fffffe01fff libSystem.B.dylib ??? (???) <95E02DD0-ADEA-745B-E7FA-ABA064E4658C> /usr/lib/libSystem.B.dylib Model: MacBookPro6,2, BootROM MBP61.0057.B0C, 2 processors, Intel Core i5, 2.4 GHz, 4 GB, SMC 1.58f16 Graphics: NVIDIA GeForce GT 330M, NVIDIA GeForce GT 330M, PCIe, 256 MB Graphics: Intel HD Graphics, Intel HD Graphics, Built-In, 288 MB Memory Module: global_name AirPort: spairport_wireless_card_type_airport_extreme (0x14E4, 0x93), Broadcom BCM43xx 1.0 (5.10.131.16.1) Bluetooth: Version 2.3.7f1, 2 service, 12 devices, 1 incoming serial ports Network Service: AirPort, AirPort, en1 Serial ATA Device: Hitachi HTS545032B9SA02, 298,09 GB Serial ATA Device: MATSHITADVD-R UJ-898 USB Device: Hub, 0x0424 (SMSC), 0x2514, 0xfa100000 USB Device: Internal Memory Card Reader, 0x05ac (Apple Inc.), 0x8403, 0xfa130000 USB Device: Apple Internal Keyboard / Trackpad, 0x05ac (Apple Inc.), 0x0237, 0xfa120000 USB Device: BRCM2070 Hub, 0x0a5c (Broadcom Corp.), 0x4500, 0xfa110000 USB Device: Bluetooth USB Host Controller, 0x05ac (Apple Inc.), 0x8218, 0xfa113000 USB Device: Hub, 0x0424 (SMSC), 0x2514, 0xfd100000 USB Device: External HDD, 0x1058 (Western Digital Technologies, Inc.), 0x0705, 0xfd130000 USB Device: IR Receiver, 0x05ac (Apple Inc.), 0x8242, 0xfd120000 USB Device: Built-in iSight, 0x05ac (Apple Inc.), 0x8507, 0xfd110000 A: Does your numpy work well? Did you run its tests? Its installation notes remind of ABI mismatches and right compiler choice; probably a wrong choice might lead to a segfault. The crash happens near init_module_vigranumpycore; maybe it's not vigra yet.
Mac OS X python 'import vigra' error
I want to use vigra under Mac OS X 10.6.4. So I installed all dependencies with Macpotrs. Everything compiled and I could install vigra too. But when I try to import vigra, then I get a 'Segmentation fault'. Do someone know how to solve this problem? Here the Mac OS X error report: Process: Python [784] Path: /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python Identifier: Python Version: ??? (???) Code Type: X86-64 (Native) Parent Process: bash [779] Date/Time: 2010-10-02 14:21:08.522 +0200 OS Version: Mac OS X 10.6.4 (10F569) Report Version: 6 Interval Since Last Report: 3444718 sec Crashes Since Last Report: 91 Per-App Crashes Since Last Report: 12 Anonymous UUID: D1732CEB-3906-4947-832C-99C1C260905E Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Codes: KERN_INVALID_ADDRESS at 0x0000000000000000 Crashed Thread: 0 Dispatch queue: com.apple.main-thread Thread 0 Crashed: Dispatch queue: com.apple.main-thread 0 ??? 000000000000000000 0 + 0 1 org.python.python 0x00000001010977f2 PyImport_Import + 139 2 org.python.python 0x000000010109799f PyImport_ImportModule + 40 3 vigranumpycore.so 0x0000000100557b33 init_module_vigranumpycore() + 19 4 libboost_python-mt.dylib 0x000000010071f511 boost::python::handle_exception_impl(boost::function0) + 273 5 libboost_python-mt.dylib 0x0000000100720676 bool boost::python::handle_exception(void (*)()) + 54 6 libboost_python-mt.dylib 0x000000010072041b boost::python::detail::init_module(char const*, void (*)()) + 91 7 org.python.python 0x00000001000d3911 _PyImport_LoadDynamicModule + 177 8 org.python.python 0x00000001000d1bcf import_submodule + 383 9 org.python.python 0x00000001000d20ea load_next + 234 10 org.python.python 0x00000001000d23fb PyImport_ImportModuleLevel + 363 11 org.python.python 0x00000001000af973 builtin_import + 131 12 org.python.python 0x000000010000b902 PyObject_Call + 98 13 org.python.python 0x00000001000b0bb7 PyEval_CallObjectWithKeywords + 87 14 org.python.python 0x00000001000b4e7e PyEval_EvalFrameEx + 12622 15 org.python.python 0x00000001000b9af5 PyEval_EvalCodeEx + 2197 16 org.python.python 0x00000001000b9c16 PyEval_EvalCode + 54 17 org.python.python 0x00000001000ceac0 PyImport_ExecCodeModuleEx + 208 18 org.python.python 0x00000001000cfd22 load_source_module + 722 19 org.python.python 0x00000001000d12df load_package + 463 20 org.python.python 0x00000001000d1bcf import_submodule + 383 21 org.python.python 0x00000001000d20ea load_next + 234 22 org.python.python 0x00000001000d23fb PyImport_ImportModuleLevel + 363 23 org.python.python 0x00000001000af973 builtin_import + 131 24 org.python.python 0x000000010000b902 PyObject_Call + 98 25 org.python.python 0x00000001000b0bb7 PyEval_CallObjectWithKeywords + 87 26 org.python.python 0x00000001000b4e7e PyEval_EvalFrameEx + 12622 27 org.python.python 0x00000001000b9af5 PyEval_EvalCodeEx + 2197 28 org.python.python 0x00000001000b9c16 PyEval_EvalCode + 54 29 org.python.python 0x00000001000de50c PyRun_InteractiveOneFlags + 380 30 org.python.python 0x00000001000de76e PyRun_InteractiveLoopFlags + 78 31 org.python.python 0x00000001000defe1 PyRun_AnyFileExFlags + 161 32 org.python.python 0x00000001000ee40c Py_Main + 2764 33 org.python.python 0x0000000100000f14 0x100000000 + 3860 Thread 0 crashed with X86 Thread State (64-bit): rax: 0x000000010113ed88 rbx: 0x000000010058f030 rcx: 0x0000000000000000 rdx: 0x0000000100592030 rdi: 0x0000000000000000 rsi: 0x0000000000000000 rbp: 0x00007fff5fbfccf0 rsp: 0x00007fff5fbfcce8 r8: 0x0000000000000100 r9: 0x0000000010035468 r10: 0x000000000000002a r11: 0x0000000100592054 r12: 0x0000000000000000 r13: 0x0000000000000000 r14: 0x000000010058f030 r15: 0x00007fff5fbfcf20 rip: 0x0000000000000000 rfl: 0x0000000000010206 cr2: 0x0000000000000000 Binary Images: 0x100000000 - 0x100000fff +org.python.python 2.6.6 (2.6.6) <9D90DD3B-6C94-741D-4900-0FDD4139E880> /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Resources/Python.app/Contents/MacOS/Python 0x100003000 - 0x10014fff7 +org.python.python 2.6.6, (c) 2004-2008 Python Software Foundation. (2.6.6) /opt/local/Library/Frameworks/Python.framework/Versions/2.6/Python 0x1002e3000 - 0x1002e5ff7 +readline.so ??? (???) /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-dynload/readline.so 0x100440000 - 0x100468ff7 +libreadline.6.1.dylib 6.1.0 (compatibility 6.0.0) /opt/local/lib/libreadline.6.1.dylib 0x10047e000 - 0x1004c3fef +libncursesw.5.dylib 5.0.0 (compatibility 5.0.0) /opt/local/lib/libncursesw.5.dylib 0x1004d2000 - 0x1004fcff7 +libncurses.5.dylib 5.0.0 (compatibility 5.0.0) <9829BCEB-0A54-5FA7-788E-0F0593301164> /opt/local/lib/libncurses.5.dylib 0x100555000 - 0x10056efff +vigranumpycore.so ??? (???) <9B417A36-C0B4-47FC-0D7C-C24E9AFC1A42> /opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/vigra/vigranumpycore.so 0x100700000 - 0x10073fff7 +libboost_python-mt.dylib ??? (???) <1D14BD86-A204-EBD7-59EE-A733E09C1A96> /opt/local/lib/libboost_python-mt.dylib 0x101000000 - 0x101110ff7 org.python.python 2.6.1 (2.6.1) /System/Library/Frameworks/Python.framework/Versions/2.6/Python 0x7fff5fc00000 - 0x7fff5fc3bdef dyld 132.1 (???) /usr/lib/dyld 0x7fff803e9000 - 0x7fff8049ffff libobjc.A.dylib 227.0.0 (compatibility 1.0.0) /usr/lib/libobjc.A.dylib 0x7fff8293e000 - 0x7fff82942ff7 libmathCommon.A.dylib 315.0.0 (compatibility 1.0.0) <95718673-FEEE-B6ED-B127-BCDBDB60D4E5> /usr/lib/system/libmathCommon.A.dylib 0x7fff82c46000 - 0x7fff82e04fff libicucore.A.dylib 40.0.0 (compatibility 1.0.0) <0E53A4A6-AC06-1B61-2285-248F534EE356> /usr/lib/libicucore.A.dylib 0x7fff83b44000 - 0x7fff83cb9ff7 com.apple.CoreFoundation 6.6.3 (550.29) <48810602-63C3-994D-E563-DD02B16E76E1> /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation 0x7fff86454000 - 0x7fff864a0fff libauto.dylib ??? (???) <205CE82B-3DE0-4A9D-CEB9-F6A3DDA22ED4> /usr/lib/libauto.dylib 0x7fff86b03000 - 0x7fff86b80fef libstdc++.6.dylib 7.9.0 (compatibility 7.0.0) <35ECA411-2C08-FD7D-11B1-1B7A04921A5C> /usr/lib/libstdc++.6.dylib 0x7fff8752e000 - 0x7fff876eefef libSystem.B.dylib 125.2.0 (compatibility 1.0.0) <95E02DD0-ADEA-745B-E7FA-ABA064E4658C> /usr/lib/libSystem.B.dylib 0x7fff88245000 - 0x7fff88256ff7 libz.1.dylib 1.2.3 (compatibility 1.0.0) /usr/lib/libz.1.dylib 0x7fffffe00000 - 0x7fffffe01fff libSystem.B.dylib ??? (???) <95E02DD0-ADEA-745B-E7FA-ABA064E4658C> /usr/lib/libSystem.B.dylib Model: MacBookPro6,2, BootROM MBP61.0057.B0C, 2 processors, Intel Core i5, 2.4 GHz, 4 GB, SMC 1.58f16 Graphics: NVIDIA GeForce GT 330M, NVIDIA GeForce GT 330M, PCIe, 256 MB Graphics: Intel HD Graphics, Intel HD Graphics, Built-In, 288 MB Memory Module: global_name AirPort: spairport_wireless_card_type_airport_extreme (0x14E4, 0x93), Broadcom BCM43xx 1.0 (5.10.131.16.1) Bluetooth: Version 2.3.7f1, 2 service, 12 devices, 1 incoming serial ports Network Service: AirPort, AirPort, en1 Serial ATA Device: Hitachi HTS545032B9SA02, 298,09 GB Serial ATA Device: MATSHITADVD-R UJ-898 USB Device: Hub, 0x0424 (SMSC), 0x2514, 0xfa100000 USB Device: Internal Memory Card Reader, 0x05ac (Apple Inc.), 0x8403, 0xfa130000 USB Device: Apple Internal Keyboard / Trackpad, 0x05ac (Apple Inc.), 0x0237, 0xfa120000 USB Device: BRCM2070 Hub, 0x0a5c (Broadcom Corp.), 0x4500, 0xfa110000 USB Device: Bluetooth USB Host Controller, 0x05ac (Apple Inc.), 0x8218, 0xfa113000 USB Device: Hub, 0x0424 (SMSC), 0x2514, 0xfd100000 USB Device: External HDD, 0x1058 (Western Digital Technologies, Inc.), 0x0705, 0xfd130000 USB Device: IR Receiver, 0x05ac (Apple Inc.), 0x8242, 0xfd120000 USB Device: Built-in iSight, 0x05ac (Apple Inc.), 0x8507, 0xfd110000
[ "Does your numpy work well? Did you run its tests? Its installation notes remind of ABI mismatches and right compiler choice; probably a wrong choice might lead to a segfault. The crash happens near init_module_vigranumpycore; maybe it's not vigra yet.\n" ]
[ 0 ]
[]
[]
[ "macos", "python" ]
stackoverflow_0003845702_macos_python.txt
Q: Encoding problem downloading HTML using mechanize and Python 2.6 browser = mechanize.Browser() page = browser.open(url) html = page.get_data() print html It shows some strange characters. I suppose that it is UTF-8 string but Python doesn't know that and cannot show it properly. How can I convert this string to unicode string like u = u'test' A: It was gzipped def ungzipResponse(r,b): headers = r.info() if headers['Content-Encoding']=='gzip': import gzip gz = gzip.GzipFile(fileobj=r, mode='rb') html = gz.read() gz.close() headers["Content-type"] = "text/html; charset=utf-8" r.set_data( html ) b.set_response(r) response = browser.open(url) ungzipResponse(response, browser) html = response.read() A: u = html.decode('utf-8') A: you need to define the encoding like : #!/usr/bin/python # -*- coding: iso-8859-15 -*- mechanize need it . for more information check this out http://www.python.org/dev/peps/pep-0263/
Encoding problem downloading HTML using mechanize and Python 2.6
browser = mechanize.Browser() page = browser.open(url) html = page.get_data() print html It shows some strange characters. I suppose that it is UTF-8 string but Python doesn't know that and cannot show it properly. How can I convert this string to unicode string like u = u'test'
[ "It was gzipped\ndef ungzipResponse(r,b):\n headers = r.info()\n if headers['Content-Encoding']=='gzip':\n import gzip\n gz = gzip.GzipFile(fileobj=r, mode='rb')\n html = gz.read()\n gz.close()\n headers[\"Content-type\"] = \"text/html; charset=utf-8\"\n r.set_data( h...
[ 4, 1, 1 ]
[]
[]
[ "encoding", "mechanize", "python", "unicode", "utf_8" ]
stackoverflow_0003804572_encoding_mechanize_python_unicode_utf_8.txt
Q: How to call a static method of a class using method name and class name Starting with a class like this: class FooClass(object): @staticmethod def static_method(x): print x normally, I would call the static method of the class with: FooClass.static_method('bar') Is it possible to invoke this static method having just the class name and the method name? class_name = 'FooClass' method_name = 'static_method' A: You shouldn't mess with locals() as suggested in other answers. If you have your classname as a string and need to resolve it, use registry of some sort. A dictionary will work fine. E.g. class FooClass(object): @staticmethod def static_method(x): print x registry = {'FooClass':FooClass} (I assume you will want to add many more classes to this registry) the lookup then becomes almost trivial: getattr(registry['FooClass'], 'static_method')("bar") A: Here is a crude way: >>> class FooClass(object): @staticmethod def static_method(x): print x >>> class_name = 'FooClass' >>> method_name = 'static_method' >>> getattr(locals().get(class_name), method_name)("bar") bar Breakup: locals().get(class_name) First, locate the class. In this case I'm using locals() as I know that the class is available in the local dictionary. This will fail if the class is not present in the local dictionary. Next, find the method of the class. getattr(locals().get(class_name), method_name) This uses getattr(). Finally, call the method. getattr(locals().get(class_name), method_name)("bar") A: you can use getattr twice. the first time on the module that contains the class and the second time on the class itself class_name = 'Foo' method_name = 'Bar' cls = getattr(mod, clsname) method = getattr(cls, method_name) method(args) This is not as flexible as building a registry (which you can do with a decorator) but if you are not going to do that, than this is a far better alternative than messing with the stack and stylistically, cleaner than messing with sys.modules. Note that a module can import itself with no adverse effects. so the classes don't have to be in a different module for this to work. A: If the class type is accessible from the current module, you can access the class in the globals() dict and the method using getattr: class FooClass(object): @staticmethod def static_method(x): print x class_name = 'FooClass' method_name = 'static_method' getattr(globals()[class_name], method_name)("test")
How to call a static method of a class using method name and class name
Starting with a class like this: class FooClass(object): @staticmethod def static_method(x): print x normally, I would call the static method of the class with: FooClass.static_method('bar') Is it possible to invoke this static method having just the class name and the method name? class_name = 'FooClass' method_name = 'static_method'
[ "You shouldn't mess with locals() as suggested in other answers. If you have your classname as a string and need to resolve it, use registry of some sort. A dictionary will work fine. E.g.\nclass FooClass(object):\n @staticmethod\n def static_method(x):\n print x\n\nregistry = {'FooClass':FooClass}\n\n...
[ 9, 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003849576_python.txt
Q: itertools or hand-written generator - what is preferable? I have a number of Python generators, which I want to combine into a new generator. I can easily do this by a hand-written generator using a bunch of yield statements. On the other hand, the itertools module is made for things like this and to me it seems as if the pythonic way to create the generator I need is to plug together various iterators of that itertools module. However, in the problem at hand, it soon gets quite complicated (the generator needs to maintain a sort of state --- e.g. whether the first or later items are being processed ---, the i-th output further depends on conditions on the i-th input items and the various input lists have to be processed differently before they are being joined to the generated list. As the composition of standard iterators that would solve my problem is --- due to the one-dimensional nature of writing down source code --- nearly incomprehensible, I wonder whether there are any advantages of using standard itertools generators versus hand-written generator functions (in basic and in more advanced cases). Actually, I think that in 90% of the cases, the hand-written versions are much easier to read --- probably due to their more imperative style compared to the functional style of chaining iterators. EDIT In order to illustrate my problem, here is a (toy) example: Let a and b be two iterables of the same length (the input data). The items of a consist of integers, the items of b are iterables themselves, whose individual items are strings. The output should correspond to the output of the following generator function: from itertools import * def generator(a, b): first = True for i, s in izip(a, b): if first: yield "First line" first = False else: yield "Some later line" if i == 0: yield "The parameter vanishes." else: yield "The parameter is:" yield i yield "The strings are:" comma = False for t in s: if comma: yield ',' else: comma = True yield t If I write down the same program in functional style using generator expressions and the itertools module, I end up with something like: from itertools import * def generator2(a, b): return (z for i, s, c in izip(a, b, count()) for y in (("First line" if c == 0 else "Some later line",), ("The parameter vanishes.",) if i == 0 else ("The parameter is:", i), ("The strings are:",), islice((x for t in s for x in (',', t)), 1, None)) for z in y) EXAMPLE >>> a = (1, 0, 2), ("ab", "cd", "ef") >>> print([x for x in generator(a, b)]) ['First line', 'The parameter is:', 1, 'The strings are:', 'a', ',', 'b', 'Some later line', 'The parameter vanishes.', 'The strings are:', 'c', ',', 'd', 'Some later line', 'The parameter is:', 2, 'The strings are:', 'e', ',', 'f'] >>> print([x for x in generator2(a, b)]) ['First line', 'The parameter is:', 1, 'The strings are:', 'a', ',', 'b', 'Some later line', 'The parameter vanishes.', 'The strings are:', 'c', ',', 'd', 'Some later line', 'The parameter is:', 2, 'The strings are:', 'e', ',', 'f'] This is possibly more elegant than my first solution but it looks like a write-once-do-not-understand-later piece of code. I am wondering whether this way of writing my generator has enough advantages that one should do so. P.S.: I guess part of my problem with the functional solution is that in order to minimize the amount of keywords in Python, some keywords like "for", "if" and "else" have been recycled for use in expressions so that their placement in the expression takes getting used to (the ordering in the generator expression z for x in a for y in x for z in y looks, at least to me, less natural than the ordering in the classic for loop: for x in a: for y in x: for z in y: yield z). A: I did some profiling and the regular generator function is way faster than either your second generator or my implementation. $ python -mtimeit -s'import gen; a, b = gen.make_test_case()' 'list(gen.generator1(a, b))' 10 loops, best of 3: 169 msec per loop $ python -mtimeit -s'import gen; a, b = gen.make_test_case()' 'list(gen.generator2(a, b))' 10 loops, best of 3: 489 msec per loop $ python -mtimeit -s'import gen; a, b = gen.make_test_case()' 'list(gen.generator3(a, b))' 10 loops, best of 3: 385 msec per loop It also happens to be the most readable so I think i'd go with that. That being said, I'll still post my solution because I think it's a cleaner example of the sort of functional programming you can do with itertools (though clearly still not optimal, I feel like it should be able to smoke the regular generator function. I'll hack on it) def generator3(parameters, strings): # replace strings with a generator of generators for the individual charachters strings = (it.islice((char for string_char in string_ for char in (',', string_char)), 1, None) for string_ in strings) # interpolate strings with the notices strings = (it.chain(('The strings are:',), string_) for string_ in strings) # nest them in tuples so they're ate the same level as the other generators separators = it.chain((('First line',),), it.cycle((('Some later line',),))) # replace the parameters with the appropriate tuples parameters = (('The parameter is:', p) if p else ('The parameter vanishes.',) for p in parameters) # combine the separators, parameters and strings output = it.izip(separators, parameters, strings) # flatten it twice and return it output = it.chain.from_iterable(output) return it.chain.from_iterable(output) for reference, the test case is: def make_test_case(): a = [i % 100 for i in range(10000)] b = [('12345'*10)[:(i%50)+1] for i in range(10000)] return a, b
itertools or hand-written generator - what is preferable?
I have a number of Python generators, which I want to combine into a new generator. I can easily do this by a hand-written generator using a bunch of yield statements. On the other hand, the itertools module is made for things like this and to me it seems as if the pythonic way to create the generator I need is to plug together various iterators of that itertools module. However, in the problem at hand, it soon gets quite complicated (the generator needs to maintain a sort of state --- e.g. whether the first or later items are being processed ---, the i-th output further depends on conditions on the i-th input items and the various input lists have to be processed differently before they are being joined to the generated list. As the composition of standard iterators that would solve my problem is --- due to the one-dimensional nature of writing down source code --- nearly incomprehensible, I wonder whether there are any advantages of using standard itertools generators versus hand-written generator functions (in basic and in more advanced cases). Actually, I think that in 90% of the cases, the hand-written versions are much easier to read --- probably due to their more imperative style compared to the functional style of chaining iterators. EDIT In order to illustrate my problem, here is a (toy) example: Let a and b be two iterables of the same length (the input data). The items of a consist of integers, the items of b are iterables themselves, whose individual items are strings. The output should correspond to the output of the following generator function: from itertools import * def generator(a, b): first = True for i, s in izip(a, b): if first: yield "First line" first = False else: yield "Some later line" if i == 0: yield "The parameter vanishes." else: yield "The parameter is:" yield i yield "The strings are:" comma = False for t in s: if comma: yield ',' else: comma = True yield t If I write down the same program in functional style using generator expressions and the itertools module, I end up with something like: from itertools import * def generator2(a, b): return (z for i, s, c in izip(a, b, count()) for y in (("First line" if c == 0 else "Some later line",), ("The parameter vanishes.",) if i == 0 else ("The parameter is:", i), ("The strings are:",), islice((x for t in s for x in (',', t)), 1, None)) for z in y) EXAMPLE >>> a = (1, 0, 2), ("ab", "cd", "ef") >>> print([x for x in generator(a, b)]) ['First line', 'The parameter is:', 1, 'The strings are:', 'a', ',', 'b', 'Some later line', 'The parameter vanishes.', 'The strings are:', 'c', ',', 'd', 'Some later line', 'The parameter is:', 2, 'The strings are:', 'e', ',', 'f'] >>> print([x for x in generator2(a, b)]) ['First line', 'The parameter is:', 1, 'The strings are:', 'a', ',', 'b', 'Some later line', 'The parameter vanishes.', 'The strings are:', 'c', ',', 'd', 'Some later line', 'The parameter is:', 2, 'The strings are:', 'e', ',', 'f'] This is possibly more elegant than my first solution but it looks like a write-once-do-not-understand-later piece of code. I am wondering whether this way of writing my generator has enough advantages that one should do so. P.S.: I guess part of my problem with the functional solution is that in order to minimize the amount of keywords in Python, some keywords like "for", "if" and "else" have been recycled for use in expressions so that their placement in the expression takes getting used to (the ordering in the generator expression z for x in a for y in x for z in y looks, at least to me, less natural than the ordering in the classic for loop: for x in a: for y in x: for z in y: yield z).
[ "I did some profiling and the regular generator function is way faster than either your second generator or my implementation. \n$ python -mtimeit -s'import gen; a, b = gen.make_test_case()' 'list(gen.generator1(a, b))'\n10 loops, best of 3: 169 msec per loop\n\n$ python -mtimeit -s'import gen; a, b = gen.make_test...
[ 7 ]
[]
[]
[ "generator", "iterator", "python" ]
stackoverflow_0003849702_generator_iterator_python.txt
Q: Python mechanize, following link by url and what is the nr parameter? I'm sorry to have to ask something like this but python's mechanize documentation seems to really be lacking and I can't figure this out.. they only give one example that I can find for following a link: response1 = br.follow_link(text_regex=r"cheese\s*shop", nr=1) But I don't want to use a regex, I just want to follow a link based on its url, how would I do this.. also what is "nr" that is used sometimes for following links? Thanks for any info A: br.follow_link takes either a Link object or a keyword arg (such as nr=0). br.links() lists all the links. br.links(url_regex='...') lists all the links whose urls matches the regex. br.links(text_regex='...') lists all the links whose link text matches the regex. br.follow_link(nr=num) follows the numth link on the page, with counting starting at 0. It returns a response object (the same kind what br.open(...) returns) br.find_link(url='...') returns the Link object whose url exactly equals the given url. br.find_link, br.links, br.follow_link, br.click_link all accept the same keywords. Run help(br.find_link) to see documentation on those keywords. Edit: If you have a target url that you wish to follow, you could do something like this: import mechanize br = mechanize.Browser() response=br.open("http://www.example.com/") target_url='http://www.rfc-editor.org/rfc/rfc2606.txt' for link in br.links(): print(link) # Link(base_url='http://www.example.com/', url='http://www.rfc-editor.org/rfc/rfc2606.txt', text='RFC 2606', tag='a', attrs=[('href', 'http://www.rfc-editor.org/rfc/rfc2606.txt')]) print(link.url) # http://www.rfc-editor.org/rfc/rfc2606.txt if link.url == target_url: print('match found') # match found break br.follow_link(link) # link still holds the last value it had in the loop print(br.geturl()) # http://www.rfc-editor.org/rfc/rfc2606.txt A: I found this way to do it, for reference for anyone who doesn't want to use regex: r = br.open("http://www.somewebsite.com") br.find_link(url='http://www.somewebsite.com/link1.html') req = br.click_link(url='http://www.somewebsite.com/link1.html') br.open(req) print br.response().read() Or, it will work by the link's text also: r = br.open("http://www.somewebsite.com") br.find_link(text='Click this link') req = br.click_link(text='Click this link') br.open(req) print br.response().read() A: From looking at the code, I suspect you want response1 = br.follow_link(link=LinkObjectToFollow) nr is the same as documented under the find_link call. EDIT: In my first cursory glance, I didn't realize "link" wasn't a simple link. A: nr is used for where exactly link you follow. if the text or url you has been regex more than one. default is 0 so if you use default you will follow link first regex at all . for example the source : <a href="link.html>Click this link</a> <a href="link2.html>Click this link</a> in this example we need to follow "Click this link" text but we choose link2.html to follow exactly br.click_link(text='Click this link', nr=1) by it you will get link2.html response
Python mechanize, following link by url and what is the nr parameter?
I'm sorry to have to ask something like this but python's mechanize documentation seems to really be lacking and I can't figure this out.. they only give one example that I can find for following a link: response1 = br.follow_link(text_regex=r"cheese\s*shop", nr=1) But I don't want to use a regex, I just want to follow a link based on its url, how would I do this.. also what is "nr" that is used sometimes for following links? Thanks for any info
[ "br.follow_link takes either a Link object or a keyword arg (such as nr=0). \nbr.links() lists all the links.\nbr.links(url_regex='...') lists all the links whose urls matches the regex.\nbr.links(text_regex='...') lists all the links whose link text matches the regex.\nbr.follow_link(nr=num) follows the numth link...
[ 50, 16, 2, 2 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0003569622_mechanize_python.txt
Q: Python - The request headers for mechanize I am looking for a way to view the request (not response) headers, specifically what browser mechanize claims to be. Also how would I go about manipulating them, eg setting another browser? Example: import mechanize browser = mechanize.Browser() # Now I want to make a request to eg example.com with custom headers using browser The purpose is of course to test a website and see whether or not it shows different pages depending on the reported browser. It has to be the mechanize browser as the rest of the code depends on it (but is left out as it's irrelevant.) A: browser.addheaders = [('User-Agent', 'Mozilla/5.0 blahblah')] A: You've got an answer on how to change the headers, but if you want to see the exact headers that are being used try using a proxy that displays the traffic. e.g. Fiddler2 on windows or see this question for some Linux altenatives. A: you can modify referer too... br.addheaders = [('Referer', 'http://google.com')]
Python - The request headers for mechanize
I am looking for a way to view the request (not response) headers, specifically what browser mechanize claims to be. Also how would I go about manipulating them, eg setting another browser? Example: import mechanize browser = mechanize.Browser() # Now I want to make a request to eg example.com with custom headers using browser The purpose is of course to test a website and see whether or not it shows different pages depending on the reported browser. It has to be the mechanize browser as the rest of the code depends on it (but is left out as it's irrelevant.)
[ "browser.addheaders = [('User-Agent', 'Mozilla/5.0 blahblah')]\n\n", "You've got an answer on how to change the headers, but if you want to see the exact headers that are being used try using a proxy that displays the traffic. e.g. Fiddler2 on windows or see this question for some Linux altenatives.\n", "you ca...
[ 8, 2, 2 ]
[]
[]
[ "mechanize", "python" ]
stackoverflow_0003325052_mechanize_python.txt
Q: python mechanize proxy question I've got mechanize setup and working with python. I am adding support for using a proxy, but how do I check that I am actually using the proxy? Here is some code I am using: ip = 'some proxy ip address' br.set_proxies({"http://": ip} ) I started to wonder if it was working because just to do some testing I typed in: ip = 'asdfasdf' and it didn't throw an error. So how do I go about checking if it is really using the ip address for the proxy that I pass in or the ip address of my computer? Is there a way to return info on your ip in mechanize? A: maybe like this ? br = mechanize.Browser() br.set_proxies({"http": '127.0.0.1:80'}) you need to debug for more information br.set_debug_http(True) br.set_debug_redirects(True) A: I am not sure how to handle this issue with mechanize, but you could read the next link that explains how to do it without mechanize (but still in python): Proxy Check in python The simple solution provided at the above-mentioned link could be easily adapted to your needs. Thus, instead of the line: print "Connection error! (Check proxy)" you could replace by SucceededYesNo="NO" and instead of print "All was fine" just replace by SucceededYesNo="YES" Now, you have a variable available for further processing. I am however afraid this will not cover the cases when the target web page is down because the same error might occur out of two causes (so one would not know whether a NO outcome is coming from a not working proxy server or from a bad web page), but still could be a solution: what about to check with the above-mentioned code a working web page? i.e. www.google.com? In this way, you could eliminate one cause and it remains the other.
python mechanize proxy question
I've got mechanize setup and working with python. I am adding support for using a proxy, but how do I check that I am actually using the proxy? Here is some code I am using: ip = 'some proxy ip address' br.set_proxies({"http://": ip} ) I started to wonder if it was working because just to do some testing I typed in: ip = 'asdfasdf' and it didn't throw an error. So how do I go about checking if it is really using the ip address for the proxy that I pass in or the ip address of my computer? Is there a way to return info on your ip in mechanize?
[ "maybe like this ?\nbr = mechanize.Browser()\nbr.set_proxies({\"http\": '127.0.0.1:80'})\n\nyou need to debug for more information\nbr.set_debug_http(True)\nbr.set_debug_redirects(True)\n\n", "I am not sure how to handle this issue with mechanize, but you could read the next link that explains how to do it withou...
[ 2, 0 ]
[]
[]
[ "django", "mechanize", "proxy", "python" ]
stackoverflow_0002227117_django_mechanize_proxy_python.txt
Q: using unicode characters with wxPython i have a problem with wxpython and his rich text control, when I try to insert unicode characters... \xb2 prints an apex '2', '\u2074' should print an apex '4'... edit: I use windows vista... and I tried 'coding cp1252 ' and 'utf-8' but with the same result... 2edit: on vista it crashs, on xp it shows a strange square (i guess it's when the pc doesn't recognize the character...) here is the source code: from __future__ import unicode_literals import wx import wx.richtext as rt class Trial(wx.Frame):    def __init__(self):        wx.Frame.__init__(self, None, -1, 'Prova',                size=(400, 400))        self.rtc = rt.RichTextCtrl(self, style=wx.VSCROLL|wx.HSCROLL|wx.NO_BORDER)        wx.CallAfter(self.rtc.SetFocus)        #self.rtc.Freeze()        self.rtc.BeginFontSize(14)        self.rtc.WriteText('hei!\xb2') #alright        self.rtc.WriteText('hi\u2074!')#crash        self.rtc.EndFontSize()               if __name__ == '__main__':    app = wx.PySimpleApp()    frame = Trial()    frame.Show()    app.MainLoop() but when I try to run it, it crashs... Traceback (most recent call last):  File "<pyshell#6>", line 1, in <module>    frame = display.Trial()  File "C:\Users\expert\Desktop\display.py", line 15, in __init__    self.rtc.WriteText('hi\u2074!')  File "C:\Python26\lib\site-packages\wx-2.8-msw-ansi\wx\richtext.py", line 2507, in WriteText    return _richtext.RichTextCtrl_WriteText(*args, **kwargs)  File "C:\Python26\lib\encodings\cp1252.py", line 12, in encode    return codecs.charmap_encode(input,errors,encoding_table) UnicodeEncodeError: 'charmap' codec can't encode character u'\u2074' in position 4: character maps to <undefined> so...what should I do? I really need to show it... thanks everybody!! A: If you want Unicode support then you should be using the unicode version of wxpython. There are two versions of wxPython for each of the supported Python versions on Win32. They are nearly identical, except one of them has been compiled with support for the Unicode version of the platform APIs. Unless you've been told differently, you probably want to get the Unicode build of wxPython. Most other platforms also have two versions. It works fine if you pass the actual symbols e.g self.rtc.WriteText("hei!²") A: This can sometimes occur if you forget to set your encoding. Put this at the top of the code: # -*- encoding: utf-8 -*- before any code including comments but after the shebang (#!/usr/bin/python)
using unicode characters with wxPython
i have a problem with wxpython and his rich text control, when I try to insert unicode characters... \xb2 prints an apex '2', '\u2074' should print an apex '4'... edit: I use windows vista... and I tried 'coding cp1252 ' and 'utf-8' but with the same result... 2edit: on vista it crashs, on xp it shows a strange square (i guess it's when the pc doesn't recognize the character...) here is the source code: from __future__ import unicode_literals import wx import wx.richtext as rt class Trial(wx.Frame):    def __init__(self):        wx.Frame.__init__(self, None, -1, 'Prova',                size=(400, 400))        self.rtc = rt.RichTextCtrl(self, style=wx.VSCROLL|wx.HSCROLL|wx.NO_BORDER)        wx.CallAfter(self.rtc.SetFocus)        #self.rtc.Freeze()        self.rtc.BeginFontSize(14)        self.rtc.WriteText('hei!\xb2') #alright        self.rtc.WriteText('hi\u2074!')#crash        self.rtc.EndFontSize()               if __name__ == '__main__':    app = wx.PySimpleApp()    frame = Trial()    frame.Show()    app.MainLoop() but when I try to run it, it crashs... Traceback (most recent call last):  File "<pyshell#6>", line 1, in <module>    frame = display.Trial()  File "C:\Users\expert\Desktop\display.py", line 15, in __init__    self.rtc.WriteText('hi\u2074!')  File "C:\Python26\lib\site-packages\wx-2.8-msw-ansi\wx\richtext.py", line 2507, in WriteText    return _richtext.RichTextCtrl_WriteText(*args, **kwargs)  File "C:\Python26\lib\encodings\cp1252.py", line 12, in encode    return codecs.charmap_encode(input,errors,encoding_table) UnicodeEncodeError: 'charmap' codec can't encode character u'\u2074' in position 4: character maps to <undefined> so...what should I do? I really need to show it... thanks everybody!!
[ "If you want Unicode support then you should be using the unicode version of wxpython.\n\nThere are two versions of wxPython for\n each of the supported Python versions\n on Win32. They are nearly identical,\n except one of them has been compiled\n with support for the Unicode version\n of the platform APIs. U...
[ 2, 0 ]
[]
[]
[ "character", "python", "unicode", "wxpython" ]
stackoverflow_0003849817_character_python_unicode_wxpython.txt
Q: Using Python and Mechanize with ASP Forms I'm trying to submit a form on an .asp page but Mechanize does not recognize the name of the control. The form code is: <form id="form1" name="frmSearchQuick" method="post"> .... <input type="button" name="btSearchTop" value="SEARCH" class="buttonctl" onClick="uf_Browse('dledir_search_quick.asp');" > My code is as follows: br = mechanize.Browser() br.open(BASE_URL) br.select_form(name='frmSearchQuick') resp = br.click(name='btSearchTop') I've also tried the last line as: resp = br.submit(name='btSearchTop') The error I get is: raise ControlNotFoundError("no control matching "+description) ControlNotFoundError: no control matching name 'btSearchTop', kind 'clickable' If I print br I get this: IgnoreControl(btSearchTop=) But I don't see that anywhere in the HTML. Any advice on how to submit this form? A: The button doesn't submit the form - it calls some javascript function. Mechanize can't run javascript, so you can't use it to click that button. The easy way out is to read that function yourself, and see what it does - if it just submits the form, then maybe you can get around it by submitting the form without clicking on anything. A: you need to inspect element first, did mechanize recognize the form ? for form in br.forms(): print form
Using Python and Mechanize with ASP Forms
I'm trying to submit a form on an .asp page but Mechanize does not recognize the name of the control. The form code is: <form id="form1" name="frmSearchQuick" method="post"> .... <input type="button" name="btSearchTop" value="SEARCH" class="buttonctl" onClick="uf_Browse('dledir_search_quick.asp');" > My code is as follows: br = mechanize.Browser() br.open(BASE_URL) br.select_form(name='frmSearchQuick') resp = br.click(name='btSearchTop') I've also tried the last line as: resp = br.submit(name='btSearchTop') The error I get is: raise ControlNotFoundError("no control matching "+description) ControlNotFoundError: no control matching name 'btSearchTop', kind 'clickable' If I print br I get this: IgnoreControl(btSearchTop=) But I don't see that anywhere in the HTML. Any advice on how to submit this form?
[ "The button doesn't submit the form - it calls some javascript function.\nMechanize can't run javascript, so you can't use it to click that button.\nThe easy way out is to read that function yourself, and see what it does - if it just submits the form, then maybe you can get around it by submitting the form without...
[ 5, 0 ]
[]
[]
[ "asp_classic", "mechanize", "python" ]
stackoverflow_0002679595_asp_classic_mechanize_python.txt
Q: Filling textarea with Python mechanize module Is there a way to fill out textarea that is part of form using mechanize module for Python? A: The forms reference has a couple of examples of filling text controls in response objects. A relevant quote: # The kind argument can also take values "multilist", "singlelist", "text", # "clickable" and "file": # find first control that will accept text, and scribble in it form.set_value("rhubarb rhubarb", kind="text", nr=0) The kind argument can be used with the form.find_control() and form.set_value() methods to locate "text" controls. Digging a little into the mechanize _form.py source, We have an explanation. Mechanize TextControl covers (among others) the TEXTAREA form element. #--------------------------------------------------- class TextControl(ScalarControl): """Textual input control. Covers: INPUT/TEXT INPUT/PASSWORD INPUT/HIDDEN TEXTAREA """ def __init__(self, type, name, attrs, index=None): ScalarControl.__init__(self, type, name, attrs, index) if self.type == "hidden": self.readonly = True if self._value is None: self._value = "" def is_of_kind(self, kind): return kind == "text" A: You can do something like import mechanize br = mechanize.Browser() br.open("http://pypi.python.org/pypi") br.select_form("searchform") br['term'] = "Mechanize" response = br.submit() The br['term'] = "Mechanize" is the relevant line. And you seriously need to accept some answers on your questions. A: you can inspect element form first and how many forms in the page can be done with for form in br.forms(): print form
Filling textarea with Python mechanize module
Is there a way to fill out textarea that is part of form using mechanize module for Python?
[ "The forms reference has a couple of examples of filling text controls in response objects.\nA relevant quote:\n# The kind argument can also take values \"multilist\", \"singlelist\", \"text\",\n# \"clickable\" and \"file\":\n# find first control that will accept text, and scribble in it\nform.set_value(\"rhubarb ...
[ 6, 6, 1 ]
[]
[]
[ "mechanize", "python", "textarea" ]
stackoverflow_0002881121_mechanize_python_textarea.txt
Q: Convert gzipped data fetched by urllib2 to HTML I currently use mechanize to read gzipped web page as below: br = mechanize.Browser() br.set_handle_gzip(True) response = br.open(url) data = response.read() I wonder how to decompress gzipped data fetched by urllib2 to HTML text? req = urllib2.Request(url) opener = urllib2.build_opener() response = opener.open(req) data = response.read() if response.info()['content-encoding'] == 'gzip': HOW TO DECOMPRESS DATA TO HTML A: Try this: import StringIO data = StringIO.StringIO(data) import gzip gzipper = gzip.GzipFile(fileobj=data) html = gzipper.read() html should now hold the HTML (Print it to see). See here for more info.
Convert gzipped data fetched by urllib2 to HTML
I currently use mechanize to read gzipped web page as below: br = mechanize.Browser() br.set_handle_gzip(True) response = br.open(url) data = response.read() I wonder how to decompress gzipped data fetched by urllib2 to HTML text? req = urllib2.Request(url) opener = urllib2.build_opener() response = opener.open(req) data = response.read() if response.info()['content-encoding'] == 'gzip': HOW TO DECOMPRESS DATA TO HTML
[ "Try this:\nimport StringIO\ndata = StringIO.StringIO(data)\nimport gzip\ngzipper = gzip.GzipFile(fileobj=data)\nhtml = gzipper.read()\n\nhtml should now hold the HTML (Print it to see). See here for more info.\n" ]
[ 14 ]
[ "def ungzip(r,b):\n headers = r.info()\n if ('Content-Encoding' in headers.keys() and headers['Content-Encoding']=='gzip') or \\\n ('content-encoding' in headers.keys() and headers['content-encoding']=='gzip'):\n import gzip\n gz = gzip.GzipFile(fileobj=r, mode='rb')\n html = gz.rea...
[ -2 ]
[ "gzip", "python", "urllib2" ]
stackoverflow_0001704754_gzip_python_urllib2.txt
Q: Handling errors in Python scripts Using pyblog.py, I got the following error, which I then tried to more gracefully handle: Traceback (most recent call last): File "C:\Python26\Lib\SITE-P~1\PYTHON~1\pywin\framework\scriptutils.py", line 325, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\mmorisy\Desktop\My Dropbox\python\betterblogmaster.py", line 11, in <module> date = blogurl.get_recent_posts(1)[0]['dateCreated'] File "C:\Documents and Settings\mmorisy\Desktop\My Dropbox\python\pyblog.py", line 129, in get_recent_posts return self.execute('metaWeblog.getRecentPosts', blogid, self.username, self.password, numposts) File "C:\Documents and Settings\mmorisy\Desktop\My Dropbox\python\pyblog.py", line 93, in execute raise BlogError(fault.faultString) BlogError: XML-RPC services are disabled on this blog. An admin user can enable them at http://example.com/blogname/wp-admin/options-writing.php >>> So I tried the following code to without crashing the script: for blog in bloglist: try: blogurl = pyblog.WordPress('http://example.com' + blog + 'xmlrpc.php', 'admin', 'laxbro24') date = blogurl.get_recent_posts(1)[0]['dateCreated'] print blog + ', ' + str(date.timetuple().tm_mon) + '/' + str(date.timetuple().tm_mday) + '/' + str(date.timetuple().tm_year) except BlogError: print "Oops! The blog at " + blogurl + " is not configured properly." Only to get the following error: Traceback (most recent call last): File "C:\Python26\Lib\SITE-P~1\PYTHON~1\pywin\framework\scriptutils.py", line 325, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\mmorisy\Desktop\My Dropbox\python\betterblogmaster.py", line 13, in <module> except BlogError: NameError: name 'BlogError' is not defined Isn't the name blog error defined by PyBlog, since that's where I got that name in the first place? Am I using "except" wrong? Thanks for any tips! A: Yes, it is using BlogError, but you have not imported BlogError into your namespace to reference. You instead want to be using pyblog.BlogError: for blog in bloglist: try: blogurl = pyblog.WordPress('http://example.com' + blog + 'xmlrpc.php', 'admin', 'laxbro24') date = blogurl.get_recent_posts(1)[0]['dateCreated'] print blog + ', ' + str(date.timetuple().tm_mon) + '/' + str(date.timetuple().tm_mday) + '/' + str(date.timetuple().tm_year) except pyblog.BlogError: print "Oops! The blog at " + blogurl + " is not configured properly." Remember that exceptions follow the same rules of scoping that any python object does. A: Your except is syntactically correct. And yet it fails because you haven't explicitly imported the BlogError exception class into your program's namespace. To fix this explicitly import the BlogError class. For e.g. from pyblog import BlogError try: ... except BlogError: ... A: the code will be from pyblog import BlogError
Handling errors in Python scripts
Using pyblog.py, I got the following error, which I then tried to more gracefully handle: Traceback (most recent call last): File "C:\Python26\Lib\SITE-P~1\PYTHON~1\pywin\framework\scriptutils.py", line 325, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\mmorisy\Desktop\My Dropbox\python\betterblogmaster.py", line 11, in <module> date = blogurl.get_recent_posts(1)[0]['dateCreated'] File "C:\Documents and Settings\mmorisy\Desktop\My Dropbox\python\pyblog.py", line 129, in get_recent_posts return self.execute('metaWeblog.getRecentPosts', blogid, self.username, self.password, numposts) File "C:\Documents and Settings\mmorisy\Desktop\My Dropbox\python\pyblog.py", line 93, in execute raise BlogError(fault.faultString) BlogError: XML-RPC services are disabled on this blog. An admin user can enable them at http://example.com/blogname/wp-admin/options-writing.php >>> So I tried the following code to without crashing the script: for blog in bloglist: try: blogurl = pyblog.WordPress('http://example.com' + blog + 'xmlrpc.php', 'admin', 'laxbro24') date = blogurl.get_recent_posts(1)[0]['dateCreated'] print blog + ', ' + str(date.timetuple().tm_mon) + '/' + str(date.timetuple().tm_mday) + '/' + str(date.timetuple().tm_year) except BlogError: print "Oops! The blog at " + blogurl + " is not configured properly." Only to get the following error: Traceback (most recent call last): File "C:\Python26\Lib\SITE-P~1\PYTHON~1\pywin\framework\scriptutils.py", line 325, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\mmorisy\Desktop\My Dropbox\python\betterblogmaster.py", line 13, in <module> except BlogError: NameError: name 'BlogError' is not defined Isn't the name blog error defined by PyBlog, since that's where I got that name in the first place? Am I using "except" wrong? Thanks for any tips!
[ "Yes, it is using BlogError, but you have not imported BlogError into your namespace to reference. You instead want to be using pyblog.BlogError:\nfor blog in bloglist:\n try:\n blogurl = pyblog.WordPress('http://example.com' + blog + 'xmlrpc.php', 'admin', 'laxbro24')\n date = blogurl.get_recent_p...
[ 5, 2, 2 ]
[]
[]
[ "python", "wordpress", "xml" ]
stackoverflow_0003850077_python_wordpress_xml.txt
Q: Jython - attempting to call functions from JFrame, receiving 'NoneType' error So I'm playing around with Jython, trying to slap together a generic GUI. Nothing beyond what they have on the Jython Wiki for swing examples. So I declare a JFrame, and then try to add a panel, some text fields, all that good stuff. I get this error when I run it, however. "'NoneType' object has no attribute 'add'" Here's the basic code I have. from javax.swing import * frame = JFrame('E-mail Gathering', defaultCloseOperation = JFrame.EXIT_ON_CLOSE, size =(600,400), locationRelativeTo = None).setVisible(True) pnl = JPanel() frame.add(pnl) self.textfield1 = JTextField('username:',15) pnl.add(self.textfield1) self.textfield2 = JTextField('password:', 15) pnl.add(self.textfield2) mailButton = JButton('Login',actionPerformed=self.checkmail) pnl.add(mailButton) frame.pack() frame.setVisible(True) I know the relevant part where it's crashing is at 'frame.add(pnl)' with the aforementioned error. I figured I'd throw the rest up there just in case I'm making some even greater mistakes. I feel like something's wrong where I'm not declaring frame as a JFrame properly, but I know that's not the case because it creates the frame just fine if I don't try to add anything to it. Thanks for any advice or suggestions you have. A: In this line: frame = JFrame('E-mail Gathering', defaultCloseOperation = JFrame.EXIT_ON_CLOSE, size =(600,400), locationRelativeTo = None).setVisible(True) you are creating a JFrame, calling its setVisible method, and assigning the return value of setVisible to frame. setVisible doesn't return a value, so frame is None. This causes frame.add to fail. As you call setVisible at the end anyway, and because you probably don't want to make the frame visible before you have added other components to it and called pack, just remove the setVisible call: frame = JFrame('E-mail Gathering', defaultCloseOperation = JFrame.EXIT_ON_CLOSE, size =(600,400), locationRelativeTo = None)
Jython - attempting to call functions from JFrame, receiving 'NoneType' error
So I'm playing around with Jython, trying to slap together a generic GUI. Nothing beyond what they have on the Jython Wiki for swing examples. So I declare a JFrame, and then try to add a panel, some text fields, all that good stuff. I get this error when I run it, however. "'NoneType' object has no attribute 'add'" Here's the basic code I have. from javax.swing import * frame = JFrame('E-mail Gathering', defaultCloseOperation = JFrame.EXIT_ON_CLOSE, size =(600,400), locationRelativeTo = None).setVisible(True) pnl = JPanel() frame.add(pnl) self.textfield1 = JTextField('username:',15) pnl.add(self.textfield1) self.textfield2 = JTextField('password:', 15) pnl.add(self.textfield2) mailButton = JButton('Login',actionPerformed=self.checkmail) pnl.add(mailButton) frame.pack() frame.setVisible(True) I know the relevant part where it's crashing is at 'frame.add(pnl)' with the aforementioned error. I figured I'd throw the rest up there just in case I'm making some even greater mistakes. I feel like something's wrong where I'm not declaring frame as a JFrame properly, but I know that's not the case because it creates the frame just fine if I don't try to add anything to it. Thanks for any advice or suggestions you have.
[ "In this line:\nframe = JFrame('E-mail Gathering', defaultCloseOperation = JFrame.EXIT_ON_CLOSE, size =(600,400), locationRelativeTo = None).setVisible(True)\n\nyou are creating a JFrame, calling its setVisible method, and assigning the return value of setVisible to frame. setVisible doesn't return a value, so fram...
[ 1 ]
[]
[]
[ "jython", "python", "swing" ]
stackoverflow_0003850144_jython_python_swing.txt
Q: Why won't the len() function output anything in python 3.1.2? I installed the 3.1.2 IDLE python console, then I entered this code: >>> a = ['a', 'b', 'c', 'd'] >>> len(a) 4 Directly from the python official docs http://docs.python.org/py3k/tutorial/introduction.html#lists But it does not work in the interpreter as it should, it does not return 4. What am I doing wrong? Are the official docs wrong? I've looked in a few other sites but many are talking about Python 2.x. A: There is no bug; you have misunderstood what should happen. Python can be called interactively (by running python.exe at the prompt). This mode automatically prints the result of a line when it is finished, for ease of reading/debugging. However, it's not very useful for writing any serious amount of code. The way do to that is to put the code in a script (a plain text file with a .py ending on Windows) and call the script with python.exe foo.py. In this case, something else happens: Python executes the script and does not automatically print the result of every line. That's what the print function/statement is for. Write print(len(a)) instead. Note that this has nothing to do with the version of Python you are using.
Why won't the len() function output anything in python 3.1.2?
I installed the 3.1.2 IDLE python console, then I entered this code: >>> a = ['a', 'b', 'c', 'd'] >>> len(a) 4 Directly from the python official docs http://docs.python.org/py3k/tutorial/introduction.html#lists But it does not work in the interpreter as it should, it does not return 4. What am I doing wrong? Are the official docs wrong? I've looked in a few other sites but many are talking about Python 2.x.
[ "There is no bug; you have misunderstood what should happen.\nPython can be called interactively (by running python.exe at the prompt). This mode automatically prints the result of a line when it is finished, for ease of reading/debugging. However, it's not very useful for writing any serious amount of code.\nThe w...
[ 6 ]
[]
[]
[ "list", "python" ]
stackoverflow_0003850098_list_python.txt
Q: Google App Engine counters For all my data in the GAE Datastore I have a model for keeping track of counters/total number of records (since we can't use traditional SUM queries). I want to know the most efficient way of incrementing these global count values whenever I insert/delete a record. This is what I'm currently doing: counter = DBCounter.all().fetch(1) dbc = DBCounter(totalTopics=counter[0].totalTopics+1) dbc.put() But this seems quite sloppy to me. Any thoughts on a better way to do this? A: There are a few issues with your approach: It may under-count since you don't use a transaction to atomically update the counter. It is inefficient: Contention may become a problem if you need to update this counter frequently. Since you only have one counter, it won't scale well. Datastore entities can only be written at a rate of at most 5 times per second. You're writing to the datastore twice every time you insert a record. If you end up using transactions to fix the above problem, then you'll be making two round-trips to the datastore every time you insert the record (once to insert, and once to update the counter). You might be able to use an approach which avoids this extra round-trip to the datastore. Here are some alternate approaches (from least accurate [and fastest] to most accurate [and slowest]): If you only need a rough count of the number of entities of particular kind in the datastore, then you can use the Stats API. The counts you retrieve are not constantly updated, however. If you need more granularity but are okay with a small possibility of occasionally under-counting, then you could use a memcache-enhanced counter. There are several good implementations discussed in this question. In particular, see the code in the comments in this recipe. If you really want to avoid undercounting, then you should consider a sharded datastore counter. This will eliminate the contention issue from above. A: If you need to keep scalability while counting, you should look into Joe Gregorio's article on sharding counters and DocSavage's implementation of the idea. AppEngineFan's excellent blog also has info on scalable non-sharded counters, see this one which uses task queues and points to the previous article on using cron jobs instead.
Google App Engine counters
For all my data in the GAE Datastore I have a model for keeping track of counters/total number of records (since we can't use traditional SUM queries). I want to know the most efficient way of incrementing these global count values whenever I insert/delete a record. This is what I'm currently doing: counter = DBCounter.all().fetch(1) dbc = DBCounter(totalTopics=counter[0].totalTopics+1) dbc.put() But this seems quite sloppy to me. Any thoughts on a better way to do this?
[ "There are a few issues with your approach:\n\nIt may under-count since you don't use a transaction to atomically update the counter.\nIt is inefficient: \n\n\nContention may become a problem if you need to update this counter frequently. Since you only have one counter, it won't scale well. Datastore entities ca...
[ 5, 4 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python", "transactions" ]
stackoverflow_0003850180_google_app_engine_google_cloud_datastore_python_transactions.txt
Q: Replacing a single color in PIL? I have an Image, I'd like to replace all the pixels of one color with those in a different color, what is the simplest way to go about that? More or less I have an image in tkinter, and when a button is pressed I want the color to change. A: try this. #!/usr/bin/python from PIL import Image import sys img = Image.open(sys.argv[1]) img = img.convert("RGBA") pixdata = img.load() # Clean the background noise, if color != white, then set to black. for y in xrange(img.size[1]): for x in xrange(img.size[0]): if pixdata[x, y] == (255, 255, 255, 255): pixdata[x, y] = (0, 0, 0, 255) you can use color picker in gimp to absorb the color and see that's rgba color A: I think that the fastest way to do that is to use the Image.load() method. Something like this should work: from PIL import Image im = Image.open("image.jpg") image_data = im.load() # Here you have access to the RGB color of each pixel # image_data[x,y] = (R,G,B)
Replacing a single color in PIL?
I have an Image, I'd like to replace all the pixels of one color with those in a different color, what is the simplest way to go about that? More or less I have an image in tkinter, and when a button is pressed I want the color to change.
[ "try this.\n#!/usr/bin/python\nfrom PIL import Image\nimport sys\n\nimg = Image.open(sys.argv[1])\nimg = img.convert(\"RGBA\")\n\npixdata = img.load()\n\n# Clean the background noise, if color != white, then set to black.\n\nfor y in xrange(img.size[1]):\n for x in xrange(img.size[0]):\n if pixdata[x, y] ...
[ 4, 3 ]
[]
[]
[ "python", "python_imaging_library", "tkinter" ]
stackoverflow_0003169384_python_python_imaging_library_tkinter.txt
Q: python string is default global I have a question about global variable in Python. The code is following. If I do not use global M in function test, It would issue error. But Why it does not show error for string s. I do not declare it as global. global M M = [] s = "abc" def test(): ### global M print M M.append(s) print M UnboundLocalError: local variable 'M' referenced before assignment A: If I do not use global M in function test, It would issue error. This statement of yours is simply not true!!! >>> M = [] >>> s = "abc" >>> >>> def test(): ... M.append(s) ... >>> M [] >>> test() >>> M ['abc'] I think you're confusing two utterly and completely different concepts: binding a barename -- usually by assignment (i.e. =), but also possibly by a few other statements (def, &c) calling a method (such as append) which "may" happen to mutate the object (only if that object is mutable and the method is a mutator of course, but that does apply when the object is a list and the method is append) I'm not sure why people can confuse the two poles-apart concepts, but, they surely can. Maybe it's the fact that some non-plain-vanilla "kinds" of assignment are actually calling a (special) method "behind the curtains", e.g., assignment to qualified names (a.b=c is actually calling type(a).__setitem__(a, b), so, calling a method, not rebinding any barename) and augmented assignment (a+=b is actually doing a = type(a).__iadd__(a, b), so, both calling a method and rebinding a barename). You need global (alas) if and only if you're doing "1": rebinding a barename (including rebinding it by augmented assignment but not including any other special case). Eschew global unless it's really indispensable (and many would say it's never truly indispensable... just "apparently kind of handy" in some cases;-). A: I'm not quite sure what error you would be getting, but you seem to be using global wrong. The global keyword is not required (or recommended) for declaring globals. It is instead used inside a function to specify that a local variable should not be created. Consider the 2 different functions: M = [] def test1(): M = [1] def test2(): global M M = [2] test1 will create a new local variable, while test2 will write to the global M A: As @Alex Martelli pointed out your code as shown doesn't produce an error, but putting that aside for now to build on @cobbal's answer (sorry I cannot comment yet) you need to be really careful when it comes to the scope here In @cobbal's answer: def test1(): M = [1] creates a new variable M local to the function test1. However, if instead of doing an assignment M = [1] he had used M.append(1), as was done in the question, instead of creating a new local variable Python would look up from the local scope of the function into the higher scopes, in this case the global scope where there is indeed already a variable M which points to an empty list. In this case Python will find this variable and simply append to the existing list resulting in global M now pointing to [1]. In the second example: def test2(): global M M = [2] The use of the global keyword is essential to avoid the local assignment which would otherwise occur. By invoking global use of M in the local scope of the function will point to the already existing [] object outside of the function. You can prove this to yourself by inserting id(M) into the various forms of the function to show which implementations cause the M inside the function to point to a global or local object.
python string is default global
I have a question about global variable in Python. The code is following. If I do not use global M in function test, It would issue error. But Why it does not show error for string s. I do not declare it as global. global M M = [] s = "abc" def test(): ### global M print M M.append(s) print M UnboundLocalError: local variable 'M' referenced before assignment
[ "\nIf I do not use global M in function\n test, It would issue error.\n\nThis statement of yours is simply not true!!!\n>>> M = []\n>>> s = \"abc\"\n>>> \n>>> def test():\n... M.append(s)\n... \n>>> M\n[]\n>>> test()\n>>> M\n['abc']\n\nI think you're confusing two utterly and completely different concepts:\n\n...
[ 6, 3, 0 ]
[]
[]
[ "global", "python", "scope", "string" ]
stackoverflow_0003840349_global_python_scope_string.txt
Q: Where do you get Python SOAPPy forwindows? I can't seem to install it, computer doesn't know what to open it with, is there something wrong? Do you know a website where I can install it? A: SOAPPy is now part of Python Web Services. You can get it from the Python Web Services page at sourceforge.
Where do you get Python SOAPPy forwindows?
I can't seem to install it, computer doesn't know what to open it with, is there something wrong? Do you know a website where I can install it?
[ "SOAPPy is now part of Python Web Services. You can get it from the Python Web Services page at sourceforge. \n" ]
[ 0 ]
[]
[]
[ "python", "soappy" ]
stackoverflow_0003850545_python_soappy.txt
Q: Encrypting a Sqlite db file that will be bundled in a pyexe file I have been working on developing this analytical tool to help interpret and analyze a database that is bundled within the package. It is very important for us to secure the database in a way that can only be accessed with our software. What is the best way of achieving it in Python? I am aware that there may not be a definitive solution, but deterrence is what really matters here. Thank you very much. A: Someone has gotten Python and SQLCipher working together by rebuilding SQLCipher as a DLL and replacing Python's sqlite3.dll here. A: This question comes up on the SQLite users mailing list about once a month. No matter how much encryption etc you do, if the database is on the client machine then the key to decrypt will also be on the machine at some point. An attacker will be able to get that key since it is their machine. A better way of looking at this is in terms of money - how much would a bad guy need to spend in order to get the data. This will generally be a few hundred dollars at most. And all it takes is any one person to get the key and they can then publish the database for everyone. So either go for a web service as mentioned by Donal or just spend a few minutes obfuscating the database. For example if you use APSW then you can write a VFS in a few lines that XORs the database content so regular SQLite will not open it, nor will a file viewer show the normal SQLite header. (There is example code in APSW showing how to do this.) Consequently anyone who does have the database content had to knowingly do so.
Encrypting a Sqlite db file that will be bundled in a pyexe file
I have been working on developing this analytical tool to help interpret and analyze a database that is bundled within the package. It is very important for us to secure the database in a way that can only be accessed with our software. What is the best way of achieving it in Python? I am aware that there may not be a definitive solution, but deterrence is what really matters here. Thank you very much.
[ "Someone has gotten Python and SQLCipher working together by rebuilding SQLCipher as a DLL and replacing Python's sqlite3.dll here.\n", "This question comes up on the SQLite users mailing list about once a month.\nNo matter how much encryption etc you do, if the database is on the client machine then the key to d...
[ 5, 3 ]
[]
[]
[ "database", "encryption", "python", "sqlite" ]
stackoverflow_0003848658_database_encryption_python_sqlite.txt
Q: Multiple visualizations in one page I am using python-visualization library for computing the datasource. I tried to put more than one visualization in a single page. Both are line charts and data comes from a seperate URLs for each visualizations. <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript" src="/site_media/js/jquery-1.2.6.min.js"></script> <script type="text/javascript"> google.load('visualization', '1', { packages: ['linechart'] }); </script> <script type="text/javascript"> var visualization1, visualization2; function drawVisualization1() { var query1 = new google.visualization.Query('/datasource1/'); query1.send(handleQueryResponse1); var query2 = new google.visualization.Query('/datasource2/'); query2.send(handleQueryResponse2); } function handleQueryResponse1(response) { if (response.isError()) { alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage()); return; } var data1 = response.getDataTable(); visualization1 = new google.visualization.LineChart(document.getElementById('visualization1')); var options = {}; options['width'] = 600; options['height'] = 200; visualization1.draw(data1, options); } function handleQueryResponse2(response) { if (response.isError()) { alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage()); return; } var data2 = response.getDataTable(); visualization2 = new google.visualization.LineChart(document.getElementById('visualization2')); var options = {}; options['width'] = 600; options['height'] = 200; visualization2.draw(data2, options); } google.setOnLoadCallback(drawVisualization1); </script> <body> <div id="visualization1" class="span-15"><br /><br /></div> <div id="visualization2" class="span-15"><br /><br /></div> </body> Datasources: def datasource1(request): data = [] description = {"col1": ("number", "col1"),"col2": ("number", "col2"),} for i in range(datetime.today().hour + 1): data.append({"col1":datetime.today().hour,"col2":datetime.today().hour }) data_table = gviz_api.DataTable(description) data_table.LoadData(data) return HttpResponse(data_table.ToJSonResponse(columns_order=( "col1","col2",))) def datasource2(request): data = [] description = {"col1": ("number", "col1"),"col2": ("number", "col2"),} for i in range(datetime.today().hour + 1): data.append({"col1":datetime.today().hour,"col2":datetime.today().hour }) data_table = gviz_api.DataTable(description) data_table.LoadData(data) return HttpResponse(data_table.ToJSonResponse(columns_order=( "col1","col2",))) When I render the page only the first visualization comes up , the second visualization never appears. Can some one help me out? A: You can try something like function Charts(){ var self = this; self.chart = []; self.settings = { width: 650, height: 250 }; self.add = function(type, element, dataTable, options){ self.chart.push({ o: new google.visualization[type]($(element)[0]), data: dataTable, draw: function(){ var settings = $.extend({}, self.settings, options); this.o.draw(this.data, settings); } }); return self; }; self.draw = function(){ $.each(self.chart, function(i, chart){ chart.draw(); }); return self; }; } and then //var data1 = 'someDataTable', // data2 = 'anotherDataTable'; charts = new Charts(); var settings = {width:600, height:200 }; charts.add('LineChart', '#visualization1', settings, data1); charts.add('LineChart', '#visualization2', settings, data2); charts.draw(); Sorry, havn't tested myself, just thought it can help you. And I'll advice is to load from Google jQuery as well. google.load("jquery", "1.2.6"); Hope it'll help you :) A: Happened to me too. The solution was for the server to return the reqId parameter. If you have two visualizations on the same page, one will have reqId 0 and the other reqId 1. make sure the server returns those reqIds back appropriately in the response. If both responses return '0' then only one visualization will render (the first one).
Multiple visualizations in one page
I am using python-visualization library for computing the datasource. I tried to put more than one visualization in a single page. Both are line charts and data comes from a seperate URLs for each visualizations. <script type="text/javascript" src="http://www.google.com/jsapi"></script> <script type="text/javascript" src="/site_media/js/jquery-1.2.6.min.js"></script> <script type="text/javascript"> google.load('visualization', '1', { packages: ['linechart'] }); </script> <script type="text/javascript"> var visualization1, visualization2; function drawVisualization1() { var query1 = new google.visualization.Query('/datasource1/'); query1.send(handleQueryResponse1); var query2 = new google.visualization.Query('/datasource2/'); query2.send(handleQueryResponse2); } function handleQueryResponse1(response) { if (response.isError()) { alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage()); return; } var data1 = response.getDataTable(); visualization1 = new google.visualization.LineChart(document.getElementById('visualization1')); var options = {}; options['width'] = 600; options['height'] = 200; visualization1.draw(data1, options); } function handleQueryResponse2(response) { if (response.isError()) { alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage()); return; } var data2 = response.getDataTable(); visualization2 = new google.visualization.LineChart(document.getElementById('visualization2')); var options = {}; options['width'] = 600; options['height'] = 200; visualization2.draw(data2, options); } google.setOnLoadCallback(drawVisualization1); </script> <body> <div id="visualization1" class="span-15"><br /><br /></div> <div id="visualization2" class="span-15"><br /><br /></div> </body> Datasources: def datasource1(request): data = [] description = {"col1": ("number", "col1"),"col2": ("number", "col2"),} for i in range(datetime.today().hour + 1): data.append({"col1":datetime.today().hour,"col2":datetime.today().hour }) data_table = gviz_api.DataTable(description) data_table.LoadData(data) return HttpResponse(data_table.ToJSonResponse(columns_order=( "col1","col2",))) def datasource2(request): data = [] description = {"col1": ("number", "col1"),"col2": ("number", "col2"),} for i in range(datetime.today().hour + 1): data.append({"col1":datetime.today().hour,"col2":datetime.today().hour }) data_table = gviz_api.DataTable(description) data_table.LoadData(data) return HttpResponse(data_table.ToJSonResponse(columns_order=( "col1","col2",))) When I render the page only the first visualization comes up , the second visualization never appears. Can some one help me out?
[ "You can try something like \nfunction Charts(){\n var self = this;\n self.chart = [];\n self.settings = { width: 650, height: 250 };\n self.add = function(type, element, dataTable, options){\n self.chart.push({\n o: new google.visualization[type]($(element)[0]),\n data: dat...
[ 0, 0 ]
[]
[]
[ "django", "google_visualization", "javascript", "jquery", "python" ]
stackoverflow_0001448638_django_google_visualization_javascript_jquery_python.txt
Q: Google Chart API: trouble with rendering a XYLine graph I'm trying to make an XYLine with the Google Chart API via the not-so-well-documented GChartWrapper libraries. Here's a portion of the code that is supposed to generate the graph: data = [] traffic_max = 0 date_minmax = [] #I have a number of timestamped readings in two series for site in sites: site_data = get_datapoints_for(site) date_values = [datetime_to_unix(item.timestamp) for item in site_data] date_minmax = minmax(date_minmax + date_values) #get min and max values for #scaling traffic_values = [item.traffic for item in site_data] traffic_max = max(traffic_max, *traffic_values) #just get maximum for readings #build graph data.append(date_values) data.append(traffic_values) #add leeway to axes date_minmax[0] -= 500 date_minmax[1] += 500 traffic_max /= 0.9 #build graph chart = LineXY(data) chart.legend(*sites) chart.color("green", "red") chart.size(600,400) chart.scale(date_minmax[0], date_minmax[1], 0, traffic_max) chart.axes.type("xy") chart.axes.range(0, *date_minmax) chart.axes.range(1, 0, traffic_max) chart_url = chart.url However, this is what I get: Question: What happened to the red series? For your convenience, here is data after some pretty print love: [[1286116241.448437, 1286118544.4077079, 1286119431.18503, 1286121011.5838161], [6710.9899999999998, 6716.2799999999997, 6641.8900000000003, 6644.9499999999998], [1286116241.979831, 1286118545.0123601, 1286119431.9650409, 1286121012.1839011], [38323.860000000001, 38326.620000000003, 38327.660000000003, 38329.610000000001]] Here is the list of parameters generated by the wrapper, also after some pretty print love: chco=008000,FF0000 chd=t:1286116241.0,1286118544.0,1286119431.0,1286121011.0 6711.0,6716.3,6641.9,6644.9 1286116241.0,1286118545.0,1286119431.0,1286121012.0 38323.9,38326.6,38327.7,38329.6 chdl=gaming.stackexchange.com serverfault.com chds=1286115741.0,1286121512.0,0,42588.4555556 chs=600x400 cht=lxy chxr=0,1286115741.0,1286121512.0 1,0,42588.4555556 chxt=x,y cht=lxy chxr=0,1286116241.45,1286121012.18 1,0,42588.4555556 chxt=x,y A: The problem was here: chart.scale(date_minmax[0], date_minmax[1], 0, traffic_max) The Google API allows you to define a different scale per each series. Thus, you need to specify the scaling for each series, whereas the above only affected the first series. Changing that line to: chart.scale(*[date_minmax[0], date_minmax[1], 0, traffic_max]*len(sites)) ...forces all series to the same scaling.
Google Chart API: trouble with rendering a XYLine graph
I'm trying to make an XYLine with the Google Chart API via the not-so-well-documented GChartWrapper libraries. Here's a portion of the code that is supposed to generate the graph: data = [] traffic_max = 0 date_minmax = [] #I have a number of timestamped readings in two series for site in sites: site_data = get_datapoints_for(site) date_values = [datetime_to_unix(item.timestamp) for item in site_data] date_minmax = minmax(date_minmax + date_values) #get min and max values for #scaling traffic_values = [item.traffic for item in site_data] traffic_max = max(traffic_max, *traffic_values) #just get maximum for readings #build graph data.append(date_values) data.append(traffic_values) #add leeway to axes date_minmax[0] -= 500 date_minmax[1] += 500 traffic_max /= 0.9 #build graph chart = LineXY(data) chart.legend(*sites) chart.color("green", "red") chart.size(600,400) chart.scale(date_minmax[0], date_minmax[1], 0, traffic_max) chart.axes.type("xy") chart.axes.range(0, *date_minmax) chart.axes.range(1, 0, traffic_max) chart_url = chart.url However, this is what I get: Question: What happened to the red series? For your convenience, here is data after some pretty print love: [[1286116241.448437, 1286118544.4077079, 1286119431.18503, 1286121011.5838161], [6710.9899999999998, 6716.2799999999997, 6641.8900000000003, 6644.9499999999998], [1286116241.979831, 1286118545.0123601, 1286119431.9650409, 1286121012.1839011], [38323.860000000001, 38326.620000000003, 38327.660000000003, 38329.610000000001]] Here is the list of parameters generated by the wrapper, also after some pretty print love: chco=008000,FF0000 chd=t:1286116241.0,1286118544.0,1286119431.0,1286121011.0 6711.0,6716.3,6641.9,6644.9 1286116241.0,1286118545.0,1286119431.0,1286121012.0 38323.9,38326.6,38327.7,38329.6 chdl=gaming.stackexchange.com serverfault.com chds=1286115741.0,1286121512.0,0,42588.4555556 chs=600x400 cht=lxy chxr=0,1286115741.0,1286121512.0 1,0,42588.4555556 chxt=x,y cht=lxy chxr=0,1286116241.45,1286121012.18 1,0,42588.4555556 chxt=x,y
[ "The problem was here:\nchart.scale(date_minmax[0], date_minmax[1], 0, traffic_max)\n\nThe Google API allows you to define a different scale per each series. Thus, you need to specify the scaling for each series, whereas the above only affected the first series.\nChanging that line to:\nchart.scale(*[date_minmax[0]...
[ 0 ]
[]
[]
[ "google_visualization", "python" ]
stackoverflow_0003850561_google_visualization_python.txt
Q: Editing values in a xml file with Python Hey. I want to have a config.xml file for settings in a Python web app. I made car.xml manually. It looks like this: <car> <lights> <blinkers>off</blinkers> </lights> </car> Now I want to see whether the blinkers are on or off, using xml.etree.ElementTree. import xml.etree.ElementTree as ET tree = ET.parse('car.xml') blinkers = tree.findtext('lights/blinkers') print blinkers > off Now I want to turn the blinkers on and off, how can I do this? A: You can remove nodes by calling the parent node's remove method, and insert nodes by calling ET.SubElement: import xml.etree.ElementTree as ET def flip_lights(tree): lights = tree.find('lights') state=get_blinker(tree) blinkers = tree.find('lights/blinkers') lights.remove(blinkers) new_blinkers = ET.SubElement(lights, "blinkers") new_blinkers.text='on' if state=='off' else 'off' def get_blinker(tree): blinkers = tree.find('lights/blinkers') return blinkers.text tree = ET.parse('car.xml') print(get_blinker(tree)) # off flip_lights(tree) print(get_blinker(tree)) # on flip_lights(tree) print(get_blinker(tree)) # off flip_lights(tree) print(get_blinker(tree)) # on tree.write('car2.xml') A: Without addressing the merits of using XML instead of a Python module for managing configuration files, here's how to do what you asked using lxml: >>> from lxml import etree >>> xml = """<car> <lights> <blinkers>on</blinkers> </lights> </car>""" >>> doc = etree.fromstring(xml) >>> elm = doc.xpath("/car/lights/blinkers")[0] >>> elm.text="off" >>> etree.tostring(doc) '<car>\n <lights>\n <blinkers>off</blinkers>\n </lights>\n</car>' A: Take a look at this article. But consider AaronMcSmooth's comment above -- this may be the wrong approach to your overall problem. A: Use beautifulstonesoup. Here is the section on modifying xml: http://www.crummy.com/software/BeautifulSoup/documentation.html#Modifying%20the%20Parse%20Tree A: XML is a rather poor way of storing configuration settings. For one, XML is not exactly human friendly in the context of settings. In the Python universe in particular you are better off using a settings module (as @AaronMcSmooth commented). Unfortunately a lot of projects in the Java world have (mis?)used XML for settings thereby making it a trend. I'd argue that this trend really sucks. Use native settings (module in Python) or something more human friendly like YAML.
Editing values in a xml file with Python
Hey. I want to have a config.xml file for settings in a Python web app. I made car.xml manually. It looks like this: <car> <lights> <blinkers>off</blinkers> </lights> </car> Now I want to see whether the blinkers are on or off, using xml.etree.ElementTree. import xml.etree.ElementTree as ET tree = ET.parse('car.xml') blinkers = tree.findtext('lights/blinkers') print blinkers > off Now I want to turn the blinkers on and off, how can I do this?
[ "You can remove nodes by calling the parent node's remove method,\nand insert nodes by calling ET.SubElement:\nimport xml.etree.ElementTree as ET\n\ndef flip_lights(tree):\n lights = tree.find('lights')\n state=get_blinker(tree)\n blinkers = tree.find('lights/blinkers')\n lights.remove(blinkers)\n ne...
[ 2, 2, 1, 0, 0 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0003849976_elementtree_python_xml.txt
Q: Python multiprocessing I have a "master" process that needs to spawn some child processes. How can I manage these child processes? (for example, restart if the process is dead) Thanks! A: Have a look at celery. A: If you use the multiprocessing package, every child process has is_alive method you can check. So one option to to hold a list of all running processes and periodically check is_alive and re-spawn dead processes. If you're on POSIX system, you can also catch SIGCHLD (using signal) and get notified when a child process dies. A: This will help http://docs.python.org/library/multiprocessing.html edit : a good tutorial http://www.ibm.com/developerworks/aix/library/au-multiprocessing/
Python multiprocessing
I have a "master" process that needs to spawn some child processes. How can I manage these child processes? (for example, restart if the process is dead) Thanks!
[ "Have a look at celery.\n", "If you use the multiprocessing package, every child process has is_alive method you can check. So one option to to hold a list of all running processes and periodically check is_alive and re-spawn dead processes.\nIf you're on POSIX system, you can also catch SIGCHLD (using signal) an...
[ 4, 3, 1 ]
[]
[]
[ "multiprocessing", "python" ]
stackoverflow_0003850708_multiprocessing_python.txt
Q: Python style: for-in syntax, checking for empty lists and dictionaries I'm new to python and haven't yet read a lot of code to verify which styles are considered 'pythonic'. As I've started to code, I've been using this pattern alot. listThatMightBeEmpty = [] for items in listThatMightBeEmpty: print "this may or may not print but the loop won't cause any errors" I assume that it would be redundant to first check if the list is empty - that I can just let the for-in loop do nothing if the list is empty. But I want to make sure there aren't any gotchas for any situation including using old versions of python, and including using a for-in loop on dictionaries, using enumerate(), or iteritems(), or using list comprehensions etc. A: Yes you are right. There are no gotchas here. You can use it on an empty list. Old but still holds good : http://effbot.org/zone/python-list.htm A: To check whether a list is empty, you can do this: >>> x = [] >>> if not x: # do something If the list is empty, # do something will run and you can handle the execution there. However, there is nothing wrong with your approach. A: Yes it is redundant (unless you want to perform something special for empty input). In general, the for loop and and function that return another thing that you can iterate on will not give any "surprising behaviors" if you have an input of zero items. This includes enumerate() , iteritems(), and even slicing ([][1:] == []). >>> list( enumerate([]) ) [] >>> list( {}.iteritems() ) [] >>> [][1:] [] >>> [x*x for x in []] []
Python style: for-in syntax, checking for empty lists and dictionaries
I'm new to python and haven't yet read a lot of code to verify which styles are considered 'pythonic'. As I've started to code, I've been using this pattern alot. listThatMightBeEmpty = [] for items in listThatMightBeEmpty: print "this may or may not print but the loop won't cause any errors" I assume that it would be redundant to first check if the list is empty - that I can just let the for-in loop do nothing if the list is empty. But I want to make sure there aren't any gotchas for any situation including using old versions of python, and including using a for-in loop on dictionaries, using enumerate(), or iteritems(), or using list comprehensions etc.
[ "Yes you are right. There are no gotchas here. You can use it on an empty list. \n\nOld but still holds good : http://effbot.org/zone/python-list.htm\n\n", "To check whether a list is empty, you can do this:\n>>> x = []\n>>> if not x:\n # do something\n\nIf the list is empty, # do something will run and y...
[ 2, 1, 1 ]
[]
[]
[ "idioms", "list", "python" ]
stackoverflow_0003850791_idioms_list_python.txt
Q: Rotate dictionary keys in python I have a dictionary with several values that I want to keep constant, but I need to rotate them throughout the different keys. Is there a built in function or external library that would be able to do this or would I be better off just writing the entire thing myself? Example of what I am trying to do: >>> firstdict = {'a':'a','b':'b','c':'c'} >>> firstdict.dorotatemethod() >>> firstdict {'a':'b','b':'c','c':'a'} >>> I does not have to be in order, I just need the values to be associated to a different key each time. A: >>> from itertools import izip >>> def rotateItems(dictionary): ... if dictionary: ... keys = dictionary.iterkeys() ... values = dictionary.itervalues() ... firstkey = next(keys) ... dictionary = dict(izip(keys, values)) ... dictionary[firstkey] = next(values) ... return dictionary ... >>> firstdict {'a': 'a', 'c': 'c', 'b': 'b'} >>> rotateItems(firstdict) {'a': 'b', 'c': 'a', 'b': 'c'}
Rotate dictionary keys in python
I have a dictionary with several values that I want to keep constant, but I need to rotate them throughout the different keys. Is there a built in function or external library that would be able to do this or would I be better off just writing the entire thing myself? Example of what I am trying to do: >>> firstdict = {'a':'a','b':'b','c':'c'} >>> firstdict.dorotatemethod() >>> firstdict {'a':'b','b':'c','c':'a'} >>> I does not have to be in order, I just need the values to be associated to a different key each time.
[ ">>> from itertools import izip\n>>> def rotateItems(dictionary):\n... if dictionary:\n... keys = dictionary.iterkeys()\n... values = dictionary.itervalues()\n... firstkey = next(keys)\n... dictionary = dict(izip(keys, values))\n... dictionary[firstkey] = next(values)\n... return dictionary\...
[ 7 ]
[]
[]
[ "dictionary", "key", "python", "rotation" ]
stackoverflow_0003850786_dictionary_key_python_rotation.txt
Q: Why is this division not performed correctly? I've a strange issue in Python: the division is not performed correctly: print pointB[1] print pointA[1] print pointB[0] print pointA[0] print (pointB[1]-pointA[1]) / (pointB[0]-pointA[0]) These are the results: 100 50 100 40 0 thanks A: The above behavior is true for Python 2. The behavior of / was fixed in Python 3. In Python 2 you can use: from __future__ import division and then use / to get the result you desire. >>> 5 / 2 2 >>> from __future__ import division >>> 5 / 2 2.5 Since you are dividing two integers, you get the result as an integer. Or, change one of the numbers to a float. >>> 5.0 / 2 2.5 A: It is done correctly. 50/60 = 0 Maybe you are looking for 50.0/60.0 = 0.83333333333333337, you can cast your variables to float to get that: print float(pointB[1]-pointA[1]) / (pointB[0]-pointA[0]) A: This is how integer division works in python. Either use floats or convert to float in your calculation: float(pointB[1]-pointA[1]) / (pointB[0]-pointA[0])
Why is this division not performed correctly?
I've a strange issue in Python: the division is not performed correctly: print pointB[1] print pointA[1] print pointB[0] print pointA[0] print (pointB[1]-pointA[1]) / (pointB[0]-pointA[0]) These are the results: 100 50 100 40 0 thanks
[ "The above behavior is true for Python 2. The behavior of / was fixed in Python 3. In Python 2 you can use:\nfrom __future__ import division\n\nand then use / to get the result you desire.\n>>> 5 / 2\n2\n>>> from __future__ import division\n>>> 5 / 2\n2.5\n\nSince you are dividing two integers, you get the result a...
[ 18, 9, 3 ]
[]
[]
[ "division", "python", "python_2.x" ]
stackoverflow_0003851002_division_python_python_2.x.txt
Q: Running matplotlib in tkinter I have this beautiful sphere I made in matplotlib. How would I go about putting it in a tkinter frame widget? It'd be nice to be able to integrate it into an existing tkinter GUI. Also is it possible to rid of the menu bar below the display? I have no need to save the output or zoom, so it's useless to me. from mpl_toolkits.mplot3d import axes3d,Axes3D import matplotlib.pyplot as plt from matplotlib import cm import numpy as np fig = plt.figure() ax = Axes3D(fig) #<-- Note the difference from your original code.. u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = 10 * np.outer(np.cos(u), np.sin(v)) y = 10 * np.outer(np.sin(u), np.sin(v)) z = 10 * np.outer(np.ones(np.size(u)), np.cos(v)) ax.plot_surface(x, y, z, rstride=4, cstride=4, color='lightgreen',linewidth=0) #,antialiased=False #cmap=cm.jet plt.show() A: Have a look at the examples for embedding plots in a tk GUI, it should be enough to get you started in the right direction. user_interfaces example code: embedding_in_tk.py user_interfaces example code: embedding_in_tk2.py As for removing the toolbar, it's a case of not adding it when you are embedding plots in a GUI. If you are using matplotlib.pyplot the toolbar will be created automatically for every figure. If you are writing your own user interface code, you can add the toolbar as a widget.
Running matplotlib in tkinter
I have this beautiful sphere I made in matplotlib. How would I go about putting it in a tkinter frame widget? It'd be nice to be able to integrate it into an existing tkinter GUI. Also is it possible to rid of the menu bar below the display? I have no need to save the output or zoom, so it's useless to me. from mpl_toolkits.mplot3d import axes3d,Axes3D import matplotlib.pyplot as plt from matplotlib import cm import numpy as np fig = plt.figure() ax = Axes3D(fig) #<-- Note the difference from your original code.. u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = 10 * np.outer(np.cos(u), np.sin(v)) y = 10 * np.outer(np.sin(u), np.sin(v)) z = 10 * np.outer(np.ones(np.size(u)), np.cos(v)) ax.plot_surface(x, y, z, rstride=4, cstride=4, color='lightgreen',linewidth=0) #,antialiased=False #cmap=cm.jet plt.show()
[ "Have a look at the examples for embedding plots in a tk GUI, it should be enough to get you started in the right direction.\nuser_interfaces example code: embedding_in_tk.py\nuser_interfaces example code: embedding_in_tk2.py\nAs for removing the toolbar, it's a case of not adding it when you are embedding plots in...
[ 22 ]
[]
[]
[ "matplotlib", "python", "tkinter" ]
stackoverflow_0003845407_matplotlib_python_tkinter.txt
Q: Embedding Matplotlib in Tkinter, display problems I'm currently trying to graph a sphere in a tkinter window using matplotlib. How do I go about making the display square? I'd like the sphere to have as little distortion as possible. My code: #!/usr/bin/env python import matplotlib matplotlib.use('TkAgg') from mpl_toolkits.mplot3d import axes3d,Axes3D import matplotlib.pyplot as plt from matplotlib import cm import numpy as np from numpy import arange, sin, pi from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.figure import Figure import Tkinter import sys class ElectronOrbitalGenerator(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.protocol("WM_DELETE_WINDOW", self.dest) self.main() def main(self): self.fig = plt.figure() ax = Axes3D(self.fig) u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = 10 * np.outer(np.cos(u), np.sin(v)) y = 10 * np.outer(np.sin(u), np.sin(v)) z = 10 * np.outer(np.ones(np.size(u)), np.cos(v)) t = ax.plot_surface(x, y, z, rstride=4, cstride=4, color='lightgreen',linewidth=0) self.frame = Tkinter.Frame(self) self.frame.pack(padx=15,pady=15) self.canvas = FigureCanvasTkAgg(self.fig, master=self.frame) self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1) self.canvas._tkcanvas.pack(side='top', fill='both', expand=1) self.btn = Tkinter.Button(self,text='button',command=self.alt) self.btn.pack() def alt (self): print 9 def dest(self): self.destroy() sys.exit() if __name__ == "__main__": app = ElectronOrbitalGenerator(None) app.title('Embedding in TK') app.mainloop() EDIT I tried self.fig.set_figwidth(100.0) self.fig.set_figheigth(100.0) and got this AttributeError: 'Figure' object has no attribute 'set_figheigth' A: You can make use of pyplot.figure()'s figsize paramater to set the figure size. e.g. self.fig = plt.figure(figsize=(5,5)) A: Did you try to set the figure size attributes? fig.set_figwidth and fig.set_figheigh t
Embedding Matplotlib in Tkinter, display problems
I'm currently trying to graph a sphere in a tkinter window using matplotlib. How do I go about making the display square? I'd like the sphere to have as little distortion as possible. My code: #!/usr/bin/env python import matplotlib matplotlib.use('TkAgg') from mpl_toolkits.mplot3d import axes3d,Axes3D import matplotlib.pyplot as plt from matplotlib import cm import numpy as np from numpy import arange, sin, pi from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.figure import Figure import Tkinter import sys class ElectronOrbitalGenerator(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.protocol("WM_DELETE_WINDOW", self.dest) self.main() def main(self): self.fig = plt.figure() ax = Axes3D(self.fig) u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = 10 * np.outer(np.cos(u), np.sin(v)) y = 10 * np.outer(np.sin(u), np.sin(v)) z = 10 * np.outer(np.ones(np.size(u)), np.cos(v)) t = ax.plot_surface(x, y, z, rstride=4, cstride=4, color='lightgreen',linewidth=0) self.frame = Tkinter.Frame(self) self.frame.pack(padx=15,pady=15) self.canvas = FigureCanvasTkAgg(self.fig, master=self.frame) self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1) self.canvas._tkcanvas.pack(side='top', fill='both', expand=1) self.btn = Tkinter.Button(self,text='button',command=self.alt) self.btn.pack() def alt (self): print 9 def dest(self): self.destroy() sys.exit() if __name__ == "__main__": app = ElectronOrbitalGenerator(None) app.title('Embedding in TK') app.mainloop() EDIT I tried self.fig.set_figwidth(100.0) self.fig.set_figheigth(100.0) and got this AttributeError: 'Figure' object has no attribute 'set_figheigth'
[ "You can make use of pyplot.figure()'s figsize paramater to set the figure size.\ne.g. \nself.fig = plt.figure(figsize=(5,5)) \n", "Did you try to set the figure size attributes?\nfig.set_figwidth and fig.set_figheigh\nt\n" ]
[ 3, 1 ]
[]
[]
[ "matplotlib", "python", "tkinter" ]
stackoverflow_0003847242_matplotlib_python_tkinter.txt
Q: Refactoring long statement in Python I have a very long conditional statement for deciding what action to take for a pair of variables a and b. action = 0 if (a==0) else 1 if (a>1 and b==1) else 2 if (a==1 and b>1) else 3 if (a>1 and b>1) else -1 While it is nice with the compactness (in lines;) ) of this statement, it must exist a more elegant way to do this? A: if a==0: action = 0 elif a>1 and b==1: action = 1 elif a==1 and b>1: action = 2 elif a>1 and b>1: action = 3 else: action = -1 From the Zen of Python (excerpts): Simple is better than complex. Flat is better than nested. Readability counts. A: If a and b both have known, small, integer ranges, you could make a dict. Say they're both always 0,1, or 2: actionTable = { (0,0): 0, (0,1): 0, (0,2): 0, (1,0):-1, (1,1):-1, (1,2): 2, (2,0):-1, (2,1): 1, (2,2): 3 } return actionTable[ (a,b) ] But this is a little bit opaque, unscalable, and hard to maintain. If the action table is big and complex and able to be generated programmatically, though, it's a useful technique for the toolbox.
Refactoring long statement in Python
I have a very long conditional statement for deciding what action to take for a pair of variables a and b. action = 0 if (a==0) else 1 if (a>1 and b==1) else 2 if (a==1 and b>1) else 3 if (a>1 and b>1) else -1 While it is nice with the compactness (in lines;) ) of this statement, it must exist a more elegant way to do this?
[ "if a==0:\n action = 0\nelif a>1 and b==1:\n action = 1\nelif a==1 and b>1:\n action = 2\nelif a>1 and b>1:\n action = 3\nelse:\n action = -1\n\nFrom the Zen of Python (excerpts):\nSimple is better than complex.\nFlat is better than nested.\nReadability counts.\n\n", "If a and b both have known, small, ...
[ 9, 2 ]
[]
[]
[ "conditional", "if_statement", "python", "refactoring" ]
stackoverflow_0003851094_conditional_if_statement_python_refactoring.txt
Q: Why do I get inconsistent exceptions on Python? I encountered a very strange behavior in Python, a behavior that is not consistent. ... except IOError as msg: sys.exit("###ERROR IOError: %s" % (msg)) Usually this would get me a message like: ###ERROR IOError: [Errno 13] Permission denied: 'filename' In same cases the above code is giving me a tuple instead of a proper error message. ###ERROR IOError: (13, 'Permission denied') This is very strange because in all case the exception come from the same python method, codecs.open(...) What makes me wonder more about this is that if I remove the handling the exception will reach upper levels with the right text (full error message), always! except IOError as msg: print(msg) raise msg The above example will always print a complete message, like IOError: [Errno 13] Permission denied: u'filename'. Why is this happening and how do I prevent this, I don't want to give incomplete error messages to the users. I wanted to reproduce this behavior in a test file, but I was not able to reproduce this outside the project. I suspect that is has something to do with the usage of sys.exit() because print(msg) will give good result but sys.exit not. A: First, when reraising an exception, never do except Exc as e: raise e. It is always just plain raise with no arguments. This will preserve the traceback. No, this has nothing to do with sys.exit and everything to do with how the exception was instantiated. You are always getting an exception; just sometimes its string representation will resemble that of a tuple. >>> print IOError(13, 'Permission denied') [Errno 13] Permission denied >>> print IOError((13, 'Permission denied')) (13, 'Permission denied') Without showing the full traceback, there's no way to tell what exactly is raising the error in this way. Also, without properly reraising like I pointed out, you won't be getting the full traceback. A: Before Python 1.5 exceptions were strings. After that they changed it to classes to maintain backwards compatibility. Nowadays you can only raise exception instances or classes. I imagine there was a code like this: error = (13, 'Permision denied') #more code raise error After they changed it to exception somebody just did: raise IOError(error) A: I would suggest that you don't depend on the string representation of the exception; you might name it msg, but it's neither a string nor a message; it's an exception instance. So you might want to construct your own string from the msg.args tuple, and use that as the “message” you want to display.
Why do I get inconsistent exceptions on Python?
I encountered a very strange behavior in Python, a behavior that is not consistent. ... except IOError as msg: sys.exit("###ERROR IOError: %s" % (msg)) Usually this would get me a message like: ###ERROR IOError: [Errno 13] Permission denied: 'filename' In same cases the above code is giving me a tuple instead of a proper error message. ###ERROR IOError: (13, 'Permission denied') This is very strange because in all case the exception come from the same python method, codecs.open(...) What makes me wonder more about this is that if I remove the handling the exception will reach upper levels with the right text (full error message), always! except IOError as msg: print(msg) raise msg The above example will always print a complete message, like IOError: [Errno 13] Permission denied: u'filename'. Why is this happening and how do I prevent this, I don't want to give incomplete error messages to the users. I wanted to reproduce this behavior in a test file, but I was not able to reproduce this outside the project. I suspect that is has something to do with the usage of sys.exit() because print(msg) will give good result but sys.exit not.
[ "First, when reraising an exception, never do except Exc as e: raise e. It is always just plain raise with no arguments. This will preserve the traceback.\nNo, this has nothing to do with sys.exit and everything to do with how the exception was instantiated. You are always getting an exception; just sometimes its s...
[ 5, 1, 0 ]
[]
[]
[ "exception_handling", "ioerror", "python" ]
stackoverflow_0003638656_exception_handling_ioerror_python.txt
Q: Urllib raising invalid argument URLError in Python 3, urllib.request.urlopen New to Python, but I'm trying to...retrieve data from a site: import urllib.request response = urllib.request.urlopen("http://www.python.org") This is the same code I've seen from the Python 3.1 docs. And a lot of sites. However, I get: Message File Name Line Position Traceback <module> G:\My Documents\Python\HTTP.py 14 urlopen E:\Python 3.1\Lib\urllib\request.py 119 open E:\Python 3.1\Lib\urllib\request.py 342 _open E:\Python 3.1\Lib\urllib\request.py 360 _call_chain E:\Python 3.1\Lib\urllib\request.py 320 http_open E:\Python 3.1\Lib\urllib\request.py 1063 do_open E:\Python 3.1\Lib\urllib\request.py 1048 URLError: <urlopen error [Errno 10022] An invalid argument was supplied> I have no idea what's causing this. Anyone know? A: Maybe try turning off the firewall? Since you are on Windows, that might be the problem.
Urllib raising invalid argument URLError in Python 3, urllib.request.urlopen
New to Python, but I'm trying to...retrieve data from a site: import urllib.request response = urllib.request.urlopen("http://www.python.org") This is the same code I've seen from the Python 3.1 docs. And a lot of sites. However, I get: Message File Name Line Position Traceback <module> G:\My Documents\Python\HTTP.py 14 urlopen E:\Python 3.1\Lib\urllib\request.py 119 open E:\Python 3.1\Lib\urllib\request.py 342 _open E:\Python 3.1\Lib\urllib\request.py 360 _call_chain E:\Python 3.1\Lib\urllib\request.py 320 http_open E:\Python 3.1\Lib\urllib\request.py 1063 do_open E:\Python 3.1\Lib\urllib\request.py 1048 URLError: <urlopen error [Errno 10022] An invalid argument was supplied> I have no idea what's causing this. Anyone know?
[ "Maybe try turning off the firewall? Since you are on Windows, that might be the problem.\n" ]
[ 2 ]
[]
[]
[ "python", "python_3.x", "urllib", "urlopen" ]
stackoverflow_0003851224_python_python_3.x_urllib_urlopen.txt
Q: Why does my GtkTreeView sort func receive a row with None in it? I've set up a gtk.TreeView with a gtk.TreeStore. One column contains formatted dollar amounts, and I've set up sorting by that column as follows: def sortmon(model, i1, i2): v1 = model[i1][COL_MONEY] v2 = model[i2][COL_MONEY] return cmp(float(v1.replace("$","").replace(",","")), float(v2.replace("$","").replace(",",""))) self.hsModel.set_sort_func(COL_MONEY, sortmon) This works fine, except that sometimes, when I append a row, I get: stderr : INFO Traceback (most recent call last): stderr : INFO File "C:\Users\DrClaud\bumhunter\gui\widgets\replay\ReplayWidget.py", line 141, in sortpot stderr : INFO float(v2.replace("$","").replace(",",""))) stderr : INFO AttributeError: 'NoneType' object has no attribute 'replace' I did more print outs, and it seems that when I insert a row, one of model[i1][x] or model[i2][x] for any x will be None. I'm certain I'm not inserting a row with None elements in it.. so what happens? A: If you append a row to a sorted model, GTK+ automatically searches for a proper position for it and thus your sort function is called if it's on that column. You should either handle None specially, or specify initial values in append() call, like: model.append (parent, [x, y, z]) The latter of course only solves the problem if you can specify something more appropriate than None, an empty string, perhaps.
Why does my GtkTreeView sort func receive a row with None in it?
I've set up a gtk.TreeView with a gtk.TreeStore. One column contains formatted dollar amounts, and I've set up sorting by that column as follows: def sortmon(model, i1, i2): v1 = model[i1][COL_MONEY] v2 = model[i2][COL_MONEY] return cmp(float(v1.replace("$","").replace(",","")), float(v2.replace("$","").replace(",",""))) self.hsModel.set_sort_func(COL_MONEY, sortmon) This works fine, except that sometimes, when I append a row, I get: stderr : INFO Traceback (most recent call last): stderr : INFO File "C:\Users\DrClaud\bumhunter\gui\widgets\replay\ReplayWidget.py", line 141, in sortpot stderr : INFO float(v2.replace("$","").replace(",",""))) stderr : INFO AttributeError: 'NoneType' object has no attribute 'replace' I did more print outs, and it seems that when I insert a row, one of model[i1][x] or model[i2][x] for any x will be None. I'm certain I'm not inserting a row with None elements in it.. so what happens?
[ "If you append a row to a sorted model, GTK+ automatically searches for a proper position for it and thus your sort function is called if it's on that column. You should either handle None specially, or specify initial values in append() call, like:\nmodel.append (parent, [x, y, z])\n\nThe latter of course only so...
[ 1 ]
[]
[]
[ "gtk", "gtktreeview", "pygtk", "python" ]
stackoverflow_0003842609_gtk_gtktreeview_pygtk_python.txt
Q: Web page scraping: press javascript button I am trying to scrape a web page and to recieve the data i need to press a button. This is the source code for the button: "a class="press-me_btn" href="javascript:void( NewPage['DemoPage'].startDemo() );" id="js_press-me_btn">PRESS ME Is it possible to "press" the button somehow without using a browser? either by using wget with the --post-data argument or maybe a small python, ruby, perl etc. application? Any ideas are appreciated! A: In this case these is not a button, it is an anchor element, i think that you will need to run the js code, that is in the href attribute: javascript:void( NewPage['DemoPage'].startDemo() );
Web page scraping: press javascript button
I am trying to scrape a web page and to recieve the data i need to press a button. This is the source code for the button: "a class="press-me_btn" href="javascript:void( NewPage['DemoPage'].startDemo() );" id="js_press-me_btn">PRESS ME Is it possible to "press" the button somehow without using a browser? either by using wget with the --post-data argument or maybe a small python, ruby, perl etc. application? Any ideas are appreciated!
[ "In this case these is not a button, it is an anchor element, i think that you will need to run the js code, that is in the href attribute:\njavascript:void( NewPage['DemoPage'].startDemo() );\n\n" ]
[ 1 ]
[]
[]
[ "python", "screen_scraping", "wget" ]
stackoverflow_0003851413_python_screen_scraping_wget.txt
Q: Trying to group values? I have some data like this: 1 2 3 4 5 9 2 6 3 7 and am looking for an output like this (group-id and the members of that group): 1: 1 2 6 2: 3 4 7 3: 5 9 First row because 1 is "connected" to 2 and 2 is connected to 6. Second row because 3 is connected to 4 and 3 is connected to 7 This looked to me like a graph traversal but the final order does not matter so I was wondering if someone can suggest a simpler solution that I can use on a large dataset (billions of entries). From the comments: The problem is to find the set of disjoint sub-graphs given a set of edges. The edges are not directed; the line '1 2' means that 1 is connected to 2 and 2 is connected to 1. The '1:' in the sample output could be 'A:' without changing the meaning of the answer. EDIT 1: Problem looks solved now. Thanks to everyone for their help. I need some more help picking the best solution that can be used on billions of such entries. EDIT 2: Test Input file: 1 27 1 134 1 137 1 161 1 171 1 275 1 309 1 413 1 464 1 627 1 744 2 135 2 398 2 437 2 548 2 594 2 717 2 738 2 783 2 798 2 912 5 74 5 223 7 53 7 65 7 122 7 237 7 314 7 701 7 730 7 755 7 821 7 875 7 884 7 898 7 900 7 930 8 115 9 207 9 305 9 342 9 364 9 493 9 600 9 676 9 830 9 941 10 164 10 283 10 380 10 423 10 468 10 577 11 72 11 132 11 276 11 306 11 401 11 515 11 599 12 95 12 126 12 294 13 64 13 172 13 528 14 396 15 35 15 66 15 210 15 226 15 360 15 588 17 263 17 415 17 474 17 648 17 986 21 543 21 771 22 47 23 70 23 203 23 427 23 590 24 286 24 565 25 175 26 678 27 137 27 161 27 171 27 275 27 309 27 413 27 464 27 627 27 684 27 744 29 787 Benchmarks: I tried out everything and the version posted by TokenMacGuy is the fastest on the sample dataset that I tried. The dataset has about 1 million entries for which it took me about 6 seconds on a Dual Quad-Core 2.4GHz machine. I haven't gotten a chance to run it on the entire dataset yet but I will post the benchmark as soon as it is available. A: I've managed O(n log n). Here is a (somewhat intense) C++ implementation: #include <boost/pending/disjoint_sets.hpp> #include <boost/property_map/property_map.hpp> #include <map> #include <set> #include <iostream> typedef std::map<int, int> rank_t; typedef std::map<int, int> parent_t; typedef boost::associative_property_map< rank_t > rank_pmap_t; typedef boost::associative_property_map< parent_t > parent_pmap_t; typedef boost::disjoint_sets< rank_pmap_t, parent_pmap_t > group_sets_t; typedef std::set<int> key_set; typedef std::map<int, std::set<int> > output; With some typedefs out of the way, here's the real meat. I'm using boost::disjoint_sets, which is just happens to be an exceptionally good representation for the problem. This first function checks to see if either of the keys given have been seen before, and adds them to the collections if needed. the important part is really the union_set(a, b) which links the two sets together. If one or the other of the sets are already in the groups collection, they get linked too. void add_data(int a, int b, group_sets_t & groups, key_set & keys) { if (keys.count(a) < 1) groups.make_set(a); if (keys.count(b) < 1) groups.make_set(b); groups.union_set(a, b); keys.insert(a); keys.insert(b); } This isn't too exciting, it just iterates through all of the keys we've seen and gets the representative key for that key, then adds the pair (representative, key) to a map. Once that's done, print out the map. void build_output(group_sets_t & groups, key_set & keys) { output out; for (key_set::iterator i(keys.begin()); i != keys.end(); i++) out[groups.find_set(*i)].insert(*i); for (output::iterator i(out.begin()); i != out.end(); i++) { std::cout << i->first << ": "; for (output::mapped_type::iterator j(i->second.begin()); j != i->second.end(); j++) std::cout << *j << " "; std::cout << std::endl; } } int main() { rank_t rank; parent_t parent; rank_pmap_t rank_index(rank); parent_pmap_t parent_index(parent); group_sets_t groups( rank_index, parent_index ); key_set keys; int a, b; while (std::cin >> a) { std::cin >> b; add_data(a, b, groups, keys); } build_output(groups, keys); //std::cout << "number of sets: " << // groups.count_sets(keys.begin()), keys.end()) << std::endl; } I stayed up many hours learning how to use boost::disjoint_sets on this problem. There doesn't seem to be much of any documentation on it. About the performance. The disjoint_sets structure is O(α(n) ) for its key operations (make_set, find_set and union_set) which is pretty close to constant, and so if it were just a matter of building the structure, the whole algorithm would be O(n α(n) ) (which is effectively O(n) ) but we have to print it out. That means we have to build up some associative containers, which cannot perform better than O(n log n). It might be possible to get a constant factor speedup by choosing a different associative containers (say, hash_set etc), since once you populate the initial list, you can reserve an optimal amount of space. A: Here is a sample Perl solution that works on the original data set: 1 2 3 4 5 9 2 6 3 7 Group 1: 1 2 6 Group 2: 3 4 7 Group 3: 5 9 On the big data set, it produces the output: Group 1: 1 27 134 137 161 171 275 309 413 464 627 684 744 Group 2: 2 135 398 437 548 594 717 738 783 798 912 Group 3: 5 74 223 Group 4: 7 53 65 122 237 314 701 730 755 821 875 884 898 900 930 Group 5: 8 115 Group 6: 9 207 305 342 364 493 600 676 830 941 Group 7: 10 164 283 380 423 468 577 Group 8: 11 72 132 276 306 401 515 599 Group 9: 12 95 126 294 Group 10: 13 64 172 528 Group 11: 14 396 Group 12: 15 35 66 210 226 360 588 Group 13: 17 263 415 474 648 986 Group 14: 21 543 771 Group 15: 22 47 Group 16: 23 70 203 427 590 Group 17: 24 286 565 Group 18: 25 175 Group 19: 26 678 Group 20: 29 787 Whether it is efficient enough is a separate matter... use strict; use warnings; my %cache = (); while (<>) { chomp; my($x,$y) = split /\s+/; #print "$x $y\n"; $cache{$x}{$y} = 1; $cache{$y}{$x} = 1; } my $grp = 1; foreach my $key (sort { $a <=> $b } keys %cache) { #print "key: $key\n"; if (defined $cache{$key}) { my %result = (); subkey_search(\%result, $key); print "Group $grp:"; $grp++; foreach my $val (sort { $a <=> $b } keys %result) { print " $val"; } print "\n"; } } sub subkey_search { my($resultref, $key) = @_; my %hash = %{$cache{$key}}; delete $cache{$key}; $resultref->{$key} = 1; foreach my $subkey (sort keys %hash) { #print "subkey: $subkey\n"; subkey_search($resultref, $subkey) if (defined $cache{$subkey}); } } A: Ok so I got something working in parallel to the other solution posted by @Jonathan (first of all, many thanks for your time). My solution looks deceptively simple but would love some suggestions on whether this is correct (maybe I'm missing a corner case somewhere?) because it seems to produce the output I wanted but I'll have to parse it in a second pass to group the same group numbers which is trivial. The logic is that everytime it finds a new number not in the array it increments a group_id counter: My code in PHP: <?php //$fp = fopen("./resemblance.1.out", "r"); $fp = fopen("./wrong", "r"); $groups = array(); $group["-1"] = 1; $groups[] = $group; $map = array(); //Maintain a count $group = 1; while(!feof($fp)) { $source = trim(fgets($fp, 4096)); //echo $source."\n"; $source = explode(" ", $source); if(array_key_exists($source[0], $map) && !array_key_exists($source[1], $map)) { $map[$source[1]] = $map[$source[0]]; } else if(array_key_exists($source[1], $map) && !array_key_exists($source[0], $map)) { $map[$source[0]] = $map[$source[1]]; } else if(array_key_exists($source[1], $map) && array_key_exists($source[0], $map) && $map[$source[1]] != $map[$source[0]]) { // Adjust the groups - change the groups of one of the elements to the other $keys = array_keys($map, $map[$source[1]]); print_r($keys); foreach($keys as $key) { $map[$key] = $map[$source[0]]; } } else { $group++; $map[$source[0]] = $group; $map[$source[1]] = $group; } } print_r($map); ?> Output: Array ( [1] => 2 [2] => 2 [3] => 3 [4] => 3 [5] => 4 [9] => 4 [6] => 2 [7] => 3 [] => 5 ) EDIT: Fixed the bug that was mentioned in the comment. Just playing around out of curiosity :) Feel free to point out any other bugs. I am currently testing out which solution is faster. A: Here's a slightly different version in Python, which builds a graph containing the edges specified, then converts that to a list of connected subgraphs. I might want to use this later so I wrote it as a general-purpose version that doesn't do input from a file or output with print statements, just converting data structures. def graph_to_connected_subgraphs(graph): trees = [] for start in graph.keys(): if start in graph: list = [start] append_tree_from(graph, start, list) trees.append(list) return trees def append_tree_from(graph, node, list): if node in graph: for endpoint in graph[node]: list.append(endpoint) append_tree_from(graph, endpoint, list) del graph[node] return list def add_edge(graph, f, s): if s < f: # ensure f < s to handle cyclic graphs f, s = s, f if f not in graph: graph[f] = [s] else: graph[f].append(s) graph = {} add_edge(graph, 1,2) add_edge(graph, 2,6) add_edge(graph, 3,4) add_edge(graph, 5,9) add_edge(graph, 3,7) print graph_to_connected_subgraphs(graph) Output [[1, 2, 6], [3, 4, 7], [5, 9]] A: This is a typical application of DFS (Depth First Search) algorithm performed on graphs. Try read this dfs Complexity of this algorithm is O(|V|+|E|), where V - number of vertices and E - number of edges A: Here's my stab at an answer. Python. groups = [] infile = open("so2.txt") for line in infile.readlines(): newset = set(line.split()) matchgroups = [] excludegroups = [] for group in groups: if len(newset & group): newset |= group else: excludegroups.append(group) groups = excludegroups groups.append( newset) for i, s in enumerate(groups): print "%d: %s"%(i, " ".join(s)) The Idea here is that forming graphs is not really right. Each pair of numbers in the input is a set. The rule is to return only disjoint sets. So I read each line and convert them to sets, then I check all of the existing sets for intersections, and merge those into the new set. Nonintersecting sets are just added to the new list of sets, and once I'm done I add the new, merged set into the new list of sets. This way I can be sure that only disjoint sets make it into the list. A: My version in PHP actually is only a refactoring of your code. It fixes one issue in your code (you have one group too much) and is implemented slightly more efficient (Exec time drops from 0.0035 to 0.0020 on slow machine): $group = 0; $map = array(); do { list($a, $b) = explode(' ', fgets($file)); $a = (int) $a; $b = (int) $b; if (!isset($map[$a]) && !isset($map[$b])) { $map[$a] = $map[$b] = ++$group; } elseif (!isset($map[$b])) { $map[$b] = $map[$a]; } elseif (!isset($map[$a])) { $map[$a] = $map[$b]; } elseif ($map[$a] != $map[$b]) { // move one group to the other foreach ($map as $n => $g) { if ($g == $map[$b]) { $map[$n] = $map[$a]; } } } } while (!feof($file)); // print results $results = array(); foreach ($map as $val => $group) { $results[$group][] = $val; } echo '<pre>'; $i = 0; foreach ($results as $result) { sort($result); echo 'Group ', ++$i, ': ', implode(' ', $result), "\n"; } A: If the input is sorted, like your huge test set, you can do it in Θ(input) time and Ο(input) space. If the input is unsorted, you could modify this fairly easily and get Ο(input log input) time and Θ(input) space. This is very quick because : it stores a hash map from a node to its "ultimate owner" (which is the node with the lowest ID in the connected component) which allows Ο(1) "ultimate owner" lookup and insertion. it stores a hash map from each "ultimate owner" to a result line which allows Ο(1) result line lookup and insertion. each result line is a linked list which allows Ο(1) appending. it stores a linked list of result lines which allows : Ο(1) appending. access to it without going through the expense of asking the prior hash map for all its values import java.util.Scanner; import java.util.Map; import java.util.HashMap; import java.util.List; import java.util.LinkedList; public final class Solver { public static void main(String[] args) { Scanner in = new Scanner(System.in); final Map<Integer, Integer> ultimateOwners = new HashMap<Integer, Integer>(); final Map<Integer, List<Integer>> ownerToOwned = new HashMap<Integer, List<Integer>>(); final List<List<Integer>> results = new LinkedList<List<Integer>>(); while (in.hasNextInt()) { // Get ultimate owner. int owner = in.nextInt(); if (ultimateOwners.containsKey(owner)) owner = ultimateOwners.get(owner); // Get owned and register its ultimate owner. final int owned = in.nextInt(); ultimateOwners.put(owned, owner); // Add owned to result. if (ownerToOwned.containsKey(owner)) ownerToOwned.get(owner).add(owned); else { final List<Integer> resultLine = new LinkedList<Integer>(); resultLine.add(owner); resultLine.add(owned); ownerToOwned.put(owner, resultLine); results.add(resultLine); } } int lineNumber = 1; for (final List<Integer> line : results) { System.out.printf("%d: ", lineNumber++); for (final Integer value : line) { System.out.printf("%d ", value); } System.out.println(); } } } A: After not being completely satisfied with my first 2 attempts at this, and some research, I came across this recipe for disjoint sets in Python, with Raymond Hettinger's blessing and input. (Raymond Hettinger is a long-time very active Python core developer.) Here is an adaptation of that recipe that's very close to my first 2 attempts, but the recipe itself may be a better reference. Collecting should be as efficient as possible for very large sets of data, as much of the set operations in Python are implemented in C. The input data does not have to be sorted. For printing, I sorted outputs solely for readability, but if this affects performance, connections can be printed without sorting. # ~~~~~ # data, setup input = ''' 1 2 3 4 2 3 ''' # etc. def lgen(): for l in input.splitlines(): l = l.strip() if l: yield tuple(int(i) for i in l.split()) # ~~~~~ # collect connections = {} # this is a mapping of values to the connections they are in # each node will map to a shared object instance of the connection it is in # e.g. {1: set([1,2]), 2: set([1,2])}, where the 2 sets are the same object for x, y in lgen(): cx = connections.setdefault(x, set([x])) # if not found, create new connection with this single value cy = connections.get(y) # defaults to None if not found if not cy: # if we haven't come across this value yet... cx.add(y) # ...add it to the current connection... connections[y] = cx # ...and update the reference elif cy is not cx: # if the cy connection is not the exact same object as the cx connection... if len(cy) > len(cx): # \ cx, cy = cy, cx # >... merge them ... cx |= cy # / connections[y] = cx # ...and update the reference # ~~~~~ # print seen = set() for key in sorted(connections.keys()): if key not in seen: c = connections[key] print sorted(c) seen |= c A: This actually is a very classic Union-find. If M is the number of edges, N the number of nodes, the time complexity is O(M * α(M)) which is a O(M) for all practical M and the space complexity if O(N) with N the number of nodes. The algorithm is online and does not need to know in advance all the edges (compared to other graph-traversal solutions) and hence can scale very well. Also there is no need to order the edges, they can be given in any order. For graph with billions of nodes you'll need 64 bits / long int and a lot of RAM, but it should handle millions of nodes and billions of edges very well. The implementation is in C++ but only use vector/map that you can find in almost any language you might want to use. But since you have unique id for each element we need to map these id to (contiguous) integers. First version without mapping (suppose that all nodes between 1 and N exists): #include <cstdio> #include <algorithm> #include <vector> using namespace std; const int MAX_N = 1000*1000; int p[MAX_N],f[MAX_N]; int parent(int a) { return p[a] == a ? a : p[a] = parent(p[a]); } bool join(int a, int b) { p[a = parent(a)] = parent(b); return p[a] != a; } int main() { // First integer in the file : number of nodes in the graph int N; scanf("%d",&N); // Union-find in O(M * alpha(M)) ~= O(M) // M = number of lines in the file for(int i = 1; i <= N ; i++) { p[i] = i; f[i] = -1; } int a,b; while(scanf("%d%d",&a,&b) != EOF) join(a,b); // Determine the number of groups : O(M) int nG = 0; for(int i = 1 ; i <= N ; i++) { p[i] = parent(p[i]); if(f[p[i]] == -1) f[p[i]] = nG++; } // Build groups : O(M) vector< vector<int> > Groups(N+1); for(int i = 1 ; i <= N ; i++) Groups[ f[p[i]] ].push_back(i); // Output result for(int i = 0 ; i < Groups.size() ; i++) { if(!Groups[i].size()) continue; printf("%d : ",i); for(int j = 0 ; j < Groups[i].size() ; j++) printf("%d ",Groups[i][j]); printf("\n"); } } Version with mapping : for that version we need to build the mapping. Since I don't know anything about your data, I'm using a classical map to build it in O(M log(N)), if you can send the id of all nodes at the begin of the input file, it can be O(N log(N)) or even better if your are using a Hash Map ( O(N)) or if you can build the mapping yourself, with some knowing of the graph. Anyway, here is the code : #include <cstdio> #include <algorithm> #include <vector> #include <map> using namespace std; const int MAX_N = 1000*1000; int p[MAX_N],f[MAX_N]; int parent(int a) { return p[a] == a ? a : p[a] = parent(p[a]); } bool join(int a, int b) { p[a = parent(a)] = parent(b); return p[a] != a; } // Mapping int N = 0; map<int,int> indMap,invMap; int IND(int x) { if(indMap.find(x) == indMap.end()) { N++; p[N] = N; f[N] = -1; indMap[x] = N; } invMap[ indMap[x] ] = x; return indMap[x]; } int main() { // Union-find in O(M * alpha(M)) ~= O(M) // M = number of lines in the file int a,b; while(scanf("%d%d",&a,&b) != EOF) join(IND(a),IND(b)); // Determine the number of groups : O(M) int nG = 0; for(int i = 1 ; i <= N ; i++) { p[i] = parent(p[i]); if(f[p[i]] == -1) f[p[i]] = nG++; } // Build groups : O(M) vector< vector<int> > Groups(N+1); for(int i = 1 ; i <= N ; i++) Groups[ f[p[i]] ].push_back(i); // Output result for(int i = 0 ; i < Groups.size() ; i++) { if(!Groups[i].size()) continue; printf("%d : ",i+1); for(int j = 0 ; j < Groups[i].size() ; j++) printf("%d ", invMap[ Groups[i][j] ]); printf("\n"); } }
Trying to group values?
I have some data like this: 1 2 3 4 5 9 2 6 3 7 and am looking for an output like this (group-id and the members of that group): 1: 1 2 6 2: 3 4 7 3: 5 9 First row because 1 is "connected" to 2 and 2 is connected to 6. Second row because 3 is connected to 4 and 3 is connected to 7 This looked to me like a graph traversal but the final order does not matter so I was wondering if someone can suggest a simpler solution that I can use on a large dataset (billions of entries). From the comments: The problem is to find the set of disjoint sub-graphs given a set of edges. The edges are not directed; the line '1 2' means that 1 is connected to 2 and 2 is connected to 1. The '1:' in the sample output could be 'A:' without changing the meaning of the answer. EDIT 1: Problem looks solved now. Thanks to everyone for their help. I need some more help picking the best solution that can be used on billions of such entries. EDIT 2: Test Input file: 1 27 1 134 1 137 1 161 1 171 1 275 1 309 1 413 1 464 1 627 1 744 2 135 2 398 2 437 2 548 2 594 2 717 2 738 2 783 2 798 2 912 5 74 5 223 7 53 7 65 7 122 7 237 7 314 7 701 7 730 7 755 7 821 7 875 7 884 7 898 7 900 7 930 8 115 9 207 9 305 9 342 9 364 9 493 9 600 9 676 9 830 9 941 10 164 10 283 10 380 10 423 10 468 10 577 11 72 11 132 11 276 11 306 11 401 11 515 11 599 12 95 12 126 12 294 13 64 13 172 13 528 14 396 15 35 15 66 15 210 15 226 15 360 15 588 17 263 17 415 17 474 17 648 17 986 21 543 21 771 22 47 23 70 23 203 23 427 23 590 24 286 24 565 25 175 26 678 27 137 27 161 27 171 27 275 27 309 27 413 27 464 27 627 27 684 27 744 29 787 Benchmarks: I tried out everything and the version posted by TokenMacGuy is the fastest on the sample dataset that I tried. The dataset has about 1 million entries for which it took me about 6 seconds on a Dual Quad-Core 2.4GHz machine. I haven't gotten a chance to run it on the entire dataset yet but I will post the benchmark as soon as it is available.
[ "I've managed O(n log n).\nHere is a (somewhat intense) C++ implementation:\n#include <boost/pending/disjoint_sets.hpp>\n#include <boost/property_map/property_map.hpp>\n\n#include <map>\n#include <set>\n#include <iostream>\n\n\ntypedef std::map<int, int> rank_t;\ntypedef std::map<int, int> parent_t;\n\ntypedef boos...
[ 4, 1, 1, 1, 1, 0, 0, 0, 0, 0 ]
[]
[]
[ "algorithm", "c++", "graph", "php", "python" ]
stackoverflow_0003848239_algorithm_c++_graph_php_python.txt
Q: Easiest way to send emails via Python Possible Duplicate: Receive and send emails in python I've been looking into sending mail with python and found a few different options (setting up my own mailserver, using gmail's smtp, etc) but was wondering if there was some simple way to do it. I am running the python script via wsgi on apache2 on an ubuntu box. Thanks for any tips! A: There's a great example here. As you seem to know, you'll just need an smtp server to do the actual sending. That particular step is not dependent on python. If g-mails smtp server let's you send mail, I'd go that route. When I last set this up (for an svn backup script), I luckily got to use my company's smtp server.
Easiest way to send emails via Python
Possible Duplicate: Receive and send emails in python I've been looking into sending mail with python and found a few different options (setting up my own mailserver, using gmail's smtp, etc) but was wondering if there was some simple way to do it. I am running the python script via wsgi on apache2 on an ubuntu box. Thanks for any tips!
[ "There's a great example here. As you seem to know, you'll just need an smtp server to do the actual sending. That particular step is not dependent on python.\nIf g-mails smtp server let's you send mail, I'd go that route. When I last set this up (for an svn backup script), I luckily got to use my company's smtp se...
[ 1 ]
[]
[]
[ "email", "python", "smtp", "ubuntu" ]
stackoverflow_0003851633_email_python_smtp_ubuntu.txt
Q: Compare folders recursively using python I'm going to implement recursive folder comparison on python. What do you think would best algorithm for this? Get two lists of the files for the folders Sort both lists Compare using filecmp module for a file Repeat for every folder recursively In result I need to get only the list of the files that are different (content difference is not needed here), the list of the files that are missing in one of the comparable folders. Thank you. A: Make recursive search over directory and for each file store md5 or sha checksum of file in dictionary as key and path/name as value. Make this dictionary for both directories. Then you can remove pairs from each directory and result is missing/different files. This will make simple O(n) algorhitm, where n is volume of directory. A: If I was you, I would check if another software doesn't already implement this feature, like rsync or diff. For what I see, both have the features you need. There are more information about it here. If you really need to do this in Python, I would modify slightly your algorithm, making it look like this: Store both paths contents in two separate list variables using os.walk; Iterate on each value of the first list to find a corresponding value in the second list; If a corresponding value have been found, compare it using the filecmp module. Otherwise, display the missing file; Remove the value from the second list; Go to #2 until the first list is empty; Print everything left in the second list;
Compare folders recursively using python
I'm going to implement recursive folder comparison on python. What do you think would best algorithm for this? Get two lists of the files for the folders Sort both lists Compare using filecmp module for a file Repeat for every folder recursively In result I need to get only the list of the files that are different (content difference is not needed here), the list of the files that are missing in one of the comparable folders. Thank you.
[ "Make recursive search over directory and for each file store md5 or sha checksum of file in dictionary as key and path/name as value. Make this dictionary for both directories. Then you can remove pairs from each directory and result is missing/different files.\nThis will make simple O(n) algorhitm, where n is vo...
[ 2, 1 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0003851884_algorithm_python.txt
Q: Python: Rare problem generating .gif with ffmpeg I have a problem when I generate an animated gif from a movie.avi using ffmpeg from python in Win7. If I open a cmd window and execute this line: "C:\ffmpeg\ffmpeg.exe" -i "C:\ffmpeg\video.avi" -pix_fmt rgb24 -r 10.0 -loop_output 0 -ss 5 -t 10 -s 352x288 -f gif "C:\ffmpeg\video.gif" ffmpeg.exe generates a gif perfectly from the video. I want to use ffmpeg.exe from my code in python for do the same but, when I execute this code from my python program: argList = ["-i", "C:\\ffmpeg\\video.avi", "-pix_fmt", "rgb24", "-r", "10.0", "-loop_output", "0", "-ss", "5", "-t", "10", "-s", "352x288", "-f", "gif", "C:\\ffmpeg\\video.gif"] os.spawnv(os.P_DETACH, "C:\\ffmpeg\\ffmpeg.exe", argList) Something really rare happends: My video.avi lose all its size, now is a blank file with 0 bytes and the movie.gif is a blank file with 0 bytes too so, the same code in cmd windows works fine and into my python program modifiques my movie.avi file and erase all its content (but the file movie.avi doesn't dessapear, the file still exists but now is a blank file) and generates a blank movie.gif file. Someone know why this happens? Thanks in advance. A: Your arglist for spawnv needs to start with "C:\\ffmpeg\\ffmpeg.exe". Try that and see how it goes. argList = ["C:\\ffmpeg\\ffmpeg.exe", "-i", "C:\\ffmpeg\\video.avi", "-pix_fmt", "rgb24", "-r", "10.0", "-loop_output", "0", "-ss", "5", "-t", "10", "-s", "352x288", "-f", "gif", "C:\\ffmpeg\\video.gif"] os.spawnv(os.P_DETACH, "C:\\ffmpeg\\ffmpeg.exe", argList) A: @JoshD argList = ["-y", "-ss", "750", "-i", "C:\\ffmpeg\\video.avi", "-f", "mjpeg", "-vframes", "1", "-s", "1280x720", "-an", "C:\\ffmpeg\\thumbnail.jpg"] os.spawnv(os.P_DETACH, "C:\\ffmpeg\\ffmpeg.exe", argList) This works fine without "C:\\ffmpeg\\ffmpeg.exe" in the start of spawnv, my confusion came from this. Thanks a lot.
Python: Rare problem generating .gif with ffmpeg
I have a problem when I generate an animated gif from a movie.avi using ffmpeg from python in Win7. If I open a cmd window and execute this line: "C:\ffmpeg\ffmpeg.exe" -i "C:\ffmpeg\video.avi" -pix_fmt rgb24 -r 10.0 -loop_output 0 -ss 5 -t 10 -s 352x288 -f gif "C:\ffmpeg\video.gif" ffmpeg.exe generates a gif perfectly from the video. I want to use ffmpeg.exe from my code in python for do the same but, when I execute this code from my python program: argList = ["-i", "C:\\ffmpeg\\video.avi", "-pix_fmt", "rgb24", "-r", "10.0", "-loop_output", "0", "-ss", "5", "-t", "10", "-s", "352x288", "-f", "gif", "C:\\ffmpeg\\video.gif"] os.spawnv(os.P_DETACH, "C:\\ffmpeg\\ffmpeg.exe", argList) Something really rare happends: My video.avi lose all its size, now is a blank file with 0 bytes and the movie.gif is a blank file with 0 bytes too so, the same code in cmd windows works fine and into my python program modifiques my movie.avi file and erase all its content (but the file movie.avi doesn't dessapear, the file still exists but now is a blank file) and generates a blank movie.gif file. Someone know why this happens? Thanks in advance.
[ "Your arglist for spawnv needs to start with \"C:\\\\ffmpeg\\\\ffmpeg.exe\". Try that and see how it goes.\nargList = [\"C:\\\\ffmpeg\\\\ffmpeg.exe\", \"-i\", \"C:\\\\ffmpeg\\\\video.avi\", \"-pix_fmt\", \"rgb24\", \"-r\", \"10.0\", \"-loop_output\", \"0\", \"-ss\", \"5\", \"-t\", \"10\", \"-s\", \"352x288\", \"-f\...
[ 1, 0 ]
[]
[]
[ "cmd", "gif", "python", "thumbnails" ]
stackoverflow_0003851966_cmd_gif_python_thumbnails.txt
Q: Reactor stopping earlier than I would have expected? I am trying to teach myself some rudimentary Twisted programming thanks to this tutorial and many others. I have come to this current example which I Can't figure out why it's doing what it is doing. Short summary: I have instantiated three reactors that count down from 5 to 1 with different delays in their counting. Only thing is, it looks like when the first counter (with the shortest delay) gets to 0, it stops not only its own reactor, but all the others. #!/usr/bin/env python class Countdown(object): counter = 5 def count1(self): from twisted.internet import reactor if self.counter == 0: reactor.stop() else: print self.counter, '...1' self.counter -= 1 reactor.callLater(1, self.count1) def count2(self): from twisted.internet import reactor if self.counter == 0: reactor.stop() else: print self.counter, '...2' self.counter -= 1 reactor.callLater(0.5, self.count2) def count3(self): from twisted.internet import reactor if self.counter == 0: reactor.stop() else: print self.counter, '...3' self.counter -= 1 reactor.callLater(0.25, self.count3) from twisted.internet import reactor reactor.callWhenRunning(Countdown().count1) reactor.callWhenRunning(Countdown().count2) reactor.callWhenRunning(Countdown().count3) print 'Start!' reactor.run() print 'Stop!' Output Start! 5 ...1 5 ...2 5 ...3 4 ...3 4 ...2 3 ...3 2 ...3 4 ...1 3 ...2 1 ...3 Stop! I was under the impression that while all three counters should count down at their own speed and complete their 5->0 progression, the program would wait for them all to complete before exiting. Am I misunderstanding something in the ways of Twisted here? A: I am unfamiliar with twisted, but from skimming google results it looks like reactor is an event loop. You only have one of them, so the first counter to hit reactor.stop() stops the loop. To do what you want you need to remove the reactor.stop() calls and structure things so that when the last timer hits the end it, and only it, calls reactor.stop() A: He talks a bit about that in part 3. You might be mixing up "starting three reactors in one server" and "starting three different servers". The examples suggest to do the latter; your code is attempting to do the former. Basically the reactor is a singleton, and cannot be restarted once stopped. So you can only have one per process, or maybe one per thread. Instead of starting three reactors, you want to set up three different timed callbacks on the same reactor. They will all get fired at the appropriate time.
Reactor stopping earlier than I would have expected?
I am trying to teach myself some rudimentary Twisted programming thanks to this tutorial and many others. I have come to this current example which I Can't figure out why it's doing what it is doing. Short summary: I have instantiated three reactors that count down from 5 to 1 with different delays in their counting. Only thing is, it looks like when the first counter (with the shortest delay) gets to 0, it stops not only its own reactor, but all the others. #!/usr/bin/env python class Countdown(object): counter = 5 def count1(self): from twisted.internet import reactor if self.counter == 0: reactor.stop() else: print self.counter, '...1' self.counter -= 1 reactor.callLater(1, self.count1) def count2(self): from twisted.internet import reactor if self.counter == 0: reactor.stop() else: print self.counter, '...2' self.counter -= 1 reactor.callLater(0.5, self.count2) def count3(self): from twisted.internet import reactor if self.counter == 0: reactor.stop() else: print self.counter, '...3' self.counter -= 1 reactor.callLater(0.25, self.count3) from twisted.internet import reactor reactor.callWhenRunning(Countdown().count1) reactor.callWhenRunning(Countdown().count2) reactor.callWhenRunning(Countdown().count3) print 'Start!' reactor.run() print 'Stop!' Output Start! 5 ...1 5 ...2 5 ...3 4 ...3 4 ...2 3 ...3 2 ...3 4 ...1 3 ...2 1 ...3 Stop! I was under the impression that while all three counters should count down at their own speed and complete their 5->0 progression, the program would wait for them all to complete before exiting. Am I misunderstanding something in the ways of Twisted here?
[ "I am unfamiliar with twisted, but from skimming google results it looks like reactor is an event loop. You only have one of them, so the first counter to hit reactor.stop() stops the loop.\nTo do what you want you need to remove the reactor.stop() calls and structure things so that when the last timer hits the end...
[ 1, 0 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0003851899_python_twisted.txt
Q: Justadistraction: tokenizing English without whitespaces. Murakami SheepMan I wondered how you would go about tokenizing strings in English (or other western languages) if whitespaces were removed? The inspiration for the question is the Sheep Man character in the Murakami novel 'Dance Dance Dance' In the novel, the Sheep Man is translated as saying things like: "likewesaid, we'lldowhatwecan. Trytoreconnectyou, towhatyouwant," said the Sheep Man. "Butwecan'tdoit-alone. Yougottaworktoo." So, some punctuation is kept, but not all. Enough for a human to read, but somewhat arbitrary. What would be your strategy for building a parser for this? Common combinations of letters, syllable counts, conditional grammars, look-ahead/behind regexps etc.? Specifically, python-wise, how would you structure a (forgiving) translation flow? Not asking for a completed answer, just more how your thought process would go about breaking the problem down. I ask this in a frivolous manner, but I think it's a question that might get some interesting (nlp/crypto/frequency/social) answers. Thanks! A: I actually did something like this for work about eight months ago. I just used a dictionary of English words in a hashtable (for O(1) lookup times). I'd go letter by letter matching whole words. It works well, but there are numerous ambiguities. (asshit can be ass hit or as shit). To resolve those ambiguities would require much more sophisticated grammar analysis. A: First of all, I think you need a dictionary of English words -- you could try some methods that rely solely on some statistical analysis, but I think a dictionary has better chances of good results. Once you have the words, you have two possible approaches: You could categorize the words into grammar categories and use a formal grammar to parse the sentences -- obviously, you would sometimes get no match or multiple matches -- I'm not familiar with techniques that would allow you to loosen the grammar rules in case of no match, but I'm sure there must be some. On the other hand, you could just take some large corpus of English text and compute relative probabilities of certain words being next to each other -- getting a list of pair and triples of words. Since that data structure would be rather big, you could use word categories (grammatical and/or based on meaning) to simplify it. Then you just build an automaton and choose the most probable transitions between the words. I am sure there are many more possible approaches. You can even combine the two I mentioned, building some kind of grammar with weight attached to its rules. It's a rich field for experimenting. A: I don't know if this is of much help to you, but you might be able to make use of this spelling corrector in some way. A: This is just some quick code I wrote out that I think would work fairly well to extract words from a snippet like the one you gave... Its not fully thought out, but I think something along these lines would work if you can't find a pre-packaged type of solution textstring = "likewesaid, we'lldowhatwecan. Trytoreconnectyou, towhatyouwant," said the Sheep Man. "Butwecan'tdoit-alone. Yougottaworktoo." indiv_characters = list(textstring) #splits string into individual characters teststring = '' sequential_indiv_word_list = [] for cur_char in indiv_characters: teststring = teststring + cur_char # do some action here to test the testsring against an English dictionary where you can API into it to get True / False if it exists as an entry if in_english_dict == True: sequential_indiv_word_list.append(teststring) teststring = '' #at the end just assemble a sentence from the pieces of sequential_indiv_word_list by putting a space between each word There are some more issues to be worked out, such as if it never returns a match, this would obviously not work as it would never match if it just kept adding in more characters, however since your demo string had some spaces you could have it recognize these too and automatically start over at each of these. Also you need to account for punctuation, write conditionals like if cur_char == ',' or cur_char =='.': #do action to start new "word" automatically
Justadistraction: tokenizing English without whitespaces. Murakami SheepMan
I wondered how you would go about tokenizing strings in English (or other western languages) if whitespaces were removed? The inspiration for the question is the Sheep Man character in the Murakami novel 'Dance Dance Dance' In the novel, the Sheep Man is translated as saying things like: "likewesaid, we'lldowhatwecan. Trytoreconnectyou, towhatyouwant," said the Sheep Man. "Butwecan'tdoit-alone. Yougottaworktoo." So, some punctuation is kept, but not all. Enough for a human to read, but somewhat arbitrary. What would be your strategy for building a parser for this? Common combinations of letters, syllable counts, conditional grammars, look-ahead/behind regexps etc.? Specifically, python-wise, how would you structure a (forgiving) translation flow? Not asking for a completed answer, just more how your thought process would go about breaking the problem down. I ask this in a frivolous manner, but I think it's a question that might get some interesting (nlp/crypto/frequency/social) answers. Thanks!
[ "I actually did something like this for work about eight months ago. I just used a dictionary of English words in a hashtable (for O(1) lookup times). I'd go letter by letter matching whole words. It works well, but there are numerous ambiguities. (asshit can be ass hit or as shit). To resolve those ambiguities wou...
[ 4, 2, 1, 1 ]
[]
[]
[ "linguistics", "nlp", "python" ]
stackoverflow_0003851723_linguistics_nlp_python.txt
Q: Python: obtain the url? Whats the simpliest way to obtain the URL of the webpage you are currently on? For example if i have a python function and i call it from within a webpage, whats the best way to obtain the URL. What maybe an easier question how is how do you obtain the variables passed within the URL i.e. after the "?" I've tried calling: def return_query(self): self.request.url I have also tried def return_query2(self): self.request.query_string But i get a attrbiute error for request A: Try using def return_query(self): return self.request.URL Python is case-sensitive. Note that I have not tried this myself, but after looking at the documentation, I would hazard a guess that your only problem is the case of URL - make sure it is all capitals and you should be fine. A: Is this a Zope question? context.absolute_url() might come close to what the original questioner intended.
Python: obtain the url?
Whats the simpliest way to obtain the URL of the webpage you are currently on? For example if i have a python function and i call it from within a webpage, whats the best way to obtain the URL. What maybe an easier question how is how do you obtain the variables passed within the URL i.e. after the "?" I've tried calling: def return_query(self): self.request.url I have also tried def return_query2(self): self.request.query_string But i get a attrbiute error for request
[ "Try using\ndef return_query(self):\n return self.request.URL\n\nPython is case-sensitive. \nNote that I have not tried this myself, but after looking at the documentation, I would hazard a guess that your only problem is the case of URL - make sure it is all capitals and you should be fine.\n", "Is this a Zo...
[ 1, 1 ]
[]
[]
[ "python", "zope" ]
stackoverflow_0003252010_python_zope.txt
Q: Sending email from gmail using Python I'm trying to teaching myself how to program by building programs/scrips that will be useful to me. I'm trying to retool a script I found online to send an email through gmail using a python script (Source). This example has a portion of code to attach files, which I don't want/need. I have tweaked the code so that I don't have to attach any files, but when I do this I lose the body of the email. Any help/tips on how to modify the code to keep the body of the email intact? Appreciate the help. A: The sample code you're using creates a multi-part MIME message. Everything is an attachment, including the message body. If you just want to send a plain old single-part plain text or HTML message, you don't need any of the MIME stuff. It just adds complexity. See that bit in your sample's sendmail() call where it says msg.as_string()? Well, that just converts the MIME objects you've created to text. It's easy enough to specify the text yourself, if you are dealing with text to start with. The function below is similar to code I used for mailing a log file in a script I wrote. It takes a plain text body and converts it to preformatted HTML (to work better in Outlook). If you want to keep it plain text, just take out the line that adds the HTML tags, and change the Content-Type header to "text/plain." import smtplib def sendmail(sender, recipient, subject, body, server="localhost"): "Sends an e-mail to the specified recipient." body = ("<html><head></head><body><pre>%s</pre></body></html>" % body.replace("&", "&amp;").replace("<", "&lt;")) headers = ["From: " + sender, "Subject: " + subject, "To: " + recipient, "MIME-Version: 1.0", "Content-Type: text/html"] headers = "\r\n".join(headers) session = smtplib.SMTP(server) session.sendmail(sender, recipient, headers + "\r\n\r\n" + body) session.quit() A: I see you have a clue about what you did wrong. In this case, the method attach() refers to adding something to the email. This is confusing because when we thing about attaching things and email, we think about adding extra files, not the body. Based on some other examples, it seems that the attach method is used to add either text to the body or a file to the email. So, to answer your question, the attach method does what you think it does and more--it also adds text to the body. Welcome to SO, by the way. Smart choice picking Python for learning how to script.
Sending email from gmail using Python
I'm trying to teaching myself how to program by building programs/scrips that will be useful to me. I'm trying to retool a script I found online to send an email through gmail using a python script (Source). This example has a portion of code to attach files, which I don't want/need. I have tweaked the code so that I don't have to attach any files, but when I do this I lose the body of the email. Any help/tips on how to modify the code to keep the body of the email intact? Appreciate the help.
[ "The sample code you're using creates a multi-part MIME message. Everything is an attachment, including the message body. If you just want to send a plain old single-part plain text or HTML message, you don't need any of the MIME stuff. It just adds complexity. See that bit in your sample's sendmail() call where it...
[ 5, 1 ]
[]
[]
[ "gmail", "python" ]
stackoverflow_0003852193_gmail_python.txt
Q: python re problem i test re on some pythonwebshelll, all of them are encounter issue if i use a=re.findall(r"""<ul>[\s\S]*?<li><a href="(?P<link>[\s\S]*?)"[\s\S]*?<img src="(?P<img>[\s\S]*?)"[\s\S]*?<br/>[\s\S]*?</li>[\s\S]*?</li>[\s\S]*?</li>[\s\S]*?</ul>""",html) print a it's ok but if i use a=re.findall(r"""<ul>[\s\S]*?<li><a href="(?P<link>[\s\S]*?)"[\s\S]*?<img src="(?P<img>[\s\S]*?)"[\s\S]*?<br/>[\s\S]*?</li>[\s\S]*?</li>[\s\S]*?</li>[\s\S]*?</ul>d""",html) print a it will block the server and wait always like the server is dead,also i have tested on regexbuddy the only difference betwwen the two snippet code is at the end of the second snippet code's regur expression,i add a character 'd' any one can explain why occures this A: The expression [\s\S]*? can match any amount of anything. This can potentially cause an enormous amount of backtracking in the case that the match fails. If you are more specific about what you can and can't match then it will allow the match to fail faster. Also, I'd advise you to use an HTML parser instead of regular expressions for this. Beautiful Soup is an excellent library that is easy to use. A: Your regex is suffering from catastrophic backtracking. If it can find a match it's fine, but if it can't, it has to try a virtually infinite number of possibilities before it gives up. Every one of those [\s\S]*? constructs ends up trying to match all the way to the end of the document, and the interaction between them creates a staggering amount of useless work. Python doesn't support atomic groups, but here's a little trick you can use to imitate them: a=re.findall(r"""(?=(<ul>[\s\S]*?<li><a href="(?P<link>[\s\S]*?)"[\s\S]*?<img src="(?P<img>[\s\S]*?)"[\s\S]*?<br/>[\s\S]*?</li>[\s\S]*?</li>[\s\S]*?</li>[\s\S]*?</ul>))\1d""",html) print a If the lookahead succeeds, the whole <UL> element is captured in group #1, the match position resets to the beginning of the element, then the \1 backreference consumes the element. But if the next character is not d, it does not go back and muck about with all those [\s\S]*? constructs again, like your regex does. Instead, the regex engine goes straight back to the beginning of the <UL> element, then bumps ahead one position (so it's between the < and the u) and tries the lookahead again from the beginning. It keeps doing that until it finds another match for the lookahead, or it reaches the end of the document. In this way, it will fail (the expected result) in about the same time your first regex took to succeed. Note that I'm not presenting this trick as a solution, just trying to answer your question as to why your regex seems to hang. If I were offering a solution, I would say to stop using [\s\S]*? (or [\s\S]*, or .*, or .*?); you're relying on that too much. Try to be as specific as you reasonably can--for example, instead of: <a href="(?P<link>[\s\S]*?)"[\s\S]*?<img src="(?P<img>[\s\S]*?)"[\s\S]*? ...use: <a href="(?P<link>[^"]*)"[^>]*><img src="(?P<img>[^"]*)"[^>]*> But even that has serious problems. You should seriously consider using an HTML parser for this job. I love regexes too, but you're asking too much from them.
python re problem
i test re on some pythonwebshelll, all of them are encounter issue if i use a=re.findall(r"""<ul>[\s\S]*?<li><a href="(?P<link>[\s\S]*?)"[\s\S]*?<img src="(?P<img>[\s\S]*?)"[\s\S]*?<br/>[\s\S]*?</li>[\s\S]*?</li>[\s\S]*?</li>[\s\S]*?</ul>""",html) print a it's ok but if i use a=re.findall(r"""<ul>[\s\S]*?<li><a href="(?P<link>[\s\S]*?)"[\s\S]*?<img src="(?P<img>[\s\S]*?)"[\s\S]*?<br/>[\s\S]*?</li>[\s\S]*?</li>[\s\S]*?</li>[\s\S]*?</ul>d""",html) print a it will block the server and wait always like the server is dead,also i have tested on regexbuddy the only difference betwwen the two snippet code is at the end of the second snippet code's regur expression,i add a character 'd' any one can explain why occures this
[ "The expression [\\s\\S]*? can match any amount of anything. This can potentially cause an enormous amount of backtracking in the case that the match fails. If you are more specific about what you can and can't match then it will allow the match to fail faster.\nAlso, I'd advise you to use an HTML parser instead of...
[ 7, 4 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003852009_python_regex.txt
Q: Howto do reference to ints by name in Python I want to have a a reference that reads as "whatever variable of name 'x' is pointing to" with ints so that it behaves as: >>> a = 1 >>> b = 2 >>> c = (a, b) >>> c (1, 2) >>> a = 3 >>> c (3, 2) I know I could do something similar with lists by doing: >>> a = [1] >>> b = [2] >>> c = (a, b) >>> c ([1], [2]) >>> a[0] = 3 >>> c ([3], [2]) but this can be easily lost if one assigns a or b to something instead of their elements. Is there a simple way to do this? A: No, there isn't a direct way to do this in Python. The reason is that both scalar values (numbers) and tuples are immutable. Once you have established a binding from a name to an immutable value (such as the name c with the tuple (1, 2)), nothing you do except reassigning c can change the value it's bound to. Note that in your second example, although the tuple is itself immutable, it contains references to mutable values. So it appears as though the tuple changes, but the identity of the tuple remains constant and only the mutable parts are changing. A: Whatever possible solution you come up with the second last line will always destroy it: a = 3 This will assign a completely new content to the variable. Unless a stands for a property of an object or something (or a key in a list, as you did in your own example), you won't be able to have a relation between the first and last a. A: If you just need the current values to be placed in a tuple on the fly you could use a lambda. You'll have to call c, not just return it or use it, but that may be acceptable in your situation. Something like this: >>> a = 1 >>> b = 2 >>> c = lambda: (a, b) >>> c() (1, 2) >>> a = 3 >>> c() (3, 2) A: There isn't a way in Python, not only because numbers are immutable, but also because you don't have pointers. Wrapping the value in a list simulates that you have pointers, so that's the best you can do. A: class ByRefValue(object): def __init__(self, value): self.value = value Pass it around wherever you like, remembering that you need to access the value member rather than the entire object. Alternatively, globals().get('a', 0) will return the value of a if it is in the global namespace (or zero if it isn't). Finally: import threading tls = threading.local() tls.a = 1 If you import tls into every module where you need it, you will access the same value for a on each thread. Depending on how your program is set up, this may be acceptable, ideal or useless. A: You can try creating your own pointer class and your own pointer storage object to emulate the system's internal stack.
Howto do reference to ints by name in Python
I want to have a a reference that reads as "whatever variable of name 'x' is pointing to" with ints so that it behaves as: >>> a = 1 >>> b = 2 >>> c = (a, b) >>> c (1, 2) >>> a = 3 >>> c (3, 2) I know I could do something similar with lists by doing: >>> a = [1] >>> b = [2] >>> c = (a, b) >>> c ([1], [2]) >>> a[0] = 3 >>> c ([3], [2]) but this can be easily lost if one assigns a or b to something instead of their elements. Is there a simple way to do this?
[ "No, there isn't a direct way to do this in Python. The reason is that both scalar values (numbers) and tuples are immutable. Once you have established a binding from a name to an immutable value (such as the name c with the tuple (1, 2)), nothing you do except reassigning c can change the value it's bound to.\nNot...
[ 4, 2, 2, 1, 1, 0 ]
[]
[]
[ "pass_by_reference", "python", "standard_library" ]
stackoverflow_0003851829_pass_by_reference_python_standard_library.txt
Q: Syntax error with IF statement in Python 3.0 I am teaching myself some Python and I have come across a problem which is probably plainly obvious, except that I can't see it and I need another pair of eyes. I am making a small game I made into a gui program. I have this section of code, which when run gives me "Traceback (most recent call last): File "", line 21, in Syntax Error: if playguess == "A":: , line 2124" Line 21 being if playguess == "A": There may be a couple unrelated things wrong, but it's the IF statement that is baffling me right now. I have imported the Tkinter module, I just copied the part that I thought was relevant. def compare(): R = Label(main, text = 'Yes you are right !') W = Label(main, text = "No, It's "+str(states[state]) #if playerguess == str(states[state]): if playguess == "A": R.pack() else: W.pack() #print ("Guess State Capitols") state = choosestate() main = Tk() main.title("Guess State Capitols") main.geometry('450x100+200+100') Q = Label(main,text = 'What is the capitol of ' +state) Q.pack() playerguess = Entry(main) playerguess.pack() playguess = playerguess.get() main.mainloop() A: The line: W = Label(main, text = "No, It's "+str(states[state]) Doesn't have a closing parentheses for the Label() class/function. Therefore, the if statement is interpreted as being inside parentheses, which doesn't work.
Syntax error with IF statement in Python 3.0
I am teaching myself some Python and I have come across a problem which is probably plainly obvious, except that I can't see it and I need another pair of eyes. I am making a small game I made into a gui program. I have this section of code, which when run gives me "Traceback (most recent call last): File "", line 21, in Syntax Error: if playguess == "A":: , line 2124" Line 21 being if playguess == "A": There may be a couple unrelated things wrong, but it's the IF statement that is baffling me right now. I have imported the Tkinter module, I just copied the part that I thought was relevant. def compare(): R = Label(main, text = 'Yes you are right !') W = Label(main, text = "No, It's "+str(states[state]) #if playerguess == str(states[state]): if playguess == "A": R.pack() else: W.pack() #print ("Guess State Capitols") state = choosestate() main = Tk() main.title("Guess State Capitols") main.geometry('450x100+200+100') Q = Label(main,text = 'What is the capitol of ' +state) Q.pack() playerguess = Entry(main) playerguess.pack() playguess = playerguess.get() main.mainloop()
[ "The line:\nW = Label(main, text = \"No, It's \"+str(states[state])\n\nDoesn't have a closing parentheses for the Label() class/function.\nTherefore, the if statement is interpreted as being inside parentheses, which doesn't work.\n" ]
[ 3 ]
[]
[]
[ "python", "syntax" ]
stackoverflow_0003852722_python_syntax.txt
Q: Uploading multiple files in Django without using django.forms So I've created a form that includes the following item <input type="file" name="form_file" multiple/> This tells the browser to allow the user to select multiple files while browsing. The problem I am having is is that when reading / writing the files that are being uploaded, I can only see the last of the files, not all of them. I was pretty sure I've seen this done before, but had no luck searching. Here's generally what my read looks like if request.FILES: filename = parent_id + str(random.randrange(0,100)) output_file = open(settings.PROJECT_PATH + "static/img/inventory/" + filename + ".jpg", "w") output_file.write(request.FILES["form_file"].read()) output_file.close() Now, as you can see I'm not looping through each file, because I've tried a few different ways and can't seem to find the other files (in objects and such) I added in this print(request.FILES["form_file"]) and was only getting the last filename, as expected. Is there some trick to get to the other files? Am I stuck with a single file upload? Thanks! A: Based on your file element form_file, the value in request.FILES['form_file'] should be a list of files. So you can do something like: for upfile in request.FILES.getlist('form_file'): filename = upfile.name # instead of "filename" specify the full path and filename of your choice here fd = open(filename, 'w') fd.write(upfile['content']) fd.close() Using chunks: for upfile in request.FILES.getlist('form_file'): filename = upfile.name fd = open(filename, 'w+') # or 'wb+' for binary file for chunk in upfile.chunks(): fd.write(chunk) fd.close()
Uploading multiple files in Django without using django.forms
So I've created a form that includes the following item <input type="file" name="form_file" multiple/> This tells the browser to allow the user to select multiple files while browsing. The problem I am having is is that when reading / writing the files that are being uploaded, I can only see the last of the files, not all of them. I was pretty sure I've seen this done before, but had no luck searching. Here's generally what my read looks like if request.FILES: filename = parent_id + str(random.randrange(0,100)) output_file = open(settings.PROJECT_PATH + "static/img/inventory/" + filename + ".jpg", "w") output_file.write(request.FILES["form_file"].read()) output_file.close() Now, as you can see I'm not looping through each file, because I've tried a few different ways and can't seem to find the other files (in objects and such) I added in this print(request.FILES["form_file"]) and was only getting the last filename, as expected. Is there some trick to get to the other files? Am I stuck with a single file upload? Thanks!
[ "Based on your file element form_file, the value in request.FILES['form_file'] should be a list of files. So you can do something like: \nfor upfile in request.FILES.getlist('form_file'):\n filename = upfile.name\n # instead of \"filename\" specify the full path and filename of your choice here\n fd = op...
[ 6 ]
[]
[]
[ "django", "file_upload", "python" ]
stackoverflow_0003852744_django_file_upload_python.txt
Q: error with django model query I encountered an error when doing the following retrieval: class status(models.Model): pid = models.IntegerField() phase = models.TextField() rejected = models.IntegerField() accepted = models.IntegerField() type = models.IntegerField(default=1) date = models.DateTimeField(primary_key = True) time_taken = models.IntegerField(null = True) class Meta: db_table = "crawl_status_ss" query: statusIn = status.objects.get(pid=12345,phase='crawling') Error: django.db.utils.DatabaseError: current transaction is aborted, commands ignored until end of transaction block Does anyone knows whats the reason? EDIT: In my previous section of my code, I have an exception when inserting an entry to another table, but i caught the exception: for entry in blogEntries: link = entry['link'].encode('utf-8') title = entry['title'].encode('utf-8') date1 = entry['date'][:10].encode('utf-8') content = entry['content'].encode('utf-8') try: post = postTitle(site_id=url,post_url=link,post_title=title) post.save() postId = post.post_id hashString = getMD5Hash(content) blogContent = postContent(post_content=content,post_id=post,hash=hashString,site_id = url,post_date=date1) blogContent.save() except: print 'Error:' + str(sys.exc_value) continue A: Django stats a database transaction for your view. So when you catch the exception, it means the transaction is in a failed state and you can't run any more SQls. You should really try to figure what the actual problem is when it fails either in your post.save or blogContent.save methods. If you really don't care (since you just catch the exception and continue), you should manage transactions yourself. See the docs for help on this: Managing database transactions
error with django model query
I encountered an error when doing the following retrieval: class status(models.Model): pid = models.IntegerField() phase = models.TextField() rejected = models.IntegerField() accepted = models.IntegerField() type = models.IntegerField(default=1) date = models.DateTimeField(primary_key = True) time_taken = models.IntegerField(null = True) class Meta: db_table = "crawl_status_ss" query: statusIn = status.objects.get(pid=12345,phase='crawling') Error: django.db.utils.DatabaseError: current transaction is aborted, commands ignored until end of transaction block Does anyone knows whats the reason? EDIT: In my previous section of my code, I have an exception when inserting an entry to another table, but i caught the exception: for entry in blogEntries: link = entry['link'].encode('utf-8') title = entry['title'].encode('utf-8') date1 = entry['date'][:10].encode('utf-8') content = entry['content'].encode('utf-8') try: post = postTitle(site_id=url,post_url=link,post_title=title) post.save() postId = post.post_id hashString = getMD5Hash(content) blogContent = postContent(post_content=content,post_id=post,hash=hashString,site_id = url,post_date=date1) blogContent.save() except: print 'Error:' + str(sys.exc_value) continue
[ "Django stats a database transaction for your view. So when you catch the exception, it means the transaction is in a failed state and you can't run any more SQls. You should really try to figure what the actual problem is when it fails either in your post.save or blogContent.save methods. If you really don't ca...
[ 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003852813_django_django_models_python.txt
Q: Django authentication from an automated source I have a set of URL's in my django application that trigger certain actions or processes. This would be similar to cron jobs. I have a script that polls one or more of these URLS at some regular inverval and I'm interested in adding a layer of security. I'd like to set up an account for the script and require authentication before the proccesses would execute. I've been reading around in the Django user authentication documentation, along with python's urllib2 library and I'm just a bit lost. I have some ideas of how this might be done, but I dont' have a lot of experience in security like this. Any suggested reading materials? A: I have a script that polls one or more of these URLS at some regular inverval and I'm interested in adding a layer of security. Have you considered using Celery? Celery works seamlessly with Django. This will let you periodically run jobs using the same authentication mechanism as the rest of the project. You can also make things a bit more uniform by avoiding urllib2.
Django authentication from an automated source
I have a set of URL's in my django application that trigger certain actions or processes. This would be similar to cron jobs. I have a script that polls one or more of these URLS at some regular inverval and I'm interested in adding a layer of security. I'd like to set up an account for the script and require authentication before the proccesses would execute. I've been reading around in the Django user authentication documentation, along with python's urllib2 library and I'm just a bit lost. I have some ideas of how this might be done, but I dont' have a lot of experience in security like this. Any suggested reading materials?
[ "\nI have a script that polls one or more of these URLS at some regular inverval and I'm interested in adding a layer of security.\n\nHave you considered using Celery? Celery works seamlessly with Django. This will let you periodically run jobs using the same authentication mechanism as the rest of the project. You...
[ 1 ]
[]
[]
[ "django", "django_authentication", "python", "urllib2" ]
stackoverflow_0003852933_django_django_authentication_python_urllib2.txt
Q: Run a python script and a compiled c code without terminal or dock item in Mac OS X For great help from stackoverflow, the development for the Mac version of my program is done. Now I need to deploy my program, and I was wondering if there is any way to "hide" my running Python code (it also runs .so library and it seems it makes a dock item to appear). The program is supposed to be running in the background and it would be great if I can hide any terminal or dock items. In Windows or linux, it was easy, but I am still not that used to Mac and could not figure out how to do this. Thank you, Joon A: Are you using py2app and distributing a package? If so, you can set LSBackgroundOnly in info.plist. right-click on your package choose *Show Package Contents* double click on info.plist in Contents to open the property list editor Add Child "Application is background only" (That makes the application invisible. If your application has a UI and you just want to hide the dock icon, use LSUIElement, which is "Application is agent" in the property list editor.) A: have you tried using the nohup? lets say you have a launch script to start your program: launch.sh: nohup your_program & exit
Run a python script and a compiled c code without terminal or dock item in Mac OS X
For great help from stackoverflow, the development for the Mac version of my program is done. Now I need to deploy my program, and I was wondering if there is any way to "hide" my running Python code (it also runs .so library and it seems it makes a dock item to appear). The program is supposed to be running in the background and it would be great if I can hide any terminal or dock items. In Windows or linux, it was easy, but I am still not that used to Mac and could not figure out how to do this. Thank you, Joon
[ "Are you using py2app and distributing a package? If so, you can set LSBackgroundOnly in info.plist. \nright-click on your package\nchoose *Show Package Contents*\ndouble click on info.plist in Contents to open the property list editor\nAdd Child \"Application is background only\"\n\n(That makes the application inv...
[ 1, 0 ]
[]
[]
[ "command_line", "macos", "python" ]
stackoverflow_0003853038_command_line_macos_python.txt
Q: Running cx_Oracle under jython on tomcat I'm trying to load cx_Oracle using tomcat. Loading from python works fine, but for jython I'm getting "module not found". My system.path includes site-packages that contains cx_Oracle.so. I'm new to jython and I've not had time to familiarize myself with all the variables but I believe I have all the necessary environment variables exported, though clearly something is amiss. A: Ben, not all modules that work with Python in CPython implementation will work on other implementations. If such module use system specific calls, or binds to some .dll/.so file it will not work on other Python implementation. cx_Oracle is one os such modules: it binds to Oracle client (there are cx_Oracle versions for various Oracle versions and various operational systems). I think you should use JDBC driver if you want to access Oracle from Jython. Then you can use JDBC calls, or use zxJDBC Jython module that makes JDBC drivers available via DB API calls. I used both JDBC (with zxJDBC) and cx_Oracle in programs that can work from CPython and Jython. To see it in action look to my recipe to dump Oracle db schema to text
Running cx_Oracle under jython on tomcat
I'm trying to load cx_Oracle using tomcat. Loading from python works fine, but for jython I'm getting "module not found". My system.path includes site-packages that contains cx_Oracle.so. I'm new to jython and I've not had time to familiarize myself with all the variables but I believe I have all the necessary environment variables exported, though clearly something is amiss.
[ "Ben, not all modules that work with Python in CPython implementation will work on other implementations. If such module use system specific calls, or binds to some .dll/.so file it will not work on other Python implementation. cx_Oracle is one os such modules: it binds to Oracle client (there are cx_Oracle version...
[ 4 ]
[]
[]
[ "cx_oracle", "jython", "python" ]
stackoverflow_0003820593_cx_oracle_jython_python.txt
Q: Creating and rendering structure with years and months in django In my blogging app I need a structure (created as a variable in context processor) that will store months number and corresponding year of 5 consecutive months till current one. So if current month is december, we will have year: 2010 and months: 12,11,10,9,8. If month will be january we will have years 2010: months: 1 and years: 2009 months: 12, 11, 10, 9 . My goal is to show an archive in the following form: - 2010 - January - 2009 - December - November - October - September How to create it and what structure should I use ? And then how to show it ? I think I need some nested structure but which will be possible to render in django < 1.2 ? I've started it on my own but got completely lost at some point : now = datetime.datetime.now() years = [] months = [] archive = [] if now.month in range(5, 12, 1): months = range(now.month, now.month-5, -1) if months: years = now.year else: diff = 5 - now.month for i in range(1, now.month, 1): archive.append({ "month": i, "year": now.year, }) for i in range(0, diff, 1): tmpMonth = 12 - int(i) archive.append({ "month": tmpMonth, "year": now.year-1, }) if archive: years = [now.year, now.year-1] A: How to create it and what structure should I use ? I'd go with a list of year-month tuples. Here is a sample implementation. You'll need the handy python-dateutil library to make this work. from datetime import datetime from dateutil.relativedelta import relativedelta def get_5_previous_year_months(a_day): """Returns a list of year, month tuples for the current and previous 5 months relative to a_day""" current_year, current_month = a_day.year, a_day.month first_of_month = datetime(current_year, current_month, 1) previous_months = (first_of_month - relativedelta(months = months) for months in range(0, 5)) return ((pm.year, pm.month) for pm in previous_months) def get_current_and_5_previous_months(): return get_5_previous_year_months(datetime.today()) And then how to show it ? Here is a very simplistic way to show it. I think you can clean it up by replacing the <ul> elements with <div> and styling it appropriately. <ul> {% for year, month in previous_year_months %} {% ifchanged year %} </ul><li>{{ year }}</li><ul> {% endifchanged %} <li>{{ month }}</li> {% endfor %} </ul> Where previous_year_months is a context variable corresponding to the result returned by get_current_and_5_previous_months.
Creating and rendering structure with years and months in django
In my blogging app I need a structure (created as a variable in context processor) that will store months number and corresponding year of 5 consecutive months till current one. So if current month is december, we will have year: 2010 and months: 12,11,10,9,8. If month will be january we will have years 2010: months: 1 and years: 2009 months: 12, 11, 10, 9 . My goal is to show an archive in the following form: - 2010 - January - 2009 - December - November - October - September How to create it and what structure should I use ? And then how to show it ? I think I need some nested structure but which will be possible to render in django < 1.2 ? I've started it on my own but got completely lost at some point : now = datetime.datetime.now() years = [] months = [] archive = [] if now.month in range(5, 12, 1): months = range(now.month, now.month-5, -1) if months: years = now.year else: diff = 5 - now.month for i in range(1, now.month, 1): archive.append({ "month": i, "year": now.year, }) for i in range(0, diff, 1): tmpMonth = 12 - int(i) archive.append({ "month": tmpMonth, "year": now.year-1, }) if archive: years = [now.year, now.year-1]
[ "\nHow to create it and what structure should I use ?\n\nI'd go with a list of year-month tuples. Here is a sample implementation. You'll need the handy python-dateutil library to make this work. \nfrom datetime import datetime\nfrom dateutil.relativedelta import relativedelta\n\ndef get_5_previous_year_months(a_da...
[ 2 ]
[]
[]
[ "django", "django_templates", "python", "python_datetime" ]
stackoverflow_0003852255_django_django_templates_python_python_datetime.txt
Q: My python code won't run outside of my IDE The following code runs fine in my IDE (PyScripter), however it won't run outside of it. When I go into computer then python26 and double click the file (a .pyw in this case) it fails to run. I have no idea why it's doing this, can anyone please shed some light? This is in windows 7 BTW. My code: #!/usr/bin/env python import matplotlib from mpl_toolkits.mplot3d import axes3d,Axes3D import matplotlib.pyplot as plt from matplotlib import cm import numpy as np from numpy import arange, sin, pi from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.figure import Figure from matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter import Tkinter import sys class E(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.protocol("WM_DELETE_WINDOW", self.dest) self.main() def main(self): self.fig = plt.figure() self.fig = plt.figure(figsize=(4,4)) ax = Axes3D(self.fig) u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = 10 * np.outer(np.cos(u), np.sin(v)) y = 10 * np.outer(np.sin(u), np.sin(v)) z = 10 * np.outer(np.ones(np.size(u)), np.cos(v)) t = ax.plot_surface(x, y, z, rstride=4, cstride=4,color='lightgreen',linewidth=1) self.frame = Tkinter.Frame(self) self.frame.pack(padx=15,pady=15) self.canvas = FigureCanvasTkAgg(self.fig, master=self.frame) self.canvas.get_tk_widget().pack(side='top', fill='both') self.canvas._tkcanvas.pack(side='top', fill='both', expand=1) self.btn = Tkinter.Button(self,text='button',command=self.alt) self.btn.pack() def alt (self): print 9 def dest(self): self.destroy() sys.exit() if __name__ == "__main__": app = E(None) app.title('Embedding in TK') app.mainloop() EDIT: I tried to import the module in the command line and got the following warning. Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import matplotlib Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python26\lib\site-packages\matplotlib\__init__.py", line 129, in <module> from rcsetup import defaultParams, validate_backend, validate_toolbar File "C:\Python26\lib\site-packages\matplotlib\rcsetup.py", line 19, in <module> from matplotlib.colors import is_color_like File "C:\Python26\lib\site-packages\matplotlib\colors.py", line 54, in <module> import matplotlib.cbook as cbook File "C:\Python26\lib\site-packages\matplotlib\cbook.py", line 168, in <module> class Scheduler(threading.Thread): AttributeError: 'module' object has no attribute 'Thread' >>> EDIT(2) I tried what McSmooth said and got the following output. Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import threading >>> print threading.__file__ threading.pyc >>> threading.Thread Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'Thread' >>> A: unless you've been messing around with your standard library, it seems that you have a file named threading.py somewhere on your python path that is replacing the standard one. Try: >>>import threading >>>print threading.__file__ and make sure that it's the one in your python lib directory (it should beC:\python26\lib). If it's not the right file that's getting imported, then you'll have to rename the fake one to something else. If it is the right file, then try: >>>threading.Thread and see if that throws an exception in the REPL. update That's weird. on my system, it gives the name of the source file. either save as a file or run at the command line the following code to find it. import os.path as op import sys files = (op.join(path, 'threading.py') for path in sys.path) print filter(op.exists, files) A: You most likely need to adjust your PYTHONPATH; this is a list of directories Python uses to find modules. See also How to add to the pythonpath in windows 7? . A: From Windows command shell get into python shell by typing python binary (you should get something like '>>>'). Here type import matplotlib (your package name which you are trying to import), if you get an error like ImportError: No module named matplotlib that means as Matthew F suggested you need to update your PYTHONPATH (either in User specific env or in Windows System env) otherwise post the error message that you are getting while running the script.
My python code won't run outside of my IDE
The following code runs fine in my IDE (PyScripter), however it won't run outside of it. When I go into computer then python26 and double click the file (a .pyw in this case) it fails to run. I have no idea why it's doing this, can anyone please shed some light? This is in windows 7 BTW. My code: #!/usr/bin/env python import matplotlib from mpl_toolkits.mplot3d import axes3d,Axes3D import matplotlib.pyplot as plt from matplotlib import cm import numpy as np from numpy import arange, sin, pi from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg from matplotlib.figure import Figure from matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter import Tkinter import sys class E(Tkinter.Tk): def __init__(self,parent): Tkinter.Tk.__init__(self,parent) self.parent = parent self.protocol("WM_DELETE_WINDOW", self.dest) self.main() def main(self): self.fig = plt.figure() self.fig = plt.figure(figsize=(4,4)) ax = Axes3D(self.fig) u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = 10 * np.outer(np.cos(u), np.sin(v)) y = 10 * np.outer(np.sin(u), np.sin(v)) z = 10 * np.outer(np.ones(np.size(u)), np.cos(v)) t = ax.plot_surface(x, y, z, rstride=4, cstride=4,color='lightgreen',linewidth=1) self.frame = Tkinter.Frame(self) self.frame.pack(padx=15,pady=15) self.canvas = FigureCanvasTkAgg(self.fig, master=self.frame) self.canvas.get_tk_widget().pack(side='top', fill='both') self.canvas._tkcanvas.pack(side='top', fill='both', expand=1) self.btn = Tkinter.Button(self,text='button',command=self.alt) self.btn.pack() def alt (self): print 9 def dest(self): self.destroy() sys.exit() if __name__ == "__main__": app = E(None) app.title('Embedding in TK') app.mainloop() EDIT: I tried to import the module in the command line and got the following warning. Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import matplotlib Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\Python26\lib\site-packages\matplotlib\__init__.py", line 129, in <module> from rcsetup import defaultParams, validate_backend, validate_toolbar File "C:\Python26\lib\site-packages\matplotlib\rcsetup.py", line 19, in <module> from matplotlib.colors import is_color_like File "C:\Python26\lib\site-packages\matplotlib\colors.py", line 54, in <module> import matplotlib.cbook as cbook File "C:\Python26\lib\site-packages\matplotlib\cbook.py", line 168, in <module> class Scheduler(threading.Thread): AttributeError: 'module' object has no attribute 'Thread' >>> EDIT(2) I tried what McSmooth said and got the following output. Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import threading >>> print threading.__file__ threading.pyc >>> threading.Thread Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'Thread' >>>
[ "unless you've been messing around with your standard library, it seems that you have a file named threading.py somewhere on your python path that is replacing the standard one. Try:\n>>>import threading\n>>>print threading.__file__\n\nand make sure that it's the one in your python lib directory (it should beC:\\py...
[ 5, 1, 1 ]
[]
[]
[ "matplotlib", "python", "windows_7" ]
stackoverflow_0003853136_matplotlib_python_windows_7.txt
Q: Using cython .pxd files to Augment pure python files Following the example here, "Augementing .pxd", I'm trying to use ".pxd" files to augment a pure python file. (Add type definitions external to the pure python file). python file: class A(object): def foo(self, i=3, x=None): print "Big" if i > 1000 else "Small" pxd file: cdef class A: cpdef foo(self, int i, x) I've got a dictionary, which I'm defaulting to "None" in python. Unfortunately, cython doesn't like this. If I use my "pure" python file, without declaring a type or declare the type as "dict" in the pxd file I get the error: "Signature not compatible with previous declaration" I noticed that it will compile if I do NOT specify a default value, but there's a reason for declaring the defaults. Is there a way this can be handled? A: Optional arguments in cpdef functions are declared differently from cdef functions which essentially is same as python functions. Your .pxd file should be modified to be written as cdef class A: cpdef foo(self, int i=*, x=*)
Using cython .pxd files to Augment pure python files
Following the example here, "Augementing .pxd", I'm trying to use ".pxd" files to augment a pure python file. (Add type definitions external to the pure python file). python file: class A(object): def foo(self, i=3, x=None): print "Big" if i > 1000 else "Small" pxd file: cdef class A: cpdef foo(self, int i, x) I've got a dictionary, which I'm defaulting to "None" in python. Unfortunately, cython doesn't like this. If I use my "pure" python file, without declaring a type or declare the type as "dict" in the pxd file I get the error: "Signature not compatible with previous declaration" I noticed that it will compile if I do NOT specify a default value, but there's a reason for declaring the defaults. Is there a way this can be handled?
[ "Optional arguments in cpdef functions are declared differently from cdef functions which essentially is same as python functions.\nYour .pxd file should be modified to be written as\ncdef class A:\n cpdef foo(self, int i=*, x=*)\n\n" ]
[ 14 ]
[]
[]
[ "cython", "python" ]
stackoverflow_0003852742_cython_python.txt
Q: Success unit testing pyinotify? I'm using pyinotify to mirror files from a source directory to a destination directory. My code seems to be working when I execute it manually, but I'm having trouble getting accurate unit test results. I think the problem boils down to this: I have to use ThreadedNotifier in my tests, otherwise they will just hang, waiting for manual input. Because I'm using another thread, my tests and the Notifier get out of sync. Tests that pass when running observational, manual tests fail when running the unit tests. Has anyone succeeded in unit testing pyinotify? A: When unit testing, things like threads and the file system should normally be factored out. Do you have a reason to unit test with the actual file system, user input, etc.? Python makes it very easy to monkey patch; you could for example, replace the entire os/sys module with a mock object (such as Python Mock) so that you never need to deal with the file system. This will also make your tests run much more quickly. If you want to do functional testing with the file system, I'd recommend setting up a virtual machine that will have a known state, and reverting to that state every time you run the tests. You could also simulate user input, file operations, etc. as needed. Edit Here's a simple example of how to fake, or mock the "open" function. Say you've got a module, my_module, with a get_text_upper function: def get_text_upper(filename): return open(filename).read().upper() You want to test this without actually touching the file system (eventually you'll start just passing file objects instead of file names to avoid this but for now...). You can mock the open function so that it returns a StringIO object instead: from cStringIO import StringIO def fake_open(text): fp = StringIO() fp.write(text) fp.seek(0) return fp def test_get_text(): my_module.open = lambda *args, **kwargs : fake_open("foo") text = my_module.get_text_upper("foo.txt") assert text == "FOO", text Using a mocking library just makes this process a lot easier and more flexible. Here's a stackoverflow post on mocking libraries for python.
Success unit testing pyinotify?
I'm using pyinotify to mirror files from a source directory to a destination directory. My code seems to be working when I execute it manually, but I'm having trouble getting accurate unit test results. I think the problem boils down to this: I have to use ThreadedNotifier in my tests, otherwise they will just hang, waiting for manual input. Because I'm using another thread, my tests and the Notifier get out of sync. Tests that pass when running observational, manual tests fail when running the unit tests. Has anyone succeeded in unit testing pyinotify?
[ "When unit testing, things like threads and the file system should normally be factored out. Do you have a reason to unit test with the actual file system, user input, etc.?\nPython makes it very easy to monkey patch; you could for example, replace the entire os/sys module with a mock object (such as Python Mock) s...
[ 5 ]
[]
[]
[ "pyinotify", "python", "synchronization", "unit_testing" ]
stackoverflow_0003852935_pyinotify_python_synchronization_unit_testing.txt
Q: Google App Engine Python - sort by density in ListProperty Is that possible to return a db result which sort by density matching in ListProperty For example, I have a db.ListProperty(basestring) with below value: list_A = ['a1','a2','a3','a4','a5'] list_B = ['b1','b2','b3','b4','b5'] list_C = ['a1','a2','b1','b2','b3'] giving to_be_match_list = ['a1','b1','b2'] and return result in order of density match list_C return 1st, matching a1, b1 and b2 list_B return 2nd, matching b1 and b2 list_A return last, matching a1 Thanks in advance. A: No, you can't do that in BigTable (GQL). If you grabbed all of the results, however, and wanted to sort them, you could do something like this: some_lists = [list_A, list_B, list_C] some_lists.sort(key=lambda x: len(set(to_be_match_list) & set(x)), reverse=True)
Google App Engine Python - sort by density in ListProperty
Is that possible to return a db result which sort by density matching in ListProperty For example, I have a db.ListProperty(basestring) with below value: list_A = ['a1','a2','a3','a4','a5'] list_B = ['b1','b2','b3','b4','b5'] list_C = ['a1','a2','b1','b2','b3'] giving to_be_match_list = ['a1','b1','b2'] and return result in order of density match list_C return 1st, matching a1, b1 and b2 list_B return 2nd, matching b1 and b2 list_A return last, matching a1 Thanks in advance.
[ "No, you can't do that in BigTable (GQL).\nIf you grabbed all of the results, however, and wanted to sort them, you could do something like this:\nsome_lists = [list_A, list_B, list_C]\nsome_lists.sort(key=lambda x: len(set(to_be_match_list) & set(x)), reverse=True)\n\n" ]
[ 4 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003853598_google_app_engine_python.txt
Q: How to access a data structure from a currently running Python process on Linux? I have a long-running Python process that is generating more data than I planned for. My results are stored in a list that will be serialized (pickled) and written to disk when the program completes -- if it gets that far. But at this rate, it's more likely that the list will exhaust all 1+ GB free RAM and the process will crash, losing all my results in the process. I plan to modify my script to write results to disk periodically, but I'd like to save the results of the currently-running process if possible. Is there some way I can grab an in-memory data structure from a running process and write it to disk? I found code.interact(), but since I don't have this hook in my code already, it doesn't seem useful to me (Method to peek at a Python program running right now). I'm running Python 2.5 on Fedora 8. Any thoughts? Thanks a lot. Shahin A: There is not much you can do for a running program. The only thing I can think of is to attach the gdb debugger, stop the process and examine the memory. Alternatively make sure that your system is set up to save core dumps then kill the process with kill --sigsegv <pid>. You should then be able to open the core dump with gdb and examine it at your leisure. There are some gdb macros that will let you examine python data structures and execute python code from within gdb, but for these to work you need to have compiled python with debug symbols enabled and I doubt that is your case. Creating a core dump first then recompiling python with symbols will NOT work, since all the addresses will have changed from the values in the dump. Here are some links for introspecting python from gdb: http://wiki.python.org/moin/DebuggingWithGdb http://chrismiles.livejournal.com/20226.html or google for 'python gdb' N.B. to set linux to create coredumps use the ulimit command. ulimit -a will show you what the current limits are set to. ulimit -c unlimited will enable core dumps of any size. A: While certainly not very pretty you could try to access data of your process through the proc filesystem.. /proc/[pid-of-your-process]. The proc filesystem stores a lot of per process information such as currently open file pointers, memory maps and what not. With a bit of digging you might be able to access the data you need though. Still i suspect you should rather look at this from within python and do some runtime logging&debugging. A: +1 Very interesting question. I don't know how well this might work for you (especially since I don't know if you'll reuse the pickled list in the program), but I would suggest this: as you write to disk, print out the list to STDOUT. When you run your python script (I'm guessing also from command line), redirect the output to append to a file like so: python myScript.py >> logFile. This should store all the lists in logFile. This way, you can always take a look at what's in logFile and you should have the most up to date data structures in there (depending on where you call print). Hope this helps A: This answer has info on attaching gdb to a python process, with macros that will get you into a pdb session in that process. I haven't tried it myself but it got 20 votes. Sounds like you might end up hanging the app, but also seems to be worth the risk in your case.
How to access a data structure from a currently running Python process on Linux?
I have a long-running Python process that is generating more data than I planned for. My results are stored in a list that will be serialized (pickled) and written to disk when the program completes -- if it gets that far. But at this rate, it's more likely that the list will exhaust all 1+ GB free RAM and the process will crash, losing all my results in the process. I plan to modify my script to write results to disk periodically, but I'd like to save the results of the currently-running process if possible. Is there some way I can grab an in-memory data structure from a running process and write it to disk? I found code.interact(), but since I don't have this hook in my code already, it doesn't seem useful to me (Method to peek at a Python program running right now). I'm running Python 2.5 on Fedora 8. Any thoughts? Thanks a lot. Shahin
[ "There is not much you can do for a running program. The only thing I can think of is to attach the gdb debugger, stop the process and examine the memory. Alternatively make sure that your system is set up to save core dumps then kill the process with kill --sigsegv <pid>. You should then be able to open the cor...
[ 3, 1, 0, 0 ]
[]
[]
[ "disk", "fedora", "linux", "memory", "python" ]
stackoverflow_0003852857_disk_fedora_linux_memory_python.txt
Q: Get process ID with python How to get the current process id with python on windows? there are this function os.geteuid() but its only works with linux/unix could someone tell what it the pythonic way to get the current process id on windows. A: Do you really want the process ID? Then the answer is this: >>> import os >>> os.getpid() 5328 on either Windows or Unix (documentation of os.getpid). os.geteuid() doesn't get the process ID, which makes me wonder whether you're really asking a different question...?
Get process ID with python
How to get the current process id with python on windows? there are this function os.geteuid() but its only works with linux/unix could someone tell what it the pythonic way to get the current process id on windows.
[ "Do you really want the process ID? Then the answer is this:\n>>> import os\n>>> os.getpid()\n5328\n\non either Windows or Unix (documentation of os.getpid).\nos.geteuid() doesn't get the process ID, which makes me wonder whether you're really asking a different question...?\n" ]
[ 48 ]
[]
[]
[ "python", "winapi", "windows" ]
stackoverflow_0003853703_python_winapi_windows.txt
Q: Manipulating the DateTime object in Google app engine I am making a blog and store the publishing date of a blog post in the datastore. It looks like this: post.date = datetime.datetime.now() It now displays like: 2010-10-04 07:30:15.204352 But I want the datetime to be displayed differently. How (and where) can I set that how the date is displayed? I'd like to set the date format like in UNIX date function (like %Y/%m etc). I tried to add some parameters in my templates but that returned errors. Thanks in advance! -skazhy A: I think strftime is the method you're looking for. From the link: >>> d.strftime("%d/%m/%y") '11/03/02' If you pass in the result of the strftime in your 'template_values' or similar (the dictionary you use to pass parameters to the template) instead of the actual date it will be displayed instead. A: You can use .strftime() on a datetime object to do the formatting. See the relevant python documentation for details.
Manipulating the DateTime object in Google app engine
I am making a blog and store the publishing date of a blog post in the datastore. It looks like this: post.date = datetime.datetime.now() It now displays like: 2010-10-04 07:30:15.204352 But I want the datetime to be displayed differently. How (and where) can I set that how the date is displayed? I'd like to set the date format like in UNIX date function (like %Y/%m etc). I tried to add some parameters in my templates but that returned errors. Thanks in advance! -skazhy
[ "I think strftime is the method you're looking for.\nFrom the link:\n>>> d.strftime(\"%d/%m/%y\")\n'11/03/02'\n\nIf you pass in the result of the strftime in your 'template_values' or similar (the dictionary you use to pass parameters to the template) instead of the actual date it will be displayed instead.\n", "...
[ 5, 2 ]
[]
[]
[ "datetime", "google_app_engine", "python" ]
stackoverflow_0003853877_datetime_google_app_engine_python.txt
Q: Python doctest example failure This is probably a silly question. I am experimenting with python doctest, and I try to run this example ending with if __name__ == "__main__": import doctest doctest.testfile("example.txt") I have put "example.txt" in the same folder as the source file containing the example code, but I get the following error: Traceback (most recent call last): File "test_av_funktioner.py", line 61, in <module> doctest.testfile("example.txt") File "C:\Python26\lib\doctest.py", line 1947, in testfile text, filename = _load_testfile(filename, package, module_relative) File "C:\Python26\lib\doctest.py", line 219, in _load_testfile return open(filename).read(), filename IOError: [Errno 2] No such file or directory: 'example.txt' Can I somehow tell/set where the doctest module is searching for the specified file? A: Doctest searches relative to the calling module's directory by default (but you can override this). Quoting the docs for doctest.testfile: Optional argument module_relative specifies how the filename should be interpreted: If module_relative is True (the default), then filename specifies an OS-independent module-relative path. By default, this path is relative to the calling module’s directory; but if the package argument is specified, then it is relative to that package. To ensure OS-independence, filename should use / characters to separate path segments, and may not be an absolute path (i.e., it may not begin with /). If module_relative is False, then filename specifies an OS-specific path. The path may be absolute or relative; relative paths are resolved with respect to the current working directory.
Python doctest example failure
This is probably a silly question. I am experimenting with python doctest, and I try to run this example ending with if __name__ == "__main__": import doctest doctest.testfile("example.txt") I have put "example.txt" in the same folder as the source file containing the example code, but I get the following error: Traceback (most recent call last): File "test_av_funktioner.py", line 61, in <module> doctest.testfile("example.txt") File "C:\Python26\lib\doctest.py", line 1947, in testfile text, filename = _load_testfile(filename, package, module_relative) File "C:\Python26\lib\doctest.py", line 219, in _load_testfile return open(filename).read(), filename IOError: [Errno 2] No such file or directory: 'example.txt' Can I somehow tell/set where the doctest module is searching for the specified file?
[ "Doctest searches relative to the calling module's directory by default (but you can override this).\nQuoting the docs for doctest.testfile:\n\nOptional argument module_relative specifies how the filename should be interpreted:\n\nIf module_relative is True (the default), then filename specifies an OS-independent m...
[ 3 ]
[]
[]
[ "doctest", "python" ]
stackoverflow_0003853980_doctest_python.txt
Q: Can I unit test an inner function in python? Is there any way to write unittests or doctests for innerfunc? def outerfunc(): def innerfunc(): do_something() return innerfunc() A: Only if you provide a way to extract the inner function object itself, e.g. def outerfunc(calltheinner=True): def innerfunc(): do_something() if calltheinner: return innerfunc() else: return innerfunc If your outer function insists on hiding the inner one entirely inside itself (never letting it percolate outside when properly cajoled to do so), your unit-tests are powerless to defeat this strong bid for extreme and total privacy;-). A: This is actually an old open Python issue: Issue 1650090: doctest doesn't find nested functions There's a candidate patch (from 2007) that makes doctest find nested functions, but someone probably needs to push this.
Can I unit test an inner function in python?
Is there any way to write unittests or doctests for innerfunc? def outerfunc(): def innerfunc(): do_something() return innerfunc()
[ "Only if you provide a way to extract the inner function object itself, e.g.\ndef outerfunc(calltheinner=True):\n def innerfunc():\n do_something()\n if calltheinner:\n return innerfunc()\n else:\n return innerfunc\n\nIf your outer function insists on hiding the inner one entirely insi...
[ 8, 4 ]
[]
[]
[ "doctest", "python", "unit_testing" ]
stackoverflow_0002136910_doctest_python_unit_testing.txt
Q: approximate comparison in python I want to make '==' operator use approximate comparison in my program: float values x and y are equal (==) if abs(x-y)/(0.5(x+y)) < 0.001 What's a good way to do that? Given that float is a built-in type, I don't think I can redefine the == operator, can I? Note that I would like to use other features of float, the only thing that I'd like to change is the equality operator. EDIT: Thank you for the answers, and I understand your arguments about readability and other issues. That said, I really would prefer, if possible, to actually keep using the regular float type, instead of having a new class or a new comparison function. Is it even possible to redefine == operator for regular floats? My reasons are:: (a) everyone using the program I'm writing wants the floats to be compared this way (b) there's no way in the world anyone would ever want to use the default == for floats.. Why is it even in the language??? (c) I dislike extra words in the code; obviously using the existing float results in no changes in the code whatsoever EDIT 2. Now that I know I can't overload the == operator for float, I have to change my question. It will become so different that I'll make a new one at custom comparison for built-in containers A: You can create a new class deriving from the builtin float type, and then overwrite the necessary operators: class InexactFloat(float): def __eq__(self, other): try: return abs(self.real - other) / (0.5 * (abs(self.real) + abs(other))) < 0.001 except ZeroDivisionError: # Could do another inexact comparison here, this is just an example: return self.real == other def __ne__(self, other): return not self.__eq__(other) print 5.2 == 5.20000000000001 # False print 5.2 != 5.20000000000001 # True print InexactFloat(5.2) == InexactFloat(5.20000000000001) # True print InexactFloat(5.2) != InexactFloat(5.20000000000001) # False print InexactFloat(-5) == -5 # True # Works for InexactFloat <-> float comparison print 5.0 == InexactFloat(5.0) # True print InexactFloat(5.0) == 5.0 # True # Zero division case (note how I implemented it above!) print InexactFloat(-0.00001) == InexactFloat(0.00001) # False print InexactFloat(-0.000000001) == InexactFloat(0.000000001) # False print InexactFloat(-5) == InexactFloat(5) # False # Unit test for fixed negative numbers problem print InexactFloat(-5) == InexactFloat(-10) # False You may also want to overwrite operators like <= etc. A: Your definition has two problems: Missing an * Will attempt to divide by zero if x + y == 0.0 (which covers a possibly frequent case x == y == 0.0) Try this instead: define approx_Equal(x, y, tolerance=0.001): return abs(x-y) <= 0.5 * tolerance * (x + y) Edit: Note the use of <= instead of < ... needed to make the x == y == 0.0 case work properly. I wouldn't try to override == Edit 2: You wrote: there's no way in the world anyone would ever want to use the default == for floats.. Why is it even in the language??? No way? Suppose you have a function that returns a float, and you have a brainwave about an algorithm that would produce the same answers faster and/or more elegantly; how do you test it? A: If you wrap the numbers in a class you can overload "==" with: def __eq__(self, x): return abs(x - self.x) / (0.5 * (x + self.x)) < 0.001 however you should rewrite the expression to abs(x - self.x) < 0.0005 * (x + self.x) to avoid zero division.
approximate comparison in python
I want to make '==' operator use approximate comparison in my program: float values x and y are equal (==) if abs(x-y)/(0.5(x+y)) < 0.001 What's a good way to do that? Given that float is a built-in type, I don't think I can redefine the == operator, can I? Note that I would like to use other features of float, the only thing that I'd like to change is the equality operator. EDIT: Thank you for the answers, and I understand your arguments about readability and other issues. That said, I really would prefer, if possible, to actually keep using the regular float type, instead of having a new class or a new comparison function. Is it even possible to redefine == operator for regular floats? My reasons are:: (a) everyone using the program I'm writing wants the floats to be compared this way (b) there's no way in the world anyone would ever want to use the default == for floats.. Why is it even in the language??? (c) I dislike extra words in the code; obviously using the existing float results in no changes in the code whatsoever EDIT 2. Now that I know I can't overload the == operator for float, I have to change my question. It will become so different that I'll make a new one at custom comparison for built-in containers
[ "You can create a new class deriving from the builtin float type, and then overwrite the necessary operators:\nclass InexactFloat(float):\n def __eq__(self, other):\n try:\n return abs(self.real - other) / (0.5 * (abs(self.real) + abs(other))) < 0.001\n except ZeroDivisionError:\n ...
[ 18, 8, 3 ]
[]
[]
[ "comparison", "python" ]
stackoverflow_0003854047_comparison_python.txt
Q: Python asyncore with very low timeout I have written a program that communicates with many servers at once using the asyncore module. For the most part I am just responding to data received from the servers, but occasionally I need to send some data "out-of-sync". With the default timeout of 30 seconds there is an obvious delay before the packet gets sent, so I have lowered the timeout to 0.1 for more responsiveness. My question is: is it a good idea performance-wise to use a timeout with such a low value, and if not, is there another more performant way of accomplishing the same thing? What's the best practice for doing this? A: To answer my own question: For this type of polling application it is necessary to have a small timeout value. The timeout specifies how long the internal select function blocks waiting for a socket to become active. If you are sending data frequently you need to set the timeout to a small value, so that select polls your socket for writable data at an acceptable interval. Otherwise select will block for too long before checking and can cause these kinds of delays. In the end I used a timeout of 0.05 seconds.
Python asyncore with very low timeout
I have written a program that communicates with many servers at once using the asyncore module. For the most part I am just responding to data received from the servers, but occasionally I need to send some data "out-of-sync". With the default timeout of 30 seconds there is an obvious delay before the packet gets sent, so I have lowered the timeout to 0.1 for more responsiveness. My question is: is it a good idea performance-wise to use a timeout with such a low value, and if not, is there another more performant way of accomplishing the same thing? What's the best practice for doing this?
[ "To answer my own question: \nFor this type of polling application it is necessary to have a small timeout value. The timeout specifies how long the internal select function blocks waiting for a socket to become active. If you are sending data frequently you need to set the timeout to a small value, so that select ...
[ 1 ]
[]
[]
[ "asyncore", "python", "sockets" ]
stackoverflow_0003789220_asyncore_python_sockets.txt
Q: How to distinguish between a sequence and a mapping I would like to perform an operation on an argument based on the fact that it might be a map-like object or a sequence-like object. I understand that no strategy is going to be 100% reliable for type-like checking, but I'm looking for a robust solution. Based on this answer, I know how to determine whether something is a sequence and I can do this check after checking if the object is a map. def ismap(arg): # How to implement this? def isseq(arg): return hasattr(arg,"__iter__") def operation(arg): if ismap(arg): # Do something with a dict-like object elif isseq(arg): # Do something with a sequence-like object else: # Do something else Because a sequence can be seen as a map where keys are integers, should I just try to find a key that is not an integer? Or maybe I could look at the string representation? or...? UPDATE I selected SilentGhost's answer because it looks like the most "correct" one, but for my needs, here is the solution I ended up implementing: if hasattr(arg, 'keys') and hasattr(arg, '__getitem__'): # Do something with a map elif hasattr(arg, '__iter__'): # Do something with a sequence/iterable else: # Do something else Essentially, I don't want to rely on an ABC because there are many custom classes that behave like sequences and dictionary but that still do not extend the python collections ABCs (see @Manoj comment). I thought the keys attribute (mentioned by someone who removed his/her answer) was a good enough check for mappings. Classes extending the Sequence and Mapping ABCs will work with this solution as well. A: >>> from collections import Mapping, Sequence >>> isinstance('ac', Sequence) True >>> isinstance('ac', Mapping) False >>> isinstance({3:42}, Mapping) True >>> isinstance({3:42}, Sequence) False collections abstract base classes (ABCs) A: Sequences have an __add__ method that implements the + operator. Maps do not have that method, since adding to a map requires both a key and a value, and the + operator only has one right-hand side. So you may try: def ismap(arg): return isseq(arg) and not hasattr(arg, "__add__")
How to distinguish between a sequence and a mapping
I would like to perform an operation on an argument based on the fact that it might be a map-like object or a sequence-like object. I understand that no strategy is going to be 100% reliable for type-like checking, but I'm looking for a robust solution. Based on this answer, I know how to determine whether something is a sequence and I can do this check after checking if the object is a map. def ismap(arg): # How to implement this? def isseq(arg): return hasattr(arg,"__iter__") def operation(arg): if ismap(arg): # Do something with a dict-like object elif isseq(arg): # Do something with a sequence-like object else: # Do something else Because a sequence can be seen as a map where keys are integers, should I just try to find a key that is not an integer? Or maybe I could look at the string representation? or...? UPDATE I selected SilentGhost's answer because it looks like the most "correct" one, but for my needs, here is the solution I ended up implementing: if hasattr(arg, 'keys') and hasattr(arg, '__getitem__'): # Do something with a map elif hasattr(arg, '__iter__'): # Do something with a sequence/iterable else: # Do something else Essentially, I don't want to rely on an ABC because there are many custom classes that behave like sequences and dictionary but that still do not extend the python collections ABCs (see @Manoj comment). I thought the keys attribute (mentioned by someone who removed his/her answer) was a good enough check for mappings. Classes extending the Sequence and Mapping ABCs will work with this solution as well.
[ ">>> from collections import Mapping, Sequence\n>>> isinstance('ac', Sequence)\nTrue\n>>> isinstance('ac', Mapping)\nFalse\n>>> isinstance({3:42}, Mapping)\nTrue\n>>> isinstance({3:42}, Sequence)\nFalse\n\ncollections abstract base classes (ABCs)\n", "Sequences have an __add__ method that implements the + operato...
[ 9, 3 ]
[]
[]
[ "dictionary", "python", "sequence" ]
stackoverflow_0003854470_dictionary_python_sequence.txt
Q: Python: Replacing an element in a list of lists (#2) A previous question with the same title as mine has been posted, with (I think) the same question, but had other problems in the code. I was not able to determine if that case was identical to mine or not. Anyway, I want to replace an element within a list in a list. Code: myNestedList = [[0,0]]*4 # [[0, 0], [0, 0], [0, 0], [0, 0]] myNestedList[1][1] = 5 I now expect: [[0, 0], [0, 5], [0, 0], [0, 0]] But I get: [[0, 5], [0, 5], [0, 5], [0, 5]] Why? This is replicated in the command line. Python 3.1.2 (r312:79147, Apr 15 2010, 15:35:48) [GCC 4.4.3] on linux2 A: You are having four references to same object by * 4, use instead list comprehension with range for counting: my_nested_list = [[0,0] for count in range(4)] my_nested_list[1][1] = 5 print(my_nested_list) To explain little more concretely the problem: yourNestedList = [[0,0]]*4 yourNestedList[1][1] = 5 print('Original wrong: %s' % yourNestedList) my_nested_list = [[0,0] for count in range(4)] my_nested_list[1][1] = 5 print('Corrected: %s' % my_nested_list) # your nested list is actually like this one_list = [0,0] your_nested_list = [ one_list for count in range(4) ] one_list[1] = 5 print('Another way same: %s' % your_nested_list)
Python: Replacing an element in a list of lists (#2)
A previous question with the same title as mine has been posted, with (I think) the same question, but had other problems in the code. I was not able to determine if that case was identical to mine or not. Anyway, I want to replace an element within a list in a list. Code: myNestedList = [[0,0]]*4 # [[0, 0], [0, 0], [0, 0], [0, 0]] myNestedList[1][1] = 5 I now expect: [[0, 0], [0, 5], [0, 0], [0, 0]] But I get: [[0, 5], [0, 5], [0, 5], [0, 5]] Why? This is replicated in the command line. Python 3.1.2 (r312:79147, Apr 15 2010, 15:35:48) [GCC 4.4.3] on linux2
[ "You are having four references to same object by * 4, use instead list comprehension with range for counting:\nmy_nested_list = [[0,0] for count in range(4)]\nmy_nested_list[1][1] = 5\nprint(my_nested_list)\n\nTo explain little more concretely the problem:\nyourNestedList = [[0,0]]*4\nyourNestedList[1][1] = 5\npri...
[ 22 ]
[]
[]
[ "list", "mutable", "python" ]
stackoverflow_0003854870_list_mutable_python.txt
Q: What is for Python what 'explode' is for PHP? I had a string which is stored in a variable myvar = "Rajasekar SP". I want to split it with delimiter like we do using explode in PHP. What is the equivalent in Python? A: Choose one you need: >>> s = "Rajasekar SP def" >>> s.split(' ') ['Rajasekar', 'SP', '', 'def'] >>> s.split() ['Rajasekar', 'SP', 'def'] >>> s.partition(' ') ('Rajasekar', ' ', 'SP def') str.split and str.partition A: The alternative for explode in php is split. The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default. >>> "Rajasekar SP".split() ['Rajasekar', 'SP'] >>> "Rajasekar SP".split('a',2) ['R','j','sekar SP']
What is for Python what 'explode' is for PHP?
I had a string which is stored in a variable myvar = "Rajasekar SP". I want to split it with delimiter like we do using explode in PHP. What is the equivalent in Python?
[ "Choose one you need:\n>>> s = \"Rajasekar SP def\"\n>>> s.split(' ')\n['Rajasekar', 'SP', '', 'def']\n>>> s.split()\n['Rajasekar', 'SP', 'def']\n>>> s.partition(' ')\n('Rajasekar', ' ', 'SP def')\n\nstr.split and str.partition\n", "The alternative for explode in php is split.\nThe first parameter is the delimi...
[ 200, 17 ]
[]
[]
[ "php", "python", "string" ]
stackoverflow_0003854867_php_python_string.txt
Q: Django 1.2 : strange logging behavior I have a really strange problem with the standard logging module used in django views. Sometimes it works perfectly and sometimes it does not log messages. Here is the structure of my code : /mysite/ (Django root) my_logging.py (logging configuration) settings.py views.py (global views) data_objects.py (objects only containing data, similar to POJO) uploader/ (application) views.py (uploader views) --> This is where I have problems Here is the code of my_logging.py : import logging import logging.handlers from django.conf import settings is_initialized = False def init_logger(): """ Initializes the logging for the application. Configure the root logger and creates the handlers following the settings. This function should not be used directly from outside the module and called only once. """ # Create the logger server_logger = logging.getLogger() server_logger.setLevel(logging.DEBUG) # Set the logging format for files files_formatter = logging.Formatter(settings.LOGGING_FORMAT_FILE) # Rotating file handler for errors error_handler = logging.handlers.RotatingFileHandler( settings.LOGGING_ERROR_FILE, maxBytes=settings.LOGGING_ERROR_FILE_SIZE, backupCount=settings.LOGGING_ERROR_FILE_COUNT, ) error_handler.setLevel(logging.WARNING) error_handler.setFormatter(files_formatter) # Rotating file handler for info info_handler = logging.handlers.RotatingFileHandler( settings.LOGGING_INFO_FILE, maxBytes=settings.LOGGING_INFO_FILE_SIZE, backupCount=settings.LOGGING_INFO_FILE_COUNT, ) info_handler.setLevel(logging.INFO) info_handler.setFormatter(files_formatter) # Add the handlers to the logger server_logger.addHandler(info_handler) server_logger.addHandler(error_handler) # Init once at first import if not is_initialized: init_logger() is_initialized = True Here are parts of uploader/views.py (#... = code skipped): #... import mysite.my_logging import logging #... # The messages in the following view are written correctly : @login_required def delete(request, file_id): """ Delete the file corresponding to the given ID and confirm the deletion to the user. @param request: the HTTP request object @type request: django.http.HttpRequest @return: django.http.HttpResponse - the response to the client (html) """ # Get the file object form the database and raise a 404 if not found f = get_object_or_404(VideoFile, pk=file_id) # TODO: check if the deletion is successful # Get the video directory dir_path = os.path.dirname(f.file.path) # Delete the file f.delete() try: # Delete the video directory recursively shutil.rmtree(dir_path) logging.info("File \"%(file)s\" and its directory have been deleted by %(username)s",{'file': f.title,'username': request.user.username}) messages.success(request, _('The video file "%s" has been successfully deleted.') % f.title) except OSError: logging.warning("File \"%(id)d\" directory cannot be completely deleted. Some files may still be there.",{'id': f.id,}) messages.warning(request, _("The video file \"%s\" has been successfully deleted, but not its directory. There should not be any problem but useless disk usage.") % f.title) return HttpResponseRedirect(reverse('mysite.uploader.views.list')) #... # The messages in the following view are NOT written at all: @csrf_exempt def get_thumblist(request,file_id): """ This view can be called only by POST and with the id of a video file ready for the scene editor. @param request: the HTTP request object. Must have POST as method. @type request: django.http.HttpRequest @return: django.http.HttpResponse - the response to the client (json) """ #TODO: Security, TEST logging.info("Demand of metadata for file %(id)d received.",{'id': file_id,}) if request.method == 'POST': if file_id: # Get the video file object form the database and raise a 404 if not found vid = get_object_or_404(VideoFile, pk=file_id) # ... try: # ... file operations except IOError: logging.error("Error when trying to read index file for file %(id)d !",{'id': file_id,}) except TypeError: logging.error("Error when trying to parse index file JSON for file %(id)d !",{'id': file_id,}) # ... logging.info("Returning metadata for file %(id)d.",{'id': file_id,}) return HttpResponse(json,content_type="application/json") else: logging.warning("File %(id)d is not ready",{'id': file_id,}) return HttpResponseBadRequest('file_not_ready') else: logging.warning("bad POST parameters") return HttpResponseBadRequest('bad_parameters') else: logging.warning("The GET method is not allowed") return HttpResponseNotAllowed(['POST']) and the interesting part of settings.py: # --------------------------------------- # Logging settings # --------------------------------------- #: Minimum level for logging messages. If logging.NOTSET, logging is disabled LOGGING_MIN_LEVEL = logging.DEBUG #: Error logging file path. Can be relative to the root of the project or absolute. LOGGING_ERROR_FILE = os.path.join(DIRNAME,"log/error.log") #: Size (in bytes) of the error files LOGGING_ERROR_FILE_SIZE = 10485760 # 10 MiB #: Number of backup error logging files LOGGING_ERROR_FILE_COUNT = 5 #: Info logging file path. Can be relative to the root of the project or absolute. LOGGING_INFO_FILE = os.path.join(DIRNAME,"log/info.log") #: Size (in bytes) of the info files LOGGING_INFO_FILE_SIZE = 10485760 # 10 MiB #: Number of backup error info files LOGGING_INFO_FILE_COUNT = 5 #: Format for the log files LOGGING_FORMAT_FILE = "%(asctime)s:%(name)s:%(levelname)s:%(message)s" Note that except logging everything is working fine. The data can be returned correctly in JSON format. I think there is no error in the rest of the code. Please ask if you need more information. I'm sorry about the code I removed, but I have to because of confidentiality. A: Instead of using the logging.info('My statement') syntax, I suggest you use something like the following: import logging logger = logging.getLogger('MySite') logger.info('My statement') That is, call your log statements against a logger object, instead of the logging module directly. Likewise, you'll have to tweak my_logging.py to configure that logger: # Create the logger server_logger = logging.getLogger('MySite') server_logger.setLevel(logging.DEBUG) In your views, you can log against logging.getLogger('MySite') or logging.getLogger('MySite.views'), etc.. Any logger which starts with 'MySite' will inherit your configuration. Also, while you have the right idea by setting and checking is_initialized, I don't believe that approach will work. Each time my_logging.py is imported, that variable will be set to False, thus defeating its purpose. You can use the following in settings.py to ensure that logging is only configured once: # Init once at first import if not hasattr(my_logging, 'is_initialized'): my_logging.is_initialized = False if not my_logging.is_initialized: my_logging.init_logger() my_logging.is_initialized = True I start all of my modules (except settings.py) with the following two lines: import logging logging.getLogger('MySite.ModuleInit').debug('Initializing %s' % str(__name__)) If you are still having trouble, please add those lines and then post the module initialization order for your site. There may be a strange quirk based on the order of your imports.
Django 1.2 : strange logging behavior
I have a really strange problem with the standard logging module used in django views. Sometimes it works perfectly and sometimes it does not log messages. Here is the structure of my code : /mysite/ (Django root) my_logging.py (logging configuration) settings.py views.py (global views) data_objects.py (objects only containing data, similar to POJO) uploader/ (application) views.py (uploader views) --> This is where I have problems Here is the code of my_logging.py : import logging import logging.handlers from django.conf import settings is_initialized = False def init_logger(): """ Initializes the logging for the application. Configure the root logger and creates the handlers following the settings. This function should not be used directly from outside the module and called only once. """ # Create the logger server_logger = logging.getLogger() server_logger.setLevel(logging.DEBUG) # Set the logging format for files files_formatter = logging.Formatter(settings.LOGGING_FORMAT_FILE) # Rotating file handler for errors error_handler = logging.handlers.RotatingFileHandler( settings.LOGGING_ERROR_FILE, maxBytes=settings.LOGGING_ERROR_FILE_SIZE, backupCount=settings.LOGGING_ERROR_FILE_COUNT, ) error_handler.setLevel(logging.WARNING) error_handler.setFormatter(files_formatter) # Rotating file handler for info info_handler = logging.handlers.RotatingFileHandler( settings.LOGGING_INFO_FILE, maxBytes=settings.LOGGING_INFO_FILE_SIZE, backupCount=settings.LOGGING_INFO_FILE_COUNT, ) info_handler.setLevel(logging.INFO) info_handler.setFormatter(files_formatter) # Add the handlers to the logger server_logger.addHandler(info_handler) server_logger.addHandler(error_handler) # Init once at first import if not is_initialized: init_logger() is_initialized = True Here are parts of uploader/views.py (#... = code skipped): #... import mysite.my_logging import logging #... # The messages in the following view are written correctly : @login_required def delete(request, file_id): """ Delete the file corresponding to the given ID and confirm the deletion to the user. @param request: the HTTP request object @type request: django.http.HttpRequest @return: django.http.HttpResponse - the response to the client (html) """ # Get the file object form the database and raise a 404 if not found f = get_object_or_404(VideoFile, pk=file_id) # TODO: check if the deletion is successful # Get the video directory dir_path = os.path.dirname(f.file.path) # Delete the file f.delete() try: # Delete the video directory recursively shutil.rmtree(dir_path) logging.info("File \"%(file)s\" and its directory have been deleted by %(username)s",{'file': f.title,'username': request.user.username}) messages.success(request, _('The video file "%s" has been successfully deleted.') % f.title) except OSError: logging.warning("File \"%(id)d\" directory cannot be completely deleted. Some files may still be there.",{'id': f.id,}) messages.warning(request, _("The video file \"%s\" has been successfully deleted, but not its directory. There should not be any problem but useless disk usage.") % f.title) return HttpResponseRedirect(reverse('mysite.uploader.views.list')) #... # The messages in the following view are NOT written at all: @csrf_exempt def get_thumblist(request,file_id): """ This view can be called only by POST and with the id of a video file ready for the scene editor. @param request: the HTTP request object. Must have POST as method. @type request: django.http.HttpRequest @return: django.http.HttpResponse - the response to the client (json) """ #TODO: Security, TEST logging.info("Demand of metadata for file %(id)d received.",{'id': file_id,}) if request.method == 'POST': if file_id: # Get the video file object form the database and raise a 404 if not found vid = get_object_or_404(VideoFile, pk=file_id) # ... try: # ... file operations except IOError: logging.error("Error when trying to read index file for file %(id)d !",{'id': file_id,}) except TypeError: logging.error("Error when trying to parse index file JSON for file %(id)d !",{'id': file_id,}) # ... logging.info("Returning metadata for file %(id)d.",{'id': file_id,}) return HttpResponse(json,content_type="application/json") else: logging.warning("File %(id)d is not ready",{'id': file_id,}) return HttpResponseBadRequest('file_not_ready') else: logging.warning("bad POST parameters") return HttpResponseBadRequest('bad_parameters') else: logging.warning("The GET method is not allowed") return HttpResponseNotAllowed(['POST']) and the interesting part of settings.py: # --------------------------------------- # Logging settings # --------------------------------------- #: Minimum level for logging messages. If logging.NOTSET, logging is disabled LOGGING_MIN_LEVEL = logging.DEBUG #: Error logging file path. Can be relative to the root of the project or absolute. LOGGING_ERROR_FILE = os.path.join(DIRNAME,"log/error.log") #: Size (in bytes) of the error files LOGGING_ERROR_FILE_SIZE = 10485760 # 10 MiB #: Number of backup error logging files LOGGING_ERROR_FILE_COUNT = 5 #: Info logging file path. Can be relative to the root of the project or absolute. LOGGING_INFO_FILE = os.path.join(DIRNAME,"log/info.log") #: Size (in bytes) of the info files LOGGING_INFO_FILE_SIZE = 10485760 # 10 MiB #: Number of backup error info files LOGGING_INFO_FILE_COUNT = 5 #: Format for the log files LOGGING_FORMAT_FILE = "%(asctime)s:%(name)s:%(levelname)s:%(message)s" Note that except logging everything is working fine. The data can be returned correctly in JSON format. I think there is no error in the rest of the code. Please ask if you need more information. I'm sorry about the code I removed, but I have to because of confidentiality.
[ "Instead of using the logging.info('My statement') syntax, I suggest you use something like the following:\nimport logging\nlogger = logging.getLogger('MySite')\nlogger.info('My statement')\n\nThat is, call your log statements against a logger object, instead of the logging module directly. Likewise, you'll have to...
[ 1 ]
[]
[]
[ "django", "logging", "python" ]
stackoverflow_0003853480_django_logging_python.txt
Q: What's wrong in my python code? Can anyone tell me what's wrong in this code: #!/usr/local/bin/python import os import string, sys a='sys.argv[1]' b='sys.argv[2]' os.system("scp a:/export/home/sample/backup.sql b:/home/rushi/abc.sql") it's giving the following error: ssh: a: node name or service name not known A: What is wrong: a and b don't have second and third values of sys.argv as you might've intended a and b are not related to the os.system call you're using os.system you're importing module that you're not using How to fix: use a = sys.argv[1] without the quotes, same for b. use .format method or similar % to format a string have a look at subprocess module don't import string A: the very first character of that first line should be #. A: You have bound the names "a" and "b" to the arguments passed on the command line (actually, you would have done that if you had removed the quotes after the equal sign,). But in the command that you are executing, you are NOT using them, you are using the literal "a" and "b" drives. This is a dangerous approach because you risk injections. In any case, if you trust the source of the inputs, you can escape the values for a and b, something like os.system("scp %s:/export/home/sample/backup.sql %s:/home/rushi/abc.sql" % (a, b)) This is not the recommended way to do it. A: Your code should be changed to this a=sys.argv[1] b=sys.argv[2] Since right now you are treating sys.argv[1] as strings by adding quotes also you want to do this: os.system("scp %s:/export/home/sample/backup.sql %s:/home/rushi/abc.sql" % (a,b) ) so that you add the variables to the string you are trying to call with os.system
What's wrong in my python code?
Can anyone tell me what's wrong in this code: #!/usr/local/bin/python import os import string, sys a='sys.argv[1]' b='sys.argv[2]' os.system("scp a:/export/home/sample/backup.sql b:/home/rushi/abc.sql") it's giving the following error: ssh: a: node name or service name not known
[ "What is wrong:\n\na and b don't have second and third values of sys.argv as you might've intended\na and b are not related to the os.system call\nyou're using os.system\nyou're importing module that you're not using\n\nHow to fix:\n\nuse a = sys.argv[1] without the quotes, same for b.\nuse .format method or simila...
[ 5, 2, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003854957_python.txt
Q: I have a Python list of the prime factors of a number. How do I (pythonically) find all the factors? I'm working on a Project Euler problem which requires factorization of an integer. I can come up with a list of all of the primes that are the factor of a given number. The Fundamental Theorem of Arithmetic implies that I can use this list to derive every factor of the number. My current plan is to take each number in the list of base primes and raise its power until it is no longer an integer factor to find the maximum exponents for each prime. Then, I will multiply every possible combination of prime-exponent pairs. So for example, for 180: Given: prime factors of 180: [2, 3, 5] Find maximum exponent of each factor: 180 / 2^1 = 90 180 / 2^2 = 45 180 / 2^3 = 22.5 - not an integer, so 2 is the maximum exponent of 2. 180 / 3^1 = 60 180 / 3^2 = 20 180 / 3^3 = 6.6 - not an integer, so 2 is the maximum exponent of 3. 180 / 5^1 = 36 180 / 5^2 = 7.2 - not an integer, so 1 is the maximum exponent of 5. Next, do every combination of these up to the maximum exponent to get the factors: 2^0 * 3^0 * 5^0 = 1 2^1 * 3^0 * 5^0 = 2 2^2 * 3^0 * 5^0 = 4 2^0 * 3^1 * 5^0 = 3 2^1 * 3^1 * 5^0 = 6 2^2 * 3^1 * 5^0 = 12 2^0 * 3^2 * 5^0 = 9 2^1 * 3^2 * 5^0 = 18 2^2 * 3^2 * 5^0 = 36 2^0 * 3^0 * 5^1 = 5 2^1 * 3^0 * 5^1 = 10 2^2 * 3^0 * 5^1 = 20 2^0 * 3^1 * 5^1 = 15 2^1 * 3^1 * 5^1 = 30 2^2 * 3^1 * 5^1 = 60 2^0 * 3^2 * 5^1 = 45 2^1 * 3^2 * 5^1 = 90 2^2 * 3^2 * 5^1 = 180 So the list of factors = [1, 2, 3, 4, 5, 6, 9, 10, 12, 15, 18, 20, 30, 36, 45, 60, 90, 180] Here is the code I have so far. Two problems: First, I don't think it is very Pythonic at all. I'd like to fix that. Second, I really don't have a Pythonic way to do the combinatoric second step. Out of shame, I've spared you from the ridiculous set of loops. n is the number we want to factor. listOfAllPrimes is a precalculated list of the primes up to 10 million. def getListOfFactors(n, listOfAllPrimes): maxFactor = int(math.sqrt(n)) + 1 eligiblePrimes = filter(lambda x: x <= maxFactor, listOfAllPrimes) listOfBasePrimes = filter(lambda x: n % x ==0, eligiblePrimes) listOfExponents = [] #(do I have to do this?) for x in listOfBasePrimes: y = 1 while (x**(y+1)) % n == 0: y += 1 listOfExponents.append(y) A: Instead of a list of exponents, consider simply repeating each prime factor by the number of times it is a factor. After that, working on the resulting primefactors list-with-repetitions, itertools.combinations does just what you need -- you'll just require the combinations of length 2 to len(primefactors) - 1 items included (the combinations of just one are the prime factors, that of all of them will be the original number -- if you want those too, just use range(1, len(primefactors) + 1) instead of the range(2, len(primefactors)) which my main suggestion would use). There will be repetitions in the results (e.g., 6 will appear twice as a factor of 12, since the latter's primefactors will be [2, 2, 3]) and they can of course be weeded out in the usual ways (i.e. sorted(set(results)) for example). To compute primefactors given listOfAllPrimes, consider for example: def getprimefactors(n): primefactors = [] primeind = 0 p = listOfAllPrimes[primeind] while p <= n: if n % p == 0: primefactors.append(p) n //= p else: primeind += 1 p = listOfAllPrimes[primeind] return primefactors A: Why do you begin your solution from the set of prime factors? when you factorize a number you can as easily get all its prime factors (repeated) and from them the exponents for each factor. With this in mind, you can write this: import itertools prime_factors = get_prime_factors(180) # 2, 2, 3, 3, 5 factorization = [(f, len(list(fs))) for (f, fs) in itertools.groupby(prime_factors)] # [(2, 2), (3, 2), (5, 1)] values = [[(factor**e) for e in range(exp+1)] for (factor, exp) in factorization] # [[1, 2, 4], [1, 3, 9], [1, 5]] print sorted(product(xs) for xs in itertools.product(*values)) # [1, 2, 3, 4, 5, 6, 9, 10, 12, 15, 18, 20, 30, 36, 45, 60, 90, 180] get_prime_factors and product are not implemented here, but you get the idea (both are pretty simple to write) IMHO, being mathematic problems, the Euler problems can be nicely solved using functional instead of imperative style (though I acknowledge that some solutions may not come out as pythonic as desired). A: You could use itertools.combinations() to get all possible combinations of factors once you've gotten your list of repeated-primes, such as [2, 2, 3, 3, 5] for 180. Then, simply multiplying the components from each combination will get you a factor. A: With a few cooler Python features: def factors( num ): for p in primes: if num==1: break # stop when num is 1 while True: # these factors may be repeated new, rest = divmod(num, p) # does div and mod at once if rest==0: # its divisible yield p # current prime is factor num = new # continue with the div'd number else: break # no factor so break from the while print list(factors(2*2*3*3*5*7*11*11*13)) # [2, 2, 3, 3, 5, 7, 11, 11, 13] ofc A: Here's a simple and efficient solution to the original problem: def getDivisors(n): divisors = [] d = 1 while d*d < n: if n % d == 0: divisors.append(d) divisors.append(n / d); d += 1 if d*d == n: divisors.append(d) return divisors The output list is unsorted. You can make it more "pythonic" if you want, whatever that means. A: An all in one solution; i.e. no need for an existing list of the prime factors. #!/usr/bin/python3 -O from primegen import erat3 as generate_primes # see Note[1] import operator as op, functools as ft, itertools as it def all_factors(number): prime_powers= [] for prime in generate_primes(): # for prime in listOfAllPrimes if prime > number: break this_prime_powers= [1] new_number, modulo= divmod(number, prime) while not modulo: number= new_number this_prime_powers.append(this_prime_powers[-1] * prime) new_number, modulo= divmod(number, prime) if len(this_prime_powers) > 1: prime_powers.append(this_prime_powers) # at this point: # if number was 360, prime_powers is [[1, 2, 4, 8], [1, 3, 9], [1, 5]] # if number was 210, prime_powers is [[1, 2], [1, 3], [1, 5], [1, 7]] return sorted( ft.reduce(op.mul, combination, 1) for combination in it.product(*prime_powers)) if __name__ == "__main__": def num_result(number): return number, all_factors(number) print(num_result(360)) print(num_result(210)) print(num_result(7)) Note[1]: As a prime number generator, you can choose one from How to implement an efficient infinite generator of prime numbers in Python? or use your own (e.g. your listOfAllPrimes). This produces a full factor list, i.e. including 1 and the number argument itself. If you want to omit these, you can use all_factors(number)[1:-1]. $ allfactors.py (360, [1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 18, 20, 24, 30, 36, 40, 45, 60, 72, 90, 120, 180, 360]) (210, [1, 2, 3, 5, 6, 7, 10, 14, 15, 21, 30, 35, 42, 70, 105, 210]) (7, [1, 7])
I have a Python list of the prime factors of a number. How do I (pythonically) find all the factors?
I'm working on a Project Euler problem which requires factorization of an integer. I can come up with a list of all of the primes that are the factor of a given number. The Fundamental Theorem of Arithmetic implies that I can use this list to derive every factor of the number. My current plan is to take each number in the list of base primes and raise its power until it is no longer an integer factor to find the maximum exponents for each prime. Then, I will multiply every possible combination of prime-exponent pairs. So for example, for 180: Given: prime factors of 180: [2, 3, 5] Find maximum exponent of each factor: 180 / 2^1 = 90 180 / 2^2 = 45 180 / 2^3 = 22.5 - not an integer, so 2 is the maximum exponent of 2. 180 / 3^1 = 60 180 / 3^2 = 20 180 / 3^3 = 6.6 - not an integer, so 2 is the maximum exponent of 3. 180 / 5^1 = 36 180 / 5^2 = 7.2 - not an integer, so 1 is the maximum exponent of 5. Next, do every combination of these up to the maximum exponent to get the factors: 2^0 * 3^0 * 5^0 = 1 2^1 * 3^0 * 5^0 = 2 2^2 * 3^0 * 5^0 = 4 2^0 * 3^1 * 5^0 = 3 2^1 * 3^1 * 5^0 = 6 2^2 * 3^1 * 5^0 = 12 2^0 * 3^2 * 5^0 = 9 2^1 * 3^2 * 5^0 = 18 2^2 * 3^2 * 5^0 = 36 2^0 * 3^0 * 5^1 = 5 2^1 * 3^0 * 5^1 = 10 2^2 * 3^0 * 5^1 = 20 2^0 * 3^1 * 5^1 = 15 2^1 * 3^1 * 5^1 = 30 2^2 * 3^1 * 5^1 = 60 2^0 * 3^2 * 5^1 = 45 2^1 * 3^2 * 5^1 = 90 2^2 * 3^2 * 5^1 = 180 So the list of factors = [1, 2, 3, 4, 5, 6, 9, 10, 12, 15, 18, 20, 30, 36, 45, 60, 90, 180] Here is the code I have so far. Two problems: First, I don't think it is very Pythonic at all. I'd like to fix that. Second, I really don't have a Pythonic way to do the combinatoric second step. Out of shame, I've spared you from the ridiculous set of loops. n is the number we want to factor. listOfAllPrimes is a precalculated list of the primes up to 10 million. def getListOfFactors(n, listOfAllPrimes): maxFactor = int(math.sqrt(n)) + 1 eligiblePrimes = filter(lambda x: x <= maxFactor, listOfAllPrimes) listOfBasePrimes = filter(lambda x: n % x ==0, eligiblePrimes) listOfExponents = [] #(do I have to do this?) for x in listOfBasePrimes: y = 1 while (x**(y+1)) % n == 0: y += 1 listOfExponents.append(y)
[ "Instead of a list of exponents, consider simply repeating each prime factor by the number of times it is a factor. After that, working on the resulting primefactors list-with-repetitions, itertools.combinations does just what you need -- you'll just require the combinations of length 2 to len(primefactors) - 1 it...
[ 11, 6, 3, 2, 1, 1 ]
[]
[]
[ "algorithm", "factorization", "python" ]
stackoverflow_0003643725_algorithm_factorization_python.txt
Q: Runtime model generation using django I have an application that needs to generate its models on runtime. This will be done according to the current database scheme. How can it be done? How can I create classes on runtime in python? Should I create a json representation and save it in a database and then unserialize it into a python object? A: You can try to read this http://code.djangoproject.com/wiki/DynamicModels Here is example how to create python model class: Person = type('Person', (models.Model,), { 'first_name': models.CharField(max_length=255), 'last_name': models.CharField(max_length=255), }) You can also read about python meta classes: - What is a metaclass in Python? - http://www.ibm.com/developerworks/linux/library/l-pymeta.html - http://gnosis.cx/publish/programming/metaclass_1.html A: You could base yourself on the legacy database support of django which allows you to obtain django models from the definitions found in the database : See here : http://docs.djangoproject.com/en/dev/howto/legacy-databases/?from=olddocs In particular, manage.py inspectdb allows you to create the classes in a file. You should then be able to import them on the fly. That said, it seems to me that you are on a risky path by doing this. A: I have an application that needs to generate its models on runtime. Take a look at the source code for the inspectdb management command. Inspectdb "Introspects the database tables in the database pointed-to by the NAME setting and outputs a Django model module (a models.py file) to standard output." How can I create classes on runtime in python? One way to do this is to use the functions provided by the new module (this module has been deprecated in favor of types since 2.6). Should I create a json representation and save it in a database and then unserialize it into a python object? This doesn't sound like a good idea to me. PS: All said you ought to really rethink the premise for creating classes at runtime. It seems rather extreme for a web application. Just my 2c.
Runtime model generation using django
I have an application that needs to generate its models on runtime. This will be done according to the current database scheme. How can it be done? How can I create classes on runtime in python? Should I create a json representation and save it in a database and then unserialize it into a python object?
[ "You can try to read this http://code.djangoproject.com/wiki/DynamicModels\nHere is example how to create python model class:\nPerson = type('Person', (models.Model,), {\n 'first_name': models.CharField(max_length=255),\n 'last_name': models.CharField(max_length=255),\n})\n\nYou can also read about python met...
[ 8, 2, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0003854159_django_django_models_python.txt
Q: error when exec'ing scp from python this code is giving following error: os.system("scp %s:/export/home/sample/backup.sql %s:/home/rushi/abc.sql" % (a, b)) Permission denied (publickey,keyboard-interactive). lost connection a and b are the command line arguments which accept user name and machine name as arguments: eg: root@10.88.77.77 . A: This has nothing to do with Python and everything to do with SSH. Permission denied (publickey,keyboard-interactive). It's telling you you have failed to log in. I suggest you either sort your key-based auth out or pass it a password. See: http://unixhelp.ed.ac.uk/CGI/man-cgi?ssh+1 Or instead of trying to use the scp command, use a pure-python method. A: That error is coming from scp. What happens if you run the command yourself? Are you expecting to use public key to connect or do you have to enter a password?
error when exec'ing scp from python
this code is giving following error: os.system("scp %s:/export/home/sample/backup.sql %s:/home/rushi/abc.sql" % (a, b)) Permission denied (publickey,keyboard-interactive). lost connection a and b are the command line arguments which accept user name and machine name as arguments: eg: root@10.88.77.77 .
[ "This has nothing to do with Python and everything to do with SSH.\n\nPermission denied (publickey,keyboard-interactive).\n\nIt's telling you you have failed to log in. I suggest you either sort your key-based auth out or pass it a password.\nSee: http://unixhelp.ed.ac.uk/CGI/man-cgi?ssh+1\nOr instead of trying to ...
[ 9, 0 ]
[]
[]
[ "python", "scp", "ssh" ]
stackoverflow_0003855250_python_scp_ssh.txt
Q: WX.Python and multiprocessing I have a wx.python application that takes some files and processes them when a button is clicked. I need to process them in parallel. I use this code inside the bound button function: my_pool = multiprocessing.Pool(POOLSIZE) results=[digest_pool.apply_async(self.fun, [args]) for file in list_files() ] my_pool.close() my_pool.join() for result in results : print result.get() But it seems this code is not run at all, even if I print something on fun. I didn't get any result and my GUI application got stuck. Could someone help? What is the problem here and how can I solve it using the pool multiprocessing module inside my wx frame class? A: It looks like you're running up against a pretty common problem encountered by people attempting to use threading with GUI toolkits. The core of the issue is that you must never block the main GUI thread in your code. The graphical toolkit needs to be able to constantly respond to events. When you do the my_pool.join() call, you're putting the main thread to sleep and the result is that your entire process will appear to lock up. I'm not particularly familiar with wxWidgets but I'm sure there are a few patterns out there for how to use threads with it. It's easy to spin off background threads from the GUI thread but getting the results back is usually the trick. You'll need some sort of asynchronous "work done" event that you can send to the main GUI thread when the background operation completes. Exactly how that's done differs from toolkit to toolkit. I'm not sure what the mechanism is for wxWidgets but I'd expect a quick google search would turn up an answer (or perhaps a kind commenter will provide a link ;-)
WX.Python and multiprocessing
I have a wx.python application that takes some files and processes them when a button is clicked. I need to process them in parallel. I use this code inside the bound button function: my_pool = multiprocessing.Pool(POOLSIZE) results=[digest_pool.apply_async(self.fun, [args]) for file in list_files() ] my_pool.close() my_pool.join() for result in results : print result.get() But it seems this code is not run at all, even if I print something on fun. I didn't get any result and my GUI application got stuck. Could someone help? What is the problem here and how can I solve it using the pool multiprocessing module inside my wx frame class?
[ "It looks like you're running up against a pretty common problem encountered by people attempting to use threading with GUI toolkits. The core of the issue is that you must never block the main GUI thread in your code. The graphical toolkit needs to be able to constantly respond to events. When you do the my_pool.j...
[ 1 ]
[]
[]
[ "multithreading", "python", "wxpython", "wxwidgets" ]
stackoverflow_0003854414_multithreading_python_wxpython_wxwidgets.txt
Q: How to pickle and unpickle instances of a class that inherits from defaultdict? I have a class that inherits from defaultdict like this: class listdict(defaultdict): def __init__(self): defaultdict.__init__(self, list) I can pickle it, but when I unpickle it, this happens: ('__init__() takes exactly 1 argument (2 given)', <class 'listdict'>, (<type 'list'>,)) The class does not define any special methods of the pickle protocol. Pickling and unpickling of a normal defaultdict(list) works as expected. Can anyone enlighten me? A: Types define how instances of it get pickled by defining one or more of a (fairly large) set of methods. Each has its own subtle behaviour. See the docs on the pickle protocol. In the case of collections.defaultdict, it uses the __reduce__ method: >>> l = collections.defaultdict(list) >>> l.__reduce__() (<type 'collections.defaultdict'>, (<type 'list'>,), None, None, <dictionary-itemiterator object at 0x7f031fb3c470>) The first item in the tuple there is the type, and the second item is the tuple of arguments to pass to the type when instantiating it. If you don't override __reduce__, the first item will correctly change to your type, but the second item will not. This causes the error you see. A crude example of how you could fix it: >>> import collections >>> import pickle >>> class C(collections.defaultdict): ... def __init__(self): ... collections.defaultdict.__init__(self, list) ... def __reduce__(self): ... t = collections.defaultdict.__reduce__(self) ... return (t[0], ()) + t[2:] ... >>> c = C() >>> c[1].append(2) >>> c[2].append(3) >>> c2 = pickle.loads(pickle.dumps(c)) >>> c2 == c True It's only a crude example because there's more to pickling (like __reduce_ex__) and it's all fairly intricate. In this case, using __getinitargs__ may be more convenient. Alternatively, you could make your class's __init__ method take an optional callable, defaulting to list, or you could just use a function instead of a class: def listdict(): return collections.defaultdict(list)
How to pickle and unpickle instances of a class that inherits from defaultdict?
I have a class that inherits from defaultdict like this: class listdict(defaultdict): def __init__(self): defaultdict.__init__(self, list) I can pickle it, but when I unpickle it, this happens: ('__init__() takes exactly 1 argument (2 given)', <class 'listdict'>, (<type 'list'>,)) The class does not define any special methods of the pickle protocol. Pickling and unpickling of a normal defaultdict(list) works as expected. Can anyone enlighten me?
[ "Types define how instances of it get pickled by defining one or more of a (fairly large) set of methods. Each has its own subtle behaviour. See the docs on the pickle protocol. In the case of collections.defaultdict, it uses the __reduce__ method:\n>>> l = collections.defaultdict(list)\n>>> l.__reduce__()\n(<type ...
[ 8 ]
[ "That error indicates that your 'listdict' class was expected to take one argument (the implicit self), but got two arguments.\nYour class inherits from defaultdict, and defines an initializer. This initializer calls defaultdict's initializer and passes 'list' to it, which in this case may be either a function or a...
[ -1 ]
[ "pickle", "python" ]
stackoverflow_0003855428_pickle_python.txt
Q: Longest distinct consecutive list in Python I have a list: a = [2, 3, 5, 6, 6, 7, 10, 11, 13, 14, 15, 16, 16, 17, 18, 20, 21] Is it possible to make a function that shows the longest list of distinct, consecutive elements? Please, show how to do it In this case the answer should be: 13, 14, 15, 16, 17, 18 A: Assuming your list is sorted: >>> from itertools import groupby >>> z = zip(a, a[1:]) >>> tmp = [list(j) for i, j in groupby(z, key=lambda x: (x[1] - x[0]) <= 1)] >>> max(tmp, key=len) [(13, 14), (14, 15), (15, 16), (16, 16), (16, 17), (17, 18)] >>> list(range(_[0][0], _[-1][-1]+1)) [13, 14, 15, 16, 17, 18] ETA: fixed last step; A: The simplest thing to do seems to be to loop through the list once, building any sequences you can find and then print the longest one. a = [2, 3, 5, 6, 6, 7, 10, 11, 13, 14, 15, 16, 16, 17, 18, 20, 21] seqlist = [] # List of Sequences seq = [] # Current Sequence last = -1 for item in a: # Start a new sequence if the gap from the last item is too big if item - last > 1: seqlist.append(seq) seq = [] # only add item to the sequence if it's not the same as the last if item != last: seq.append(item) last = item # Print longest sequence found print max(seqlist) A: There is probably a more pythonic way, but I can't think of it right now, so here a very basic solution: def longestDistinctConsecutiveList ( lst ): lst = list( set( lst ) ) # get rid of duplicated elements lst.sort() # sort s, l = 0, 0 for i in range( len( lst ) ): for j in range( i, len( lst ) ): if lst[j] - lst[i] == len( lst[i:j] ) > l: l = 1 + a[j] - a[i] s = i return lst[s:s+l]
Longest distinct consecutive list in Python
I have a list: a = [2, 3, 5, 6, 6, 7, 10, 11, 13, 14, 15, 16, 16, 17, 18, 20, 21] Is it possible to make a function that shows the longest list of distinct, consecutive elements? Please, show how to do it In this case the answer should be: 13, 14, 15, 16, 17, 18
[ "Assuming your list is sorted:\n>>> from itertools import groupby\n>>> z = zip(a, a[1:])\n>>> tmp = [list(j) for i, j in groupby(z, key=lambda x: (x[1] - x[0]) <= 1)]\n>>> max(tmp, key=len)\n[(13, 14), (14, 15), (15, 16), (16, 16), (16, 17), (17, 18)]\n>>> list(range(_[0][0], _[-1][-1]+1))\n[13, 14, 15, 16, 17, 18]...
[ 7, 2, 0 ]
[]
[]
[ "iteration", "list", "python" ]
stackoverflow_0003856016_iteration_list_python.txt
Q: How to make a Python string out of non-ascii "bytes" I need to create a Python string consisting of non-ascii bytes to be used as a command buffer in a C module. I can do that if I write the string by hand: mybuffer = "\x00\x00\x10" But I cannot figure out how to create the string on the fly if I have a set of integers which will become the bytes in the string. Concatenating an integer with a string is a TypeError. So if I have a list of integers lets say: myintegers = [1, 2, 3, 10] How can I convert that into a string "\x01\x02\x03\x0A" I am using Python 2.6. A: u''.join(map(unichr, myintegers)) will do what you want nicely. A: Python 2.X ''.join(chr(i) for i in myintegers) Python 3.X bytes(myintegers) A: In [28]: import struct In [29]: struct.pack('{0}B'.format(len(myintegers)),*myintegers) Out[29]: '\x01\x02\x03\n' Note that In [47]: '\x01\x02\x03\n'=="\x01\x02\x03\x0A" Out[47]: True
How to make a Python string out of non-ascii "bytes"
I need to create a Python string consisting of non-ascii bytes to be used as a command buffer in a C module. I can do that if I write the string by hand: mybuffer = "\x00\x00\x10" But I cannot figure out how to create the string on the fly if I have a set of integers which will become the bytes in the string. Concatenating an integer with a string is a TypeError. So if I have a list of integers lets say: myintegers = [1, 2, 3, 10] How can I convert that into a string "\x01\x02\x03\x0A" I am using Python 2.6.
[ "u''.join(map(unichr, myintegers)) will do what you want nicely.\n", "Python 2.X\n''.join(chr(i) for i in myintegers)\n\nPython 3.X\nbytes(myintegers)\n\n", "In [28]: import struct\n\nIn [29]: struct.pack('{0}B'.format(len(myintegers)),*myintegers)\nOut[29]: '\\x01\\x02\\x03\\n'\n\nNote that \nIn [47]: '\\x01\\...
[ 4, 3, 0 ]
[]
[]
[ "byte", "python", "string" ]
stackoverflow_0003855093_byte_python_string.txt
Q: In Python, how can I access the namespace of the main module from an imported module? Specifically, I need to get at some objects and globals from the main module in an imported module. I know how to find those things when the parent module wants some particular thing from a child module, but I can't figure out how to go in the other direction. A: import __main__ But don't do this. A: The answer you're looking for is: import __main__ main_global1= __main__.global1 However, whenever a module module1 needs stuff from the __main__ module, then: either the __main__ module should provide all necessary data as parameters to a module1 function/class, or you should put everything that needs to be shared in another module, and import it as import module2 in both __main__ and module1. A: I think this would work: import sys main_mod = sys.modules['__main__'] A: Not sure if it is a good practice but maybe you could pass the objects and variables you need as parameters to the methods or classes you call in the imported module.
In Python, how can I access the namespace of the main module from an imported module?
Specifically, I need to get at some objects and globals from the main module in an imported module. I know how to find those things when the parent module wants some particular thing from a child module, but I can't figure out how to go in the other direction.
[ "import __main__\n\nBut don't do this.\n", "The answer you're looking for is:\nimport __main__\n\nmain_global1= __main__.global1\n\nHowever, whenever a module module1 needs stuff from the __main__ module, then:\n\neither the __main__ module should provide all necessary data as parameters to a module1 function/cla...
[ 15, 11, 2, 1 ]
[]
[]
[ "module", "namespaces", "python" ]
stackoverflow_0003648339_module_namespaces_python.txt
Q: How to draw polygons with Point2D in wxPython? I have input values of x, y, z coordinates in the following format: [-11.235865 5.866001 -4.604924] [-11.262565 5.414276 -4.842384] [-11.291885 5.418229 -4.849229] [-11.235865 5.866001 -4.604924] I want to draw polygons and succeeded with making a list of wx.point objects. But I need to plot floating point coordinates so I had to change it to point2D objects but DrawPolygon doesn't seem to understand floating points, which returns error message: TypeError: Expected a sequence of length-2 sequences or wxPoints. I can't find anywhere in the API that can draw shapes based on point2D coordinates, could anyone tell me a function name will do the job? Thanks A: You just have to pass a list of XY tuples. In wxPython you don't have to explicitly use Point2D objects. points = [ (-11.235865, 5.866001), (-11.262565, 5.414276), (-11.291885, 5.418229), (-11.235865, 5.866001), ] dc.DrawPolygon(points) A: DC's only use integers. Try using Cairo or wx.GraphicsContext. A: I think you should use matplotlib as it seems you need numerical data plotting.
How to draw polygons with Point2D in wxPython?
I have input values of x, y, z coordinates in the following format: [-11.235865 5.866001 -4.604924] [-11.262565 5.414276 -4.842384] [-11.291885 5.418229 -4.849229] [-11.235865 5.866001 -4.604924] I want to draw polygons and succeeded with making a list of wx.point objects. But I need to plot floating point coordinates so I had to change it to point2D objects but DrawPolygon doesn't seem to understand floating points, which returns error message: TypeError: Expected a sequence of length-2 sequences or wxPoints. I can't find anywhere in the API that can draw shapes based on point2D coordinates, could anyone tell me a function name will do the job? Thanks
[ "You just have to pass a list of XY tuples. In wxPython you don't have to explicitly use Point2D objects.\npoints = [\n (-11.235865, 5.866001),\n (-11.262565, 5.414276),\n (-11.291885, 5.418229),\n (-11.235865, 5.866001),\n]\n\ndc.DrawPolygon(points)\n\n", "DC's only use integers. Try using Cairo or ...
[ 0, 0, 0 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0003852146_python_wxpython.txt
Q: django project directory structure and the python path I am trying to get the best possible set up for developing my django project from the start and I'm having trouble getting everything to play nicely in the directory structure. I have set up virtualenv's (env in this example) so that I can deploy a clean empty python environment for every django project. The basic structure is as follows: /env/ /bin /db <--- Django DB /downloads /lib /static <--- Where css/imgs/js etc is served from /project/ <--- Django root /__init__.py /settings.py /manage.py /appsfolder/ /appname/ /__init__.py /models/ /__init__.py /somemodel.py /urls/ /__init__.py /someurl.py /views/ /__init__.py /someview.py This is the basic layout; I want each project to have a directory for applications, and in each application have a separate folder for models, view and urls. The problem I am having is with the python path and how the modules are handled. Within an application, I don't want to have to refer to the project when importing models i.e I should be using : import appname.models.modelname not: import projectname.models.modelname to help reusablility In the models directory, I have the following init.py from model1 import ModelName1 from model2 import ModelName2 from model3 import ModelName3 __all__ = ['ModelName1', 'ModelName2', 'ModelName3'] But when I try to use a separate url file (in /appname/urls/urlfile.py) and import the models like the following: from appname.models.somemodel import ModelName I get a "module not found" error. while: from appsfolder.appname.models.somemodel import ModelName works ok I presume this is because the application is not directly on the python path, instead it is in a subfolder called appsfolder, but I'm not sure how to go about fixing this, while keeping everything reuseable and relative. I know one solution is to put all apps directly on the python path under site-packages, but I don't really like this idea, as I think that the applications should be in the project if you are using virtualenv's A: You can put the following in your settings.py to add your appsfolder to your PYTHONPATH: import os import sys PROJECT_ROOT = os.path.dirname(__file__) sys.path.insert(0, os.path.join(PROJECT_ROOT, 'appsfolder'))
django project directory structure and the python path
I am trying to get the best possible set up for developing my django project from the start and I'm having trouble getting everything to play nicely in the directory structure. I have set up virtualenv's (env in this example) so that I can deploy a clean empty python environment for every django project. The basic structure is as follows: /env/ /bin /db <--- Django DB /downloads /lib /static <--- Where css/imgs/js etc is served from /project/ <--- Django root /__init__.py /settings.py /manage.py /appsfolder/ /appname/ /__init__.py /models/ /__init__.py /somemodel.py /urls/ /__init__.py /someurl.py /views/ /__init__.py /someview.py This is the basic layout; I want each project to have a directory for applications, and in each application have a separate folder for models, view and urls. The problem I am having is with the python path and how the modules are handled. Within an application, I don't want to have to refer to the project when importing models i.e I should be using : import appname.models.modelname not: import projectname.models.modelname to help reusablility In the models directory, I have the following init.py from model1 import ModelName1 from model2 import ModelName2 from model3 import ModelName3 __all__ = ['ModelName1', 'ModelName2', 'ModelName3'] But when I try to use a separate url file (in /appname/urls/urlfile.py) and import the models like the following: from appname.models.somemodel import ModelName I get a "module not found" error. while: from appsfolder.appname.models.somemodel import ModelName works ok I presume this is because the application is not directly on the python path, instead it is in a subfolder called appsfolder, but I'm not sure how to go about fixing this, while keeping everything reuseable and relative. I know one solution is to put all apps directly on the python path under site-packages, but I don't really like this idea, as I think that the applications should be in the project if you are using virtualenv's
[ "You can put the following in your settings.py to add your appsfolder to your PYTHONPATH:\nimport os\nimport sys\n\nPROJECT_ROOT = os.path.dirname(__file__)\nsys.path.insert(0, os.path.join(PROJECT_ROOT, 'appsfolder'))\n\n" ]
[ 16 ]
[]
[]
[ "django", "django_models", "python", "pythonpath" ]
stackoverflow_0003856891_django_django_models_python_pythonpath.txt
Q: UnicodeEncodeError when reading pdf with pyPdf Guys i had posted a question earlier pypdf python tool .dont mark this as duplicate as i get this error indicated below import sys import pyPdf def convertPdf2String(path): content = "" # load PDF file pdf = pyPdf.PdfFileReader(file(path, "rb")) # iterate pages for i in range(0, pdf.getNumPages()): # extract the text from each page content += pdf.getPage(i).extractText() + " \n" # collapse whitespaces content = u" ".join(content.replace(u"\xa0", u" ").strip().split()) return content # convert contents of a PDF file and store retult to TXT file f = open('a.txt','w+') f.write(convertPdf2String(sys.argv[1])) f.close() # or print contents to the standard out stream print convertPdf2String("/home/tom/Desktop/Hindi_Book.pdf").encode("ascii", "xmlcharrefreplace") I get this error for a the 1st pdf file UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128) and the following error for this pdf http://www.envis-icpe.com/pointcounterpointbook/Hindi_Book.pdf UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 38: ordinal not in range(128) How to resolve this A: I tried it myself and got the same result. Ignore my comment, I hadn't seen that you're writing the output to a file as well. This is the problem: f.write(convertPdf2String(sys.argv[1])) As convertPdf2String returns a Unicode string, but file.write can only write bytes, the call to f.write tries to automatically convert the Unicode string using ASCII encoding. As the PDF obviously contains non-ASCII characters, that fails. So it should be something like f.write(convertPdf2String(sys.argv[1]).encode("utf-8")) # or f.write(convertPdf2String(sys.argv[1]).encode("ascii", "xmlcharrefreplace")) EDIT: The working source code, only one line changed. # Execute with "Hindi_Book.pdf" in the same directory import sys import pyPdf def convertPdf2String(path): content = "" # load PDF file pdf = pyPdf.PdfFileReader(file(path, "rb")) # iterate pages for i in range(0, pdf.getNumPages()): # extract the text from each page content += pdf.getPage(i).extractText() + " \n" # collapse whitespaces content = u" ".join(content.replace(u"\xa0", u" ").strip().split()) return content # convert contents of a PDF file and store retult to TXT file f = open('a.txt','w+') f.write(convertPdf2String(sys.argv[1]).encode("ascii", "xmlcharrefreplace")) f.close() # or print contents to the standard out stream print convertPdf2String("Hindi_Book.pdf").encode("ascii", "xmlcharrefreplace")
UnicodeEncodeError when reading pdf with pyPdf
Guys i had posted a question earlier pypdf python tool .dont mark this as duplicate as i get this error indicated below import sys import pyPdf def convertPdf2String(path): content = "" # load PDF file pdf = pyPdf.PdfFileReader(file(path, "rb")) # iterate pages for i in range(0, pdf.getNumPages()): # extract the text from each page content += pdf.getPage(i).extractText() + " \n" # collapse whitespaces content = u" ".join(content.replace(u"\xa0", u" ").strip().split()) return content # convert contents of a PDF file and store retult to TXT file f = open('a.txt','w+') f.write(convertPdf2String(sys.argv[1])) f.close() # or print contents to the standard out stream print convertPdf2String("/home/tom/Desktop/Hindi_Book.pdf").encode("ascii", "xmlcharrefreplace") I get this error for a the 1st pdf file UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128) and the following error for this pdf http://www.envis-icpe.com/pointcounterpointbook/Hindi_Book.pdf UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 38: ordinal not in range(128) How to resolve this
[ "I tried it myself and got the same result. Ignore my comment, I hadn't seen that you're writing the output to a file as well. This is the problem:\nf.write(convertPdf2String(sys.argv[1]))\n\nAs convertPdf2String returns a Unicode string, but file.write can only write bytes, the call to f.write tries to automatical...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003856246_python.txt
Q: Python IDLE freezes when invoking File > New Window I am running Mac OS X Snow Leopard ( version 10.6.4 ) with Python Version 2.6.1 Tk Version 8.5 IDLE Version 2.6.1 If I launch IDLE and enter Python statements in the initial window that is presented, all seems fine. However, if, in the IDLE session, I invoke the menu item File > New Window a new window does appear, but I can not type anything into it, and, worse yet, can not type anything into the original IDLE session window either, and have to do a force quit. Does anyone have any suggestions as to how to properly use the File > New Window feature of IDLE on the Mac? A: It's a bug (also reported here).
Python IDLE freezes when invoking File > New Window
I am running Mac OS X Snow Leopard ( version 10.6.4 ) with Python Version 2.6.1 Tk Version 8.5 IDLE Version 2.6.1 If I launch IDLE and enter Python statements in the initial window that is presented, all seems fine. However, if, in the IDLE session, I invoke the menu item File > New Window a new window does appear, but I can not type anything into it, and, worse yet, can not type anything into the original IDLE session window either, and have to do a force quit. Does anyone have any suggestions as to how to properly use the File > New Window feature of IDLE on the Mac?
[ "It's a bug (also reported here). \n" ]
[ 1 ]
[]
[]
[ "python", "python_idle" ]
stackoverflow_0003857039_python_python_idle.txt
Q: URL Builder for CherryPy After using werkzeug as a web framework (which is great and simple, but doesnt support some features), i'm now trying cherrypy. Now what I miss in cherrypy is werkzeug's elegant way of building urls (e.g. for links in templates) using the name of a decorated function like this: @expose('/archive/<int:year>/<int:month>') def archive(request, year, month): pass >>> url_for('archive',2010,04) '/archive/2010/04' I didn't find a similar way in cherrypy, did I miss it? A: You didn't miss it. CherryPy doesn't have that sort of approach built into the 'expose' decorator. You can, however, use the builtin Routes dispatcher with your application, which has a similar URL template syntax. If you'd like to try to wrap that up into a decorator like werkzeug's, we'd love to see the code pasted on the http://tools.cherrypy.org wiki. Bonus points for sticking that logic onto the RoutesDispatcher class itself.
URL Builder for CherryPy
After using werkzeug as a web framework (which is great and simple, but doesnt support some features), i'm now trying cherrypy. Now what I miss in cherrypy is werkzeug's elegant way of building urls (e.g. for links in templates) using the name of a decorated function like this: @expose('/archive/<int:year>/<int:month>') def archive(request, year, month): pass >>> url_for('archive',2010,04) '/archive/2010/04' I didn't find a similar way in cherrypy, did I miss it?
[ "You didn't miss it. CherryPy doesn't have that sort of approach built into the 'expose' decorator. You can, however, use the builtin Routes dispatcher with your application, which has a similar URL template syntax. If you'd like to try to wrap that up into a decorator like werkzeug's, we'd love to see the code pas...
[ 3 ]
[]
[]
[ "cherrypy", "python", "werkzeug" ]
stackoverflow_0003848071_cherrypy_python_werkzeug.txt
Q: Does WSGI override `Content-Length` header? HTTP HEAD requests should contain the Content-Length header as if they were GET requests. But if I set a Content-Length header it gets overridden by the WSGI environment (discussion related to mod_wsgi). Take a look at the following example: from wsgiref.simple_server import make_server def application(environ, start_response): status = '200 OK' headers = [('Content-Type', 'text/plain'), ('Content-Length', '77')] start_response(status, headers) return [] httpd = make_server('', 8000, application) print("Serving on port 8000...") httpd.serve_forever() ... and then calling it with curl: $ curl -X HEAD http://localhost:8000/ -i HTTP/1.0 200 OK Date: Mon, 04 Oct 2010 16:02:27 GMT Server: WSGIServer/0.1 Python/2.7 Content-Type: text/plain Content-Length: 0 <-- should be 77 How can I tell the WSGI environment not to override the content length value? A: There is no such configuration setting. You have to override or modify wsgiref/handlers.py, like this: from wsgiref.simple_server import make_server from wsgiref.simple_server import ServerHandler def finish_content(self): """Ensure headers and content have both been sent""" if not self.headers_sent: if (self.environ.get('REQUEST_METHOD', '') != 'HEAD' or 'Content-Length' not in self.headers): self.headers['Content-Length'] = 0 self.send_headers() ServerHandler.finish_content = finish_content def application(environ, start_response): status = '200 OK' headers = [('Content-Type', 'text/plain'), ('Content-Length', '77')] start_response(status, headers) return [] httpd = make_server('', 8000, application) print("Serving on port 8000...") httpd.serve_forever()
Does WSGI override `Content-Length` header?
HTTP HEAD requests should contain the Content-Length header as if they were GET requests. But if I set a Content-Length header it gets overridden by the WSGI environment (discussion related to mod_wsgi). Take a look at the following example: from wsgiref.simple_server import make_server def application(environ, start_response): status = '200 OK' headers = [('Content-Type', 'text/plain'), ('Content-Length', '77')] start_response(status, headers) return [] httpd = make_server('', 8000, application) print("Serving on port 8000...") httpd.serve_forever() ... and then calling it with curl: $ curl -X HEAD http://localhost:8000/ -i HTTP/1.0 200 OK Date: Mon, 04 Oct 2010 16:02:27 GMT Server: WSGIServer/0.1 Python/2.7 Content-Type: text/plain Content-Length: 0 <-- should be 77 How can I tell the WSGI environment not to override the content length value?
[ "There is no such configuration setting. You have to override or modify wsgiref/handlers.py, like this:\nfrom wsgiref.simple_server import make_server\nfrom wsgiref.simple_server import ServerHandler\ndef finish_content(self):\n \"\"\"Ensure headers and content have both been sent\"\"\"\n if not self.headers_...
[ 0 ]
[]
[]
[ "http", "http_headers", "python", "wsgi" ]
stackoverflow_0003857029_http_http_headers_python_wsgi.txt
Q: How to access lowlevel API for storing data in Google App Engine for python What is the alternative for Entity.java in python version? I do not want any data model. I want my entities without a predefined structure. I just want them to be key and value pairs as the above Entity.java is. Can I do it in Python version? A: The 'low level' API is in google.appengine.api.datastore. There's no public documentation for it, but the module itself has fairly complete docstrings. A: Try the Expando class. class MyModel(db.Expando) pass You can then add properties by simply setting the value. And they can be removed too. edit: I should also have mentioned the dynamic properties method. It will return the list of properties defined for a particular entity.
How to access lowlevel API for storing data in Google App Engine for python
What is the alternative for Entity.java in python version? I do not want any data model. I want my entities without a predefined structure. I just want them to be key and value pairs as the above Entity.java is. Can I do it in Python version?
[ "The 'low level' API is in google.appengine.api.datastore. There's no public documentation for it, but the module itself has fairly complete docstrings.\n", "Try the Expando class.\nclass MyModel(db.Expando)\n pass\n\nYou can then add properties by simply setting the value. And they can be removed too.\nedit:\...
[ 6, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0003857140_google_app_engine_google_cloud_datastore_python.txt
Q: Python Asymmetric Encryption: Using pre-generated prv/pub keys Ok first off yes I have searched google and stackoverflow and done some reading (over 4 hours JUST in this sitting) have not found what I need for these reasons: Many of them suggest just launching an exe like gpg.exe (http://stackoverflow.com/questions/1020320) Some suggested using PyCrypto or other libraries and looking at them, either a) I can't find how to use any of their API, b) I can't find how to import a pre-existing prv/pub key or c) they use the insecure RandomPool (and me trying to updated it is just asking for trouble) Some mention it in passing but I could not find what they where linking to (or their was no link at all. So I know ask you fellow stackoverflow users how can I do this, take a string of a public key (or path (I could just write it to a temp file, (I plan to just have it as a string pub_key = "..." ) ) ) and use it to sign and secure a string (that will be posted on a forum (JSON for updating my application)? Also these are RSA keys (Putty Gen 4096 bits SSH-2-RSA) that are generated using PuttyGen (can be in any format (OpenSSH, ssh.com, ppk) This is what the public key looks like ---- BEGIN SSH2 PUBLIC KEY ---- Comment: "rsa-key-20101003" AAAAB3NzaC1yc2EAAAABJQAAAgEAi+91fFsxZ7k1UuudSe5gZoavwARUyZScCtdf WQ0ROoJC+XIqW5vVJfgmr+A1jLS5m4wNsrCqeyoX2B22T6iEwqVXrXt3QcbccKMu WkLKFK1h67q6Coc+3eOTmKrOuZbWc19YQgybdkR/GxF7XAbq4NCGNaCDtMOqX8Q2 L/a9fAYqVdTwg9trpcz3whNmdLk/B0edOABKuVX51UdLV+ZggK503+uAb1JiIIj0 mARwR/HNo4oRLMLf2PjuZsGVYYjJDdVJBU6AN4PUQSRRRPL4+YmsrLJb/TpfJeXA vj4KZMNJv15YXz7/iMZMKznDtr2RJX5wbSpuTUBNZveA7YiIHxvvvis38b/lX9SJ SYPfZ9CeQY6MvQgG2zwDTOOvKgOIB4sTGMXfcoxB8AF/QXOcxWFJkZoj36rvMd9n Po6szLjHXwcEUOUvvQfG4VvdQA0H5gGLHqYL1EehRsgi5qcCoFPaZW2K09ErKcS0 MbrLFjBkQ9KmqAM38bvM8UhCWAMA9VXOGHMxUHBV4Bir9alGS4VX0B8Y0b3dZ+7I MKkHMCwdEUJf7QVdGxGuSQtVsq8RZbIpk3g7wtv8f6I/iEC58ekdrH35tq5+1ilW dkk9+rrhUy4qrZ+HFi7AeemybpiumbSnebvnkMaIPAOo23V8C9BQ0iuxx4gIZf10 o+TPSK8= ---- END SSH2 PUBLIC KEY ---- NOT THIS --> Key Format seems to be PKCS1 so M2Crypto will NOT work (its load key function expects PEM) Latest reading I think it is SSH Public Key File Format (RFC: http://www.ietf.org/rfc/rfc4716.txt ) I also think below it wrong, I don't think it handles SSH Public Key File Format :( Also looks like Twisted might be where I should look http://www.java2s.com/Open-Source/Python/Network/Twisted/Twisted-1.0.3/Twisted-1.0.3/twisted/conch/ssh/keys.py.htm Also why does SO not allow me to post a bounty immediately?? A: Ok I found how to load it from twisted.conch.ssh import keys as Keys import base64 public_key = """\ ---- BEGIN SSH2 PUBLIC KEY ---- Comment: "rsa-key-20101003" AAAAB3NzaC1yc2EAAAABJQAAAgEAi+91fFsxZ7k1UuudSe5gZoavwARUyZScCtdf WQ0ROoJC+XIqW5vVJfgmr+A1jLS5m4wNsrCqeyoX2B22T6iEwqVXrXt3QcbccKMu WkLKFK1h67q6Coc+3eOTmKrOuZbWc19YQgybdkR/GxF7XAbq4NCGNaCDtMOqX8Q2 L/a9fAYqVdTwg9trpcz3whNmdLk/B0edOABKuVX51UdLV+ZggK503+uAb1JiIIj0 mARwR/HNo4oRLMLf2PjuZsGVYYjJDdVJBU6AN4PUQSRRRPL4+YmsrLJb/TpfJeXA vj4KZMNJv15YXz7/iMZMKznDtr2RJX5wbSpuTUBNZveA7YiIHxvvvis38b/lX9SJ SYPfZ9CeQY6MvQgG2zwDTOOvKgOIB4sTGMXfcoxB8AF/QXOcxWFJkZoj36rvMd9n Po6szLjHXwcEUOUvvQfG4VvdQA0H5gGLHqYL1EehRsgi5qcCoFPaZW2K09ErKcS0 MbrLFjBkQ9KmqAM38bvM8UhCWAMA9VXOGHMxUHBV4Bir9alGS4VX0B8Y0b3dZ+7I MKkHMCwdEUJf7QVdGxGuSQtVsq8RZbIpk3g7wtv8f6I/iEC58ekdrH35tq5+1ilW dkk9+rrhUy4qrZ+HFi7AeemybpiumbSnebvnkMaIPAOo23V8C9BQ0iuxx4gIZf10 o+TPSK8= ---- END SSH2 PUBLIC KEY ----""" key_data = ''.join(public_key.splitlines()[2:-1])# remove begin, end tags and comment blob = base64.decodestring(key_data) key = Keys.Key._fromString_BLOB(blob) A: I can think of at least two relatively simple options Use OpenSSL (or pyOpenSSL) to convert the BER to PEM Use paramiko, twisted or any other python SSH implementation to work with the keys directly
Python Asymmetric Encryption: Using pre-generated prv/pub keys
Ok first off yes I have searched google and stackoverflow and done some reading (over 4 hours JUST in this sitting) have not found what I need for these reasons: Many of them suggest just launching an exe like gpg.exe (http://stackoverflow.com/questions/1020320) Some suggested using PyCrypto or other libraries and looking at them, either a) I can't find how to use any of their API, b) I can't find how to import a pre-existing prv/pub key or c) they use the insecure RandomPool (and me trying to updated it is just asking for trouble) Some mention it in passing but I could not find what they where linking to (or their was no link at all. So I know ask you fellow stackoverflow users how can I do this, take a string of a public key (or path (I could just write it to a temp file, (I plan to just have it as a string pub_key = "..." ) ) ) and use it to sign and secure a string (that will be posted on a forum (JSON for updating my application)? Also these are RSA keys (Putty Gen 4096 bits SSH-2-RSA) that are generated using PuttyGen (can be in any format (OpenSSH, ssh.com, ppk) This is what the public key looks like ---- BEGIN SSH2 PUBLIC KEY ---- Comment: "rsa-key-20101003" AAAAB3NzaC1yc2EAAAABJQAAAgEAi+91fFsxZ7k1UuudSe5gZoavwARUyZScCtdf WQ0ROoJC+XIqW5vVJfgmr+A1jLS5m4wNsrCqeyoX2B22T6iEwqVXrXt3QcbccKMu WkLKFK1h67q6Coc+3eOTmKrOuZbWc19YQgybdkR/GxF7XAbq4NCGNaCDtMOqX8Q2 L/a9fAYqVdTwg9trpcz3whNmdLk/B0edOABKuVX51UdLV+ZggK503+uAb1JiIIj0 mARwR/HNo4oRLMLf2PjuZsGVYYjJDdVJBU6AN4PUQSRRRPL4+YmsrLJb/TpfJeXA vj4KZMNJv15YXz7/iMZMKznDtr2RJX5wbSpuTUBNZveA7YiIHxvvvis38b/lX9SJ SYPfZ9CeQY6MvQgG2zwDTOOvKgOIB4sTGMXfcoxB8AF/QXOcxWFJkZoj36rvMd9n Po6szLjHXwcEUOUvvQfG4VvdQA0H5gGLHqYL1EehRsgi5qcCoFPaZW2K09ErKcS0 MbrLFjBkQ9KmqAM38bvM8UhCWAMA9VXOGHMxUHBV4Bir9alGS4VX0B8Y0b3dZ+7I MKkHMCwdEUJf7QVdGxGuSQtVsq8RZbIpk3g7wtv8f6I/iEC58ekdrH35tq5+1ilW dkk9+rrhUy4qrZ+HFi7AeemybpiumbSnebvnkMaIPAOo23V8C9BQ0iuxx4gIZf10 o+TPSK8= ---- END SSH2 PUBLIC KEY ---- NOT THIS --> Key Format seems to be PKCS1 so M2Crypto will NOT work (its load key function expects PEM) Latest reading I think it is SSH Public Key File Format (RFC: http://www.ietf.org/rfc/rfc4716.txt ) I also think below it wrong, I don't think it handles SSH Public Key File Format :( Also looks like Twisted might be where I should look http://www.java2s.com/Open-Source/Python/Network/Twisted/Twisted-1.0.3/Twisted-1.0.3/twisted/conch/ssh/keys.py.htm Also why does SO not allow me to post a bounty immediately??
[ "Ok I found how to load it\nfrom twisted.conch.ssh import keys as Keys\nimport base64\n\npublic_key = \"\"\"\\\n---- BEGIN SSH2 PUBLIC KEY ----\nComment: \"rsa-key-20101003\"\nAAAAB3NzaC1yc2EAAAABJQAAAgEAi+91fFsxZ7k1UuudSe5gZoavwARUyZScCtdf\nWQ0ROoJC+XIqW5vVJfgmr+A1jLS5m4wNsrCqeyoX2B22T6iEwqVXrXt3QcbccKMu\nWkLKFK1h...
[ 2, 0 ]
[]
[]
[ "cryptography", "encryption_asymmetric", "python" ]
stackoverflow_0003852190_cryptography_encryption_asymmetric_python.txt
Q: Decoding if it's not unicode I want my function to take an argument that could be an unicode object or a utf-8 encoded string. Inside my function, I want to convert the argument to unicode. I have something like this: def myfunction(text): if not isinstance(text, unicode): text = unicode(text, 'utf-8') ... Is it possible to avoid the use of isinstance? I was looking for something more duck-typing friendly. During my experiments with decoding, I have run into several weird behaviours of Python. For instance: >>> u'hello'.decode('utf-8') u'hello' >>> u'cer\xf3n'.decode('utf-8') Traceback (most recent call last): File "<input>", line 1, in <module> File "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in po sition 3: ordinal not in range(128) Or >>> u'hello'.decode('utf-8') u'hello' 12:11 >>> unicode(u'hello', 'utf-8') Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: decoding Unicode is not supported By the way. I'm using Python 2.6 A: You could just try decoding it with the 'utf-8' codec, and if that does not work, then return the object. def myfunction(text): try: text = unicode(text, 'utf-8') except TypeError: return text print(myfunction(u'cer\xf3n')) # cerón When you take a unicode object and call its decode method with the 'utf-8' codec, Python first tries to convert the unicode object to a string object, and then it calls the string object's decode('utf-8') method. Sometimes the conversion from unicode object to string object fails because Python2 uses the ascii codec by default. So, in general, never try to decode unicode objects. Or, if you must try, trap it in a try..except block. There may be a few codecs for which decoding unicode objects works in Python2 (see below), but they have been removed in Python3. See this Python bug ticket for an interesting discussion of the issue, and also Guido van Rossum's blog: "We are adopting a slightly different approach to codecs: while in Python 2, codecs can accept either Unicode or 8-bits as input and produce either as output, in Py3k, encoding is always a translation from a Unicode (text) string to an array of bytes, and decoding always goes the opposite direction. This means that we had to drop a few codecs that don't fit in this model, for example rot13, base64 and bz2 (those conversions are still supported, just not through the encode/decode API)." A: I'm not aware of any good way to avoid the isinstance check in your function, but maybe someone else will be. I can point out that the two weirdnesses you cite are because you're doing something that doesn't make sense: Trying to decode into Unicode something that's already decoded into Unicode. The first should instead look like this, which decodes the UTF-8 encoding of that string into the Unicode version: >>> 'cer\xc3\xb3n'.decode('utf-8') u'cer\xf3n' And your second should look like this (not using a u'' Unicode string literal): >>> unicode('hello', 'utf-8') u'hello'
Decoding if it's not unicode
I want my function to take an argument that could be an unicode object or a utf-8 encoded string. Inside my function, I want to convert the argument to unicode. I have something like this: def myfunction(text): if not isinstance(text, unicode): text = unicode(text, 'utf-8') ... Is it possible to avoid the use of isinstance? I was looking for something more duck-typing friendly. During my experiments with decoding, I have run into several weird behaviours of Python. For instance: >>> u'hello'.decode('utf-8') u'hello' >>> u'cer\xf3n'.decode('utf-8') Traceback (most recent call last): File "<input>", line 1, in <module> File "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in po sition 3: ordinal not in range(128) Or >>> u'hello'.decode('utf-8') u'hello' 12:11 >>> unicode(u'hello', 'utf-8') Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: decoding Unicode is not supported By the way. I'm using Python 2.6
[ "You could just try decoding it with the 'utf-8' codec, and if that does not work, then return the object.\ndef myfunction(text):\n try:\n text = unicode(text, 'utf-8')\n except TypeError:\n return text\n\nprint(myfunction(u'cer\\xf3n'))\n# cerón\n\nWhen you take a unicode object and call its de...
[ 20, 0 ]
[]
[]
[ "encoding", "python", "unicode", "utf_8" ]
stackoverflow_0003857763_encoding_python_unicode_utf_8.txt
Q: Reversing dictionary by key doesn't work I have a following dictionary : {2009: [12, 11, 10, 9], 2010: [1]} I'm trying to reverse-sort it, so that 2010 comes first. Here's the code : def dictSort(dict): items = dict.items() items.sort(reverse=True) dict = {} for item in items: dict[item[0]] = item[1] return dict But in return I get the same dictionary. Until the for loop everything looks fine. Why is that ? A: A dictionary is unordered, whatever you put into it isn't stored in the order you add to it. If you want to do something to it in sorted order, you can do: items = dict.items.sort(reverse=True) for item in items: doSomething(item,mydict[item]) or for key,value in iter(sorted(mydict.iteritems(),reverse=True)) doSomething(key,value) A: Dictionary keys are not ordered. Think of a dict as a set of key/value pairs. This is coming in Python 3.1: http://docs.python.org/dev/library/collections.html#collections.OrderedDict A: Dictionaries don't have an order. If you are trying to output the dictionary in a certain order, try grabbing all the keys, sorting them, and using that list to know which order to output things. A: Here one way to generate items of dict in reversed order of key (BTW please do not use dict for variable name!): def dict_sort(thisdict, reverse=True): return ((key, thisdict[key]) for key in sorted(thisdict, reverse=reverse)) mydict = {2009: [12, 11, 10, 9], 2010: [1]} for i in dict_sort(mydict): print "%i: %s" % i
Reversing dictionary by key doesn't work
I have a following dictionary : {2009: [12, 11, 10, 9], 2010: [1]} I'm trying to reverse-sort it, so that 2010 comes first. Here's the code : def dictSort(dict): items = dict.items() items.sort(reverse=True) dict = {} for item in items: dict[item[0]] = item[1] return dict But in return I get the same dictionary. Until the for loop everything looks fine. Why is that ?
[ "A dictionary is unordered, whatever you put into it isn't stored in the order you add to it.\nIf you want to do something to it in sorted order, you can do:\nitems = dict.items.sort(reverse=True)\nfor item in items:\n doSomething(item,mydict[item])\n\nor\nfor key,value in iter(sorted(mydict.iteritems(),reverse=...
[ 2, 2, 0, 0 ]
[]
[]
[ "dictionary", "python", "sorting" ]
stackoverflow_0003857880_dictionary_python_sorting.txt
Q: pywin32: how do I get a pyDEVMODE object? How can I create a PyDEVMODE object without just having it as a return from a function call like win32api.EnumDisplaySettingsEx(name, 0)? A: It's defined in pywintypes. >>> import pywintypes >>> pywintypes.DEVMODEType() <PyDEVMODE object at 0x00F38E90> I'm curious as to what you are going to use it for?
pywin32: how do I get a pyDEVMODE object?
How can I create a PyDEVMODE object without just having it as a return from a function call like win32api.EnumDisplaySettingsEx(name, 0)?
[ "It's defined in pywintypes.\n>>> import pywintypes\n>>> pywintypes.DEVMODEType()\n<PyDEVMODE object at 0x00F38E90>\n\nI'm curious as to what you are going to use it for?\n" ]
[ 1 ]
[]
[]
[ "python", "pywin32", "winapi" ]
stackoverflow_0003857884_python_pywin32_winapi.txt
Q: Handled signal in Python causes FTP connection to interrupt This scripts checks an FTP and download files at scheduled intervals. Sending to it the right signal (SIGUSR1) should make it close gracefully, waiting checkAll to complete, if running. class ScheduledFtpCheck(FtpCheck, Scheduler): def __init__(self): ... self.aborted, self.checking = False, False def abort(self, *args, **kwargs): self.aborted = True if not self.checking: self.quit() def checkAll(self): if not self.isAborted(): self.checking = True self.checkAll() self.checking = False if self.aborted: self.quit() ... def main(): sch = ScheduledFtpCheck() signal.signal(signal.SIGUSR1, sch.abort) sch.start() the problem is I get a Interrupted system call that makes ftplib.FTP exit prematurely: Traceback (most recent call last): File "/root/my-applications/sensor/sensor/lib/importutils2.py", line 137, in connectAndCheckAll try: self.checkAll() ... File "/usr/lib/python2.6/ftplib.py", line 182, in getline line = self.file.readline() File "/usr/lib/python2.6/socket.py", line 406, in readline data = self._sock.recv(self._rbufsize) error: [Errno 4] Interrupted system call So my script handles signal correctly but scheduled check don't. Why? How can I prevent it? Thanks for your support A: I found myself the solution: running ftp process in a separate thread isolated it from main process signals threading.Thread(target=self.checkAll).start()
Handled signal in Python causes FTP connection to interrupt
This scripts checks an FTP and download files at scheduled intervals. Sending to it the right signal (SIGUSR1) should make it close gracefully, waiting checkAll to complete, if running. class ScheduledFtpCheck(FtpCheck, Scheduler): def __init__(self): ... self.aborted, self.checking = False, False def abort(self, *args, **kwargs): self.aborted = True if not self.checking: self.quit() def checkAll(self): if not self.isAborted(): self.checking = True self.checkAll() self.checking = False if self.aborted: self.quit() ... def main(): sch = ScheduledFtpCheck() signal.signal(signal.SIGUSR1, sch.abort) sch.start() the problem is I get a Interrupted system call that makes ftplib.FTP exit prematurely: Traceback (most recent call last): File "/root/my-applications/sensor/sensor/lib/importutils2.py", line 137, in connectAndCheckAll try: self.checkAll() ... File "/usr/lib/python2.6/ftplib.py", line 182, in getline line = self.file.readline() File "/usr/lib/python2.6/socket.py", line 406, in readline data = self._sock.recv(self._rbufsize) error: [Errno 4] Interrupted system call So my script handles signal correctly but scheduled check don't. Why? How can I prevent it? Thanks for your support
[ "I found myself the solution:\nrunning ftp process in a separate thread isolated it from main process signals\nthreading.Thread(target=self.checkAll).start()\n\n" ]
[ 0 ]
[]
[]
[ "python", "signals" ]
stackoverflow_0003857167_python_signals.txt
Q: Python: search playlists on youtube Is there any way to search playlists on youtube using gdata-python-client? As for documentation it is impossible, but may be there are some workarounds... A: The you tube python API seems to have a way of searching the playlists matching specific term. As per the documentation, API has the capability to retrieve a list of playlists matching a user-specified search term. http://code.google.com/apis/youtube/2.0/developers_guide_protocol_playlist_search.html [Edit : Curl output] I just used curl and the API seems to work fine. ~ $ curl 'http://gdata.youtube.com/feeds/api/playlists/snippets?q=soccer&start-index=11&max-results=10&v=2' Output: <?xml version='1.0' encoding='UTF-8'?><feed xmlns='http://www.w3.org/2005/Atom' xmlns:openSearch='http://a9.com/-/spec/opensearch/1.1/' xmlns:gd='http://schemas.google.com/g/2005' gd:etag='W/&quot;C0cHRX85eCp7ImA9Wx5VEko.&quot;'><id>tag:youtube.com,2008:playlists:snippets</id><updated>2010-10-05T09:30:34.120Z</updated><category scheme='http://schemas.google.com/g/2005#kind' term='http://gdata.youtube.com/schemas/2007#playlistLink'/><title>YouTube Playlists matching query: soccer</title><logo>http://www.youtube.com/img/pic_youtubelogo_123x63.gif</logo><link rel='http://schemas.google.com/g/2005#feed' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/playlists/snippets?v=2'/><link rel='http://schemas.google.com/g/2005#batch' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/playlists/snippets/batch?v=2'/><link rel='self' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/playlists/snippets?q=soccer&amp;start-index=11&amp;max-results=10&amp;v=2'/><link rel='service' type='application/atomsvc+xml' href='http://gdata.youtube.com/feeds/api/playlists/snippets?alt=atom-service&amp;v=2'/><link rel='previous' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/playlists/snippets?q=soccer&amp;start-index=1&amp;max-results=10&amp;v=2'/><link rel='next' type='application/atom+xml' href='http://gdata.youtube.com/feeds/api/playlists/snippets?q=soccer&amp;start-index=21&amp;max-results=10&amp;v=2'/><author><name>YouTube</name><uri>http://www.youtube.com/</uri></author><generator version='2.0' uri='http://gdata.youtube.com/'>YouTube data API</generator><openSearch:totalResults>1241773</openSearch:totalResults><openSearch:startIndex>11</openSearch:startIndex><openSearch:itemsPerPage>10</openSearch:itemsPerPage></feed>~ $
Python: search playlists on youtube
Is there any way to search playlists on youtube using gdata-python-client? As for documentation it is impossible, but may be there are some workarounds...
[ "The you tube python API seems to have a way of searching the playlists matching specific term.\nAs per the documentation, API has the capability to retrieve a list of playlists matching a user-specified search term.\n\nhttp://code.google.com/apis/youtube/2.0/developers_guide_protocol_playlist_search.html\n\n[Edit ...
[ 1 ]
[]
[]
[ "gdata_python_client", "python" ]
stackoverflow_0003857917_gdata_python_client_python.txt
Q: Python - Way to distinguish between item index in a list and item's contents in a FOR loop? For instance, if I wanted to cycle through a list and perform some operation on all but the final list entry, I could do this: z = [1,2,3,4,2] for item in z: if item != z[-1]: print z.index(item) But instead of getting the output "...0 1 2 3," I'd get "...0 2 3." Is there a way to perform an operation on all but the last item in a list (when there are IDENTICAL items in the list) without using a "for x in range (len(list) - 1)" sort of solution? I.e., I want to keep using "for item in list." Many thanks! A: Use a slice: for item in z[:-1]: # do something A: you could use: for index, item in enumerate(z): if index != len(z)-1: print index A: for index, item in enumerate(your_list): do_something A: [z.foo() for z in z[:-1] A: def all_but_last(iterable): iterable= iter(iterable) try: previous= iterable.next() except StopIteration: return for item in iterable: yield previous previous= item Put it in a module and use it wherever you need it. In your case, you'd do: for item in all_but_last(z):
Python - Way to distinguish between item index in a list and item's contents in a FOR loop?
For instance, if I wanted to cycle through a list and perform some operation on all but the final list entry, I could do this: z = [1,2,3,4,2] for item in z: if item != z[-1]: print z.index(item) But instead of getting the output "...0 1 2 3," I'd get "...0 2 3." Is there a way to perform an operation on all but the last item in a list (when there are IDENTICAL items in the list) without using a "for x in range (len(list) - 1)" sort of solution? I.e., I want to keep using "for item in list." Many thanks!
[ "Use a slice:\nfor item in z[:-1]:\n # do something\n\n", "you could use:\nfor index, item in enumerate(z):\n if index != len(z)-1:\n print index\n\n", "for index, item in enumerate(your_list):\n do_something\n\n", "[z.foo() for z in z[:-1]\n", "def all_but_last(iterable):\n iterable= ite...
[ 10, 4, 1, 1, 0 ]
[]
[]
[ "duplicates", "for_loop", "list", "loops", "python" ]
stackoverflow_0003653454_duplicates_for_loop_list_loops_python.txt
Q: AppEngine no host given exception I've got a Python app, that uses urllib.urlopen. It works fine on dev_appserver.py, but throws [Errno http error] no host given error on my GAE production server. The code is exactly the same, the url, it connects to, is hardcoded. I'm out of ideas, what could be wrong. UPD: the code: def getPic(url): sock = urllib.urlopen("http://www.quicklatex.com/latex.f?formula="+(url.replace("&amp;", "&"))) if "0" in sock.readline() : return sock.readline().partition(" ")[0] else: return "" It fetches the page, returned by quicklatex.com website. First line contains of number of errors, second -- of link to the generated image, followed by space and a number. I'm fetching the url of the picture. The url variable itself contains some LaTeX code. A: Have you tried reviewing the URL Fetch documentation? Can you show us the URL?
AppEngine no host given exception
I've got a Python app, that uses urllib.urlopen. It works fine on dev_appserver.py, but throws [Errno http error] no host given error on my GAE production server. The code is exactly the same, the url, it connects to, is hardcoded. I'm out of ideas, what could be wrong. UPD: the code: def getPic(url): sock = urllib.urlopen("http://www.quicklatex.com/latex.f?formula="+(url.replace("&amp;", "&"))) if "0" in sock.readline() : return sock.readline().partition(" ")[0] else: return "" It fetches the page, returned by quicklatex.com website. First line contains of number of errors, second -- of link to the generated image, followed by space and a number. I'm fetching the url of the picture. The url variable itself contains some LaTeX code.
[ "Have you tried reviewing the URL Fetch documentation? Can you show us the URL?\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "python", "urlopen" ]
stackoverflow_0003858876_google_app_engine_python_urlopen.txt
Q: How to add http headers in WSGI middleware? How can http headers be added within a WSGI middleware? A: I've found a nice example from the pylons book. class Middleware(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): def custom_start_response(status, headers, exc_info=None): headers.append(('Set-Cookie', "name=value")) return start_response(status, headers, exc_info) return self.app(environ, custom_start_response) The trick is to use a nested method.
How to add http headers in WSGI middleware?
How can http headers be added within a WSGI middleware?
[ "I've found a nice example from the pylons book.\nclass Middleware(object):\n def __init__(self, app):\n self.app = app\n\n def __call__(self, environ, start_response):\n\n def custom_start_response(status, headers, exc_info=None):\n headers.append(('Set-Cookie', \"name=value\"))\n ...
[ 21 ]
[]
[]
[ "python", "wsgi" ]
stackoverflow_0003859097_python_wsgi.txt
Q: create 2d array in python? this is the code i am trying to create the 2d matrix m=4 tagProb=[[]]*(m+1) count=0 index=0 for line in lines: print(line) if(count < m+1): tagProb[index].append(line.split('@@')[2].strip()) count+=1 if(count == m+1): // this check to goto next index count = 0 index+=1 print(tagProb) i get the o/p [['0.0', '0.6', '0.05', '0.3', '0.05', '0.1', '0.0', '0.6', '0.0', '0.0', '0.1', '0.0', '0.0', '0.9', '0.0', '0.1', '0.0', '0.2', '0.7', '0.0', '0.1', '0.0', '0.9', '0.0', 0.0'], ['0.0', '0.6', '0.05', '0.3', '0.05', '0.1', '0.0', '0.6', '0.0', '0.0', '0.1', '0.0', .0', '0.9', '0.0', '0.1', '0.0', '0.2', '0.7', '0.0', '0.1', '0.0', '0.9', '0.0', '0.0'], '0.0', '0.6', '0.05', '0.3', '0.05', '0.1', '0.0', '0.6', '0.0', '0.0', '0.1', '0.0', '0.0','0.9', '0.0', '0.1', '0.0', '0.2', '0.7', '0.0', '0.1', '0.0', '0.9', '0.0', '0.0'] ] all the values are appended and list has same values. How can i avoid this ? A: You are using * on lists, which has a gotcha -- it will make a list of lots of references to the same object. This is fine for immutables like ints or tuples, but not for mutables like list, because changing one of the objects will change all of them. See: >>> foo = [[]]*10 >>> foo[0].append(1) >>> foo [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]] If you don't want this to happen, the standard way to avoid it is to use a list comprehension, which will initialise the list with new objects: >>> bar = [[] for _ in range(10)] >>> bar[0].append(1) >>> bar [[1], [], [], [], [], [], [], [], [], []] However, this issue doesn't appear very much in idiomatic Python, because initialising a large list is not a common thing to do -- it's very much a C mentality. (That's not to say that it's not sometimes the right thing to do -- Python is multi-paradigm!) On a different note, your code is not nice. The for loop in Python is designed to handle iterating over objects so that you don't have to manage index variables (index and count in your code) manually. It would be better rewritten as follows: import numpy as np m = 4 tagProb = np.array(list(line.split("@@")[2].strip() for line in lines))) tagProb = tagProb.reshape((m+1,-1)).T Explanation: the first line defines tagProb as a numpy array (a fast C-based array type with a lot of linear algebra functions) of one dimension with all the values in a row. The second line coerces it into a matrix of height m+1 and inferred width (note that it must be square for this to work; you can pad it with None if necessary) and then transposes it. I believe this is what your iteration does, but it's kinda hard to follow -- let me know if you want a hand with this. A: Create one list at a time and insert them: import copy m=4 tagProb=[] count=0 index=0 for line in lines: print(line) innerlist = [] if(count < m+1): innerlist.append(line.split('@@')[2].strip()) count+=1 if(count == m+1): // this check to goto next index count = 0 index+=1 tagProb.append(copy.deepcopy(innerlist)) innerlist = [] print(tagProb) As you can see, there is an innerlist that is added to, then for each row, it adds the list to the list of lists. (You may want to do a list copy, though). A: m=4 tagProb=[] count=0 index=0 innerlist = [] for line in lines: print(line) if(count < m+1): innerlist.append(line.split('@@')[2].strip()) count+=1 if(count == m+1): // this check to goto next index count = 0 index+=1 tagProb.append(innerlist) innerlist = [] print(tagProb)
create 2d array in python?
this is the code i am trying to create the 2d matrix m=4 tagProb=[[]]*(m+1) count=0 index=0 for line in lines: print(line) if(count < m+1): tagProb[index].append(line.split('@@')[2].strip()) count+=1 if(count == m+1): // this check to goto next index count = 0 index+=1 print(tagProb) i get the o/p [['0.0', '0.6', '0.05', '0.3', '0.05', '0.1', '0.0', '0.6', '0.0', '0.0', '0.1', '0.0', '0.0', '0.9', '0.0', '0.1', '0.0', '0.2', '0.7', '0.0', '0.1', '0.0', '0.9', '0.0', 0.0'], ['0.0', '0.6', '0.05', '0.3', '0.05', '0.1', '0.0', '0.6', '0.0', '0.0', '0.1', '0.0', .0', '0.9', '0.0', '0.1', '0.0', '0.2', '0.7', '0.0', '0.1', '0.0', '0.9', '0.0', '0.0'], '0.0', '0.6', '0.05', '0.3', '0.05', '0.1', '0.0', '0.6', '0.0', '0.0', '0.1', '0.0', '0.0','0.9', '0.0', '0.1', '0.0', '0.2', '0.7', '0.0', '0.1', '0.0', '0.9', '0.0', '0.0'] ] all the values are appended and list has same values. How can i avoid this ?
[ "You are using * on lists, which has a gotcha -- it will make a list of lots of references to the same object. This is fine for immutables like ints or tuples, but not for mutables like list, because changing one of the objects will change all of them. See:\n>>> foo = [[]]*10\n>>> foo[0].append(1)\n>>> foo\n[[1], [...
[ 10, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003859301_python.txt
Q: Preventing window overlap in GTK I've got a Python/Linux application that displays bits of info I need in a GTK window. For the purposes of this discussion, it should behave exactly like a dock - exists on all virtual desktops, and maximized windows do not overlap it. The first point is pretty easy, but I have spent days bashing my head against my monitor trying to get the second point - preventing overlap. My app should not be covered if another window is maximized. Setting "always on top" is not enough, as the other windows just sit behind my info bar instead of stopping at its edge. In short: with a dock/panel style window, how can you prevent other windows from maximizing over/under it? Update: Problem solved thanks to vsemenov A: Use _NET_WM_STRUT and _NET_WM_STRUT_PARTIAL (for backwards compatibility) properties to reserve space at the edge of X Window System desktop. With PyGtk you can set these properties like so, assuming self.window is an instance of gtk.Window: self.window.get_toplevel().show() # must call show() before property_change() self.window.get_toplevel().window.property_change("_NET_WM_STRUT", "CARDINAL", 32, gtk.gdk.PROP_MODE_REPLACE, [0, 0, 0, bottom_width]) Clarification on the data parameter [0, 0, 0, bottom_width] in above: This parameter specifies the width of reserved space at each border of the desktop screen in order: [left, right, top, bottom]. So [0, 0, 0, 50] would reserve 50 pixels at the bottom of the desktop screen for your widget. Here is a simple working example: import gtk class PyGtkWidgetDockExample: def __init__(self): self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_default_size(100, gtk.gdk.screen_height()) self.window.move(gtk.gdk.screen_width()-100, 0) self.window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DOCK) self.window.show() self.window.window.property_change("_NET_WM_STRUT", "CARDINAL", 32, gtk.gdk.PROP_MODE_REPLACE, [0, 100, 0, 0]) app = PyGtkWidgetDockExample() gtk.main()
Preventing window overlap in GTK
I've got a Python/Linux application that displays bits of info I need in a GTK window. For the purposes of this discussion, it should behave exactly like a dock - exists on all virtual desktops, and maximized windows do not overlap it. The first point is pretty easy, but I have spent days bashing my head against my monitor trying to get the second point - preventing overlap. My app should not be covered if another window is maximized. Setting "always on top" is not enough, as the other windows just sit behind my info bar instead of stopping at its edge. In short: with a dock/panel style window, how can you prevent other windows from maximizing over/under it? Update: Problem solved thanks to vsemenov
[ "Use _NET_WM_STRUT and _NET_WM_STRUT_PARTIAL (for backwards compatibility) properties to reserve space at the edge of X Window System desktop.\nWith PyGtk you can set these properties like so, assuming self.window is an instance of gtk.Window:\nself.window.get_toplevel().show() # must call show() before property_ch...
[ 12 ]
[]
[]
[ "dock", "ewmh", "gtk", "python", "x11" ]
stackoverflow_0003859045_dock_ewmh_gtk_python_x11.txt
Q: Flask - how do I combine Flask-WTF and Flask-SQLAlchemy to edit db models? I'm trying to create an edit page for an existing model (already saved to db). The form object expects a multidict instance to populate its fields. This is what I have: # the model - assumes Flask-SQLAlchemy from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy(app) class Person(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), unique=True) def __init__(self, name=name): self.name = name # the form - assumes Flask-WTF ext. from flask.ext.wtf import Form, TextField, Required, BooleanField class PersonForm(Form): name = TextField('name') ## the view @app.route('/person/edit/<id>/', methods=['GET', 'POST']) def edit_person(id): person = Person.query.get(id) if person: form = PersonForm(person) #<-- raises error return render_template('edit_person.html', form=form) I could assign each field in the form to each field of the model (form.data['name'] = person.name, etc...), but that seems redundant for large models. Is there any shortcut I'm missing? A: Please refer to the wtforms documentation: http://wtforms.simplecodes.com/docs/0.6/forms.html#wtforms.form.Form You pass in the "obj" as argument. This will bind the model properties to the form fields to provide the default values: @app.route('/person/edit/<id>/', methods=['GET', 'POST']) def edit_person(id): person = Person.query.get_or_404(id) form = PersonForm(obj=person) if form.validate_on_submit(): form.populate_obj(person) Notice also the "populate_obj" method. This is a handy shortcut which will bind the form values to the model properties (only those fields you have defined in your form, so quite safe to use).
Flask - how do I combine Flask-WTF and Flask-SQLAlchemy to edit db models?
I'm trying to create an edit page for an existing model (already saved to db). The form object expects a multidict instance to populate its fields. This is what I have: # the model - assumes Flask-SQLAlchemy from flask.ext.sqlalchemy import SQLAlchemy db = SQLAlchemy(app) class Person(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80), unique=True) def __init__(self, name=name): self.name = name # the form - assumes Flask-WTF ext. from flask.ext.wtf import Form, TextField, Required, BooleanField class PersonForm(Form): name = TextField('name') ## the view @app.route('/person/edit/<id>/', methods=['GET', 'POST']) def edit_person(id): person = Person.query.get(id) if person: form = PersonForm(person) #<-- raises error return render_template('edit_person.html', form=form) I could assign each field in the form to each field of the model (form.data['name'] = person.name, etc...), but that seems redundant for large models. Is there any shortcut I'm missing?
[ "Please refer to the wtforms documentation:\nhttp://wtforms.simplecodes.com/docs/0.6/forms.html#wtforms.form.Form\nYou pass in the \"obj\" as argument. This will bind the model properties to the form fields to provide the default values:\n@app.route('/person/edit/<id>/', methods=['GET', 'POST'])\ndef edit_person(id...
[ 29 ]
[]
[]
[ "flask", "forms", "python", "sqlalchemy" ]
stackoverflow_0003850742_flask_forms_python_sqlalchemy.txt
Q: decompress name what is the easiest way to decompress a data name? For example, change compressed form: abc[3:0] into decompressed form: abc[3] abc[2] abc[1] abc[0] preferable 1 liner :) A: In Perl: #!perl -w use strict; use 5.010; my @abc = qw/ a b c d /; say join( " ", reverse @abc[0..3] ); Or if you wanted them into separate variables: my( $abc3, $abc2, $abc1, $abc0 ) = reverse @abc[0..3]; Edit: Per your clarification: my $str = "abc[3:0]"; $str =~ /(abc)\[(\d+):(\d+)\]/; my $base = $1; my $from = ( $2 < $3 ? $2 : $3 ); my $to = ( $2 > $3 ? $2 : $3 ); my @strs; foreach my $num ( $from .. $to ) { push @strs, $base . '[' . $num . ']'; } A: This is a little pyparsing exercise that I've done in the past, adapted to your example (also supports multiple ranges and unpaired indexes, all separated by commas - see the last test case): from pyparsing import (Suppress, Word, alphas, alphanums, nums, delimitedList, Combine, Optional, Group) LBRACK,RBRACK,COLON = map(Suppress,"[]:") ident = Word(alphas+"_", alphanums+"_") integer = Combine(Optional('-') + Word(nums)) integer.setParseAction(lambda t : int(t[0])) intrange = Group(integer + COLON + integer) rangedIdent = ident("name") + LBRACK + delimitedList(intrange|integer)("indexes") + RBRACK def expandIndexes(t): ret = [] for ind in t.indexes: if isinstance(ind,int): ret.append("%s[%d]" % (t.name, ind)) else: offset = (-1,1)[ind[0] < ind[1]] ret.extend( "%s[%d]" % (t.name, i) for i in range(ind[0],ind[1]+offset,offset) ) return ret rangedIdent.setParseAction(expandIndexes) print rangedIdent.parseString("abc[0:3]") print rangedIdent.parseString("abc[3:0]") print rangedIdent.parseString("abc[0:3,7,14:16,24:20]") Prints: ['abc[0]', 'abc[1]', 'abc[2]', 'abc[3]'] ['abc[3]', 'abc[2]', 'abc[1]', 'abc[0]'] ['abc[0]', 'abc[1]', 'abc[2]', 'abc[3]', 'abc[7]', 'abc[14]', 'abc[15]', 'abc[16]', 'abc[24]', 'abc[23]', 'abc[22]', 'abc[21]', 'abc[20]']
decompress name
what is the easiest way to decompress a data name? For example, change compressed form: abc[3:0] into decompressed form: abc[3] abc[2] abc[1] abc[0] preferable 1 liner :)
[ "In Perl:\n#!perl -w\n\nuse strict;\nuse 5.010;\n\nmy @abc = qw/ a b c d /;\nsay join( \" \", reverse @abc[0..3] );\n\nOr if you wanted them into separate variables:\nmy( $abc3, $abc2, $abc1, $abc0 ) = reverse @abc[0..3];\n\nEdit: Per your clarification:\nmy $str = \"abc[3:0]\";\n$str =~ /(abc)\\[(\\d+):(\\d+)\\]/;...
[ 2, 1 ]
[]
[]
[ "awk", "perl", "python" ]
stackoverflow_0003858130_awk_perl_python.txt
Q: Tips, Tricks, Shortcuts for using EnigmaCurry's Emacs configuration I just stated using emacs and wanted to find a good configuration for python programming. I choose the EnigmaCurry emacs configuration which is very extensive. There are a lot of ".el" files. The problem with this configuration is the lack of documentation on how to use the various tools. Without knowledge of emacs-lisp I feel a little in the dark as to the full capability of this configuration. So if anyone has Tips, Tricks, or Shortcuts in EnigmaCurry's configuration I would love to hear them. A: People generally don't document their personal configuration that much, especially because they are generally aware what is what. The Emacs Starter Kit is targeting newbie Emacs users and has better documentation than average. It might seem a bit self-promoting, but I encourage you to take a look at my personal config as well, since I happen to monitor a lot of Emacs channels and use a lot of innovative stuff. My configuration is also highly modular and has more comments than most. That said I'd recommend you if find something in anyone's config you can't understand to just look up the library to which the configuration relates in EmacsWiki and drop by in #emacs irc channel on freenode and ask for help. The community there is great! A: While I'm honored that you chose my emacs config to start with, I have to second Bozhidar's answer. The Emacs Starter Kit is a good place to start for beginners. I personally think that my config is well suited to the way I like to do things, especially for Python development, but it's really pretty crufty and probably unapproachable to other people. I've blogged about my Emacs config quite a bit, but I've learned that Emacs configuration is such a personal thing that if I wanted to turn it into something that was turn-key for everyone else I'd have to spend a lot more time on it to make it user-friendly. Honestly, right now I'm a lot more focused on developing things with Emacs, rather then developing Emacs itself. So, my suggestion is to start with Emacs Starter kit, and then read my config to gain new ideas to add to your own.
Tips, Tricks, Shortcuts for using EnigmaCurry's Emacs configuration
I just stated using emacs and wanted to find a good configuration for python programming. I choose the EnigmaCurry emacs configuration which is very extensive. There are a lot of ".el" files. The problem with this configuration is the lack of documentation on how to use the various tools. Without knowledge of emacs-lisp I feel a little in the dark as to the full capability of this configuration. So if anyone has Tips, Tricks, or Shortcuts in EnigmaCurry's configuration I would love to hear them.
[ "People generally don't document their personal configuration that much, especially because they are generally aware what is what. The Emacs Starter Kit is targeting newbie Emacs users and has better documentation than average. \nIt might seem a bit self-promoting, but I encourage you to take a look at my personal ...
[ 4, 4 ]
[]
[]
[ "emacs", "emacs23", "python" ]
stackoverflow_0003851067_emacs_emacs23_python.txt
Q: Better way to execute ruby file using Python and How to get ruby console output when ruby file is run from python? I am building a standalone using python. This standaloone should execute a ruby file. I have read this article - http://www.decalage.info/python/ruby_bridge I have used os.system() which works well. But I have an issue here. If a ruby file has some error, file simply terminates without error. Can you please let me know how to GET ruby console output so that I can display the same in my standalone. A: you can use subprocess module cmd="ruby myrubyscript.rb" p=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) output, errors = p.communicate() then use the output variable Just a note, your Python program will be dependent on whether you have Ruby installed or not. If possible, try to do everything in Python.
Better way to execute ruby file using Python and How to get ruby console output when ruby file is run from python?
I am building a standalone using python. This standaloone should execute a ruby file. I have read this article - http://www.decalage.info/python/ruby_bridge I have used os.system() which works well. But I have an issue here. If a ruby file has some error, file simply terminates without error. Can you please let me know how to GET ruby console output so that I can display the same in my standalone.
[ "you can use subprocess module\ncmd=\"ruby myrubyscript.rb\" \np=subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) \noutput, errors = p.communicate() \n\nthen use the output variable\...
[ 5 ]
[]
[]
[ "python", "ruby" ]
stackoverflow_0003859864_python_ruby.txt
Q: checking when all data is sent using non-blocking open If I open a a file as os.open( '/dev/ttyS2', O_RDWR | O_NDELAY ), is there any way that I can check when my 'write()' commands have finished? Or, can I open a file for non-blocking read but blocking write? A: You have a misunderstanding of what non-blocking means. It does not imply asynchronous operation - you can have any combination of asynchronous/synchronous and blocking/non-blocking. A write() just hands data off to the kernel to take care of. When write() returns successfully, the kernel has now taken care of the data - this is true regardless of whether the file descriptor is blocking or non-blocking. Whether or not the kernel has actually finished writing it at this point is a separate matter (usually, the answer is "no" - most file descriptors are asynchronous). A write() cannot complete if the kernel has no more room to buffer the data you want to write, and this is the case that is affected by non-blocking versus blocking - in the blocking case, the write() will block until space is available. In the non-blocking case, write() will return an error (EAGAIN), and it is up to you to retry it later. If you wish to wait until all data written to a terminal device has actually been sent to the hardware, use tcdrain() - but this is likely to be unnecessary. Alternatively, if you wish write() to block until your data is accepted by the kernel, then you can use fcntl() to temporarily set the file descriptor to blocking. A: If you are writing to a tty (as you are in your example), you can use termios.tcdrain to wait until all written bytes have been transmitted. Your write systems calls will still be non-blocking, so you will need to handle EWOULDBLOCK/EAGAIN errors, and use select(2), poll(2) or epoll(7) to know when you can write to the file descriptor. These are designed to be used with non-blocking file descriptors. A: The O_NDELAY flag always affects both reading and writing. To achieve a blocking write on a non-blocking file you can select (Python module) the file and write when it becomes writable in a loop. A: OS API write() returns count of written bytes. Checking this value against size of your input you can see when all input is sent. A: Open two file descriptors to the same location - one for non-blocking reads and the other for blocking writes. A: Have you tried os.fsync(fd)?
checking when all data is sent using non-blocking open
If I open a a file as os.open( '/dev/ttyS2', O_RDWR | O_NDELAY ), is there any way that I can check when my 'write()' commands have finished? Or, can I open a file for non-blocking read but blocking write?
[ "You have a misunderstanding of what non-blocking means. It does not imply asynchronous operation - you can have any combination of asynchronous/synchronous and blocking/non-blocking.\nA write() just hands data off to the kernel to take care of. When write() returns successfully, the kernel has now taken care of ...
[ 4, 3, 1, 0, 0, 0 ]
[]
[]
[ "blocking", "c", "io", "linux", "python" ]
stackoverflow_0003858238_blocking_c_io_linux_python.txt
Q: custom comparison for built-in containers In my code there's numerous comparisons for equality of various containers (list, dict, etc.). The keys and values of the containers are of types float, bool, int, and str. The built-in == and != worked perfectly fine. I just learned that the floats used in the values of the containers must be compared using a custom comparison function. I've written that function already (let's call it approxEqual(), and assume that it takes two floats and return True if they are judged to be equal and False otherwise). I prefer that the changes to the existing code are kept to a minimum. (New classes/functions/etc can be as complicated as necessary.) Example: if dict1 != dict2: raise DataMismatch The dict1 != dict2 condition needs to be rewritten so that any floats used in values of dict1 and dict2 are compared using approxEqual function instead of __eq__. The actual contents of dictionaries comes from various sources (parsing files, calculations, etc.). Note: I asked a question earlier about how to override built-in float's eq. That would have been an easy solution, but I learned that Python doesn't allow overriding built-in types' __eq__ operator. Hence this new question. A: The only route to altering the way built-in containers check equality is to make them contain as values, instead of the "originals", wrapped values (wrapped in a class that overrides __eq__ and __ne__). This is if you need to alter the way the containers themselves use equality checking, e.g. for the purpose of the in operator where the right-hand side operand is a list -- as well as in containers' method such as their own __eq__ (type(x).__eq__(y) is the typical way Python will perform internally what you code as x == y). If what you're talking about is performing your own equality checks (without altering the checks performed internally by the containers themselves), then the only way is to change every cont1 == cont2 into (e.g.) same(cont1, cont2, value_same) where value_same is a function accepting two values and returning True or False like == would. That's probably too invasive WRT the criterion you specify. If you can change the container themselves (i.e., the number of places where container objects are created is much smaller than the number of places where two containers are checked for equality), then using a container subclass which overrides __eq__ is best. E.g.: class EqMixin(object): def __eq__(self, other): return same(cont1, cont2, value_same) (with same being as I mentioned in the A's 2nd paragraph) and class EqM_list(EqMixin, list): pass (and so forth for other container types you need), then wherever you have (e.g.) x = list(someiter) change it into x = EqM_list(someiter) and be sure to also catch other ways to create list objects, e.g. replace x = [bah*2 for bah in buh] with x = EqM_list(bah*2 for bah in buh) and x = d.keys() with x = EqM_list(d.iterkeys()) and so forth. Yeah, I know, what a bother -- but it's a core principle (and practice;-) of Python that builtin types (be they containers, or value types like e.g. float) themselves cannot be changed. That's a very different philosophy from e.g. Ruby's and Javascript's (and I personally prefer it but I do see how it can seem limiting at times!). Edit: the OP specific request seems to be (in terms of this answer) "how do I implement same" for the various container types, not how to apply it without changing the == into a function call. If that's correct, then (e.g) without using iterators for simplicity: def samelist(a, b, samevalue): if len(a) != len(b): return False return all(samevalue(x, y) for x, y in zip(a, b)) def samedict(a, b, samevalue): if set(a) != set(b): return False return all(samevalue(a[x], b[x]) for x in a)) Note that this applies to values, as requested, NOT to keys. "Fuzzying up" the equality comparison of a dict's keys (or a set's members) is a REAL problem. Look at it this way: first, how to you guarantee with absolute certainty that samevalue(a, b) and samevalue(b, c) totally implies and ensures samevalue(a, c)? This transitivity condition does not apply to most semi-sensible "fuzzy comparisons" I've ever seen, and yet it's completely indispensable for the hash-table based containers (such as dicts and sets). If you pass that hurdle, then the nightmare of making the hash values somehow "magically" consistent arises -- and what if two actually different keys in one dict "map to" equality in this sense with the same key in the other dict, which of the two corresponding values should be used then...? This way madness lies, if you ask me, so I hope that when you say values you do mean, exactly, values, and not keys!-)
custom comparison for built-in containers
In my code there's numerous comparisons for equality of various containers (list, dict, etc.). The keys and values of the containers are of types float, bool, int, and str. The built-in == and != worked perfectly fine. I just learned that the floats used in the values of the containers must be compared using a custom comparison function. I've written that function already (let's call it approxEqual(), and assume that it takes two floats and return True if they are judged to be equal and False otherwise). I prefer that the changes to the existing code are kept to a minimum. (New classes/functions/etc can be as complicated as necessary.) Example: if dict1 != dict2: raise DataMismatch The dict1 != dict2 condition needs to be rewritten so that any floats used in values of dict1 and dict2 are compared using approxEqual function instead of __eq__. The actual contents of dictionaries comes from various sources (parsing files, calculations, etc.). Note: I asked a question earlier about how to override built-in float's eq. That would have been an easy solution, but I learned that Python doesn't allow overriding built-in types' __eq__ operator. Hence this new question.
[ "The only route to altering the way built-in containers check equality is to make them contain as values, instead of the \"originals\", wrapped values (wrapped in a class that overrides __eq__ and __ne__). This is if you need to alter the way the containers themselves use equality checking, e.g. for the purpose of...
[ 9 ]
[]
[]
[ "comparison", "python" ]
stackoverflow_0003860009_comparison_python.txt
Q: is all the available swig+python+mingw compile information outdated? I'm trying to build a C++ extension for python using swig. I've followed the instructions below and the others to a T and can't seem to get my extension to load. I ran across this article on the MinGW site under "How do I create Python extensions?" http://www.mingw.org/wiki/FAQ I also found these tutorials: http://boodebr.org/main/python/build-windows-extensions http://www.mail-archive.com/modwsgi@googlegroups.com/msg04655.html http://oldwiki.mingw.org/index.php/Python%20extensions I'm using Panda3d-1.7.0 to build against - panda on win32 is running python2.6.4 (MSC v.1500 compiled). I'm using MinGW gcc/g++ (GCC) 3.4.5 to compile. I've noticed that when I run setup.py with the following command: python setup.py build -cmingw32 gcc.exe runs first, then g++.exe to build the pyd. g++ is linking against: -lpython26 -lmsvcr90 she builds and links well enough (no errors) but, when I copy the _extension.pyd and extension.py files over into Panda3d-1.7.0\python\Lib\site-packages and run > python -c "import extension" from the command line, Python dumps the following: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Panda3D-1.7.0\python\Lib\site-packages\extension.py", line 25, in <module> _bullet = swig_import_helper() File "C:\Panda3D-1.7.0\python\Lib\site-packages\extension.py", line 21, in swig_import_helper _mod = imp.load_module('_extension', fp, pathname, description) ImportError: DLL load failed: The specified module could not be found. Any tips or pointers? Thanks! ct A: Two things to verify: Check the C runtime library DLL bound to your python and to your extension DLL with dependency walker to make sure that they are using the same CRT. This is a common source of trouble when building extensions for other languages. (I see it often with Lua, for instance) and can cause interesting and intermittent bugs that are particularly difficult to track down. IIRC, the "official" Python releases for Windows have switched to Visual Studio Express from MinGW. This may make it nearly impossible to use MinGW to build a C++ extension that can be called from a Python compiled and linked with Visual Studio due to irreconcilable differences in the C++ ABI. Both of these add up to advice to make sure that the ABI you are assuming in your extension DLL matches the ABI assumed by the hosting application, and that you aren't duplicating fundamental functional blocks such as the CRT that might contain or manage state that is difficult to correctly share between instances. Edit: The improved edit of the question speaks strongly to there being issues with mismatches between Microsoft's C++ ABI and the GCC C++ ABI which are known to differ.
is all the available swig+python+mingw compile information outdated?
I'm trying to build a C++ extension for python using swig. I've followed the instructions below and the others to a T and can't seem to get my extension to load. I ran across this article on the MinGW site under "How do I create Python extensions?" http://www.mingw.org/wiki/FAQ I also found these tutorials: http://boodebr.org/main/python/build-windows-extensions http://www.mail-archive.com/modwsgi@googlegroups.com/msg04655.html http://oldwiki.mingw.org/index.php/Python%20extensions I'm using Panda3d-1.7.0 to build against - panda on win32 is running python2.6.4 (MSC v.1500 compiled). I'm using MinGW gcc/g++ (GCC) 3.4.5 to compile. I've noticed that when I run setup.py with the following command: python setup.py build -cmingw32 gcc.exe runs first, then g++.exe to build the pyd. g++ is linking against: -lpython26 -lmsvcr90 she builds and links well enough (no errors) but, when I copy the _extension.pyd and extension.py files over into Panda3d-1.7.0\python\Lib\site-packages and run > python -c "import extension" from the command line, Python dumps the following: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Panda3D-1.7.0\python\Lib\site-packages\extension.py", line 25, in <module> _bullet = swig_import_helper() File "C:\Panda3D-1.7.0\python\Lib\site-packages\extension.py", line 21, in swig_import_helper _mod = imp.load_module('_extension', fp, pathname, description) ImportError: DLL load failed: The specified module could not be found. Any tips or pointers? Thanks! ct
[ "Two things to verify:\n\nCheck the C runtime library DLL bound to your python and to your extension DLL with dependency walker to make sure that they are using the same CRT. This is a common source of trouble when building extensions for other languages. (I see it often with Lua, for instance) and can cause intere...
[ 2 ]
[]
[]
[ "c++", "python", "swig" ]
stackoverflow_0003860109_c++_python_swig.txt