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: Python lists and their splitting For example, I have such code a = ["a;b", "c;d",...,"y;z"] I want to split every list element into to items of the same list. So i wanna get something like this: ["a", "b", "c", "d", ...., "y", "z"] How can I do such thing? Thanks for your answers. A: Using only string operatio...
Python lists and their splitting
For example, I have such code a = ["a;b", "c;d",...,"y;z"] I want to split every list element into to items of the same list. So i wanna get something like this: ["a", "b", "c", "d", ...., "y", "z"] How can I do such thing? Thanks for your answers.
[ "Using only string operations seem to be simplest (this is subjective, of course) and fastest (by a huge margin, compared to other solutions posted so far).\n>>> a = [\"a;b\", \"c;d\", \"y;z\"]\n>>> \";\".join(a).split(\";\")\n['a', 'b', 'c', 'd', 'y', 'z']\n\nProof / benchmarks\nSorted in ascending order of elapse...
[ 9, 5, 3, 1, 1, 0, 0, 0, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004968072_list_python.txt
Q: Variable as loop's expression Lets say I have string which changes according to input: expression=True or expression="a>1" How can I use this variable as loop's expression in the way, so I won't need to repeat myself writing double loop. (and without using eval)? Well pseudo code: expression="a<2" a=1 while expr...
Variable as loop's expression
Lets say I have string which changes according to input: expression=True or expression="a>1" How can I use this variable as loop's expression in the way, so I won't need to repeat myself writing double loop. (and without using eval)? Well pseudo code: expression="a<2" a=1 while expression: print a, a+=0.1 wo...
[ "You're asking how to run user input. The answer is eval (or - not here, but generally - exec). Of course this is a bad answer, but it's the only answer. And if the only answer is bad, the question is bad.\nWhat are you really trying to do? There are few programs (most notably programming language implementations) ...
[ 4, 4, 0 ]
[]
[]
[ "expression", "loops", "python", "variables" ]
stackoverflow_0004968979_expression_loops_python_variables.txt
Q: Extra parameters for startLogging (Twisted)? In Twisted docs, startLogging API supports *a and **kw extra arguments. What can I use these for? A: There's just one more parameter you can pass, setStdout. See the documentation for startLoggingWithObserver for details about what it does. A: I'm not sure they are...
Extra parameters for startLogging (Twisted)?
In Twisted docs, startLogging API supports *a and **kw extra arguments. What can I use these for?
[ "There's just one more parameter you can pass, setStdout. See the documentation for startLoggingWithObserver for details about what it does.\n", "I'm not sure they are used at all. See Samples and documentation where they are not used nor mentioned. Also, after reviewing the source code, it doesn't seem to use t...
[ 2, 0 ]
[]
[]
[ "logging", "python", "twisted" ]
stackoverflow_0004969379_logging_python_twisted.txt
Q: Traversing directories to count number of files with a specific string I have a directory with several levels of sub-directories. All the files in the directories are html files (approx. 500 in total), and I'd like to go through each file to see if if contains a "sub_middle_1col" division. I found a great tutorial...
Traversing directories to count number of files with a specific string
I have a directory with several levels of sub-directories. All the files in the directories are html files (approx. 500 in total), and I'd like to go through each file to see if if contains a "sub_middle_1col" division. I found a great tutorial at palewire.com and have used that as my base. The two difficulties I am ha...
[ "Well, you can try:\n import os\n\n for root,dirs,files in os.walk(path):\n for fname in files:\n if fname.endswith('.html'):\n fq = os.path.join(root, fname)\n for line in open(fq):\n if 'sub_middle_1col' in line:\n ...\n\nfind() or reg. expre...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0004969450_python.txt
Q: Why does Python's != operator think that arguments are equal and not equal at the same time? Take the following example: >>> class C(object): ... def __init__(self, p): ... self.p = p ... def __eq__(self, o): ... return True ... >>> C(1) is C(2) False >>> C(1) == C(2) True >>> C(1) != C(2)...
Why does Python's != operator think that arguments are equal and not equal at the same time?
Take the following example: >>> class C(object): ... def __init__(self, p): ... self.p = p ... def __eq__(self, o): ... return True ... >>> C(1) is C(2) False >>> C(1) == C(2) True >>> C(1) != C(2) True # <- Why?!? So now the two objects are equal and not-equal at the same time. I though the t...
[ "Python’s “Data model” explains it all:\n\nThere are no implied relationships among the comparison operators. The truth of x==y does not imply that x!=y is false. Accordingly, when defining __eq__(), one should also define __ne__() so that the operators will behave as expected.\n\nIn C(1) != C(2), it’s using the de...
[ 28, 8, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004969629_python.txt
Q: PyQt wait until page has loaded I want to save a page content to an image when it is fully loaded but sometimes i am getting output raster not rendered completely. Code: import sys import signal import os from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import QWebPage app = QApplication(...
PyQt wait until page has loaded
I want to save a page content to an image when it is fully loaded but sometimes i am getting output raster not rendered completely. Code: import sys import signal import os from PyQt4.QtCore import * from PyQt4.QtGui import * from PyQt4.QtWebKit import QWebPage app = QApplication(sys.argv) signal.signal(signal.SIGINT...
[ "I'm not sure if this even possible. For a static website this could probably work, but Google Maps will load tiles dynamically, and I'm in doubt it will emit a usuable \"I'm done\" signal.\nBut it seems you only want an image of a Google map? Have you looked at their API? They allow you to generate static maps, ju...
[ 1 ]
[]
[]
[ "pyqt", "pyqt4", "python", "qt", "qtwebkit" ]
stackoverflow_0004969393_pyqt_pyqt4_python_qt_qtwebkit.txt
Q: Socket connection through nginx i have a production server which has a nginx server to handle connection to several services. In other machine which is only visible through a VPN from the production server, I have a development server which is used to test some networks application. I want to reach services provi...
Socket connection through nginx
i have a production server which has a nginx server to handle connection to several services. In other machine which is only visible through a VPN from the production server, I have a development server which is used to test some networks application. I want to reach services provided for the development machine from ...
[ "Bad request -- means, that it is not http request.\nNginx can proxy only http/smtp/pop3/imap protocols.\nIf you want to proxy anything else, you must use for example DNAT in iptables\n" ]
[ 1 ]
[]
[]
[ "nginx", "proxy", "python", "sockets", "vpn" ]
stackoverflow_0004968860_nginx_proxy_python_sockets_vpn.txt
Q: Problem with multiple subdomains conflict : Ubuntu django nginx+apache mod_wsgi I have installed my django application on one of my subdomains .. subdomain1.mydomain.com using nginx+apache mod_wsgi on Ubuntu. It was working fine until I installed another django application on subdomain2.mydomain.com.Now subdomai...
Problem with multiple subdomains conflict : Ubuntu django nginx+apache mod_wsgi
I have installed my django application on one of my subdomains .. subdomain1.mydomain.com using nginx+apache mod_wsgi on Ubuntu. It was working fine until I installed another django application on subdomain2.mydomain.com.Now subdomain1.mydomain.com started pointing to application installed on subdomain2.mydomain.com ...
[ "As i can see, your both django applications works on the same address:port\nBy default nginx is not forwarding \"Host:\" header.\nYou must add this line to you nginx config:\nproxy_set_header Host $host;\n" ]
[ 2 ]
[]
[]
[ "apache", "django", "mod_wsgi", "nginx", "python" ]
stackoverflow_0004969530_apache_django_mod_wsgi_nginx_python.txt
Q: Emulate pipe with several outlets. Is python fast enough for this? I have input bytes from ffmpeg. I'd like to send this output to several other ffmpeg processes. Since I can't use a Unix Pipe, Socket,.. for this (or can I?) I'm using python as the receiving end of the pipe. A subroutine then copies the received d...
Emulate pipe with several outlets. Is python fast enough for this?
I have input bytes from ffmpeg. I'd like to send this output to several other ffmpeg processes. Since I can't use a Unix Pipe, Socket,.. for this (or can I?) I'm using python as the receiving end of the pipe. A subroutine then copies the received data to all previously "registered" outlets. It feels wrong! Specifically...
[ "EDIT: Thanks to Phil, who corrected an error in an earlier version (see the comments).\nUsing bash, you could do\nffmpeg ... | tee >(ffmpeg ...) >(ffmpeg ...) >(ffmepg ...) > /dev/null\n\nThis will pipe the output of the first ffmpeg to the three others.\nIf you don't use bash, you can manually create named pipes,...
[ 2, 1, 1 ]
[]
[]
[ "python", "unix" ]
stackoverflow_0004962431_python_unix.txt
Q: Python: calculate the magnetic field of a wire using biot-savart-law I want to calculate the magnetic field of a wire using biot-savart-law. Some people recommend to use numpy arrays. At first i did it with vpython and it worked. But know I want to use Matplotlib for visualisation. Therefore I need arrays right? B...
Python: calculate the magnetic field of a wire using biot-savart-law
I want to calculate the magnetic field of a wire using biot-savart-law. Some people recommend to use numpy arrays. At first i did it with vpython and it worked. But know I want to use Matplotlib for visualisation. Therefore I need arrays right? But I stuck now. I also posted this question to codereview, but they send ...
[ "Change\ndl = ((coord[i+1][0]-coord[i][0]), (coord[i+1][1]-coord[i][1]), 0)\nbfield2 = konstante*I*cross(dl, (rx,ry,rz))/r**3 # i have to use numpy arrays\n\nTo\ndl = np.array([(coord[i+1][0]-coord[i][0]), (coord[i+1][1]-coord[i][1]), 0])\nbfield2 = konstante*I*cross(dl, np.array([rx,ry,rz]))/r**3 # i have to use n...
[ 2, 2, 1, 1 ]
[]
[]
[ "arrays", "numpy", "physics", "python" ]
stackoverflow_0004969704_arrays_numpy_physics_python.txt
Q: Best way to get xml-rpc and django working together I have worked with Django for a while but I am new to xml-rpc. I have two Django servers running and the first needs to call functions from some modules of second server. I find xml-rpc easiest way to do so but don't want to run a separate server for this only....
Best way to get xml-rpc and django working together
I have worked with Django for a while but I am new to xml-rpc. I have two Django servers running and the first needs to call functions from some modules of second server. I find xml-rpc easiest way to do so but don't want to run a separate server for this only. What options do I have? Can I run Django's web-server...
[ "Easily - we use http://code.djangoproject.com/wiki/XML-RPC to add an xml-rpc server into our django server.\n", "You may also consider David Fisher's rpc4django which supports both XMLRPC and JSONRPC within a single package. Features include:\n\nDetects request type (JSONRPC or XMLRPC) based on content\nEasy id...
[ 7, 4, 0 ]
[]
[]
[ "django", "python", "xml_rpc" ]
stackoverflow_0003108507_django_python_xml_rpc.txt
Q: Python question on threads I am trying to run two thread concurrently on two function like the ones listed below : import threading def functionA(): for i in range(5): print "Calling function A" def functionB(): for i in range(5): print "Calling function B" t1 = threading.Thread(function...
Python question on threads
I am trying to run two thread concurrently on two function like the ones listed below : import threading def functionA(): for i in range(5): print "Calling function A" def functionB(): for i in range(5): print "Calling function B" t1 = threading.Thread(functionA()) t2 = threading.Thread(funct...
[ "You're calling the functions and pass the result to the Thread constructor instead of passing the function. Also, you must use the target argument (instead of the unused group which comes first). Just use Thread(target=functionA) and Thread(target=functionB). Note the lack of parens after the functions.\nNote that...
[ 2, 1, 0, 0 ]
[]
[]
[ "asynchronous", "multithreading", "python" ]
stackoverflow_0004969376_asynchronous_multithreading_python.txt
Q: How to start a program Automatically from the main method Here is my code def main(): # This code reads in data.txt and loads it into an array # Array will be used to add friends, remove and list # when we quit, we'll overwrite original friends.txt with # contents print"Welcome to the program...
How to start a program Automatically from the main method
Here is my code def main(): # This code reads in data.txt and loads it into an array # Array will be used to add friends, remove and list # when we quit, we'll overwrite original friends.txt with # contents print"Welcome to the program" print "Enter the correct number" print "Hockey fan 1...
[ "Add:\nif __name__ == \"__main__\":\n main()\n\nTo your script (indented all the way to the left; not as part of the main() function).\n", "Add:\nif __name__ == \"__main__\":\n main()\n\nto the end of the file\n", "You should try the following \nif __name__ == \"__main__\":\n main()\n\nOnce that is don...
[ 11, 4, 3 ]
[]
[]
[ "python" ]
stackoverflow_0004970375_python.txt
Q: I am getting a syntax error on line 42(4th last line) and I cant fix it can someone please help? def main(): # This code reads in data.txt and loads it into an array # Array will be used to add friends, remove and list # when we quit, we'll overwrite original friends.txt with # contents print...
I am getting a syntax error on line 42(4th last line) and I cant fix it can someone please help?
def main(): # This code reads in data.txt and loads it into an array # Array will be used to add friends, remove and list # when we quit, we'll overwrite original friends.txt with # contents print"Welcome to the program" print "Enter the correct number" print "Hockey fan 1, basketball fan...
[ "If that's really your code, your print is upper-cased.\nprint \"Quitting Goodbye!\"\nAlso, I just ran your code, and you have some improper indentation in your else clause:\ninFile = open('data.txt','r')\nlistNumbers = []\nfor numbers in inFile:\n listNumbers.append(numbers)\n print numbers\ninFile.close()\n...
[ 7, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004970676_python.txt
Q: Python calling a MQ broker and DBus My Python is worse than my Chinese (I have never seen so many smiling faces than when I try to speak Mandarin), so I need a little help: I want something to listen to MQ (for topics specified in a configuration) and relay the message to dBus and in return listen to dBus (for top...
Python calling a MQ broker and DBus
My Python is worse than my Chinese (I have never seen so many smiling faces than when I try to speak Mandarin), so I need a little help: I want something to listen to MQ (for topics specified in a configuration) and relay the message to dBus and in return listen to dBus (for topics specified in a configuration) and rel...
[ "PYMQi has sample code here: http://packages.python.org/pymqi/examples.html In order not to poll you might want to look at MQ Triggers. They enable an application to be launched when a message is put on a queue.\n", "\nI want something to listen to MQ (for topics specified in a configuration) \n and relay the m...
[ 2, 2, 1, 0 ]
[]
[]
[ "android_activity", "dbus", "ibm_mq", "pymqi", "python" ]
stackoverflow_0004812171_android_activity_dbus_ibm_mq_pymqi_python.txt
Q: Importing a module dynamically using imp I am trying to import a module from a different directory dynamically. I am following an answer from this question. I have a module named bar in a directory named foo. The main script will be running in the parent directory to foo. Here is the code i have thus far in my te...
Importing a module dynamically using imp
I am trying to import a module from a different directory dynamically. I am following an answer from this question. I have a module named bar in a directory named foo. The main script will be running in the parent directory to foo. Here is the code i have thus far in my test script (which is running in the parent dire...
[ "imp.load_source requires the pathname + file name of the module to import, you should change your source for the one below:\nmod = imp.load_source(\"bar\",\"./foo/bar.py\")\n\n", "Appears to be a simple pathing problem - check __file__ or cwd... Maybe try an absolute file path first? - This imp example may help....
[ 34, 2 ]
[]
[]
[ "dynamic", "import", "python" ]
stackoverflow_0004970235_dynamic_import_python.txt
Q: Select lines stack python i writen this code: import os import re import string ## Path = 'C:/RESULT/BATCH/' ## Nfile = 'Skin_Refined_v05' f=open(Path + Nfile + '.inp') n=open(Path + 'newfile.inp', 'w') for lines, text in enumerate(f): found = text.find('*SURFACE') while found > -1: print found, lines, t...
Select lines stack python
i writen this code: import os import re import string ## Path = 'C:/RESULT/BATCH/' ## Nfile = 'Skin_Refined_v05' f=open(Path + Nfile + '.inp') n=open(Path + 'newfile.inp', 'w') for lines, text in enumerate(f): found = text.find('*SURFACE') while found > -1: print found, lines, text found = text.find('*SUR...
[ "I think this will do what you want:\nimport os \nimport re \n\n## \nPath = 'C:/RESULT/BATCH/' \n## \nNfile = 'Skin_Refined_v05' \nf=open(Path + Nfile + '.inp') \nn=open(Path + 'newfile.inp', 'w') \nin_surface_block = False;\nfor line_num, text in enumerate(f): \n found = text.find('*SURFACE') \n if found > -...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004971097_python.txt
Q: C#'s equivalent to Python's os.path.splitext()? With Python, it has os.path.splitext() to replace the extension name to something as follows. import os.path names = os.path.splitext('hello.exe') print names[0] + ".coverage" And I have hello.coverage. Does C# has equivalent functions as python's os.path? ANSWERED...
C#'s equivalent to Python's os.path.splitext()?
With Python, it has os.path.splitext() to replace the extension name to something as follows. import os.path names = os.path.splitext('hello.exe') print names[0] + ".coverage" And I have hello.coverage. Does C# has equivalent functions as python's os.path? ANSWERED using System; using System.IO; namespace Hello { ...
[ "System.IO.Path.ChangeExtension does what you want:\nstring path = \"hello.exe\";\nstring newPath = System.IO.Path.ChangeExtension(path, \".coverage\");\n\nEDIT: \nYour using statement should be using System.IO, and then you can use it as you have it or like this:\nPath.ChangeExtension(path, newExtension);\n\nAlso,...
[ 3 ]
[]
[]
[ "c#", "python", "split", "utility" ]
stackoverflow_0004971433_c#_python_split_utility.txt
Q: How to use wifi using python? I am making an windows application which would send and receive information with an Android phone. I need to make use of the wifi to do so ( win32api for python ). The app. would be something like this: The android screen would show the desktop screen. where ever you touch , a click w...
How to use wifi using python?
I am making an windows application which would send and receive information with an Android phone. I need to make use of the wifi to do so ( win32api for python ). The app. would be something like this: The android screen would show the desktop screen. where ever you touch , a click would me made on the corresponding p...
[ "I think you're playing in the wrong layer of the network. You need to get a socket connection between your phone and your computer. \nHere's the documentation for Android sockets\nAnd here's documentation for Python sockets\n" ]
[ 3 ]
[]
[]
[ "android", "python", "pywin32", "wifi", "winapi" ]
stackoverflow_0004970651_android_python_pywin32_wifi_winapi.txt
Q: How to read a binary file? I'm trying to send a file between a client and a server in my home network. I just want to test with a simple file, client.txt. The client program should read X bytes and send it over the tcp socket I've created, but I cant wrap my head around how to do the sending part: f = open("client...
How to read a binary file?
I'm trying to send a file between a client and a server in my home network. I just want to test with a simple file, client.txt. The client program should read X bytes and send it over the tcp socket I've created, but I cant wrap my head around how to do the sending part: f = open("client.txt", "rb") while 1: // should ...
[ "Since you mentioned you have problems setting up the server part, I'll rip this out from Python documentation and edit it slightly:\nimport socket\n\nHOST = ''\nPORT = 50007\n\ns = socket.socket()\ns.bind((HOST, PORT))\ns.listen(1)\nconn, addr = s.accept()\n\nf = open(\"client.txt\", \"rb\")\nwhile 1:\n data = ...
[ 4, 1 ]
[]
[]
[ "file", "python" ]
stackoverflow_0004971413_file_python.txt
Q: How can i make the attached pyunit python script search for tests in subfolders The following python script searches and executes all pyunit tests in the current folder. """Regression testing framework This module will search for scripts in the same directory named XYZtest.py. Each such script should be a test ...
How can i make the attached pyunit python script search for tests in subfolders
The following python script searches and executes all pyunit tests in the current folder. """Regression testing framework This module will search for scripts in the same directory named XYZtest.py. Each such script should be a test suite that tests a module through PyUnit. (As of Python 2.1, PyUnit is included in ...
[ "Change:\ndef regressionTest():\n path = os.path.abspath(os.path.dirname(sys.argv[0]))\n\nTo:\ndef regressionTest(somearg):\n path = os.path.abspath(os.path.dirname(somearg))\n\nAnd then:\nfor root, dirs, files in os.walk(path):\n regressionTest(root)\n\n" ]
[ 0 ]
[]
[]
[ "python", "python_unittest" ]
stackoverflow_0004970084_python_python_unittest.txt
Q: Define a structure in python to use a function from a C library (dll) For beginning, sorry for my english. I have some trouble to use a function from a dynamic library (the gnu gsl library) in a Python script. Indeed, I know use a function but I need to define a Structure white C type datas to use a particulary fu...
Define a structure in python to use a function from a C library (dll)
For beginning, sorry for my english. I have some trouble to use a function from a dynamic library (the gnu gsl library) in a Python script. Indeed, I know use a function but I need to define a Structure white C type datas to use a particulary function. In first this is an example of the use of the function in a C++ scr...
[ "You should take a look at this ctypes tutorial (specially Structures and Callback functions).\nIt should be something like this:\nMY_FUNC_TYPE = CFUNCTYPE(c_double, c_double, c_void_p)\nclass GSL_FUNCTION(Structure):\n _fields_ = [(\"function\", MY_FUNC_TYPE),\n (\"params\", c_void_p)]\n\ndef py_...
[ 2, 0 ]
[]
[]
[ "ctypes", "data_structures", "dll", "header", "python" ]
stackoverflow_0004971509_ctypes_data_structures_dll_header_python.txt
Q: selecting the earliest entry in a list that also satisfies other criteria Say I have a list L1, and the entries in L1 have 4 parts and are formatted like this cat1, cat2, date, ID. The list is sorted, so alphabetically by the cat1 entries, then alphabetically by the cat2 entries, then by the earliest date. I wan...
selecting the earliest entry in a list that also satisfies other criteria
Say I have a list L1, and the entries in L1 have 4 parts and are formatted like this cat1, cat2, date, ID. The list is sorted, so alphabetically by the cat1 entries, then alphabetically by the cat2 entries, then by the earliest date. I want a subset of this list that contains the entry with earliest date for each cat...
[ "If dict1 and dict2's value-lists are not too big, you could generate the set of all valid IDs first, then filter L1 to contain only those tuples (X,Y,date,ID) whose IDs are in the set of value IDs:\nimport collections\ndef valid_ids(*dcts):\n valid=collections.defaultdict(int)\n for dct in dcts:\n for...
[ 1, 0 ]
[]
[]
[ "dictionary", "list", "python" ]
stackoverflow_0004971729_dictionary_list_python.txt
Q: Python module logging with eclipse I am trying to get logging going across a couple of different modules using logging.config.fileConfig() My directory looks something like this: > Package > Source __init__.py SomeSource.py > Test __init__.py SomeTests.py __init__.py Insid...
Python module logging with eclipse
I am trying to get logging going across a couple of different modules using logging.config.fileConfig() My directory looks something like this: > Package > Source __init__.py SomeSource.py > Test __init__.py SomeTests.py __init__.py Inside in Package.__init__.py I have the foll...
[ "Check your Python directory. It is probably in there.\n" ]
[ 0 ]
[]
[]
[ "eclipse", "logging", "module", "package", "python" ]
stackoverflow_0004951969_eclipse_logging_module_package_python.txt
Q: numpy array conversion to pairs I'm not sure how it is called in python i think its a pair Anyway I have a huge numpy array, its format is like FFnetlayer0 = [ 0, 243, 9, 243, 18, 243, 4, 244, 13, 244, ....etc.] I need this numpy array format to be: FFnetlayer0 = [ (0, 243), (9, 243), (1...
numpy array conversion to pairs
I'm not sure how it is called in python i think its a pair Anyway I have a huge numpy array, its format is like FFnetlayer0 = [ 0, 243, 9, 243, 18, 243, 4, 244, 13, 244, ....etc.] I need this numpy array format to be: FFnetlayer0 = [ (0, 243), (9, 243), (18, 243), (4, 244), (13, 244),...
[ "One way is to just convert it to a two-dimensional NumPy array:\nFFnetlayer0 = FFnetlayer0.reshape(-1, 2)\n\nNow, accessing FFnetlayer0[i] for some i will give you a NumPy array with two entries.\n", "Well your FFnetlayer0 isn't an numpy array, its still just a python list. You can slice it\nfrom numpy import a...
[ 7, 4, 2, 1, 0 ]
[]
[]
[ "arrays", "numpy", "python" ]
stackoverflow_0004971368_arrays_numpy_python.txt
Q: Make Python import .pyc when run in optimized mode I have to use some legacy .pyc modules (with no source) but I'm also forced to use python in optimized mode (python -O): so, when trying to import those modules, I get an import error (as python looks for .py or .pyo files). Is there a way to make it use pyc modul...
Make Python import .pyc when run in optimized mode
I have to use some legacy .pyc modules (with no source) but I'm also forced to use python in optimized mode (python -O): so, when trying to import those modules, I get an import error (as python looks for .py or .pyo files). Is there a way to make it use pyc modules as well? Or to convert .pyc into .pyo?
[ "One way to \"convert\" them is simply renaming them. Of course they won't be optimised, but at least you can use them.\n", "You can use DePython to convert your .pyc files into .py files, and then you will be able to import them.\n" ]
[ 3, 2 ]
[]
[]
[ "compiler_optimization", "import", "pyc", "python" ]
stackoverflow_0004971066_compiler_optimization_import_pyc_python.txt
Q: Embedding Python into C++ application Context: An ongoing problem we have been facing is unit testing our market data applications. These applications sit and observe data being retrieved from feeds and does something. Some critical events which are hard to trigger rarely occur and it is are difficult for the Te...
Embedding Python into C++ application
Context: An ongoing problem we have been facing is unit testing our market data applications. These applications sit and observe data being retrieved from feeds and does something. Some critical events which are hard to trigger rarely occur and it is are difficult for the Testers to verify our applications perform co...
[ "I do something similar to this in one of my projects by using SWIG to generate python bindings for the relevant parts of the C++ code. Then I embed the interpreter as others have suggested. Having done that I can execute python code at will (e.g. PyRun_SimpleString), which can access C++ code. Normally I end up us...
[ 7, 4, 3 ]
[]
[]
[ "boost", "c++", "python" ]
stackoverflow_0004971928_boost_c++_python.txt
Q: What's the best way to parse a definition list using XPath? I'm using Python + xPath to parse some HTML but I'm having trouble parsing an definition list. An example would be as follows: <dl> <dt>Section One</dt> <dd>Child one</dd> <dd>Child one.2</dd> <dt>Section Two</dt> <dd>Child two</dd> <...
What's the best way to parse a definition list using XPath?
I'm using Python + xPath to parse some HTML but I'm having trouble parsing an definition list. An example would be as follows: <dl> <dt>Section One</dt> <dd>Child one</dd> <dd>Child one.2</dd> <dt>Section Two</dt> <dd>Child two</dd> </dl> I want to transform this into an output like: {'Section One'...
[ "A solution without xpath, using lxml (which you are probably already using if you are using xpath?):\nfrom collections import defaultdict\nfrom lxml import etree\n\ndl = etree.fromstring('''<dl>\n<dt>Section One</dt>\n<dd>Child one</dd>\n<dd>Child one.2</dd>\n<dt>Section Two</dt>\n<dd>Child two</dd>\n</dl>''')\n\n...
[ 3, 0 ]
[]
[]
[ "python", "xpath", "xslt" ]
stackoverflow_0004968633_python_xpath_xslt.txt
Q: C#'s equivalent to Python's os.path.exists()? I can use os.path.exists() to check if the file exists or not with Python. What's the equivalent function in C#? A: Surely you mean .NET, not C# :) Try System.IO.File.Exists. A: Both System.IO.File and System.IO.Directory has Exists. bool dirExists = System.IO.Dire...
C#'s equivalent to Python's os.path.exists()?
I can use os.path.exists() to check if the file exists or not with Python. What's the equivalent function in C#?
[ "Surely you mean .NET, not C# :)\nTry System.IO.File.Exists.\n", "Both System.IO.File and System.IO.Directory has Exists.\nbool dirExists = System.IO.Directory.Exists(@\"C:\\directory\\\");\nbool fileExists = System.IO.File.Exists(@\"C:\\directory\\file.txt\");\nAnd for an additional bonus: Note that for cross pl...
[ 3, 3, 2 ]
[]
[]
[ "c#", "exists", "python" ]
stackoverflow_0004972087_c#_exists_python.txt
Q: How do I select all of the tr's except the last two tr's In lxml, I'm using xpath to select all of the tr's in a table (that has varying number of rows) except for the last two rows which contain gibberish. Is there a pattern match that excludes the last two rows? I was looking through xpath tutorials and apparent...
How do I select all of the tr's except the last two tr's
In lxml, I'm using xpath to select all of the tr's in a table (that has varying number of rows) except for the last two rows which contain gibberish. Is there a pattern match that excludes the last two rows? I was looking through xpath tutorials and apparently there is an "except" operator and also a "last()," but can'...
[ "Use:\nexpressionSelectingTheTable/tr[not(position() > last() -2)]\n\nwhere expressionSelectingTheTable should be substituted with a specific XPath expression that selects the table, for which the question is being asked (such as //table[@id='foo'])\nThis single XPath expression selects all tr children of the table...
[ 9, 2 ]
[]
[]
[ "except", "lxml", "python", "xpath" ]
stackoverflow_0004965342_except_lxml_python_xpath.txt
Q: Git Hooks not running automatically I am trying to setup a git hook so I can integrate with bugTracker.net. They provide a git hook script which I have pasted into the post-commit.sample file for use. I have removed the .sample suffix so the file name is now post-commit. I have installed python and set the path. T...
Git Hooks not running automatically
I am trying to setup a git hook so I can integrate with bugTracker.net. They provide a git hook script which I have pasted into the post-commit.sample file for use. I have removed the .sample suffix so the file name is now post-commit. I have installed python and set the path. The hook however is not being automaticall...
[ "I've seen this problem asked a few times over the past week or so by people trying to host a git repo on Windows so right from the start I'm almost certain what the problem is but lets run down the specifics of your setup to see.\nWhat protocol are you using to push with? Are you using SSH, HTTP(S), FTP, RSYNC, or...
[ 0 ]
[]
[]
[ "chmod", "git", "hook", "python" ]
stackoverflow_0004972188_chmod_git_hook_python.txt
Q: Stripping "\" at the end I want to convert a path name that I read from the command window to just the file name. For example, convert C:\temp\documents\tempfile to tempfile I was trying to do something like- filename=tempfilename.lstrip('\') #this gave me an error filename=tempfilename.lstrip('\\') #and this di...
Stripping "\" at the end
I want to convert a path name that I read from the command window to just the file name. For example, convert C:\temp\documents\tempfile to tempfile I was trying to do something like- filename=tempfilename.lstrip('\') #this gave me an error filename=tempfilename.lstrip('\\') #and this did nothing What am I doing wro...
[ "In Python, as in most other languages, strings can contain backslash-escaped character sequences, so instead of '\\', you need to write '\\\\' (= represents one single backslash).\nSecond, there is no method called listrip. For stripping at the end, you obviously need to use rstrip, not lstrip.\nFor your specific ...
[ 5, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004972422_python.txt
Q: Passing Argument to Python's Function I have this function: def fun(arg1=1, arg2=2, arg3=3, arg4=4) Now if I want to call fun with arg1=8 then I will do this: fun(8) and if I want to call it with arg1 = 8 and arg2 = 9 then I think this will do (correct me if I am wrong): fun(8,9) # LINE2 How to call fun if I want...
Passing Argument to Python's Function
I have this function: def fun(arg1=1, arg2=2, arg3=3, arg4=4) Now if I want to call fun with arg1=8 then I will do this: fun(8) and if I want to call it with arg1 = 8 and arg2 = 9 then I think this will do (correct me if I am wrong): fun(8,9) # LINE2 How to call fun if I want to call it with the fourth argument = 10, ...
[ "fun(arg4=10)\n\nYou just have to reference the specific argument(s) by name.\n", "just provide the arguments you want and the others will get their default values:\nfun(arg4=10)\n", ">>> def fun(arg1=1,arg2=2,arg3=3,arg4=4):\n print arg4\n\n>>> fun(arg4='I called you!')\nI called you!\n\nJust call the s...
[ 7, 1, 1, 1 ]
[]
[]
[ "arguments", "function", "python" ]
stackoverflow_0004972688_arguments_function_python.txt
Q: multi-parameter 'in' in python Let L = [1,2,3,4] be our list. Then 1 in L is True. 2 in L is also True. Is there a clean way to write (1,2) in L and have it come out true? That is, given a list L and a test list T and the relation multi-in, if all members of T are in L, then T multi-in L is True, otherwise T mult...
multi-parameter 'in' in python
Let L = [1,2,3,4] be our list. Then 1 in L is True. 2 in L is also True. Is there a clean way to write (1,2) in L and have it come out true? That is, given a list L and a test list T and the relation multi-in, if all members of T are in L, then T multi-in L is True, otherwise T multi-in L is False. Of course I can wri...
[ "You want to treat (1,2) and L as sets:\nset((1,2)).issubset(L)\n\nor, nicer if you understand the notation:\nset((1,2)) <= set(L)\n\n", "all(x in L for x in [1, 2])\n\nUnlike the set-based solutions, this (1) short-curcuits as soon as an element isn't found, (2) works for unhashable types and (3) reads out nice ...
[ 8, 5, 1, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004972735_python.txt
Q: How to shrink a text output in python Hi I have a program in python which upon running displays an output on a single page. But when I print the output to an A4 size page the output does not fit on to a page, and gets distorted. Is there a way I could shrink my output or adjust the font size of my output, and pri...
How to shrink a text output in python
Hi I have a program in python which upon running displays an output on a single page. But when I print the output to an A4 size page the output does not fit on to a page, and gets distorted. Is there a way I could shrink my output or adjust the font size of my output, and print it on to a single page?
[ "You could possibly use the formatter module. You could use the end_paragraph function to set the length of your line and you could use the push_font function to reduce the font size. \n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0004972857_python.txt
Q: R equivalent of python "_"? Python has an identifier _ that allows for storing the result of the last evaluation which makes it great for speeding up data exploration and introspection. In [1]: 43 * 2 Out[1]: 86 In [2]: _ + 1 Out[2]: 87 Is there a similar command in R? A: Tis a faff to type, but .Last.value: >...
R equivalent of python "_"?
Python has an identifier _ that allows for storing the result of the last evaluation which makes it great for speeding up data exploration and introspection. In [1]: 43 * 2 Out[1]: 86 In [2]: _ + 1 Out[2]: 87 Is there a similar command in R?
[ "Tis a faff to type, but .Last.value:\n> sqrt(2)\n[1] 1.414214\n> .Last.value\n[1] 1.414214\n\n" ]
[ 43 ]
[]
[]
[ "ipython", "python", "r" ]
stackoverflow_0004973185_ipython_python_r.txt
Q: Python: how to "new" a class instance and set its properties when in passing argument? Python code: class A: '''omitted''' pass def foo(A): pass a = A() a.xx = 1 a.yy = 2 foo(a) is it possible to rewrite above code like this? foo(a = A(), a.xx =1, a.bb = 2) Thanks! =================== thanks for the so...
Python: how to "new" a class instance and set its properties when in passing argument?
Python code: class A: '''omitted''' pass def foo(A): pass a = A() a.xx = 1 a.yy = 2 foo(a) is it possible to rewrite above code like this? foo(a = A(), a.xx =1, a.bb = 2) Thanks! =================== thanks for the solution below: foo(A()) but if A has foo1(), foo2() a = A() a.foo1() a.foo2() foo(a) how c...
[ "You mean a constructor? You just need to supply an __init__ method:\nclass A(object):\n def __init__(self, xx, yy):\n self.xx = xx\n self.yy = yy\n\nfoo(A(1, 2))\n\n", "If you're that dead set against calling foo1 and foo2 in or before the function foo, call it in the __init__ that @Santa crafte...
[ 4, 3, 0, 0 ]
[]
[]
[ "arguments", "instance", "python" ]
stackoverflow_0004966776_arguments_instance_python.txt
Q: How can i config my CACHE_BACKEND when i deal with session and page cache,i get a problem. i use memcache to store my session info, and i would like to use file to cache the site page. The quesion is they both use CACHE_BACKEND, if i make it like this: CACHE_BACKEND = 'memcached://127.0.0.1:11211/', then how can i...
How can i config my CACHE_BACKEND
when i deal with session and page cache,i get a problem. i use memcache to store my session info, and i would like to use file to cache the site page. The quesion is they both use CACHE_BACKEND, if i make it like this: CACHE_BACKEND = 'memcached://127.0.0.1:11211/', then how can i make my page cache work with file?
[ "You have three possibilities:\n0) use Beaker http://beaker.groovie.org/index.html\n1) Do not use memcache for session storing but use the db session engine by adding 'django.contrib.sessions' to your INSTALLED_APPS (do not forget to syncdb to create the session tables). If you have concerns about performance you c...
[ 1, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004965519_django_python.txt
Q: Python WMI calls not working under Windows 7 I've run into a sticky problem using WMI (via win32com) in Python under Windows 7. I haven't been able to find a resolution for this. Here is my code: from win32com.client import GetObject def get_printers(computer): """ Get a list of printers from the specified c...
Python WMI calls not working under Windows 7
I've run into a sticky problem using WMI (via win32com) in Python under Windows 7. I haven't been able to find a resolution for this. Here is my code: from win32com.client import GetObject def get_printers(computer): """ Get a list of printers from the specified computer name. """ wmiservice = GetObject(r"win...
[ "As it turns out, the problem was not related to DCOM/WMI/UAC/Firewall. What was really suprising was that the Win 7 PC had nothing reported in it's event log at all when these failures happened.\nWhat I noticed was that, as in the original problem, outgoing connections from Win 7 reported Access Denied. But I als...
[ 2, 0 ]
[]
[]
[ "python", "win32com", "wmi" ]
stackoverflow_0004972398_python_win32com_wmi.txt
Q: How to access through a path rather than just in current directory? I have written a function which reads in an excel file and manipulates it. Obviously the .py file has to be in the same directory as the excel file. Is there a way to enter the path of the file so I can leave the script in the same place? A: imp...
How to access through a path rather than just in current directory?
I have written a function which reads in an excel file and manipulates it. Obviously the .py file has to be in the same directory as the excel file. Is there a way to enter the path of the file so I can leave the script in the same place?
[ "import os\nos.chdir('/my/new/path')\n\nYou can change the current working directory by using os.chdir.\nAnother way would be to reference the excel file (however you are opening it) by an absolute path. \n", "\nObviously the .py file has to be in\n the same directory as the excel file.\n\nI don't understand \"o...
[ 4, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004973187_python.txt
Q: Amazon AWS web framework for Python I dealt with GAE before and I like simplicity of its webapp. Now I am trying to learn how to work with Amazon EC2. My question - where do I start to make a simple web application that I will be able to access form browser? I suppose I should use WSGI for this purpose. I don't wa...
Amazon AWS web framework for Python
I dealt with GAE before and I like simplicity of its webapp. Now I am trying to learn how to work with Amazon EC2. My question - where do I start to make a simple web application that I will be able to access form browser? I suppose I should use WSGI for this purpose. I don't want to use Django as I want to keep the ap...
[ "AWS and GAE are very different. GAE very strictly defines what you can and can't do in terms of development environment. AWS gives you a server to do whatever you want with. \nGAE is good when you don't want to have to figure out how all the pieces fit together to scale well. AWS is good when you need flexibili...
[ 4, 2 ]
[]
[]
[ "amazon_ec2", "python" ]
stackoverflow_0004971635_amazon_ec2_python.txt
Q: Materialize data from cache table to production table [PostgreSQL] I am trying to find the best solution (perfomance/easy code) for the following situation: Considering a database system with two tables, A (production table) and A'(cache table): Future rows are added first into A' table in order to not disturb th...
Materialize data from cache table to production table [PostgreSQL]
I am trying to find the best solution (perfomance/easy code) for the following situation: Considering a database system with two tables, A (production table) and A'(cache table): Future rows are added first into A' table in order to not disturb the production one. When a timer says go (at midnight, for example) rows f...
[ "The \"best\" solution according to the criteria you've laid out so far would just be to insert into the production table.\n...unless there's actually something extremely relevant you're not telling us\n" ]
[ 1 ]
[]
[]
[ "materialized_views", "postgresql", "python", "triggers" ]
stackoverflow_0004973316_materialized_views_postgresql_python_triggers.txt
Q: Easy-to-learn language like Python, but which requires variable declaration? Python is super easy to learn and understand; I like it for its use of keywords, lack of intricate syntax (opposite of perl, from what I've heard), and easy-to-use data structures. However, I can't stand the lack of variable declaration, ...
Easy-to-learn language like Python, but which requires variable declaration?
Python is super easy to learn and understand; I like it for its use of keywords, lack of intricate syntax (opposite of perl, from what I've heard), and easy-to-use data structures. However, I can't stand the lack of variable declaration, because it makes it impossible to explicitly tell Python what scope you want the v...
[ "Try pychecker, pylint, pyflakes or other code checking tools. They help catch errors that the interpreter doesn't complain about.\n", "You can try using Python with variable declarations:\n>>> x = 0 # a global variable\n>>> def fact(n): #n is a parameter\n... x = 0 # local variable declaration\n... z = 1...
[ 7, 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "declaration", "declare", "python", "variable_declaration" ]
stackoverflow_0004240114_declaration_declare_python_variable_declaration.txt
Q: client connects to old server thread and retrieves outdated data? I have a client thread that will ping server for one of its status attributes: def run ( self ): client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('localhost',2727)) print 'client #', self.name , 'polling'...
client connects to old server thread and retrieves outdated data?
I have a client thread that will ping server for one of its status attributes: def run ( self ): client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('localhost',2727)) print 'client #', self.name , 'polling' x = client.recv(1024) client.close() print x my server ...
[ "sThread.ServerThread() is your function, right?\nInstead of getting the device state and passing it as an argument to ServerThread(), have your implementation of ServerThread() do a call to .getDeviceState() after the request comes in to get the latest device state.\nThe way you have it set up now returns the devi...
[ 0 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0004973660_multithreading_python.txt
Q: python class in string I have name of class in string like: conf[0] = 'smtp_config' and i want to run method like: self.ui.smtp_config.setText("....") How can i do this in python? :) A: Try getattr(self.ui,conf[0]).setText(...) A: func = getattr(self.ui, conf[0]) func.setText("....")
python class in string
I have name of class in string like: conf[0] = 'smtp_config' and i want to run method like: self.ui.smtp_config.setText("....") How can i do this in python? :)
[ "Try getattr(self.ui,conf[0]).setText(...)\n", "func = getattr(self.ui, conf[0])\nfunc.setText(\"....\")\n\n" ]
[ 3, 2 ]
[]
[]
[ "class", "methods", "python" ]
stackoverflow_0004973882_class_methods_python.txt
Q: No output is produced even after putting a test case in the code from brisa.core.reactors import install_default_reactor reactor = install_default_reactor() import os import unittest from brisa.upnp.device import Device, Service from brisa.upnp.device.service import StateVariable class SwitchPower(Service): ...
No output is produced even after putting a test case in the code
from brisa.core.reactors import install_default_reactor reactor = install_default_reactor() import os import unittest from brisa.upnp.device import Device, Service from brisa.upnp.device.service import StateVariable class SwitchPower(Service): def __init__(self): Service.__init__(self, ...
[ "If you want tests to be run when you invoke the script, you need:\nif __name__ == '__main__':\n unittest.main()\n\nHowever, the generally recommended practice is to put your tests in a sep. file (with the above \"main\"), so you can keep the main section in your existing program.\n" ]
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0004973912_python.txt
Q: Error while running test case I need to test my code below. I am using one test to see if it is working or not. but dont know what exactly I should pass as a parameter in the test code. Please see the test code at the end and please guide me what value I should pass here? Because whatever I write here, it throws m...
Error while running test case
I need to test my code below. I am using one test to see if it is working or not. but dont know what exactly I should pass as a parameter in the test code. Please see the test code at the end and please guide me what value I should pass here? Because whatever I write here, it throws me an error. from brisa.core.react...
[ "In your testOne() method, you're calling _create_device(), which isn't a global function it's a method on SwitchPower objects. \nYou probably want to create a new SwitchPower object.\n", "_create_device() is not defined in class IsOddTests. It is defined in BinaryLight.\nI'm not completely sure about this, but...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004974150_python.txt
Q: Nodebox Python clean up So I tried running an example Nodebox tutorial. Here's the code: g = grid.create(2, 2, 250, 250) g.top.left.split(2, 2) g.top.left.bottom.right.split(2, 2) # fetch images from Morguefile.com web = ximport("web") img = web.morguefile.search("ocean")[:5] img = [x.download() for x in img] g....
Nodebox Python clean up
So I tried running an example Nodebox tutorial. Here's the code: g = grid.create(2, 2, 250, 250) g.top.left.split(2, 2) g.top.left.bottom.right.split(2, 2) # fetch images from Morguefile.com web = ximport("web") img = web.morguefile.search("ocean")[:5] img = [x.download() for x in img] g.content = images g.content.re...
[ "From what I can gather about the library, web defined Yahoo, morgueFile etc. They did not include youtube + google. \nWeb is a module; the module has methods and attributed hard-coded in. You can't just cut and copy out websites into the attribute and expect it to work. I'm pretty sure the reason they're hard-cod...
[ 1 ]
[]
[]
[ "nodebox", "python" ]
stackoverflow_0004973358_nodebox_python.txt
Q: Python profile output in eclipse When I run profiler in eclipse with specifying file name, I expect the output to be dumped in the file in readable format. But I see binary file being created ( even if I specify filename.txt ) which I cannot read. How do I get the output of the profiler ( profile module ) in a tex...
Python profile output in eclipse
When I run profiler in eclipse with specifying file name, I expect the output to be dumped in the file in readable format. But I see binary file being created ( even if I specify filename.txt ) which I cannot read. How do I get the output of the profiler ( profile module ) in a text file ? python 2.5 version. Thanks
[ "Use pstats to load the profile data (see the documentation here)\nIn related news: you can use gprof2dot to turn these stats into fancy graphs ;-)\n" ]
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004974310_python.txt
Q: Python pyserial - how can I determine the number of serial ports? I would like to determine the number of available serial ports, including those provided by USB adapters, under both Linux and windows without having to adapt the program for specific platforms. I seem to be chasing my tail at the moment and would a...
Python pyserial - how can I determine the number of serial ports?
I would like to determine the number of available serial ports, including those provided by USB adapters, under both Linux and windows without having to adapt the program for specific platforms. I seem to be chasing my tail at the moment and would appreciate another angle on this. Using pyserial is easy enough on eithe...
[ "Does the example not work for you:\nhttp://pyserial.svn.sourceforge.net/viewvc/checkout/pyserial/trunk/pyserial/examples/scan.py\nIt is a bit brute force (it just tries to connect to every port and ones that throw an exception are ignored as not present).\n" ]
[ 0 ]
[]
[]
[ "pyserial", "python", "serial_port" ]
stackoverflow_0004958015_pyserial_python_serial_port.txt
Q: 2 way UDP proxy in python I am trying to create a proxy for UDP in python. Here's the scenario: Client connects to server on port 6000 from a high random port (say 53273) Server reply to port 53273 from port 55385 Then the communication continue over these two ports. These 2 port number are only known when the com...
2 way UDP proxy in python
I am trying to create a proxy for UDP in python. Here's the scenario: Client connects to server on port 6000 from a high random port (say 53273) Server reply to port 53273 from port 55385 Then the communication continue over these two ports. These 2 port number are only known when the communication is initiated. The pr...
[ "I would start with this:\nhttp://docs.python.org/library/socketserver.html#asynchronous-mixins\nThis is a threaded socket server built into python. You can use it to serve up the main port and then call a handler whenever a client connects. You'll need it to be threaded since it sounds like your running some typ...
[ 0 ]
[]
[]
[ "python", "udp" ]
stackoverflow_0004950955_python_udp.txt
Q: Python's os.path libraries equivalent in C# Let's say I have a binary in C# code ae /a/b/c/xyz.exe and it expects the /a/b/c/hello.txt in the same directory. How can I get the /a/b/c/hello.txt in full path? In python, I can get the running program's path with os.path.abspath(sys.argv[0]), and I can get the direct...
Python's os.path libraries equivalent in C#
Let's say I have a binary in C# code ae /a/b/c/xyz.exe and it expects the /a/b/c/hello.txt in the same directory. How can I get the /a/b/c/hello.txt in full path? In python, I can get the running program's path with os.path.abspath(sys.argv[0]), and I can get the directory info with dirname(), and I can use join() to ...
[ "You can use Environment.CurrentDirectory, Environment.GetCommandLineArgs and the classes in System.IO.Path to do the same things. Your code would translate as:\n// using System.IO;\n\nstring newPath = Path.Combine(\n Path.GetDirectoryName(\n Path.GetFullPath(Environment.GetComman...
[ 5, 1 ]
[]
[]
[ "c#", "path", "python" ]
stackoverflow_0004974430_c#_path_python.txt
Q: How to change string to Integers in python Trying to remove single quotes from around numbers. I'm working with third paty data that's not well typed. lst = [ ('text','2','3','4'), ('text2','4','5','6') ] y= [map(int,i) for i in zip(*lst)[1:]] d = zip(*list)[0] print d c= zip(*y) print c dd = zip(d,c) pr...
How to change string to Integers in python
Trying to remove single quotes from around numbers. I'm working with third paty data that's not well typed. lst = [ ('text','2','3','4'), ('text2','4','5','6') ] y= [map(int,i) for i in zip(*lst)[1:]] d = zip(*list)[0] print d c= zip(*y) print c dd = zip(d,c) print dd this is what the out is: ('text', 'text...
[ "print [(text, int(a), int(b), int(c)) for (text, a, b, c) in lst]\n\n", "Jochen's answer is the right thing for your specific case.\nIf, for some reason, you need to take the list of types as a parameter you can do something like this:\n>>> lst = [ ('text','2','3','4'), ('text2','4','5','6') ]\n\n>>> def map_ro...
[ 8, 2, 1, 0 ]
[]
[]
[ "list", "python" ]
stackoverflow_0004974604_list_python.txt
Q: App Engine getRecord not returning content In Google App Engine, I am trying to get a specific record and the content associated with it. I use the following (relevant) code (all necessary GData is imported and the client is authenticated): sclient = gdata.spreadsheet.text_db.DatabaseClient(username, password) gd...
App Engine getRecord not returning content
In Google App Engine, I am trying to get a specific record and the content associated with it. I use the following (relevant) code (all necessary GData is imported and the client is authenticated): sclient = gdata.spreadsheet.text_db.DatabaseClient(username, password) gdata.alt.appengine.run_on_appengine(sclient) gdat...
[ "make sure you don't have any empty rows in spreadsheet. API will stop reading data when it encounters first empty line, so if your first row in spreadsheet is empty, you wont get any results.\n" ]
[ 0 ]
[]
[]
[ "google_app_engine", "google_data_api", "python" ]
stackoverflow_0004363062_google_app_engine_google_data_api_python.txt
Q: Error in running Test case I changed the code and try to run the test case but still could get better situation. Please see the code and error and guide me in getting rid of it. from brisa.core.reactors import install_default_reactor reactor = install_default_reactor() import os import unittest from brisa.up...
Error in running Test case
I changed the code and try to run the test case but still could get better situation. Please see the code and error and guide me in getting rid of it. from brisa.core.reactors import install_default_reactor reactor = install_default_reactor() import os import unittest from brisa.upnp.device import Device, Service...
[ "You're not passing in a keyword list into SetTarget. Do it like:\nself.failUnless(b1.SetTarget(NewTargetValue='something'))\n\nError with this:\nTraceback (most recent call last):\n File \"binary_light.py\", line 54, in testOne\n self.failUnless(b1.SetTarget(NewTargetValue= 'something'))\nAssertionError\n\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0004974855_python.txt
Q: Creating an object-oriented API over C using SWIG I am using SWIG to create wrappers for a C library. The C library interface has a natural mapping to an object-oriented API (which I'd like to expose in the target language), but a straightforward usage of SWIG to produce wrappers will generate a single object in t...
Creating an object-oriented API over C using SWIG
I am using SWIG to create wrappers for a C library. The C library interface has a natural mapping to an object-oriented API (which I'd like to expose in the target language), but a straightforward usage of SWIG to produce wrappers will generate a single object in the target language with all of the interfaces of the C ...
[ "I do also prefer option 2 (\"Build a custom classes in each target language that use the simple, non-OO SWIG output internally\").\nMy reasons are:\n\nYou have to mantain \"less code\". The\ncomplex part is the C library + SWIG\nwrappers, so the better is to keep\nthat as small as possible. Creating\nanother C++ w...
[ 1, 0 ]
[]
[]
[ "c", "java", "python", "swig" ]
stackoverflow_0004973410_c_java_python_swig.txt
Q: How should a Gnome applet store its configuration data? I have a Gnome applet written in Python. In order to save configuration data/settings, it creates a file ~/.appname. However, this prevents multiple instances of the applet from being added to the panel because each cannot have its own settings. How can I sto...
How should a Gnome applet store its configuration data?
I have a Gnome applet written in Python. In order to save configuration data/settings, it creates a file ~/.appname. However, this prevents multiple instances of the applet from being added to the panel because each cannot have its own settings. How can I store the settings in a way that allows each instance to have it...
[ "The recommend way for an applet would be to use GConf to store preferences and to use one key per instance so that you can store individual settings. From Panel Applet GConf Utilities:\n\nApplets typically define a set of\n preferences using a schemas file and\n panel_applet_add_preferences(). Such\n preference...
[ 7, 1 ]
[]
[]
[ "applet", "gnome", "python" ]
stackoverflow_0003018287_applet_gnome_python.txt
Q: What does this error mean? what does this error mean?? Ran 1 test in 0.002s FAILED (failures=1) ankit@ubuntu:~/Desktop$ python binary_light.py Light switched None F ====================================================================== FAIL: testOne (__main__.IsOddTests) -----------------------------------------...
What does this error mean?
what does this error mean?? Ran 1 test in 0.002s FAILED (failures=1) ankit@ubuntu:~/Desktop$ python binary_light.py Light switched None F ====================================================================== FAIL: testOne (__main__.IsOddTests) ---------------------------------------------------------------------- Tr...
[ "An AssertionError is documented under http://docs.python.org/library/exceptions.html#exceptions.AssertionError:\n\nRaised when an assert statement fails.\n\nYour unittest is asserting that SetTarget will return something that is boolean True; however, your method is returning {}, which is equivalent to boolean Fal...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0004975126_python.txt
Q: What's the newest way to develop gnome panel applets (using python) Today I've switched to GNOME (from XFCE) and found some of the cool stuff missing and I would like to (try to) do them on my own. I tried to find information on how to develop Gnome applets (items you place within the panel) and most likely in Pyt...
What's the newest way to develop gnome panel applets (using python)
Today I've switched to GNOME (from XFCE) and found some of the cool stuff missing and I would like to (try to) do them on my own. I tried to find information on how to develop Gnome applets (items you place within the panel) and most likely in Python, but it's not a hard limitation. I found the article 'Gnome applets w...
[ "Theres an article called Gnome Panel Applets in Python from 2008 on the Ubuntu forums that may help with this.\nThis includes defining a bonobo component. This Gnome documentation on applet development states that \n\nTechnically, applets are Bonobo controls embedded in the Gnome panel\n\nSo it looks like that is ...
[ 4, 2 ]
[]
[]
[ "gnome", "pygtk", "python" ]
stackoverflow_0002034834_gnome_pygtk_python.txt
Q: TypeError: 'NoneType' object does not support item assignment? So I start a root screen with a "file select" and a "go" button. The go button is disabled and I want to make it active after the file has been selected. When I select the file go should become active but instead this error "TypeError: 'NoneType' obje...
TypeError: 'NoneType' object does not support item assignment?
So I start a root screen with a "file select" and a "go" button. The go button is disabled and I want to make it active after the file has been selected. When I select the file go should become active but instead this error "TypeError: 'NoneType' object does not support item assignment" Here is some sample code import...
[ "This line:\ngo=Tkinter.Button(text='file location',command=chooseDir,state=Tkinter.DISABLED).pack()\n\nis creating a temporary object, then calling pack() on it. The pack method returns None, so go is assigned None. \nRemove the .pack() then go will be the Button object. Then call go.pack().\n", "(update for new...
[ 10, 1 ]
[]
[]
[ "python", "tkinter" ]
stackoverflow_0004975010_python_tkinter.txt
Q: How do your set the twitter byline from an application? Twitter allows applications to set a "byline" that appears after the tweeter's name, but I don't see how to set that. I'm currently using the Python API tweepy. Any ideas? A: How do I get “from [MyApp]” appended to updates sent from my API application? We n...
How do your set the twitter byline from an application?
Twitter allows applications to set a "byline" that appears after the tweeter's name, but I don't see how to set that. I'm currently using the Python API tweepy. Any ideas?
[ "\nHow do I get “from [MyApp]” appended to updates sent from my API application?\nWe now recommend developers use OAuth\nto perform authentication with the\nAPI. When applications use OAuth,\nTwitter automatically knows the source\nof status updates. We are therefore\nable to append source attribution\n(from \"[MyA...
[ 3 ]
[]
[]
[ "api", "python", "twitter" ]
stackoverflow_0004975376_api_python_twitter.txt
Q: Finding errors in a file I have a huge file whose contents are generated from running an executable over and over on different input files. The file's pattern is such: -file name followed by an arbitrary amount of text lines. I have to pick up the name of the file when there is an error in reading input data and I...
Finding errors in a file
I have a huge file whose contents are generated from running an executable over and over on different input files. The file's pattern is such: -file name followed by an arbitrary amount of text lines. I have to pick up the name of the file when there is an error in reading input data and I am not sure what the best way...
[ "This should do more or less what you need:\nf = open(\"your_file.txt\")\nfile_name = None\nfor line in f:\n if line.startswith(r\"C:\\\"):\n file_name = line\n elif line.startswith(\"Error\"):\n print \"Error for file \" + file_name\n\nAssumptions: \n  - File names will start with \"C:\\\", if ...
[ 1, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004975179_python.txt
Q: python subprocess.Popen and ssh port forwarding in the background I need to have functionality that would essentially emulate user creating a port forwrding with ssh. So, essentially that should work like that: - execute ssh -f -N -L 10000:gateway:11000 localhost - if there is an output from that command, show t...
python subprocess.Popen and ssh port forwarding in the background
I need to have functionality that would essentially emulate user creating a port forwrding with ssh. So, essentially that should work like that: - execute ssh -f -N -L 10000:gateway:11000 localhost - if there is an output from that command, show to the user and pump user's input as a response - finish The code I cam...
[ "I guess the solution was pretty easy\nssh_proc = Popen(['ssh', '-f', '-N', '-L', '10000:gateway:11000', 'localhost'], stdin=PIPE, stdout=PIPE)\nstat = ssh_proc.poll()\nwhile stat == None:\n stat = ssh_proc.poll()\n\n" ]
[ 7 ]
[]
[]
[ "fork", "popen", "python", "ssh", "subprocess" ]
stackoverflow_0004975251_fork_popen_python_ssh_subprocess.txt
Q: When does it matter to use %d over %s when formatting integers to strings in python? Assuming I don't need padding or other formatting conversion, when does it matter to use %d over %s when printing numbers ? From the snippet below, there seems to be no difference. >>> "%d %d"%(12L,-12L) '12 -12' >>> "%s %s"%(12L,...
When does it matter to use %d over %s when formatting integers to strings in python?
Assuming I don't need padding or other formatting conversion, when does it matter to use %d over %s when printing numbers ? From the snippet below, there seems to be no difference. >>> "%d %d"%(12L,-12L) '12 -12' >>> "%s %s"%(12L,-12L) '12 -12'
[ "%s can format any python object and print it is a string. The result that %d and %s print the same in this case because you are passing int/long object. Suppose if you try to pass other object, %s would print the str() representation and %d would either fail or would print its numeric defined value.\n>>> print '%d...
[ 8, 5, 3, 3, 3 ]
[]
[]
[ "python" ]
stackoverflow_0004975538_python.txt
Q: how to call python code in javascript to display bar chart i have written python code which gives me i/p to chart(json data) but i am not getting how to get these data in my javascript. i want to display it in google app engine i want to do it in same way as we can do it with PHP. A: As I've posted a few times a...
how to call python code in javascript to display bar chart
i have written python code which gives me i/p to chart(json data) but i am not getting how to get these data in my javascript. i want to display it in google app engine i want to do it in same way as we can do it with PHP.
[ "As I've posted a few times already, if you want Python to be PHP-like, try Flask\nFlask is dead-simple, extremely powerful, and intuitive. I prefer it over PHP for soo many reasons, but mainly because PHP is not Python.\nHere's what I mean by simple and intuitive. I can't really explain it in words, so here's an e...
[ 0, 0 ]
[]
[]
[ "javascript", "python" ]
stackoverflow_0002423102_javascript_python.txt
Q: Python PyGILState_{Ensure/Release} causes segfault while returning to C++ from Python code UPDATE Well, it looks like adding PyEval_InitThreads() before the call to PyGILState_Ensure() does the trick. In my haste to figure things out I incorrectly attributed my "hanging" to PyEval_InitThreads(). However, after rea...
Python PyGILState_{Ensure/Release} causes segfault while returning to C++ from Python code
UPDATE Well, it looks like adding PyEval_InitThreads() before the call to PyGILState_Ensure() does the trick. In my haste to figure things out I incorrectly attributed my "hanging" to PyEval_InitThreads(). However, after reading some Python documentation I am wondering if this is the correct solution. It is not safe t...
[ "Python expects a certain amount of initialization to be done by the main thread before anything attempts to call back in from a subthread.\nIf the main thread is an application that is embedding Python, then it should call PyEval_InitThreads() immediately after calling Py_Initialize().\nIf the main thread is inste...
[ 13, 7 ]
[]
[]
[ "c++", "gnuradio", "multithreading", "python", "segmentation_fault" ]
stackoverflow_0004866701_c++_gnuradio_multithreading_python_segmentation_fault.txt
Q: What would be a good way to deal with backslash escaped characters? I have a string in the following format; s="part1,part2,part3,part4" I can split the string into pieces by just invoking the s.split(",") command. Now, the question is what if I have a backslash escaped comma in the string? Assuming I have the fo...
What would be a good way to deal with backslash escaped characters?
I have a string in the following format; s="part1,part2,part3,part4" I can split the string into pieces by just invoking the s.split(",") command. Now, the question is what if I have a backslash escaped comma in the string? Assuming I have the following string, s="part1,part2,pa\\,rt3,part4" I'd like to be able to ge...
[ "Replacing it with a non-existing string is a nice option.\nAnd otherwise, you could use a regular expression with a negative lookbehind like this:\nre.split(r'(?<!\\\\),', 'part1,part2,pa\\\\,rt3,part4')\n\n", "The csv module can handle this as well:\nimport csv\nfrom io import StringIO\n\ns = 'part1,part2,pa\\\...
[ 11, 4 ]
[ "BTW, '\\' is not an escape character for ',' comma. So your string would have have a legal word with '\\'. If you specially want the \\, to be part of the word, then a regex based solutions looks good to me.\n" ]
[ -1 ]
[ "escaping", "python", "string" ]
stackoverflow_0004975654_escaping_python_string.txt
Q: Python Cross Module Variables I realize there are other threads addressing this problem but as I am fairly new to 'Classes' and have already constructed my class structure ... I would like to find a method that I can integrate into my code. I'm sure this will NOT be a difficult one to answer! First File: NameResul...
Python Cross Module Variables
I realize there are other threads addressing this problem but as I am fairly new to 'Classes' and have already constructed my class structure ... I would like to find a method that I can integrate into my code. I'm sure this will NOT be a difficult one to answer! First File: NameResult.py from NameAssign import * Name...
[ "NameVar is not defined in NameAssign; it only exists within NameAssign.NameWorks.InputNames() as a local variable. The easiest way to fix this is to define it in NameAssign at the global level.\nEdit:\nIt turns out that this is what you want to do:\nNameResult.py\nimport NameAssign\n\nnamelist = NameAssign.NameWor...
[ 4 ]
[]
[]
[ "module", "python", "variables" ]
stackoverflow_0004976375_module_python_variables.txt
Q: Magic method to make class work as list index? I can use a boolean as a list index: isTrue = True print ('No','Yes')[isTrue] -> 'Yes' but if I define a class, class YeaOrNay(object): def __init__(self, val): self.val = bool(val) def __nonzero__(self): return self.val def __int__(sel...
Magic method to make class work as list index?
I can use a boolean as a list index: isTrue = True print ('No','Yes')[isTrue] -> 'Yes' but if I define a class, class YeaOrNay(object): def __init__(self, val): self.val = bool(val) def __nonzero__(self): return self.val def __int__(self): return int(self.val) def __str__(se...
[ "In python, bool is a subclass of int. That's why you can use a bool as an index of the tuple. However, YeaOrNea is clearly neither and thus the error. If you insist on using this object as an index to a tuple, subclass int (or bool) to trick it to make it work.\nclass YeaOrNea(int):\n ...\n\nOtherwise do it ...
[ 5, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004976418_python.txt
Q: ConfigObj way to get list of sections that contain subsections I use ConfigObj to parse config file in format: [APACHE] init_script= ... [TOMCAT] [[TOMCAT1]] init_script = [[TOMCAT2]] init_script = In some condition [TOMCAT] section may have nested subsection,sometime not - only single root instan...
ConfigObj way to get list of sections that contain subsections
I use ConfigObj to parse config file in format: [APACHE] init_script= ... [TOMCAT] [[TOMCAT1]] init_script = [[TOMCAT2]] init_script = In some condition [TOMCAT] section may have nested subsection,sometime not - only single root instance [TOMCAT] . I'm fresh in python so interesting, is there a conveni...
[ "You can use the method walk and print section that have a depth greater than one. \ndef gather_subsection(section, key):\n if section.depth > 1:\n print \"Subsection \" + section.name\n\nconfig.walk(gather_subsection)\n\nDocumentation for depth\n\ndepth\nThe nesting level of the current\n section.\nIf y...
[ 4 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0004970098_parsing_python.txt
Q: track logins in appengine I'm building a groupon-y service to learn app engine. I want to track a list of accounts that log in to the site (using google authentication). What's the best way to do this? Since I use google authentication there's no single point in time where they 'sign up'; they could log in at any ...
track logins in appengine
I'm building a groupon-y service to learn app engine. I want to track a list of accounts that log in to the site (using google authentication). What's the best way to do this? Since I use google authentication there's no single point in time where they 'sign up'; they could log in at any url. Here is what I've tried: ...
[ "You could use a decorator - you'll have to remember to put it in front of any handlers that require login anyway - or you could do it in a base RequestHandler that all your handlers extend (my personal preference), or you could write some WSGI middleware that does it. It's up to you.\n", "There isn't a way to ex...
[ 1, 0, 0 ]
[]
[]
[ "decorator", "google_app_engine", "python" ]
stackoverflow_0004600213_decorator_google_app_engine_python.txt
Q: Python: Delete CSV headers row and rewrite new headers row Still teaching myself python so please don't hate me if my code is terrible... My code: ifile = csv.reader(open("TE.csv",'rb')) shutil.copy("TE.csv","temp") tempfile = csv.reader(open("temp","rb")) ofile = csv.writer(open("TE-RESULTS.csv","ab")) for row i...
Python: Delete CSV headers row and rewrite new headers row
Still teaching myself python so please don't hate me if my code is terrible... My code: ifile = csv.reader(open("TE.csv",'rb')) shutil.copy("TE.csv","temp") tempfile = csv.reader(open("temp","rb")) ofile = csv.writer(open("TE-RESULTS.csv","ab")) for row in ifile: #do some web scraping stuff here VC_s = str(ce...
[ "Process the header row before the for loop.\nrowAdd = tempfile.next()\nofile.writerow(rowAdd + ['HEADER4', 'HEADER5', 'HEADER6'])\n\nfor ...\n\n" ]
[ 0 ]
[]
[]
[ "csv", "header", "python" ]
stackoverflow_0004976475_csv_header_python.txt
Q: try: statement fails I have some python code that fails: import sys print ("MathCheats Times-Ed by jtl999") numbermodechoice = raw_input ("Are you using a number with a decimal? yes/no ") if numbermodechoice == "yes": try: numberx1 = float(raw_input('Enter first number: ')) except ValueError: print ("O...
try: statement fails
I have some python code that fails: import sys print ("MathCheats Times-Ed by jtl999") numbermodechoice = raw_input ("Are you using a number with a decimal? yes/no ") if numbermodechoice == "yes": try: numberx1 = float(raw_input('Enter first number: ')) except ValueError: print ("Oops you typed it wrong") t...
[ "Python is whitespace sensitive, with regards to the leading whitespace.\nyour code probably should be indented like\nimport sys\nfrom sys import exit\nprint (\"MathCheats Times-Ed by jtl999\")\nnumbermodechoice = raw_input (\"Are you using a number with a decimal? yes/no \")\nif numbermodechoice == \"yes\":\n t...
[ 2, 1, 0, 0, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004975811_python.txt
Q: VB.Net HTTPWebRequest Speed is slow comparing Python URLOpen Hi I am coding a web-crawler which will crawl the websites and selectively parse different sections of a web site. I am a .Net developer so the choice was obvious that I did it in .Net but the speed was very slow which included downloading and parsing of...
VB.Net HTTPWebRequest Speed is slow comparing Python URLOpen
Hi I am coding a web-crawler which will crawl the websites and selectively parse different sections of a web site. I am a .Net developer so the choice was obvious that I did it in .Net but the speed was very slow which included downloading and parsing of HTMLPages Then I tried to just download the contents first using ...
[ "HttpWebRequest is limited to 2 connections at a time, so if you're downloading content along with html (such as images, stylesheets, js etc.) or you are using multiple threads then you'll hit the connection limit.\nyou'll need to change the settings in ServicePointManager.\nhttp://msdn.microsoft.com/en-us/library/...
[ 2 ]
[]
[]
[ "comparison", "http", "python", "vb.net" ]
stackoverflow_0004976678_comparison_http_python_vb.net.txt
Q: What speech libraries are available in Linux? When it comes to TTS (text-to-speech) libraries in Linux, what choices do developers have? What libraries ship with the majority of distros? Are there minimal libraries? What functionality does each library offer? I'm approaching this primarily from a C++ point of view...
What speech libraries are available in Linux?
When it comes to TTS (text-to-speech) libraries in Linux, what choices do developers have? What libraries ship with the majority of distros? Are there minimal libraries? What functionality does each library offer? I'm approaching this primarily from a C++ point of view, although Python would suit me too.
[ "Ubuntu comes with eSpeak, which is quite simple to use. From the console, simply enter:\nespeak \"Hello World\"\n\nOther options include Festival and Flite. Festival is the most sophisticated one I've used so far, and I've successfully installed new, less artificial-sounding voices (for Ubuntu, see http://ubuntufo...
[ 5, 1 ]
[]
[]
[ "c++", "linux", "python", "text_to_speech" ]
stackoverflow_0002854554_c++_linux_python_text_to_speech.txt
Q: How to properly use relative or absolute imports in Python modules? Usage of relative imports in Python has one drawback, you will not be able to run the modules as standalones anymore because you will get an exception: ValueError: Attempted relative import in non-package # /test.py: just a sample file importing f...
How to properly use relative or absolute imports in Python modules?
Usage of relative imports in Python has one drawback, you will not be able to run the modules as standalones anymore because you will get an exception: ValueError: Attempted relative import in non-package # /test.py: just a sample file importing foo module import foo ... # /foo/foo.py: from . import bar ... if __name_...
[ "You could just start 'to run the modules as standalones' in a bit a different way:\nInstead of:\npython foo/bar.py\n\nUse:\npython -mfoo.bar\n\nOf course, the foo/__init__.py file must be present.\nPlease also note, that you have a circular dependency between foo.py and bar.py – this won't work. I guess it is just...
[ 22, 16, 1, 1, 0 ]
[ "So far the only solution I found was not to use relative imports at all. \nDue to current limitation, I'm wondering when someone is supposed to use relative imports in python.\nOn all configurations that I used the sys.path contained the current directory as first argument so just use import foo instead of from . ...
[ -2 ]
[ "module", "package", "python", "python_import", "python_module" ]
stackoverflow_0003616952_module_package_python_python_import_python_module.txt
Q: Is there function in Python which serves as main in C I want to know whether there is a main function in Python as in C, etc. ? A: The short answer is no. Typically, if __name__ == '__main__': import sys argc = len(sys.argv) argv = sys.argv is the closest thing you get to a main in Python. More in...
Is there function in Python which serves as main in C
I want to know whether there is a main function in Python as in C, etc. ?
[ "The short answer is no. Typically,\nif __name__ == '__main__':\n import sys\n argc = len(sys.argv)\n argv = sys.argv\n\nis the closest thing you get to a main in Python. More info here.\n", "No. Python scripts are executed from beginning to end, which means that there is no need for a main() function....
[ 10, 10, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004976906_python.txt
Q: Efficiency of imports in Python I have a module with many functions: Module One def a(): ... def b(): ... def c(): .... Now, from a different module, I need to import only function b. For that purpose, i am using the syntax: from One import b My question - beside from namespace considerations, is there any po...
Efficiency of imports in Python
I have a module with many functions: Module One def a(): ... def b(): ... def c(): .... Now, from a different module, I need to import only function b. For that purpose, i am using the syntax: from One import b My question - beside from namespace considerations, is there any positive effect on the time complexity ...
[ "No. The full module must be completely run (the first time) to be certain that the name will even exist within it regardless.\n", "Let's find out by benchmarking. Start with the script:\n#!/usr/bin/python\nfor i in xrange(100000):\n print \"def foo%d(): pass\\n\" % i\n\nWhich generates a large Python program....
[ 6, 5, 2 ]
[]
[]
[ "python" ]
stackoverflow_0004977268_python.txt
Q: How to use descriptors with attributes of instances? I read the docs and saw that descriptors had to be used with class attributes only. What would be an acceptable way of using them within instances of that class? I.e. class Attribute( object ): def __init__(self, value): self.value = value def ...
How to use descriptors with attributes of instances?
I read the docs and saw that descriptors had to be used with class attributes only. What would be an acceptable way of using them within instances of that class? I.e. class Attribute( object ): def __init__(self, value): self.value = value def __get__(self, obj, objtype): print "GETTING" d...
[ "Manipulate them via obj, the second argument to the descriptor's methods.\n" ]
[ 2 ]
[]
[]
[ "oop", "python" ]
stackoverflow_0004977347_oop_python.txt
Q: mysql via subprocess doesn't work import os import subprocess cmdline = ['mysql -u"username" -p"password" < query.sql'] p = subprocess.Popen(cmdline,stdout=subprocess.PIPE) stdout,stderr = p.communicate() retcode = p.wait() That's my code to connect to mysql and execute query.sql. Looks good to me, but it doesn't...
mysql via subprocess doesn't work
import os import subprocess cmdline = ['mysql -u"username" -p"password" < query.sql'] p = subprocess.Popen(cmdline,stdout=subprocess.PIPE) stdout,stderr = p.communicate() retcode = p.wait() That's my code to connect to mysql and execute query.sql. Looks good to me, but it doesn't work and the bad thing is that I don't...
[ "cmdline = ['mysql -u\"username\" -p\"password\" < query.sql']\n\nThis is not the way to use Popen. The program must be the first element of the list, and each argument that should be passed must be an element of the list, too. So it should rather be cmdline = [\"mysql\", \"-u\", username, \"-p\", password]. Furthe...
[ 7, 2 ]
[]
[]
[ "mysql", "python", "subprocess" ]
stackoverflow_0004977649_mysql_python_subprocess.txt
Q: divide ways on a map in parts of length one I have these coordinates: coord = [(10,10), (13,10), (13,13)] Now i need new coordinates. The way between two coordinates is always one. For example: (10,10) (11,10) (12,10) (13,10) (13,11) (13,12) (13,13) Any ideas? # I found the solution. for n in range(len(coord...
divide ways on a map in parts of length one
I have these coordinates: coord = [(10,10), (13,10), (13,13)] Now i need new coordinates. The way between two coordinates is always one. For example: (10,10) (11,10) (12,10) (13,10) (13,11) (13,12) (13,13) Any ideas? # I found the solution. for n in range(len(coord)-1): lengthx = coord[n+1][0] - coord[n][0] ...
[ "A simple variation on Bresenham's line algorithm will achieve what you want using integer arithmetic only (so it should be noticeably faster):\ndef steps(path):\n if len(path) > 0:\n for i in range(1, len(path)):\n for step in steps_between(path[i - 1], path[i]):\n yield step\n ...
[ 1 ]
[]
[]
[ "algorithm", "arrays", "python" ]
stackoverflow_0004977637_algorithm_arrays_python.txt
Q: Using web.webopenid with web.py to authenticate users I have a web.py app I'm running through mod_wsgi locally (http://localhost/...). I've gotten to the point of adding authentication to my app and wanted to use web.py's builtin module. I started with a brief example found here: http://log.liminastudio.com/prog...
Using web.webopenid with web.py to authenticate users
I have a web.py app I'm running through mod_wsgi locally (http://localhost/...). I've gotten to the point of adding authentication to my app and wanted to use web.py's builtin module. I started with a brief example found here: http://log.liminastudio.com/programming/howto-use-openid-with-web-py import web, web.webope...
[ "Most likely obvious causes for this were given in answer to same question on mod_wsgi list. See:\nhttps://groups.google.com/d/msg/modwsgi/iL65jNeY5jA/KgEq33E8548J\nIt is probably a combination of the first two, current working directory and Apache user access rights.\n" ]
[ 0 ]
[]
[]
[ "apache", "mod_wsgi", "openid", "python", "web.py" ]
stackoverflow_0004976657_apache_mod_wsgi_openid_python_web.py.txt
Q: python search technology: word similarity I want to get a similarity percentage of two words, eg) abcd versus zzabcdzz == 50% similarity Don't need to be very accurate. Is there any way to do that? I am using python but feel free to recomment other languages. A: Try using python-Levenshtein to calculate the edi...
python search technology: word similarity
I want to get a similarity percentage of two words, eg) abcd versus zzabcdzz == 50% similarity Don't need to be very accurate. Is there any way to do that? I am using python but feel free to recomment other languages.
[ "Try using python-Levenshtein to calculate the edit distance.\n\nThe Levenshtein Python C extension module contains functions for fast computation of\n\nLevenshtein (edit) distance, and edit operations\nstring similarity\napproximate median strings, and generally string averaging\nstring sequence and set similarity...
[ 6, 3, 1, 0 ]
[]
[]
[ "python", "search", "search_engine", "similarity" ]
stackoverflow_0004976613_python_search_search_engine_similarity.txt
Q: Tuple vs array in hashtable Python I have heard that tuple element take low space but can't be modify, so what is the best solution in terms of execution times: hash = {} hash['foo'] = [34,'foobar',[55,90]] hash['foo'][0] = hash['foo'][0] + 17 OR hash = {} hash['foo'] = (34,'foobar',[55,90]) hash['foo'] = (hash['...
Tuple vs array in hashtable Python
I have heard that tuple element take low space but can't be modify, so what is the best solution in terms of execution times: hash = {} hash['foo'] = [34,'foobar',[55,90]] hash['foo'][0] = hash['foo'][0] + 17 OR hash = {} hash['foo'] = (34,'foobar',[55,90]) hash['foo'] = (hash['foo'][0] + 17,hash['foo'][1],hash['foo']...
[ "First, don't call the dictionary hash. It shadows the built-in hash. \nIn both the cases, if you delete the last line and then time the code, the values are:\n0.545173168182 # list\n0.479876995087 # tuple\n\nAnd that is expected behaviour. Because creating a tuple is faster than creating a list.\n$ python -m...
[ 6 ]
[]
[]
[ "python" ]
stackoverflow_0004977859_python.txt
Q: Use PYTHONSTARTUP to interactively test a python file in the interpreter I want to establish a standard script file that is imported into python at startup using the PYTHONSTARTUP environment variable. Additionally, I want to be able to conveniently reload the same script file after modifying it in an external edi...
Use PYTHONSTARTUP to interactively test a python file in the interpreter
I want to establish a standard script file that is imported into python at startup using the PYTHONSTARTUP environment variable. Additionally, I want to be able to conveniently reload the same script file after modifying it in an external editor, to test its behavior after the modification. I created a ~/.pythonrc.py f...
[ "Move the import statement outside the function. You're basically importing the workbench module into the function scope, not the global scope (Try calling workbench.dull_function from inside load_wb to see for yourself).\nIn other words, change your code to:\nimport os\nimport imp\nimport workbench\n\ndef load_wb(...
[ 0, 0 ]
[]
[]
[ "python", "python_3.x" ]
stackoverflow_0004015656_python_python_3.x.txt
Q: file handling using pickle try.py: import pickle f=open('abc.dat','w') x=[320,315,316] y=pickle.load(f) f.close() f=open('abc.dat','w') for i in x: y.append(i) pickle.dump(y,f) f.close() use.py import pickle import os os.system('try.py') f=open('abc.dat', 'r') print "abc.dat = " x=pickle.load(f) print x...
file handling using pickle
try.py: import pickle f=open('abc.dat','w') x=[320,315,316] y=pickle.load(f) f.close() f=open('abc.dat','w') for i in x: y.append(i) pickle.dump(y,f) f.close() use.py import pickle import os os.system('try.py') f=open('abc.dat', 'r') print "abc.dat = " x=pickle.load(f) print x print "end of abc.dat" f.close(...
[ "The error is in try.py:\nf=open('abc.dat','w')\ny=pickle.load(f)\n\nNote that the 'w' mode resets the file to size 0 (i.e. deletes its content). Pass 'r' or nothing at all to open abc.dat for reading.\n", "Example doesn't work for me. try.py fails when the file doesn't exist.\nMy big recommendation, though, is t...
[ 3, 1 ]
[]
[]
[ "python" ]
stackoverflow_0004978041_python.txt
Q: Storing cookielib cookies in a database I'm using the cookielib module to handle HTTP cookies when using the urllib2 module in Python 2.6 in a way similar to this snippet: import cookielib, urllib2 cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) r = opener.open("http://exa...
Storing cookielib cookies in a database
I'm using the cookielib module to handle HTTP cookies when using the urllib2 module in Python 2.6 in a way similar to this snippet: import cookielib, urllib2 cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) r = opener.open("http://example.com/") I'd like to store the cookies in...
[ "cookielib.Cookie, to quote its docstring (in its sources), \n\nis deliberately a very simple class. \n It just holds attributes.\n\nso pickle (or other serialization approaches) are just fine for saving and restoring each Cookie instance.\nAs for CookieJar, set_cookie sets/adds one cookie instance, __iter__ (to u...
[ 9, 4 ]
[]
[]
[ "cookielib", "python", "urllib2" ]
stackoverflow_0003028923_cookielib_python_urllib2.txt
Q: Additional computed fields in Model I have two simple models in my Django app. Here's what they look like: class Host(models.Model): url = models.URLField(max_length= 200) ssl = models.BooleanField(default = False) class Query(models.Model): host = models.ForeignKey(Host) date = models.DateTimeFie...
Additional computed fields in Model
I have two simple models in my Django app. Here's what they look like: class Host(models.Model): url = models.URLField(max_length= 200) ssl = models.BooleanField(default = False) class Query(models.Model): host = models.ForeignKey(Host) date = models.DateTimeField(auto_now_add = True) latency = mod...
[ "You can just use class properties:\nclass Host(models.Model):\n .\n .\n .\n @property\n def average_latency(self):\n # calculate latency from Query model ...\n return latency\n\nBear in mind that this is a read-only property.\n", "You can check django-denorm, it's pretty much about w...
[ 2, 1 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0004977393_django_django_models_python.txt
Q: python twitter Api() not found error I'm trying to use the python-twitter module, but still having problems initiating the twitter.Api(). I've checked and rechecked that no other file named twitter.py or twitter.pyc is on my system. On a clean install i first try to >>> import twitter and correctly get a respon...
python twitter Api() not found error
I'm trying to use the python-twitter module, but still having problems initiating the twitter.Api(). I've checked and rechecked that no other file named twitter.py or twitter.pyc is on my system. On a clean install i first try to >>> import twitter and correctly get a response of 'module unknown' I do a easy_install...
[ "It appears that you are trying to follow the documentation for one Python Twitter module when you are in fact using another Python Twitter module.\nThe Api() method call you mention is part of this Python Twitter module. However, when you use easy_install twitter, you actually get this other Python Twitter module...
[ 7 ]
[]
[]
[ "api", "python", "twitter" ]
stackoverflow_0004977883_api_python_twitter.txt
Q: Freeing a PyTuple object What is the proper way to free a PyTuple object using the Python C-API? I know that tuples are somewhat special when it comes to the reference counting semantics, since PyTuple_SetItem "steals" the reference to the inserted element. I also know that decrementing the reference of a tuple o...
Freeing a PyTuple object
What is the proper way to free a PyTuple object using the Python C-API? I know that tuples are somewhat special when it comes to the reference counting semantics, since PyTuple_SetItem "steals" the reference to the inserted element. I also know that decrementing the reference of a tuple object decrements the reference...
[ "Add call to Py_Initialize(); at the beginning of main and try again.\n" ]
[ 3 ]
[]
[]
[ "c", "python", "python_c_api", "python_c_extension" ]
stackoverflow_0004898173_c_python_python_c_api_python_c_extension.txt
Q: Transforming expression given in prefix notation, identifying common subexpressions and dependencies I am given a bunch of expressions in prefix notation in an ANSI text file. I would like to produce another ANSI text file containing the step-by-step evaluation of these expressions. For example: - + ^ x 2 ^ y 2 1 ...
Transforming expression given in prefix notation, identifying common subexpressions and dependencies
I am given a bunch of expressions in prefix notation in an ANSI text file. I would like to produce another ANSI text file containing the step-by-step evaluation of these expressions. For example: - + ^ x 2 ^ y 2 1 should be turned into t1 = x^2 t2 = y^2 t3 = t1 + t2 t4 = t3 - 1 t4 is the result I also have to identi...
[ "To give you an idea how this would look like in Python, here is some example code:\noperators = \"+-*/^\"\n\ndef parse(it, count=1):\n token = next(it)\n if token in operators:\n op1, count = parse(it, count)\n op2, count = parse(it, count)\n tmp = \"t%s\" % count\n print tmp, \"=...
[ 5, 4, 3, 2, 2, 1, 1 ]
[]
[]
[ "erlang", "haskell", "lisp", "python", "scala" ]
stackoverflow_0004843237_erlang_haskell_lisp_python_scala.txt
Q: Python: Equivalent to Matlab's svds(A, k) for large arrays? I'm trying to port some code from Matlab to Python and I've run into a problem. I can't seem to find an equivalent to svds. I tried using numpy.corrcoef and then numpy.linalg.eig, but numpy.corrcoef doesn't work for large arrays (say 500 x 20000). Here's...
Python: Equivalent to Matlab's svds(A, k) for large arrays?
I'm trying to port some code from Matlab to Python and I've run into a problem. I can't seem to find an equivalent to svds. I tried using numpy.corrcoef and then numpy.linalg.eig, but numpy.corrcoef doesn't work for large arrays (say 500 x 20000). Here's the code in matlab, in case it makes any difference: s = size(da...
[ "So what you are looking for, would be something like this in python and numpy (I took the liberty not to 'directly translate' the matlab-code to python and numpy, instead I refactored it a little bit to 'feel' more pythonic [of'course quite similar refactoring can be applied to the matlab-code as well]):\nimport n...
[ 3, 2 ]
[]
[]
[ "matlab", "python" ]
stackoverflow_0004974808_matlab_python.txt
Q: when using ftplib in python Here is the relevant code that's causing the Error. ftp = ftplib.FTP('server') ftp.login(r'user', r'pass') #change directories to the "incoming" folder ftp.cwd('incoming') fileObj = open(fromDirectory + os.sep + f, 'rb') #push the file try: msg = ftp.storbinary('STOR %s' % f, fil...
when using ftplib in python
Here is the relevant code that's causing the Error. ftp = ftplib.FTP('server') ftp.login(r'user', r'pass') #change directories to the "incoming" folder ftp.cwd('incoming') fileObj = open(fromDirectory + os.sep + f, 'rb') #push the file try: msg = ftp.storbinary('STOR %s' % f, fileObj) except Exception as inst: ...
[ "Maybe you should increase the \"timeout\" option, and let the server more time to response.\n", "In my case, changing to ACTV mode, as @Anders Lindahl suggested, got everything back into working order.\n" ]
[ 1, 1 ]
[]
[]
[ "ftplib", "python" ]
stackoverflow_0004946960_ftplib_python.txt
Q: receive data from a python program to animate an object on a webpage good day stackoverflow! im not sure if any of you has tried this but basically i want to accomplish something like this: - a python program continuously sends data to my website - using that data computations will be made and images on the websit...
receive data from a python program to animate an object on a webpage
good day stackoverflow! im not sure if any of you has tried this but basically i want to accomplish something like this: - a python program continuously sends data to my website - using that data computations will be made and images on the website are animate so my questions are: 1. what method should i use to communic...
[ "Images are not shown \"on your website\", they are shown \"in your users' browsers\".\nThe browser needs to request the animation information from your website, which needs to request it from (wherever it comes from). Ideally, the website will cache the data so that 20 browser requests result in just one website r...
[ 0, 0 ]
[]
[]
[ "html", "python" ]
stackoverflow_0004979005_html_python.txt
Q: GBrowse API for Python Is there a python interface to GBrowse, something like Bio::Graphics in perl ? Otherwise, are there any python modules available to create genome browser like views ? A: Let me google that for you: 'python genome browser view' yields, for example, this.
GBrowse API for Python
Is there a python interface to GBrowse, something like Bio::Graphics in perl ? Otherwise, are there any python modules available to create genome browser like views ?
[ "Let me google that for you:\n'python genome browser view' yields, for example, this.\n" ]
[ 0 ]
[]
[]
[ "browser", "genome", "python" ]
stackoverflow_0004978535_browser_genome_python.txt
Q: Python simple POST method A web page has 2 form fields 1: <input type="text" maxlength="30" value="" name="poster" id="id_poster"> 2: <textarea name="content" cols="80" rows="20" id="id_content"></textarea> Also it has a button: <input type="submit" value="Submit your own idea!"> What I want is, through python ...
Python simple POST method
A web page has 2 form fields 1: <input type="text" maxlength="30" value="" name="poster" id="id_poster"> 2: <textarea name="content" cols="80" rows="20" id="id_content"></textarea> Also it has a button: <input type="submit" value="Submit your own idea!"> What I want is, through python to fill in the forms id_poster ...
[ "Personally I prefer httplib2, you would have to install it. The library is a lot better than the one given that by python out of the box.\nfrom httplib2 import Http\nfrom urllib import urlencode\nh = Http()\ndata = dict(id_poster=\"some_poster_id\", id_content=\"some_content\")\nresp, content = h.request(\"http://...
[ 7, 4 ]
[]
[]
[ "methods", "post", "python" ]
stackoverflow_0004979638_methods_post_python.txt
Q: Python: Generic Algorithmic to determine fixed length columns I am trying to write a generic function to be able to read a fixed length file. I could go through and hand count the length between columns, and then read the file, but I was wondering if there was a way to do it programmatically. I can see what nee...
Python: Generic Algorithmic to determine fixed length columns
I am trying to write a generic function to be able to read a fixed length file. I could go through and hand count the length between columns, and then read the file, but I was wondering if there was a way to do it programmatically. I can see what needs to be done, but I am not sure the proper way to do it... If I ha...
[ "One-liner using regex splits:\n>>> map(len, re.split(r\"(?<=[^ ]) \", head))\n[5, 5, 10, 13]\n\nExplanation:\nre.split splits a string at all points where a regular expression matches. The regular expression I use (others would be possible) has a lookbehind group (?<=[^ ]) which means \"preceded by a non-space\" a...
[ 3, 2, 0 ]
[]
[]
[ "algorithm", "python" ]
stackoverflow_0004970500_algorithm_python.txt
Q: python and django: execute python script from django web form? I have fully functional python program which I run from shell. All arguments and options are supplied using option parser. What I would like to do is to create simple web interface for this program using django. I am stacked on transferring values rece...
python and django: execute python script from django web form?
I have fully functional python program which I run from shell. All arguments and options are supplied using option parser. What I would like to do is to create simple web interface for this program using django. I am stacked on transferring values received from web form to python script )) Actually how can I execute py...
[ "If your python program has a bit that looks like this:\nimport sys\nif __name__ == \"__main__\":\n args = sys.argv \n main(args)\n\nThen just import it, and call it's main() method with your args in the same format as sys.argv. Sorted. That would be the pythonic way of doing things.\nOtherwise you need a general...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0004979950_django_python.txt
Q: Mapping function to numpy array, varying a parameter First, let me show you the codez: a = array([...]) for n in range(10000): func_curry = functools.partial(func, y=n) result = array(map(func_curry, a)) do_something_else(result) ... What I'm doing here is trying to apply func to an array, changin...
Mapping function to numpy array, varying a parameter
First, let me show you the codez: a = array([...]) for n in range(10000): func_curry = functools.partial(func, y=n) result = array(map(func_curry, a)) do_something_else(result) ... What I'm doing here is trying to apply func to an array, changing every time the value of the func's second parameter. Thi...
[ "Did you try numpy.vectorize?\n...\n vfunc_curry = vectorize(functools.partial(func, y=n))\n result = vfunc_curry(a)\n...\n\n", "If a is of significant size the bottleneck should not be the creation of the function, but the duplication of the array.\n", "Can you rewrite the function? If possible, you shou...
[ 6, 0, 0 ]
[]
[]
[ "arrays", "currying", "map", "numpy", "python" ]
stackoverflow_0003977581_arrays_currying_map_numpy_python.txt
Q: How do I format the output of this Python program? I am trying to figure out how to get these sets of values to line up from left to right (see below). How could I do this? def main(): for temp in range(-20, 70, 10): for windspeed in range(5, 55, 5): print int(35.74 + (0.6215*(temp)) - (35...
How do I format the output of this Python program?
I am trying to figure out how to get these sets of values to line up from left to right (see below). How could I do this? def main(): for temp in range(-20, 70, 10): for windspeed in range(5, 55, 5): print int(35.74 + (0.6215*(temp)) - (35.75* windspeed**0.16) + (0.4275*(temp)) * (windspeed**0....
[ "I think you want to transpose your output which you can do by reversing the order of the loops. As a special bonus I have formatted the output so that it appears in nice neat colums!\nfor windspeed in range(5, 55, 5):\n for temp in range(-20, 70, 10):\n print \"%3d\" % int(35.74 + (0.6215*(temp)) - (35.7...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004980281_python.txt