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: ImportError: No module named wx When I write "import wx" in the Python interpreter there is no problem, but when I run script with that line from Windows console, error "ImportError: No module named wx" appears. Result of commands help() modules contains wx wxPython wxversion sys.path contains '<site-packages pa...
ImportError: No module named wx
When I write "import wx" in the Python interpreter there is no problem, but when I run script with that line from Windows console, error "ImportError: No module named wx" appears. Result of commands help() modules contains wx wxPython wxversion sys.path contains '<site-packages path>\\wx-2.8-msw-unicode' How to solv...
[ "The Python used for the REPL is not the same as the Python the script is being run in. Print sys.executable to verify.\n" ]
[ 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0007701932_python_wxpython.txt
Q: How to make a regex for /vi/.htm(l)? My pattern that already matches e.g. /vi/9822 is /vi/([^/]+)? I also want to match e.g. /vi/9822.htm and /vi/9822.html. Can you help me? Thank you A: If the .htm or .html part is optional, this should suit your needs: /vi/(\d+)(\.html?)?, otherwise use just /vi/(\d+)\.html?....
How to make a regex for /vi/.htm(l)?
My pattern that already matches e.g. /vi/9822 is /vi/([^/]+)? I also want to match e.g. /vi/9822.htm and /vi/9822.html. Can you help me? Thank you
[ "If the .htm or .html part is optional, this should suit your needs: /vi/(\\d+)(\\.html?)?, otherwise use just /vi/(\\d+)\\.html?.\n", "Add \\.html? to the end of what you already have, optionally removing or moving the existing ?.\n" ]
[ 3, 2 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007702050_python_regex.txt
Q: printing an element of array (python) There are two lists/arrays and I want to assign one by one. import Mybench process = [] benchmarks = options.benchmark.split(',') for bench_name in benchmarks: process.append(getattr(Mybench, bench_name)) Assume another list (cpus) is also created. Now I want to do this: i...
printing an element of array (python)
There are two lists/arrays and I want to assign one by one. import Mybench process = [] benchmarks = options.benchmark.split(',') for bench_name in benchmarks: process.append(getattr(Mybench, bench_name)) Assume another list (cpus) is also created. Now I want to do this: i = 0 for i, cpu in cpus: print "cpu", i,...
[ "for i, cpu in enumerate(cpus):\n print \"cpu\", i, \"assigned to \", process[i]\n cpu.workload = process[i]\n\n" ]
[ 0 ]
[]
[]
[ "arrays", "printing", "python" ]
stackoverflow_0007702101_arrays_printing_python.txt
Q: plot data from a txt file I would like to plot data from a txt file to a graph: 13/7/2009 12:50:50 147425826 0 4716298 36645030 3757926 228230 13/7/2009 13:5:1 147517368 0 4717954 36687455 3761270 228375 13/7/2009 13:10:0 147550312 0 4718599 36701448 3762634 228437 The date should be the x axis and the r...
plot data from a txt file
I would like to plot data from a txt file to a graph: 13/7/2009 12:50:50 147425826 0 4716298 36645030 3757926 228230 13/7/2009 13:5:1 147517368 0 4717954 36687455 3761270 228375 13/7/2009 13:10:0 147550312 0 4718599 36701448 3762634 228437 The date should be the x axis and the remaining columns should be the ...
[ "one of the best python package for plotting data is matplotlib. \nthen, you only have to parse your input file:\nimport time\n\ndata = []\nfor line in open('input.txt'):\n date,time,*samples = line.split()\n data.append((time.strptime(str.join(' ', (date, time)), '%d/%m/%Y %H:%M:%S'), samples))\n\nthen use m...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007702508_python.txt
Q: How to get rid of "Command Line" window when running Python script with GUI? Possible Duplicate: How can I hide the console window in a PyQt app running on Windows? I am programming under Python2.6 + PyQT + Eric4 environment. All the GUI and Program parts are done, but here is the problem. When I run my program,...
How to get rid of "Command Line" window when running Python script with GUI?
Possible Duplicate: How can I hide the console window in a PyQt app running on Windows? I am programming under Python2.6 + PyQT + Eric4 environment. All the GUI and Program parts are done, but here is the problem. When I run my program, two windows pop up. One is the window (or frame) I want, the other is like a pyt...
[ "I suppose you are using Windows, the only operating system I know to open a prompt when you double click a script. There are two solutions AFAIK: execute the file with the pythonw.exe executable, as suggested by @Adrien. If you save the file with the .pyw extension, Windows automatically uses pythonw.exe for execu...
[ 5, 4, 3 ]
[]
[]
[ "pyqt4", "python", "windows", "windows_console" ]
stackoverflow_0007702495_pyqt4_python_windows_windows_console.txt
Q: Using a language such as Ruby or Python to interact with API's I'm looking to start building web apps. I need basic CRUD functionality. I understand the basics of how to do this in ruby and python - but here's where I'm stuck: How do I parse a GET or POST request in Ruby/Python? I'm trying to interact with so...
Using a language such as Ruby or Python to interact with API's
I'm looking to start building web apps. I need basic CRUD functionality. I understand the basics of how to do this in ruby and python - but here's where I'm stuck: How do I parse a GET or POST request in Ruby/Python? I'm trying to interact with someone else's API, I know the string I need, just not how to referenc...
[ "This is a very rough example of how you can do this in python. It would need modification for your specific situation, but hopefully it can get you started:\nimport urllib\nimport urllib2\nurl = \"http://www.coolwebsite.com\"\npost = urllib.urlencode({\"users\":\"bob\", \"bobsgreat\":\"yes\", \"postcount\":\"14\"...
[ 1, 0 ]
[]
[]
[ "api", "parsing", "python", "ruby" ]
stackoverflow_0007701819_api_parsing_python_ruby.txt
Q: What is the best way to distribute a Python package that requires a minimal Python version I have a Python 2 project ('foo 0.1.7') that required Python 2.4 or later. Now I ported it to Python 3 ('foo 0.2.0') in a way that it still is compatible with Python 2, but the requirements are now lifted to Python 2.6 or la...
What is the best way to distribute a Python package that requires a minimal Python version
I have a Python 2 project ('foo 0.1.7') that required Python 2.4 or later. Now I ported it to Python 3 ('foo 0.2.0') in a way that it still is compatible with Python 2, but the requirements are now lifted to Python 2.6 or later. I know that there is a --target-version=2.6 option for setup.py, that can be used with upl...
[ "\nI know that there is a --target-version=2.6 option for setup.py, that can be\n used with upload, but that seems not to be meant as '2.6 or higher'\n\nIt is actually an option for bdist_wininst or bdist_msi, and indeed does not include “or higher”.\n\nThe setup command has an install_requires option, but this is...
[ 4, 2 ]
[]
[]
[ "pypi", "python", "setuptools" ]
stackoverflow_0007634298_pypi_python_setuptools.txt
Q: Why is there a need for Twisted? I have been playing around with the twisted framework for about a week now(more because of curiosity rather than having to use it) and its been a lot of fun doing event driven asynchronous network programming. However, there is something that I fail to understand. The twisted docu...
Why is there a need for Twisted?
I have been playing around with the twisted framework for about a week now(more because of curiosity rather than having to use it) and its been a lot of fun doing event driven asynchronous network programming. However, there is something that I fail to understand. The twisted documentation starts off with Twisted is ...
[ "In a comment on another answer, you say \"Every library is supposed to have ...\". \"Supposed\" by whom? Having use-cases is certainly a nice way to nail down your requirements, but it's not the only way. It also doesn't make sense to talk about the use-cases for all of Twisted at once. There is no use case th...
[ 13, 7, 5, 4 ]
[]
[]
[ "asynchronous", "python", "twisted" ]
stackoverflow_0004031402_asynchronous_python_twisted.txt
Q: Using Sphinx with a distutils-built C extension I have written a Python module including a submodule written in C: the module itself is called foo and the C part is foo._bar. The structure looks like: src/ foo/__init__.py <- contains the public stuff foo/_bar/bar.c <- the C extension doc/ ...
Using Sphinx with a distutils-built C extension
I have written a Python module including a submodule written in C: the module itself is called foo and the C part is foo._bar. The structure looks like: src/ foo/__init__.py <- contains the public stuff foo/_bar/bar.c <- the C extension doc/ <- Sphinx configuration conf.py ... foo/__init_...
[ "Since distutils has a way of figuring out the variable build path, why not just use it?\nimport distutils.command.build\nfrom distutils.dist import Distribution\n\nb = distutils.command.build.build(Distribution())\nb.initialize_options()\nb.finalize_options()\n\nprint b.build_temp\n\n# If you're building a library...
[ 5, 2 ]
[]
[]
[ "distutils", "python", "python_sphinx" ]
stackoverflow_0004687608_distutils_python_python_sphinx.txt
Q: Can't get distutils working I've written a Python script that uses a package that I've created. I need to package it, so I can install it on several servers, but I can't get setup.py to find my scripts. There's two parts to my script: connections.py and a module that is imported as X.utils.printing (where X is my...
Can't get distutils working
I've written a Python script that uses a package that I've created. I need to package it, so I can install it on several servers, but I can't get setup.py to find my scripts. There's two parts to my script: connections.py and a module that is imported as X.utils.printing (where X is my group name). I need to bundle b...
[ "I think you'll want something like the following:\nfrom distutils.core import setup\n\nsetup(name='connections',\n version='0.1.1',\n description='Print number of IHS connections',\n author='fandingo',\n author_email='fandingo@fandingo.com',\n packages=['X'],\n scripts=['connection-st...
[ 1, 1 ]
[]
[]
[ "distutils", "python" ]
stackoverflow_0004442109_distutils_python.txt
Q: Python: Installing man pages in distutils based project I have a Python project which is basically a set of command line scripts and a helper package. As these scripts have a number of command line options I decided to create a manual page for each script and used ronn (http://rtomayko.github.com/ronn/) to write m...
Python: Installing man pages in distutils based project
I have a Python project which is basically a set of command line scripts and a helper package. As these scripts have a number of command line options I decided to create a manual page for each script and used ronn (http://rtomayko.github.com/ronn/) to write manuals in Markdown and generate mdoc from it. The question is...
[ "Your little hack in your setup.py does the trick.... In complement, you can add a special man_prefix options that can be passed at setup time to change the man path.\nYou can do this like this :\nclass lc_install(install):\n description = \"Custom Install Process\"\n\n user_options= install.user_options[:]\n...
[ 2, 2 ]
[]
[]
[ "distutils", "python" ]
stackoverflow_0003657209_distutils_python.txt
Q: How to install twisted 10.2.0 with pypy 1.4.1? I can't install twisted 10.2.0 to my ubuntu box. After download twisted source I issue the command: pypy setup.py install. After that I receive the error: building 'twisted.runner.portmap' extension creating build/temp.linux-x86_64-2.5 creating build/temp.linux-x86_64...
How to install twisted 10.2.0 with pypy 1.4.1?
I can't install twisted 10.2.0 to my ubuntu box. After download twisted source I issue the command: pypy setup.py install. After that I receive the error: building 'twisted.runner.portmap' extension creating build/temp.linux-x86_64-2.5 creating build/temp.linux-x86_64-2.5/twisted creating build/temp.linux-x86_64-2.5/tw...
[ "That's a \"bug\" in twisted build. It might be or might not be a bug - twisted does not consider it's C extensions optional, although they're far from necessary for the most part. Twisted would still work if you just point PYTHONPATH to where it is situated, but without those C extensions.\n", "You may be able t...
[ 4, 3, 2 ]
[]
[]
[ "pypy", "python", "twisted" ]
stackoverflow_0005126039_pypy_python_twisted.txt
Q: html table issue with for-loops I'm having a difficulty formatting a table in html through python. I'm using for-loops from previous information, and the first two columns have been formatted, but I'm having difficulty placing certain values in the right place. the part of my code determining the second column:...
html table issue with for-loops
I'm having a difficulty formatting a table in html through python. I'm using for-loops from previous information, and the first two columns have been formatted, but I'm having difficulty placing certain values in the right place. the part of my code determining the second column: for c in sorted(max_films): prin...
[ "Errors\n\nYou should not use table rows (tr elements) for columns!\nYou do not close open headers (th elements)\nYou should use table headers in the head onlym not in the content rows!\n\nValid table structure\n <table>\n <tr>\n <th>Year</th>\n <th>Highest Grossing Film</th>\n ...
[ 0 ]
[]
[]
[ "html", "html_table", "python" ]
stackoverflow_0007702713_html_html_table_python.txt
Q: Python - Finding each occurrence of a value in a mixed array (integers, lists) I have an array: x = [ [1, 2], 1, 1, [2, 1, [1, 2]] ] in which I want to count every occurrence of the number 1, and store that number in the variable one_counter. x.count(1) returns only 2 occurrences of 1, which is insufficient. My c...
Python - Finding each occurrence of a value in a mixed array (integers, lists)
I have an array: x = [ [1, 2], 1, 1, [2, 1, [1, 2]] ] in which I want to count every occurrence of the number 1, and store that number in the variable one_counter. x.count(1) returns only 2 occurrences of 1, which is insufficient. My code below serves my purpose and stores 5 in one_counter, however it looks messy and ...
[ "You could use recursion:\ndef flatten_count(iterable, element):\n count = 0\n for item in iterable:\n if item == element:\n count += 1\n if isinstance(item, list):\n count += flatten_count(item, element)\n return count\n\nOr more concisely:\ndef flatten_count(iterable, ...
[ 8, 3, 2 ]
[]
[]
[ "arrays", "for_loop", "python" ]
stackoverflow_0007702036_arrays_for_loop_python.txt
Q: Python does not "see" a package I followed this tutorial in order to install python2.7 on my CentOS 5.5: http://villaroad.com/2010/10/rolling-python-2-6-2-on-centos-5-3/ After installation of python 2.7 I've got: /opt/python2.7$ ls -la total 24 drwxr-xr-x 6 root root 4096 2011-10-01 22:32 . drwxr-xr-x 4 root root ...
Python does not "see" a package
I followed this tutorial in order to install python2.7 on my CentOS 5.5: http://villaroad.com/2010/10/rolling-python-2-6-2-on-centos-5-3/ After installation of python 2.7 I've got: /opt/python2.7$ ls -la total 24 drwxr-xr-x 6 root root 4096 2011-10-01 22:32 . drwxr-xr-x 4 root root 4096 2011-10-01 22:32 .. drwxr-xr-x 2...
[ "Whenever you run a a command with Bash, it caches the command's location. That may be what you're running into here. Use hash -r to clean the cache.\nNote that you have three pythons in your system now: the system's 2.6 in /usr/bin, the 2.7 in /opt/python2.7/bin/, and the virtualenv's 2.7 in env/bin. Only the last...
[ 4 ]
[]
[]
[ "flask", "pip", "python", "virtualenv" ]
stackoverflow_0007702995_flask_pip_python_virtualenv.txt
Q: How to write namespaced element attributes with LXML? I'm using lxml (2.2.8) to create and write out some XML (specifically XGMML). The app which will be reading it is apparently fairly fussy and wants to see a top level element with: <graph label="Test" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xlink="h ...
How to write namespaced element attributes with LXML?
I'm using lxml (2.2.8) to create and write out some XML (specifically XGMML). The app which will be reading it is apparently fairly fussy and wants to see a top level element with: <graph label="Test" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:xlink="h ttp://www.w3.org/1999/xlink" xmlns:rdf="http://www.w3.org/1...
[ "Unlike ElementTree or other serializers that would allow this, lxml needs you to set up these namespaces beforehand:\nNSMAP = {\"dc\" : 'http://purl.org/dc/elements/1.1',\n \"xlink\" : 'http://www.w3.org/1999/xlink'}\n\nroot = Element(\"graph\", nsmap = NSMAP)\n\n(and so on and so forth for the rest of the...
[ 27, 6 ]
[]
[]
[ "cytoscape", "lxml", "python", "xml_namespaces" ]
stackoverflow_0007703018_cytoscape_lxml_python_xml_namespaces.txt
Q: How can I put an image from DB table in Web2py? I'm trying to put an image in view section I have defined a table but it seems{{for table in tables:}} doesn't work. My code is: default.py (Controller) def index(): return dict(message=T('Hello World')) def Tables(): return dict(tables=db().select(db.table....
How can I put an image from DB table in Web2py?
I'm trying to put an image in view section I have defined a table but it seems{{for table in tables:}} doesn't work. My code is: default.py (Controller) def index(): return dict(message=T('Hello World')) def Tables(): return dict(tables=db().select(db.table.ALL)) def download(): return response.download(r...
[ "Are you trying to edit which view?\nfrom your code it will work well:\nin model\ndb.define_table('mytable',\n Field('image', type='upload'))\n\n# I do not recommend calling a table 'table' it is can be a reserved keyword\n\nin dontrollers/default.py\ndef tables(): \n return dict(tables=db().select(db.my...
[ 0 ]
[]
[]
[ "python", "web2py" ]
stackoverflow_0007702625_python_web2py.txt
Q: How do I parse lines from a log file? I need to extract the values of following output: Oct 6 17:29:52 FW kernel: [ 5470.058450] ipTables: IN= OUT=eth0 SRC=192.168.1.116 DST=192.168.1.110 LEN=516 TOS=0x10 PREC=0x00 TTL=64 ID=4949 DF PROTO=TCP SPT=22 DPT=46216 WINDOW=446 RES=0x00 ACK PSH URGP=0 I'd need for examp...
How do I parse lines from a log file?
I need to extract the values of following output: Oct 6 17:29:52 FW kernel: [ 5470.058450] ipTables: IN= OUT=eth0 SRC=192.168.1.116 DST=192.168.1.110 LEN=516 TOS=0x10 PREC=0x00 TTL=64 ID=4949 DF PROTO=TCP SPT=22 DPT=46216 WINDOW=446 RES=0x00 ACK PSH URGP=0 I'd need for example the value of PROTO stored in a value. tr...
[ "Python does this conveniently. A general solution that gets all the KEY=value pairs is:\nimport re\nimport fileinput\n\npair_re = re.compile('([^ ]+)=([^ ]+)') # Matches KEY=value pair\n\nfor line in fileinput.input(): # The script accepts both data from stdin or a filename \n\n line = line.rstrip() # Remov...
[ 4, 1, 1, 1, 0, 0 ]
[]
[]
[ "logfile", "perl", "python", "regex" ]
stackoverflow_0007679624_logfile_perl_python_regex.txt
Q: Python HttpConnection request encoding error I'm trying to use a python script to upload a zip file to a site. The site provided an API exactly for that purpose. But, when I tried to use it, an encoding error showed up when joining all the strings to send in the httplib connect request. I've traced the string in q...
Python HttpConnection request encoding error
I'm trying to use a python script to upload a zip file to a site. The site provided an API exactly for that purpose. But, when I tried to use it, an encoding error showed up when joining all the strings to send in the httplib connect request. I've traced the string in question to be the filedata (my zip file). Tracebac...
[ "It is highly likely that ISO-8859-1 is not the solution to your first problem. You need to be aware that any_random_gibberish.decode('ISO-8859-1') simply cannot fail. \nSecondly, I'm not sure why an encoding would be needed when uploading a file -- surely the object of the exercise is to reproduce the file exactly...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007703163_python.txt
Q: Sort of like concatenation but not quite for seqA in poolA: print seqA + ":", for i in seqA: print complements[i], print complements is a dict and poolA is a list. When I print complements[i] there are spaces in between, how do I remove these spaces? A: Join the items and print the resulting...
Sort of like concatenation but not quite
for seqA in poolA: print seqA + ":", for i in seqA: print complements[i], print complements is a dict and poolA is a list. When I print complements[i] there are spaces in between, how do I remove these spaces?
[ "Join the items and print the resulting string.\nprint ''.join(str(complements[i]) for i in seqA)\n\n", "Well, just don't print them out. Use either from __future__ import print_function and then print(complements[i], end = ''), or sys.stdout.write(complements[i]).\n" ]
[ 5, 2 ]
[]
[]
[ "concatenation", "python" ]
stackoverflow_0007703442_concatenation_python.txt
Q: using a for-loop in a table in python I am trying to make a table that sorts out high-grossing films and the most similar films to them. All of the code is completed but I'm having trouble finishing the table. my code: #import the data from the csv file and use DictRead to interpret the information. import csv ...
using a for-loop in a table in python
I am trying to make a table that sorts out high-grossing films and the most similar films to them. All of the code is completed but I'm having trouble finishing the table. my code: #import the data from the csv file and use DictRead to interpret the information. import csv csv_file = open("moviestats_med.csv") csv_...
[ "Some advices:\n\nWhy do you use \"actor1 actor2 actor3\" rather than main_actors = []? You can store dictionnaries inside!\nYou can also use seq in place of for c in [2000, …. ]\nFinally, you could use printf like formatting with your strings (at the end) and have:\n\nprint \"<tr><th>%s<td>%s</td><td>%s</td><td>%s...
[ 3, 1 ]
[]
[]
[ "for_loop", "html", "python" ]
stackoverflow_0007703414_for_loop_html_python.txt
Q: wxpython browse file (code needed) Can anybody post up an easy code snippet for wxpython that allows the user to browse for a *.html file and have the python program take that .html file the user browsed to, and move it to a folder on my Desktop called "user-site"? I really need help making this browse feature.. a...
wxpython browse file (code needed)
Can anybody post up an easy code snippet for wxpython that allows the user to browse for a *.html file and have the python program take that .html file the user browsed to, and move it to a folder on my Desktop called "user-site"? I really need help making this browse feature.. any help is much appreciated. Thx in adva...
[ "If you don't already have it, download the excellent wxPython demo. In the Common Dialogs section of the demo there is a FileDialog example that shows you how to do the first part. In the block starting with if dlg.ShowModal() == wx.ID_OK: you'll need something like shutil.move(path, \"C:\\path\\to\\your\\Desktop\...
[ 2 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0007703704_python_wxpython.txt
Q: Server recommendations (smtp) I'm currently working on a quite small project. I'm basing my work on smtpd.py but slowly moving toward something completely different. This is a smtp server. It currently receive and can relay mails. It's pretty straight forwards but I reached a point where i'm asking myself some que...
Server recommendations (smtp)
I'm currently working on a quite small project. I'm basing my work on smtpd.py but slowly moving toward something completely different. This is a smtp server. It currently receive and can relay mails. It's pretty straight forwards but I reached a point where i'm asking myself some questions. smtpd.py use asyncore and a...
[ "The title of the post doesn't appear to match the questions asked. Nevertheless, I can empathise with some of the issues raised and also the comments. In particular, I agree with Jim Garrison that this would be a useful learning experience to gain insight into SMTP and mail server principles. However, if the purpo...
[ 0, -1 ]
[]
[]
[ "fork", "python", "smtpd" ]
stackoverflow_0007666717_fork_python_smtpd.txt
Q: Delete files of given types IFF there are no other file types in folder I want to delete certain files of type [cue,jpg,png,m3u,etc.] but if and only if they are in a folder by themselves or other files of [cue,jpg,png,m3u,etc.] type. I already have a function that can get me all the files of type [cue,jpg,png,m3u...
Delete files of given types IFF there are no other file types in folder
I want to delete certain files of type [cue,jpg,png,m3u,etc.] but if and only if they are in a folder by themselves or other files of [cue,jpg,png,m3u,etc.] type. I already have a function that can get me all the files of type [cue,jpg,png,m3u,etc.] in any given folder and return it as a list, but I just need to delete...
[ "It sounds like you have two steps:\n1) Given a list of extensions, get the list of all files in a folder matching that extension. \n2) If all the files in your directory have an extension matching your list, remove them\nNote that this doesn't include any information about how to traverse the directory structure, ...
[ 1 ]
[]
[]
[ "conditional_statements", "delete_file", "file", "file_type", "python" ]
stackoverflow_0007703749_conditional_statements_delete_file_file_file_type_python.txt
Q: How to let the output being printed on the interactive shell with subprocess >>> import subprocess >>> subprocess.Popen("pwd") <subprocess.Popen object at 0xa7692cc> >>> subprocess.call(["ls", "-l"]) 0 I have tried the above command in Python interactive shell and expect to see the output inside the shell environ...
How to let the output being printed on the interactive shell with subprocess
>>> import subprocess >>> subprocess.Popen("pwd") <subprocess.Popen object at 0xa7692cc> >>> subprocess.call(["ls", "-l"]) 0 I have tried the above command in Python interactive shell and expect to see the output inside the shell environment. However, it ends up with just some return values. What should I do in order ...
[ "It'd help to read the documentation first.\np = subprocess.Popen('pwd', stdout = subprocess.PIPE)\np.communicate() # returns (stdout, None)\n\n", "Cat Plus Plus is right, however, if you prefer the call function, you can also do this like so:\nimport subprocess\nimport sys\n\nsubprocess.call('pwd', stdout=sys.st...
[ 4, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007704034_python.txt
Q: Sphinx-build can not be recognized as internl or external command On Python 2.5, I installed sphinx using easy_install and it is available at the following location on Windows 7: C:\Python25\Lib\site-packages\sphinx-1.0.8-py2.5.egg\sphinx I wanted to convert a couple of .rst files to HTML. But whenever I do sphin...
Sphinx-build can not be recognized as internl or external command
On Python 2.5, I installed sphinx using easy_install and it is available at the following location on Windows 7: C:\Python25\Lib\site-packages\sphinx-1.0.8-py2.5.egg\sphinx I wanted to convert a couple of .rst files to HTML. But whenever I do sphinx-build I encounter the following error: 'sphinx-build' is not recogni...
[ "The sphinx-build command should be installed in C:\\Python25\\Scripts. Either use the full path, C:\\Python25\\Scripts\\sphinx-build, to call the command, or add that directory to your PATH.\n" ]
[ 7 ]
[]
[]
[ "easy_install", "python", "python_sphinx", "windows" ]
stackoverflow_0007703938_easy_install_python_python_sphinx_windows.txt
Q: Python socked bound to secondary IP gets connection reset from server I'm trying to create a python socket script that binds to a secondary IP and connects to a server. When I run the script python gives me a "socket.error: [Errno 111] Connection refused" The TCPdump shows that the server I try to connect to send...
Python socked bound to secondary IP gets connection reset from server
I'm trying to create a python socket script that binds to a secondary IP and connects to a server. When I run the script python gives me a "socket.error: [Errno 111] Connection refused" The TCPdump shows that the server I try to connect to sends back a reset response. Running the script without the socket.bind works. ...
[ "I found the error. The firewall was configured to block the response and sent a reset flag.\n" ]
[ 0 ]
[]
[]
[ "python", "sockets", "tcpdump" ]
stackoverflow_0007659220_python_sockets_tcpdump.txt
Q: Global variabless in Python How can I create variables that all the methods in the class will share (fields or global vars)? Another question: what is the meaning of ";" in python? A: You need to provide more detail to get more meaningful answers. There are several ways to make a variable available to the method...
Global variabless in Python
How can I create variables that all the methods in the class will share (fields or global vars)? Another question: what is the meaning of ";" in python?
[ "You need to provide more detail to get more meaningful answers.\nThere are several ways to make a variable available to the methods of a class;\nInstance variable: defined in the scope of the current class instance. Commonly created with __init__(), i.e. when the instance is initiated.\nclass SomeClass(object):\n ...
[ 1, 0, 0 ]
[ "Maybe like this.\nclass A:\n x = 0\n def inc(self):\n self.__class__.x += 1\n\nb = A()\nb.inc() # A.x == 1, b.x == 1\nc = A() \nc.inc() # A.x == 2, c.x == 2\n\n; is logic line wrap for python, it is not recommended, as it make code difficult to read.\n" ]
[ -1 ]
[ "python" ]
stackoverflow_0007702972_python.txt
Q: What happens if you save a call to super in a variable for future use? Forgive me if I'm being ignorant of the obvious here, but what would happen if you save a call to super in a variable and use it later. Here is a part of a class definition to show you what I mean. class CaselessDict(dict): def __init__(se...
What happens if you save a call to super in a variable for future use?
Forgive me if I'm being ignorant of the obvious here, but what would happen if you save a call to super in a variable and use it later. Here is a part of a class definition to show you what I mean. class CaselessDict(dict): def __init__(self, *args, **kwargs): self.super = super(CaselessDict, self) # save ...
[ "The expected thing happens: self.super will just hold a super object that acts just like super(CaselessDict, self).\nThe problem with this approach is that each instance only has one super attribute, so if you had more classes that would use this technique, only the one that assigned to super last would function p...
[ 4, 0, 0 ]
[]
[]
[ "python", "super" ]
stackoverflow_0007703230_python_super.txt
Q: creating a list with separating by character in Python I'm trying to make a list of the top 4 maximum values with data from other dictionaries, but the result i get keeps separating each term into individual characters. The full code is: max_list = [] MaxSimilarity = 0 for d in year: f = FavActorFunction(m...
creating a list with separating by character in Python
I'm trying to make a list of the top 4 maximum values with data from other dictionaries, but the result i get keeps separating each term into individual characters. The full code is: max_list = [] MaxSimilarity = 0 for d in year: f = FavActorFunction(max_films[c], d) if d != MaxGrossFinder(c): i...
[ "It appears that your function FavActorFunction is returning a list of characters rather than a list of words.\nIf you iterate over a string, rather than iterating over a list of strings, this can happen. For example, notice what happens when I convert a string to a list:\n>>> print list(\"Hello, world\")\nprint li...
[ 2 ]
[]
[]
[ "for_loop", "list", "python" ]
stackoverflow_0007703130_for_loop_list_python.txt
Q: Storing incoming telnet request into a list using twisted I want to store http request line from telnet or browser into a list in python. I am using basic.LineReceiver protocol A: In YourProtocol.lineReceived(): if matched(line): self.factory.your_list.append(line)
Storing incoming telnet request into a list using twisted
I want to store http request line from telnet or browser into a list in python. I am using basic.LineReceiver protocol
[ "In YourProtocol.lineReceived():\nif matched(line):\n self.factory.your_list.append(line)\n\n" ]
[ 0 ]
[]
[]
[ "python", "twisted" ]
stackoverflow_0003723995_python_twisted.txt
Q: Error following django tutorial I'm trying to follow the django tutorial but I get this error and I can't continue. http://dpaste.com/630957/ Can someone help me? (I'm new with python and django) Thank you so much. A: From the error log: File "/arpa/h/huksy007/Projects/mysite/polls/models.py" in __unicode__ ...
Error following django tutorial
I'm trying to follow the django tutorial but I get this error and I can't continue. http://dpaste.com/630957/ Can someone help me? (I'm new with python and django) Thank you so much.
[ "From the error log:\nFile \"/arpa/h/huksy007/Projects/mysite/polls/models.py\" in __unicode__\n 22. return self.question\n\nMake sure that self actually has a property called question.\n", "You forgot to put that line on your Choice Model:\n choice = models.CharField(max_length=200)\n\nIt need to b...
[ 3, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007704092_django_python.txt
Q: pygobject creating a drag and drop source from gi.repository import Gtk, Gdk def drag_data_get_cb(widget, drag_context, selection_data, info, time): print selection_data.get_data_type() print widget.get_text() return widget.get_text() def drag_begin_cb(widget, dragcontext): print dragcontext, wid...
pygobject creating a drag and drop source
from gi.repository import Gtk, Gdk def drag_data_get_cb(widget, drag_context, selection_data, info, time): print selection_data.get_data_type() print widget.get_text() return widget.get_text() def drag_begin_cb(widget, dragcontext): print dragcontext, widget return dragcontext label = Gtk.Label()...
[ "It says in this tutorial that you cannot use widgets without windows, such as Gtk.Label as drag and drop sources. You can replace the label with a button for instance:\nlabel = Gtk.Button.new_with_label(\"Drag Me!\")\n\nin order for this example to work.\n" ]
[ 4 ]
[]
[]
[ "gtk3", "pygobject", "python" ]
stackoverflow_0007704017_gtk3_pygobject_python.txt
Q: quickest and cleanest method for inserting multiple rows django I am in a situation where I would have to insert multiple records into a postgre db through an ajax call, based on a foreignkey. Currently I am using db1.db2_set.create(...) for each record, looping over a list of dictionaries. Is this the best way t...
quickest and cleanest method for inserting multiple rows django
I am in a situation where I would have to insert multiple records into a postgre db through an ajax call, based on a foreignkey. Currently I am using db1.db2_set.create(...) for each record, looping over a list of dictionaries. Is this the best way to do it? It seems like I'm hitting the database for every insert.
[ "I'm pretty sure that django will query database when you call save() method. So if you do something like:\nfor i in objects:\n db1.db2_set.create(i)\n\ndb1.save()\n\nIt may acess database only once. But still, this might be usefull:\nhttp://djangosnippets.org/snippets/766/\nIt's a middleware that you can add to...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007696826_django_python.txt
Q: Can someone explain parallelpython versus hadoop for distributing python process across various servers? I'm new to using multiple cpu's to process jobs and was wondering if people could let me know the pro/cons of parallelpython(or any type of python module) versus hadoop streaming? I have a very large cpu inte...
Can someone explain parallelpython versus hadoop for distributing python process across various servers?
I'm new to using multiple cpu's to process jobs and was wondering if people could let me know the pro/cons of parallelpython(or any type of python module) versus hadoop streaming? I have a very large cpu intensive process that I would like to spread across several servers.
[ "The main difference is that Hadoop is good at processing big data (dozen to terabytes of data). It provides a simple logical framework called MapReduce which is well appropriate for data aggregation, and a distributed storage system called HDFS.\nIf your inputs are smaller than 1 gigabyte, you probably don't want ...
[ 2, 2 ]
[]
[]
[ "hadoop", "parallel_processing", "python" ]
stackoverflow_0007701989_hadoop_parallel_processing_python.txt
Q: Bad magic number error with ZipFile module in Python I am using Python 2.7 on Windows 7 (64 bit). When I try to unzip a zip file with ZipFile module I get the following error:- Traceback (most recent call last): File "unzip.py", line 8, in <module> z.extract(name) File "C:\Python27\lib\zipfile.py", line 95...
Bad magic number error with ZipFile module in Python
I am using Python 2.7 on Windows 7 (64 bit). When I try to unzip a zip file with ZipFile module I get the following error:- Traceback (most recent call last): File "unzip.py", line 8, in <module> z.extract(name) File "C:\Python27\lib\zipfile.py", line 950, in extract return self._extract_member(member, path...
[ "Correct ZIP files always have \"\\x50\\x4B\\x03\\x04\" in the beginning. You can test whether file is really ZIP file with this code:\nwith open('/path/to/file', 'rb') as MyZip:\n print(MyZip.read(4))\n\nIt will print header of file so you can check.\nUPDATE\nStrange, testzip() and all other functions work good. ...
[ 16, 3 ]
[]
[]
[ "python", "python_2.7", "python_zipfile", "unzip" ]
stackoverflow_0007703639_python_python_2.7_python_zipfile_unzip.txt
Q: Python tree traversal recursion depth exceeded I have a segment tree which holds data for a range of numbers (data structure chosen here). Here's the code: class SegmentTree: def __init__(self, N): def _init(b, e): if b is e: data = foo() # No dependency ret...
Python tree traversal recursion depth exceeded
I have a segment tree which holds data for a range of numbers (data structure chosen here). Here's the code: class SegmentTree: def __init__(self, N): def _init(b, e): if b is e: data = foo() # No dependency return Node(b, e, data, None, None) else: ...
[ "The real problem is not the recursion depth of your algorithm, which should be about 10 for a value like 300, but that you are comparing numbers with is. The is keyword checks for object identity, while == checks for equality:\n>>> 300 == 299+1\nTrue\n>>> 300 is 299+1\nFalse\n\nBecause of that your if condition th...
[ 6, 1 ]
[]
[]
[ "algorithm", "optimization", "python", "tree" ]
stackoverflow_0007705167_algorithm_optimization_python_tree.txt
Q: dynamically calculate number of processes to be spawned I have a list of about 15 years in the year_queue, I need to spawn one process for each year. But depending on which server I am running the code, the number of processors vary. How do I dynamically vary the variable num_processes depending on the number of p...
dynamically calculate number of processes to be spawned
I have a list of about 15 years in the year_queue, I need to spawn one process for each year. But depending on which server I am running the code, the number of processors vary. How do I dynamically vary the variable num_processes depending on the number of processers in the server? If I set num_processes > number of p...
[ "Use a multiprocessing Pool. The class does all the tedious work of selecting the right number of processes and running them for you. It also doesn't spawn a new process for each task, but reuses processes once they're done.\ndef process_year(year):\n ...\n return result\n\npool = multiprocessing.Pool()\nresu...
[ 4, 0 ]
[]
[]
[ "fork", "multiprocessing", "process", "python", "spawn" ]
stackoverflow_0007694480_fork_multiprocessing_process_python_spawn.txt
Q: unable to call exe using python I am calling an exe (which is dependent on other batch files) , Python is giving error. I am able to call exe (which is independent) what I am doing is.. import os os.system("notepad.exe") # is working but os.system("c:/ank.exe") # this is giving error as ank.exe is depend...
unable to call exe using python
I am calling an exe (which is dependent on other batch files) , Python is giving error. I am able to call exe (which is independent) what I am doing is.. import os os.system("notepad.exe") # is working but os.system("c:/ank.exe") # this is giving error as ank.exe is dependent on other batch files
[ "you have to first change the current directory so that the executable you want to run can find its dependencies:\ntarget = \"c:/ank.exe\"\nos.chdir(os.path.dirname(target))\nos.system(target)\n\notherwise, os.system() executes in the directory of the running script.\n" ]
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0007705203_python.txt
Q: Clustering ~100,000 Short Strings in Python I want to cluster ~100,000 short strings by something like q-gram distance or simple "bag distance" or maybe Levenshtein distance in Python. I was planning to fill out a distance matrix (100,000 choose 2 comparisons) and then do hierarchical clustering with pyCluster. ...
Clustering ~100,000 Short Strings in Python
I want to cluster ~100,000 short strings by something like q-gram distance or simple "bag distance" or maybe Levenshtein distance in Python. I was planning to fill out a distance matrix (100,000 choose 2 comparisons) and then do hierarchical clustering with pyCluster. But I'm running into some memory problems before...
[ "100,000 * 100,000 * 32bits = 40 GBytes, which would be a lot of RAM, so yes, you need to find another way. (And even if you could fit this data into memory, the calculation would take too long.)\nOne common and easy shortcut is to cluster a small random subset of the data, and after you find the clusters of this ...
[ 6, 2, 2, 2 ]
[]
[]
[ "cluster_analysis", "levenshtein_distance", "numpy", "python" ]
stackoverflow_0004241741_cluster_analysis_levenshtein_distance_numpy_python.txt
Q: SQLite compare query Python I've been trying to figure out the best way to write a query to compare the rows in two tables. My goal is to see if the two tuples in result Set A are in the larger result set B. I only want to see the tuples that are different in the query results. '''SELECT table1.field_b, table1.f...
SQLite compare query Python
I've been trying to figure out the best way to write a query to compare the rows in two tables. My goal is to see if the two tuples in result Set A are in the larger result set B. I only want to see the tuples that are different in the query results. '''SELECT table1.field_b, table1.field_c, table1.field_d '''FROM ta...
[ "Take results_a and make sure that they have an exact match somewhere in results_b:\nfor el in results_a:\n if el in results_b:\n ...\n\nGet partial matches:\npmatch = dict([])\ndef partial_match(a,b):\n # for instance ...\n return sum(ea == eb for (ea,eb) in zip(a,b)) >= 2\nfor el_a in results_a:\n pmatch[...
[ 1 ]
[]
[]
[ "python", "sql", "sqlite" ]
stackoverflow_0007704677_python_sql_sqlite.txt
Q: Python-LDAP integration I need to integrate Python with LDAP. I just need to choose the best way to make Python talk to LDAP. I understand there are many ways to do this, including using a prebuilt toolkit such as the AuthKit or writing a thing ourselves with LDAP modules and functions. What do you recommend? A: ...
Python-LDAP integration
I need to integrate Python with LDAP. I just need to choose the best way to make Python talk to LDAP. I understand there are many ways to do this, including using a prebuilt toolkit such as the AuthKit or writing a thing ourselves with LDAP modules and functions. What do you recommend?
[ "I have successfully used the python-ldap library to communicate with LDAP servers and Windows Active Directory. You can download it from pypi here http://pypi.python.org/pypi/python-ldap/2.3.10\n", "A couple days ago I posted some code for accessing LDAP using win32com and ADO in this thread:\nDoes Python 3 hav...
[ 1, 0, 0 ]
[]
[]
[ "authkit", "ldap", "python" ]
stackoverflow_0002023725_authkit_ldap_python.txt
Q: Is it possible to use python-ldap get user's password? As title said, I want to use python_ldap to get user's password. Here is python-ldap reference, http://www.python-ldap.org/doc/html/index.html I didn't find any function to get user's password. Is there anybody do the same thing like me? And is it possible to ...
Is it possible to use python-ldap get user's password?
As title said, I want to use python_ldap to get user's password. Here is python-ldap reference, http://www.python-ldap.org/doc/html/index.html I didn't find any function to get user's password. Is there anybody do the same thing like me? And is it possible to get user's password?
[ "No system that is designed to be secure will allow access to clear-text passwords. In fact, the system won't even know the clear-text password. \nYou might want to re-think exactly what you are trying to do.\n", "No, an ldap server will not send out passwords, plain or encrypted.\nYou can only write them if you ...
[ 2, 2, 1 ]
[]
[]
[ "ldap", "python" ]
stackoverflow_0004536513_ldap_python.txt
Q: Produce PDF files, draw polygons with rounded corners What's the right tool for the job if I want to write a Python script that produces vector graphics in PDF format? In particular, I need to draw filled polygons with rounded corners (i.e., plane figures that are composed of straight lines and circular arcs). It ...
Produce PDF files, draw polygons with rounded corners
What's the right tool for the job if I want to write a Python script that produces vector graphics in PDF format? In particular, I need to draw filled polygons with rounded corners (i.e., plane figures that are composed of straight lines and circular arcs). It seems that matplotlib makes it fairly easy to draw rectangl...
[ "Here's a somewhat hacky matplotlib solution. The main complications are related to using matplotlib Path objects to build a composite Path.\n#!/usr/bin/env python\n\nimport numpy as np\nfrom matplotlib.path import Path\nfrom matplotlib.patches import PathPatch, Polygon\nfrom matplotlib.transforms import Bbox, Bbox...
[ 14, 5 ]
[]
[]
[ "bezier", "pdf_generation", "polygons", "python", "vector_graphics" ]
stackoverflow_0007702773_bezier_pdf_generation_polygons_python_vector_graphics.txt
Q: HTTP 400 response while sending POST request to UrbanAirship I am using Web2Py to create a simple app which sends Push notifications through UrbanAirship. For some reason, I am getting a 400 response when I try to send it through my code. It UA API works fine using REST client. This is my code: url = 'https://go.u...
HTTP 400 response while sending POST request to UrbanAirship
I am using Web2Py to create a simple app which sends Push notifications through UrbanAirship. For some reason, I am getting a 400 response when I try to send it through my code. It UA API works fine using REST client. This is my code: url = 'https://go.urbanairship.com/api/push/' passman = urllib2.HTTPPasswordMgrWithD...
[ "The urllib.urlencode function is for making a URL-encoded parameter body (Content-Type: application/x-www-form-urlencoded). For JSON, which is apparently what you want, use json.dumps instead.\n" ]
[ 0 ]
[]
[]
[ "http", "post", "python", "web2py" ]
stackoverflow_0007704557_http_post_python_web2py.txt
Q: How do you load an XML file into a string with python on GAE? I'm using the latest GAE default python environment. Both of these give expected results: isTrue = os.path.exists(path) numberGreaterThanZero = os.path.getsize(path) But this: myStrLen = len(open(path)) Gives this error: TypeError: object of type 'Fak...
How do you load an XML file into a string with python on GAE?
I'm using the latest GAE default python environment. Both of these give expected results: isTrue = os.path.exists(path) numberGreaterThanZero = os.path.getsize(path) But this: myStrLen = len(open(path)) Gives this error: TypeError: object of type 'FakeFile' has no len() There are no results for that error in Google....
[ "The open function returns an open file, not a string. Open files have no len.\nYou need to actually read the string from the file, for example with the read method.\ncontents = open(path).read()\nmyStrLen = len(contents)\n\nIf you don't need the contents, you can also get the file size with os.stat.\nmyStrLen = o...
[ 6 ]
[]
[]
[ "google_app_engine", "python", "typeerror" ]
stackoverflow_0007705816_google_app_engine_python_typeerror.txt
Q: Managing Items in an Object Oriented game Every once in a while I like to take a break from my other projects to try to make a classic adventure text-based-game (in Python, this time) as a fun project, but I always have design issues implementing the item system. I'd like for the items in the game to descend from...
Managing Items in an Object Oriented game
Every once in a while I like to take a break from my other projects to try to make a classic adventure text-based-game (in Python, this time) as a fun project, but I always have design issues implementing the item system. I'd like for the items in the game to descend from one base Item class, containing some attribute...
[ "I would have your object keep a reference to all of its parents. Then, when it should be destroyed, it would notify its parents. If you're already using an event system, this should integrate nicely with the rest of the game.\nA nice way to avoid forcing your parent to explicitly notify the object whenever the ref...
[ 2, 1, 1, 0, 0 ]
[ "at first: i don't have any python experience, so think about this in a more general way\nyour item should neither know or care ... your Item should have an interface that says it is something destroyable. containers and other objects that care about things that can be destroyed, can make use of that interface\ntha...
[ -1 ]
[ "oop", "python" ]
stackoverflow_0006325775_oop_python.txt
Q: Python: Attribute error with shelve when using 2 py modules I'm trying out the shelve module and I'm running into some trouble. My intention is to have one module call a function in a second one which will modify a file inside a shelve. I made a prototype (below) that simply tries to set a variable to something st...
Python: Attribute error with shelve when using 2 py modules
I'm trying out the shelve module and I'm running into some trouble. My intention is to have one module call a function in a second one which will modify a file inside a shelve. I made a prototype (below) that simply tries to set a variable to something stored in the shelve and print that object. When I attempt to do th...
[ "Fix: \nimport SE_ex2\nfrom SE_ex2 import User\n\nSE_ex2.cacheTest()\n\nPickled class needs to be in the namespace\nThe reason is shelf uses pickle, so it uses the User class:\n\nWhen working with your own classes, you must ensure that the class\n being pickled appears in the namespace of the process reading the\n...
[ 2, 0 ]
[]
[]
[ "python", "shelve" ]
stackoverflow_0007705636_python_shelve.txt
Q: Looking for a diagram to explain WSGI To help further my understanding of WSGI I'm looking for a diagram which explains the flow of an application, from webserver (eg. apache) through a number of middlewares to "code" (as in, the print "hello world" bit). I've read various articles regarding WSGI from wsgi.org, b...
Looking for a diagram to explain WSGI
To help further my understanding of WSGI I'm looking for a diagram which explains the flow of an application, from webserver (eg. apache) through a number of middlewares to "code" (as in, the print "hello world" bit). I've read various articles regarding WSGI from wsgi.org, but it's still not "clicking" for me and as ...
[ "As I gained nothing by looking at Ian's fancy tubes I decided to draw a diagram myself. I hope it will help someone understand how WSGI flow works. As long as you have suggestions how to make it better I'm open to modify it. It was created with LUCIDCHART webapp. The original diagram you can find here and the high...
[ 20, 9, 7 ]
[]
[]
[ "diagram", "python", "wsgi" ]
stackoverflow_0001303118_diagram_python_wsgi.txt
Q: Basic usage of python class inheritance I'm just getting started with Python, and am trying to figure out the Right Way to use classes. My program currently has two classes, call them Planner and Model. The Planner is model-agnostic, given that any Model it uses presents a consistent interface. So, it seems like ...
Basic usage of python class inheritance
I'm just getting started with Python, and am trying to figure out the Right Way to use classes. My program currently has two classes, call them Planner and Model. The Planner is model-agnostic, given that any Model it uses presents a consistent interface. So, it seems like if I want to have several different available...
[ "In Python you don't generally use quite the same approaches to OOP as in statically typed languages. Specifically you don't actually need an object to implement a specific interface or derive from an abstract base class and so on. Rather that object just needs to be able to do the required operations. This is coll...
[ 3, 2, 0 ]
[]
[]
[ "class", "inheritance", "oop", "python" ]
stackoverflow_0007706520_class_inheritance_oop_python.txt
Q: How to insert duplicated values in dictionary? I have dct = {'word1': 23, 'word2': 12, 'word1' : 7, 'word2':2} and I need to get list when keys dont duplicate and contain all values of from dictionary f.e.: lst = ('word1 23 7', 'word2 12 2') Is there any possibility to make it like this in Python? A: You can't h...
How to insert duplicated values in dictionary?
I have dct = {'word1': 23, 'word2': 12, 'word1' : 7, 'word2':2} and I need to get list when keys dont duplicate and contain all values of from dictionary f.e.: lst = ('word1 23 7', 'word2 12 2') Is there any possibility to make it like this in Python?
[ "You can't have what you describe. You could have this:\ndct = {}\n\ndct['word1'] = 23\ndct['word2'] = 12\ndct['word1'] = 7\ndct['word2'] = 2\n\nBut at the end all you'd end up with is this:\n{'word1': 7, 'word2': 2}\n\nKeys in a dictionary cannot be repeated. If your code is actually set up like my first example...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0007706621_python.txt
Q: Scalable and flexible framework for e commerce website based on PHP or Django I have to build an e commerce website that aims to target very heavy traffic 2 to 3 years down the lane. I am comfortable with PHP or Python. I would like to know what would be the best framework that I should use? Which solution would o...
Scalable and flexible framework for e commerce website based on PHP or Django
I have to build an e commerce website that aims to target very heavy traffic 2 to 3 years down the lane. I am comfortable with PHP or Python. I would like to know what would be the best framework that I should use? Which solution would offer the scalability and ease of development? Moreover I would like the framework t...
[ "If you need a Django based E commerce site, I would suggest Satchmo Project:\n\nhttp://www.satchmoproject.com/\n Have you been looking for a solid open source framework to build your online store? \nDo you need a customized shopping cart or eccommerce application built with Python?\nDo you need to add a Django b...
[ 1 ]
[]
[]
[ "customization", "e_commerce", "php", "python" ]
stackoverflow_0007704579_customization_e_commerce_php_python.txt
Q: How to implement dialogs within a mainwindow class designed in QtDesigner? I'm writing a small app (learning Python and PyQt) that has an "About" box. I've designed the QMainWindow in QtDesigner and managed to make it work. I've also designed the About box in the QtDesigner as a dialog. I used pyuic4 to convert b...
How to implement dialogs within a mainwindow class designed in QtDesigner?
I'm writing a small app (learning Python and PyQt) that has an "About" box. I've designed the QMainWindow in QtDesigner and managed to make it work. I've also designed the About box in the QtDesigner as a dialog. I used pyuic4 to convert both .ui files to .py files, the main.py and about-dialog.py However, how do I "c...
[ "Read the tutorial carefully. The pyuic4 tool won't make a full dialog for you; it'll only provide a method that sets up an already existing dialog.\ndialog = QtGui.QDialog()\nui = ui_aboutDialog.Ui_aboutDlg()\nui.setupUi(dialog)\ndialog.exec_()\n\n" ]
[ 3 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0007706735_pyqt_python.txt
Q: Nested function decorators that operate on arguments in python I am writing a function decorator that will apply a conversion to the first argument of the function. It works fine if I only decorate my functions once but if I decorate them twice I get an error. Below is some code that demonstrates the problem, it i...
Nested function decorators that operate on arguments in python
I am writing a function decorator that will apply a conversion to the first argument of the function. It works fine if I only decorate my functions once but if I decorate them twice I get an error. Below is some code that demonstrates the problem, it is a simplified version of the code I'm working on. I have excluded t...
[ "The problem is that the signature of your decorated function is not the signature (getargspec) from the original. It is really well explained in the help of the decorator module which you can to solve your problem. Basically, you should use a signature-preserving decorators, so that the second decorator sees the s...
[ 5 ]
[]
[]
[ "decorator", "inspect", "keyword_argument", "python" ]
stackoverflow_0007706546_decorator_inspect_keyword_argument_python.txt
Q: Is there any loss of functionality with streaming jobs in hbase/hadoop versus using java? Sorry in advance if this is a basic question. I'm reading a book on hbase and learing but most of the examples in the book(and well as online) tend to be using Java(I guess because hbase is native to java). There are a few p...
Is there any loss of functionality with streaming jobs in hbase/hadoop versus using java?
Sorry in advance if this is a basic question. I'm reading a book on hbase and learing but most of the examples in the book(and well as online) tend to be using Java(I guess because hbase is native to java). There are a few python examples and I know I can access hbase with python(using thrift or other modules), but I'...
[ "As far as I know, you are talking about 2(or more) totally different concepts.\n\"Hadoop Streaming\" is there to stream data through your executable (independent from your choice of programming language). When using streaming there can't be any loss of functionality, since the functionality is basicly map/reduce t...
[ 2, 1 ]
[]
[]
[ "hadoop", "hbase", "java", "python", "thrift" ]
stackoverflow_0007623858_hadoop_hbase_java_python_thrift.txt
Q: google analytics under pypi doc page (packages.python.org) I'm trying to add a google analytics tracker to the documentation pages of my python project (hosted under http://packages.python.org/myProject). Doc pages are generated using sphinx. I have tried Single Domain and MultiDomain options for the tracker, but ...
google analytics under pypi doc page (packages.python.org)
I'm trying to add a google analytics tracker to the documentation pages of my python project (hosted under http://packages.python.org/myProject). Doc pages are generated using sphinx. I have tried Single Domain and MultiDomain options for the tracker, but Google Analytics seem not to detect the script (which, I have te...
[ "You probably need to use the _setCookiePath option. \nIn particular, if your app is at http://packages.python.org/myProject/:\n\nadd _gaq.push(['_setCookiePath', '/myProject/']); into your snippet, right before _gaq.push(['_trackPageViews']);. \nAlso, under the \"new\" (as of 10/2011) analytics interface, I think ...
[ 0 ]
[]
[]
[ "google_analytics", "pypi", "python" ]
stackoverflow_0006369120_google_analytics_pypi_python.txt
Q: Deserialize objective-c binary NSMutableArray in python I'm putting together a Google App Engine webapp in python and I'm seeding it with a database from an iPhone app (sqlite). I'm having a bit of difficult on 3 fields which are defined as blob fields and have binary serialized objects in them. (typically they...
Deserialize objective-c binary NSMutableArray in python
I'm putting together a Google App Engine webapp in python and I'm seeding it with a database from an iPhone app (sqlite). I'm having a bit of difficult on 3 fields which are defined as blob fields and have binary serialized objects in them. (typically they start out with "bplist" so I'm assuming it's a binary serial...
[ "If you are planning on running this script on a mac, you can use the plutil command to convert it to a more easily parseable XML format:\nplutil -convert xml1 -o outfile infile\n\nTo have the output go to stdout, use - as the output file. If you leave the -o option out, the output will overwrite the input file. If...
[ 1 ]
[]
[]
[ "objective_c", "python", "serialization", "sqlite" ]
stackoverflow_0007707292_objective_c_python_serialization_sqlite.txt
Q: searching and adding a python list I have a TList which is a list of lists. I would like to add new items to the list if they are not present before. For instance if item I is not present, then add to Tlist otherwise skip.Is there a more pythonic way of doing it ? Note : At first TList may be empty and elements a...
searching and adding a python list
I have a TList which is a list of lists. I would like to add new items to the list if they are not present before. For instance if item I is not present, then add to Tlist otherwise skip.Is there a more pythonic way of doing it ? Note : At first TList may be empty and elements are added in this code. After adding Z f...
[ "Since it would appear that the first entry in each sublist is a key of some sort, and the remaining entries are somehow derived from that key, a dictionary might be a more suitable data structure:\nvals = {'A': ['B','C'], 'D':['F','G'], 'H':['I','J']}\nif 'Z' in vals:\n print 'found Z'\nelse:\n vals['Z'] = ['aa'...
[ 2, 1, 1, 1 ]
[]
[]
[ "list", "python" ]
stackoverflow_0007705128_list_python.txt
Q: Python regular expression not matching end of line I'm trying to match a C/C++ function definition using a fairly complex regular expression. I've found a case where it's not working and I'm trying to understand why. Here is the input string which does not match: void Dump(const char * itemName, ofstream & os...
Python regular expression not matching end of line
I'm trying to match a C/C++ function definition using a fairly complex regular expression. I've found a case where it's not working and I'm trying to understand why. Here is the input string which does not match: void Dump(const char * itemName, ofstream & os) which clearly is a valid C++ method declaration. Her...
[ "The use of +-| in your character class [^;=+-|] is a range specification. This will result in the character class containing (actually excluding since you're using ^) much more than you intend. To specify a literal - in a character class, mention it first like [^-;=+|].\n", "The output of PythonRegex is somewhat...
[ 4, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0007707707_python_regex.txt
Q: My function is not returning the expected value When I run the program, the function percentagefreq returns "none". What am I doing wrong? def main(): file = raw_input("Please enter name of file: ") s = readfile(file) print print "The file contains:" print s lc = tolowercase(s) print "...
My function is not returning the expected value
When I run the program, the function percentagefreq returns "none". What am I doing wrong? def main(): file = raw_input("Please enter name of file: ") s = readfile(file) print print "The file contains:" print s lc = tolowercase(s) print "The file in lowercase is:" print lc print ...
[ "You should check the value of freq. If the value is 0, then the loop will never run and percentagefreq will not return a value.\nLooking at the loop,\nfor x in az:\n freq = compressedTxt.count(x)\n print x, \"\\t\", freq,\"\\t\"\n\nfreq will have the last value (count(z)) which is most likely zero. \n", ...
[ 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0007707891_python.txt
Q: Trying to create a look-up table but one array has an apostrophe in front I'm trying to create a look-up table between two arrays which I've created from a text file. One is letters, LET = '[AS, DF, EG, ET, AS]' The other is numbers, NUM = [1,3,1,0,6] I want to be able to retrieve the number corresponding with the...
Trying to create a look-up table but one array has an apostrophe in front
I'm trying to create a look-up table between two arrays which I've created from a text file. One is letters, LET = '[AS, DF, EG, ET, AS]' The other is numbers, NUM = [1,3,1,0,6] I want to be able to retrieve the number corresponding with the pair of letters. How can I do this? I think my problem has something to do w...
[ "'[AS, DF, EG, ET, AS]' is a string. You need to fix your code so it is a list of strings as imm suggests.\nNow you can use zip() with the two lists to make a dictionary\n>>> LET = ['AS','DF','EG','ET','AS']\n>>> NUM = [1,3,1,0,6]\n>>> dict(zip(LET, NUM))\n{'DF': 3, 'ET': 0, 'AS': 6, 'EG': 1}\n\nnote that there is ...
[ 1 ]
[]
[]
[ "python" ]
stackoverflow_0007707571_python.txt
Q: Running a python debug session from a program, not from the console I'm writing a little python IDE, and I want to add simple debugging. I don't need all the features of winpdb. How do I launch a python program (by file name) with a breakpoint set at a line number so that it runs until that line number and halts?...
Running a python debug session from a program, not from the console
I'm writing a little python IDE, and I want to add simple debugging. I don't need all the features of winpdb. How do I launch a python program (by file name) with a breakpoint set at a line number so that it runs until that line number and halts? Note that I don't want to do this from the command-line, and I don't wa...
[ "Pretty much the only viable way to do it (as far as I know) is to run Python as a subprocess from within your IDE. This avoids \"pollution\" from the current Python interpreter, which makes it fairly likely that the program will run in the same way as if you had started it independently. (If you have issues with t...
[ 7 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0007707822_debugging_python.txt
Q: WebDriverException from Selenium firefox_binary.py only when ran from mod_wsgi I am running Python 2.7, Virtualenv, Django 1.3, mod_wsgi, Apache application on Ubuntu 11.04. Everything including psycopg2 etc are working great with wsgi and app are up and running. The only issue is with Selenium. I am getting this ...
WebDriverException from Selenium firefox_binary.py only when ran from mod_wsgi
I am running Python 2.7, Virtualenv, Django 1.3, mod_wsgi, Apache application on Ubuntu 11.04. Everything including psycopg2 etc are working great with wsgi and app are up and running. The only issue is with Selenium. I am getting this error ONLY when I execute this from wsgi on creating firefox driver as follows: from...
[ "Apache processes run as special user. If that temp directory is truly owned by 'app' then Apache user likely wouldn't be able to write to it.\nWhat user does Apache run as? Are you using daemon mode and overridden what user it should run as?\n", "So I traced firefx_binary.py and figure it out the actual error wa...
[ 1, 1 ]
[]
[]
[ "mod_wsgi", "python", "selenium", "wsgi" ]
stackoverflow_0007693033_mod_wsgi_python_selenium_wsgi.txt
Q: Unresolved import org.python / working with jython and java? I'm using Eclipse and I"m trying to create a java program that can run my python code. I'm following the guidelines on this page: http://jythonpodcast.hostjava.net/jythonbook/en/1.0/JythonAndJavaIntegration.html#using-jython-within-java-applications But ...
Unresolved import org.python / working with jython and java?
I'm using Eclipse and I"m trying to create a java program that can run my python code. I'm following the guidelines on this page: http://jythonpodcast.hostjava.net/jythonbook/en/1.0/JythonAndJavaIntegration.html#using-jython-within-java-applications But when I include these statements at the top: package org.jython.boo...
[ "\nIn the Package Explorer (on the left), right click on your Java project and select Properties.\nIn the treeview on the left, select Java Build Path.\nSelect the Libraries tab.\nSelect Add External JARs...\nBrowse to your Jython installation (C:\\jython2.5.2 for me), and select jython.jar. Click OK.\nClick OK.\n\...
[ 9 ]
[]
[]
[ "jython", "python" ]
stackoverflow_0006179009_jython_python.txt
Q: Python convention for variables that won't be used, but are reuturned from a function nonetheless If I have a function like the following: def foo(): return 1, 2 I would normally call the function like: g, f = foo() But if I never plan on using the second value returned, is there a way of calling the functio...
Python convention for variables that won't be used, but are reuturned from a function nonetheless
If I have a function like the following: def foo(): return 1, 2 I would normally call the function like: g, f = foo() But if I never plan on using the second value returned, is there a way of calling the function that makes that clear, so in the future I won't get distracted by a place-filler variable? For exampl...
[ "You could get the first item directly:\ng = foo()[0]\n\nI think pylint recommends _ or dummy:\ng, _ = foo()\n\n", "I usually just ask for the index of the value I care about\ng = foo()[0]\n\n" ]
[ 6, 1 ]
[]
[]
[ "convention", "python" ]
stackoverflow_0007708486_convention_python.txt
Q: No migration fixtures found but table not updating with Django and South Trying to update my app so it has the admin page so I run syncdb: tyre77$ python manage.py syncdb Syncing... Creating tables ... Installing custom SQL ... Installing indexes ... No fixtures found. Synced: > django.contrib.auth > django.con...
No migration fixtures found but table not updating with Django and South
Trying to update my app so it has the admin page so I run syncdb: tyre77$ python manage.py syncdb Syncing... Creating tables ... Installing custom SQL ... Installing indexes ... No fixtures found. Synced: > django.contrib.auth > django.contrib.contenttypes > django.contrib.sessions > django.contrib.sites > django...
[ "The \"No fixtures found.\" has nothing to do with south. South merely tries to reload the fixture data after having performed the schema/data migrations. Based on your output, it looks like you are already at the latest revision of your migrations. \nThe fixture it is looking for in this case is: initial_data.[xml...
[ 2 ]
[]
[]
[ "django", "django_south", "migration", "python" ]
stackoverflow_0007707149_django_django_south_migration_python.txt
Q: Lining up DNA base pairs in an array Trying to import a series of base pairs into an array. I want it in the form ['AA','AT','AG','AC'...] Here's my code: paths = [str(x[4:7]) for x in mm_start] paths ['A A', 'A T', 'A G', 'A C', 'T A', 'T T', 'T G', 'T C', 'G A', 'G T', 'G G', 'G C', 'C A', 'C T', 'C G', 'C C'] ...
Lining up DNA base pairs in an array
Trying to import a series of base pairs into an array. I want it in the form ['AA','AT','AG','AC'...] Here's my code: paths = [str(x[4:7]) for x in mm_start] paths ['A A', 'A T', 'A G', 'A C', 'T A', 'T T', 'T G', 'T C', 'G A', 'G T', 'G G', 'G C', 'C A', 'C T', 'C G', 'C C'] I get spaces in between the letters...
[ "You're converting the list into a string. You really want to say \npaths = [pair.replace(\" \", \"\") for pair in paths] \n\nThat iterates over each pair in your list of strings and removes spaces rather than converting the entire list to a string.\n", "paths = str(paths).replace(\" \",\"\")\n\nWell of course it...
[ 0, 0 ]
[]
[]
[ "arrays", "python" ]
stackoverflow_0007708664_arrays_python.txt
Q: DHT: BitTorrent vs kademlia vs clones (python) I'm in the middle of implementing my own dht for internal cluster. Since it will be used in file-sharing program like bittorrent, "Mainline DHT" was the first thing I was look at. After that I found "entangled" (python, dht using twisted matrix), congress (python, dht...
DHT: BitTorrent vs kademlia vs clones (python)
I'm in the middle of implementing my own dht for internal cluster. Since it will be used in file-sharing program like bittorrent, "Mainline DHT" was the first thing I was look at. After that I found "entangled" (python, dht using twisted matrix), congress (python, dht using pyev + libev) and of course original "kademli...
[ "The kademlia paper actually calls out the optimization of dynamically splitting buckets as the routing table grows. There is no logic difference between these two approaches, it's just an optimization to save some space. When implementing a fixed full sized routing table, you have to find k nodes to send requests ...
[ 10 ]
[]
[]
[ "bittorrent", "dht", "kademlia", "python", "xor" ]
stackoverflow_0007700562_bittorrent_dht_kademlia_python_xor.txt
Q: Creating a Windows Executable with Python 3.2 & cx_Freeze So I'm trying to package a python script into an exe that can run on a Windows machine without needing a python install. I'm running WIn7 & my application uses pywin32 & the launcher is a file called console.py which takes in a couple of command line argum...
Creating a Windows Executable with Python 3.2 & cx_Freeze
So I'm trying to package a python script into an exe that can run on a Windows machine without needing a python install. I'm running WIn7 & my application uses pywin32 & the launcher is a file called console.py which takes in a couple of command line arguments and executes another script I created a setup.py file upon...
[ "Try including the win32com.gen_py package.\nYou can always look in the created zip and see if the directory exists (or as you have done - don't zip until everything works well).\nChange to the following\n#....\nexecutables = [Executable(\"console.py\", packages=[''win32com.gen_py])]\n#....\n\n" ]
[ 2 ]
[]
[]
[ "cx_freeze", "python", "pywin32", "windows" ]
stackoverflow_0007382346_cx_freeze_python_pywin32_windows.txt
Q: Python / SQLAlchemy - load relation when foreign key is updated? I have a class: class Chart(Base): __tablename__ = 'chart' id = C('chart_id', Integer, primary_key=True) element_id = C(Integer, ForeignKey('element.element_id')) element = relationship(Element) name = C(String) def __init__(self, ...
Python / SQLAlchemy - load relation when foreign key is updated?
I have a class: class Chart(Base): __tablename__ = 'chart' id = C('chart_id', Integer, primary_key=True) element_id = C(Integer, ForeignKey('element.element_id')) element = relationship(Element) name = C(String) def __init__(self, name): self.name = name Usage is pretty common, chart = Chart(...
[ "The best option is \nchart = Chart('Some name')\nchart.element = element\n\nAssign direct object to the relation ship. If you are assign element_id then until it flush it will be in memory. Internally it will fire a query SELECT * FROM ELEMENT WHERE ELEMENT.id = element_id but that element_id data is not store or ...
[ 6 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0007698717_orm_python_sqlalchemy.txt
Q: Can python projects depend on specific versions of python? I have a python project that depends on another project that depended on python-dateutil. When I tried to python setup.py install my project, it resolved the dateutil dependency to python-dateutil 2.0, which doesn't work at all on python 2.x. The only way ...
Can python projects depend on specific versions of python?
I have a python project that depends on another project that depended on python-dateutil. When I tried to python setup.py install my project, it resolved the dateutil dependency to python-dateutil 2.0, which doesn't work at all on python 2.x. The only way I found to fix the problem and make my project installable is to...
[ "I have had this same problem using python-dateutil. There is some discussion of the problem with it's author, but no real solution. The version listed on pypi is 1.5, but both pip and easy_install scrape the home page from the pypi listing for downloads and pickup up the 2.0 version (python3) that is listed there...
[ 1 ]
[]
[]
[ "dependencies", "packaging", "python" ]
stackoverflow_0007708720_dependencies_packaging_python.txt
Q: Django execute a function after django.contrib.auth.login I am using Django's default authentication system to run my website. So whenever a user logs in in urls.py I have - (r'^login/$', 'django.contrib.auth.views.login'), I guess django uses django.contrib.auth.login & django.contrib.auth.authenticate to login....
Django execute a function after django.contrib.auth.login
I am using Django's default authentication system to run my website. So whenever a user logs in in urls.py I have - (r'^login/$', 'django.contrib.auth.views.login'), I guess django uses django.contrib.auth.login & django.contrib.auth.authenticate to login. Now as part of some requirement I am needed to run some func...
[ "Just include a signal function. Whenever a user logs in, django fires a signal and your function will be called.\nRefer the documentation on auth signals.\n" ]
[ 1 ]
[]
[]
[ "django", "django_login", "python" ]
stackoverflow_0007708832_django_django_login_python.txt
Q: extract string with regex is unstable Good Early Morning, I have the following python regex file that we established on a previous post. This is meant to extract whatever info that looks like 'chr' + number + ':' + bignumber ".." + bignumber (so that looks like chr1:100000..120000) if chr1 is switched for chrX th...
extract string with regex is unstable
Good Early Morning, I have the following python regex file that we established on a previous post. This is meant to extract whatever info that looks like 'chr' + number + ':' + bignumber ".." + bignumber (so that looks like chr1:100000..120000) if chr1 is switched for chrX the regex script doesn't work anymore... Her...
[ "I don't fully understand your question, but I will attempt to give some advice based on your code.\nHere is the most important line:\nx = re.findall(r'^1..100\\t([+-])chr(\\d+):(\\d+)\\.\\.(\\d+).+$',k)\n\nObservations:\n0) I don't even know what buffering=-1 will do in a call to open(). I recommend you get rid o...
[ 3 ]
[]
[]
[ "extract", "file", "python", "regex", "string" ]
stackoverflow_0007709224_extract_file_python_regex_string.txt
Q: Why finally block is executing after calling sys.exit(0) in except block? I'm new to Python. I just want to know why the finally block is executing after calling sys.exit(0) in the except block? Code: import sys def divide_by_zero(): try: 10/0 print "It will never print" except Exception: ...
Why finally block is executing after calling sys.exit(0) in except block?
I'm new to Python. I just want to know why the finally block is executing after calling sys.exit(0) in the except block? Code: import sys def divide_by_zero(): try: 10/0 print "It will never print" except Exception: sys.exit(0) print "Printing after exit" finally: pr...
[ "All sys.exit() does is raise an exception of type SystemExit.\nFrom the documentation:\n\nExit from Python. This is implemented by raising the SystemExit\nexception, so cleanup actions specified by finally clauses of try\nstatements are honored, and it is possible to intercept the exit\nattempt at an outer level.\...
[ 96, 9 ]
[]
[]
[ "python" ]
stackoverflow_0007709411_python.txt
Q: How to draw a chart with OFC Python? I need to visualize data for my trac Plugin. Therefore I want to use Open Flash Charts 2. Trying to follow this didn't quite work out as expected. Question The Chartdata won't show, the only output is the loading-animation by OFC. Everything looks similar too the html-source i...
How to draw a chart with OFC Python?
I need to visualize data for my trac Plugin. Therefore I want to use Open Flash Charts 2. Trying to follow this didn't quite work out as expected. Question The Chartdata won't show, the only output is the loading-animation by OFC. Everything looks similar too the html-source in the tutorial. How can I load the JSON- ...
[ "You have to check if the path of the ofc folder in trac.ini is right.\nThe function chartdata_from_timetable is also not right. You only see the values of the last entry because of overwriting.\n" ]
[ 0 ]
[]
[]
[ "javascript", "open_flash_chart", "python" ]
stackoverflow_0006860573_javascript_open_flash_chart_python.txt
Q: Troubles with PyDev and external libraries in OS X I've successfully installed the latest version of PyDev in my Eclipse (3.5.1) under OS X 10.6.3, with python 2.6.1 I have troubles in making the libraries I have installed work. For example, I'm trying to use the cx_Oracle library, which is perfectly working if ca...
Troubles with PyDev and external libraries in OS X
I've successfully installed the latest version of PyDev in my Eclipse (3.5.1) under OS X 10.6.3, with python 2.6.1 I have troubles in making the libraries I have installed work. For example, I'm trying to use the cx_Oracle library, which is perfectly working if called from the python interpeter of from simple scripts m...
[ "In eclipse, set the following ‘environment variables’ under ‘PyDev’, Interpreter – Python (or which ever you are using).\n\nORACLE_HOME=[your installation path]/instantclient_10_2\nLD_LIBRARY_PATH=$ORACLE_HOME\nDYLD_LIBRARY_PATH=$ORACLE_HOME\n\nIt worked for me.\n", "Don't know if you have fixed this yet, but fr...
[ 5, 1, 0 ]
[]
[]
[ "eclipse", "pydev", "python" ]
stackoverflow_0002881055_eclipse_pydev_python.txt
Q: Running webapp2 outside of appengine, how to run it as a service/deamon? I just finished my app and would like to deploy it. But how to run my app as a service/deamon? A google search showed some different approches using some python libraries, twisted and Can I run a Python script as a service?. But can't figure ...
Running webapp2 outside of appengine, how to run it as a service/deamon?
I just finished my app and would like to deploy it. But how to run my app as a service/deamon? A google search showed some different approches using some python libraries, twisted and Can I run a Python script as a service?. But can't figure out how to do it. Any one done this? Is there a best-practice approach? ..fre...
[ "As you want your application to run standalone (if i understood correctly), you could handle this like with any other (non-web) application.\nIf you just want your program to run in the background, you could read this receipe that explains how to create a daemon application and has a nice discussion about this top...
[ 4, 2, 1 ]
[]
[]
[ "python", "webapp2" ]
stackoverflow_0007022981_python_webapp2.txt
Q: Python String to BSTR I am Using the iTunes COM interface on windows 7. The method iTunes.CurrentTrack.AddArtworkFromFile(path) requires path to be of type BSTR. I understand from some research that BSTR is a C++/Visual Basic data type that means basic string. Is there any way of converting python ascii strings to...
Python String to BSTR
I am Using the iTunes COM interface on windows 7. The method iTunes.CurrentTrack.AddArtworkFromFile(path) requires path to be of type BSTR. I understand from some research that BSTR is a C++/Visual Basic data type that means basic string. Is there any way of converting python ascii strings to BSTR? code : import urllib...
[ "Since you are using Python 2.x, I believe you simply need to use unicode rather than str and win32com will do the rest. However, I would have expected win32com to automatically convert str to unicode for you.\nYou should write it like this:\niTunes.CurrentTrack.AddArtworkFromFile(u'file://localhost/C:/Users/ArchAn...
[ 3 ]
[]
[]
[ "bstr", "com", "python" ]
stackoverflow_0007710089_bstr_com_python.txt
Q: capturing logging messages from imported python file Getting logging information from an imported python file. I am building a python based test suite. The tests are called using __import function I would like to capture the logging messages (in tests) in my test application. The logging messages are generated by...
capturing logging messages from imported python file
Getting logging information from an imported python file. I am building a python based test suite. The tests are called using __import function I would like to capture the logging messages (in tests) in my test application. The logging messages are generated by using the python logging module. How can I do that ? For ...
[ "You can easily create a custom logging handler and assign it to the logger used by your module.\nSee http://docs.python.org/library/logging.html#handler-objects\n" ]
[ 0 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0007709954_logging_python.txt
Q: Handling detailed exception in Python I am processing the data reading from test.xls file like so: from sys import exe_info try: book = xlrd.open_workbook('test.xls') sh = book.sheet_by_index(0) for row in range( 1, sh.nrows ): for index, value in enumerate(sh.row_values(row...
Handling detailed exception in Python
I am processing the data reading from test.xls file like so: from sys import exe_info try: book = xlrd.open_workbook('test.xls') sh = book.sheet_by_index(0) for row in range( 1, sh.nrows ): for index, value in enumerate(sh.row_values(row)): process_value(value) ...
[ "xlrd returns the contents of all text cells as unicode objects. You don't need to know \"the correct encoding\" -- it's NOT encoded. \nI suggest that you do something like this:\nfor row in xrange(1, sh.nrows):\n for index, value in enumerate(sh.row_values(row)):\n try:\n process_value(value)\...
[ 1 ]
[]
[]
[ "exception_handling", "python" ]
stackoverflow_0007709319_exception_handling_python.txt
Q: How to read data in Java from a Python Struck.pack I am using Java UDP datagrampacket to receive a python packet which contains a Struct.pack string. How could I unpack it in Java? A: If you have the packet as byte[] array in Java, you can use java.io.java.io.ByteArrayInputStream to create an InputStream from it...
How to read data in Java from a Python Struck.pack
I am using Java UDP datagrampacket to receive a python packet which contains a Struct.pack string. How could I unpack it in Java?
[ "If you have the packet as byte[] array in Java, you can use java.io.java.io.ByteArrayInputStream to create an InputStream from it which can be wrapped by java.io.DataInputStream which provides methods to read several simple datatypes.\nBe aware that DataInputStream works with big endian. If you use little endian s...
[ 1 ]
[]
[]
[ "java", "python" ]
stackoverflow_0007708858_java_python.txt
Q: Wrong redirections with django-piston I have a problems with my django api. I have a website that works well, and now I want make a api with django-piston to make a android app. When I try to get some data, and I sent some key in the url, the handlers of my api project are empty, these are my urls.py and handlers....
Wrong redirections with django-piston
I have a problems with my django api. I have a website that works well, and now I want make a api with django-piston to make a android app. When I try to get some data, and I sent some key in the url, the handlers of my api project are empty, these are my urls.py and handlers.py inside api app. urls.py from django.conf...
[ "I think you may have your regex's wrong in urls.py. The pattern specifier for the groups need to be inside the parenthesis, for example,\ninstead of:\nurl(r'^1.0/(?P<username>)\\w+/(?P<password>)\\w+/(?P<api_key>)\\d+/programadores.(?P<emitter_format>.+)$', prog_handler), ...\n\ntry:\nurl(r'^1.0/(?P<username>\\w+...
[ 1 ]
[]
[]
[ "django", "django_piston", "python" ]
stackoverflow_0007370860_django_django_piston_python.txt
Q: Python Functions Confusion I am learning Python. I have a function readwrite(filename, list). filename is of type string. list is a list containing strings to be wtitten in the file. I have a simple function call like this: fname = 'hello.txt' readwrite('xx'+fname, datalist) I am facing problem that when i print ...
Python Functions Confusion
I am learning Python. I have a function readwrite(filename, list). filename is of type string. list is a list containing strings to be wtitten in the file. I have a simple function call like this: fname = 'hello.txt' readwrite('xx'+fname, datalist) I am facing problem that when i print the filename argument value ins...
[ "Python is case-sensitive. The two lines below are referring to two different variables (note the capital \"N\" in the first one):\ndef readwrite(fileName, list):\n print 'arg file=',filename\n\nWhat's happening is that the second line picks up the global variable called filename instead of the function argument...
[ 12 ]
[]
[]
[ "python" ]
stackoverflow_0007711382_python.txt
Q: sql alchemy filter results on properties of joined models I have a model X and a model Y. Y contains a foreign key reference to X.id, with a instance of the related X entry available by the property x. x_id = Column(Integer, ForeignKey('xtable.id')) x = relationship('X') X also has a boolean property 'publi...
sql alchemy filter results on properties of joined models
I have a model X and a model Y. Y contains a foreign key reference to X.id, with a instance of the related X entry available by the property x. x_id = Column(Integer, ForeignKey('xtable.id')) x = relationship('X') X also has a boolean property 'publish'. Executing a query on Y, how can i filter my results to th...
[ "You need to add a join in your query to class X and use filter instead of filter_by:\nqry = DBSession.query(Y)\nqry = qry.join(X)\nqry = qry.filter(X.publish == True)\nqry.all()\n\nor in one go:\nDBSession.query(Y).join(X).filter(X.publish == True).all()\n\nSee this question regarding the difference between using ...
[ 3, 3 ]
[]
[]
[ "python", "relation", "sqlalchemy" ]
stackoverflow_0007703008_python_relation_sqlalchemy.txt
Q: Image Processing, In Python? I've recently come across a problem which requires at least a basic degree of image processing, can I do this in Python, and if so, with what? A: The best-known library is PIL. However if you are simply doing basic manipulation, you are probably better off with the Python bindings f...
Image Processing, In Python?
I've recently come across a problem which requires at least a basic degree of image processing, can I do this in Python, and if so, with what?
[ "The best-known library is PIL. However if you are simply doing basic manipulation, you are probably better off with the Python bindings for ImageMagick, which will be a good deal more efficient than writing the transforms in Python.\n", "Depending on what you mean by \"image processing\", a better choice might ...
[ 53, 46, 19, 11, 7, 6, 4, 3 ]
[]
[]
[ "image", "image_manipulation", "image_processing", "python" ]
stackoverflow_0000094875_image_image_manipulation_image_processing_python.txt
Q: Grouping values, creating a sum and writing to excel, Python i am putting together a script to take some data from an access table and write it to an excel table. In the process, I'm trying to format the excal table. I have pasted the output of the excel table below my script. In the following script, I pull the d...
Grouping values, creating a sum and writing to excel, Python
i am putting together a script to take some data from an access table and write it to an excel table. In the process, I'm trying to format the excal table. I have pasted the output of the excel table below my script. In the following script, I pull the data from the access table and get it into the excel table. it grou...
[ "You need something like the (untested) code below.\nimport arcpy, xlwt, sys, traceback, datetime\nfrom arcpy import env\n#### from xlwt import *\n#### (a) horrid, you need only 1 class (b) you already imported xlwt\n### from itertools import groupby\n#### good idea, but get some simple programming skills first\n##...
[ 0 ]
[]
[]
[ "dictionary", "python", "xlwt" ]
stackoverflow_0007707685_dictionary_python_xlwt.txt
Q: Rehash in python I am trying to read lines from a file which contains hashed data. The data was hash with the following code: encoder = hashlib.sha224() encoder.update(string) file.write(encoder.hexdigest()) how do I rehash the data? A: As already said, you can't do that, and that's the actual idea behind hashi...
Rehash in python
I am trying to read lines from a file which contains hashed data. The data was hash with the following code: encoder = hashlib.sha224() encoder.update(string) file.write(encoder.hexdigest()) how do I rehash the data?
[ "As already said, you can't do that, and that's the actual idea behind hashing. I think what you are really looking for is encryption.\nWhen the data is encrypted, nobody can read it. Only when you know how to decrypt it, you can read it again. There are many different ways of encryption, such as symmetric and asym...
[ 1 ]
[]
[]
[ "hash", "python" ]
stackoverflow_0007711345_hash_python.txt
Q: Python/Django shell won't start One of the great features of Django is that you can open a python interpreter set-up for use with your project. This can be used to analyse objects in a database and allows any python commands to be executed on your project. I find it essential for Django development. It is invoked ...
Python/Django shell won't start
One of the great features of Django is that you can open a python interpreter set-up for use with your project. This can be used to analyse objects in a database and allows any python commands to be executed on your project. I find it essential for Django development. It is invoked in the project directory using this c...
[ "It seems like IPython is installed wrongly somehow. Try starting the shell with:\n./manage.py shell --plain\n\nto start the standard Python shell, rather than IPython. If that works, then trying removing IPython completely and reinstalling it.\n", "IPython 0.11 has a different API, for which a fix exists in the ...
[ 12, 7 ]
[]
[]
[ "django", "python", "shell" ]
stackoverflow_0002078059_django_python_shell.txt
Q: IPython doesn't work in Django shell I've just recently switched over to using 64-bit Python 2.6.1 on Mac OS X 10.6 (Snow Leopard). IPython won't work with Django anymore, but IPython works from the command-line. The error says: shell = IPython.Shell.IPShell(argv=[]) AttributeError: 'module' object has no att...
IPython doesn't work in Django shell
I've just recently switched over to using 64-bit Python 2.6.1 on Mac OS X 10.6 (Snow Leopard). IPython won't work with Django anymore, but IPython works from the command-line. The error says: shell = IPython.Shell.IPShell(argv=[]) AttributeError: 'module' object has no attribute 'Shell' I could use the ./manage.p...
[ "IPython 0.11 has a different API, for which a fix exists in the last Django versions.\nFor older Django versions, you can use IPython 0.10, which does work:\npip install ipython==0.10\n\n", "Does this work when you run it from Python interactive console?\nimport IPython; IPython.Shell\n\n", "I got the same pro...
[ 28, 0, 0 ]
[]
[]
[ "django", "osx_snow_leopard", "python" ]
stackoverflow_0002109075_django_osx_snow_leopard_python.txt
Q: How to remove duplicates in strings within list? I have list of string but in each string is duplicate I need to remove. f.e.: lst = ('word1 2 36 2 2' ' word2 96 5 5 5 14' 'word3 45 6 45 45') etc. I need: lst = ('word1 2 36' 'word2 96 5 14' 'word3 45 6') A: Generally: Create a dictionary for each key wordN ...
How to remove duplicates in strings within list?
I have list of string but in each string is duplicate I need to remove. f.e.: lst = ('word1 2 36 2 2' ' word2 96 5 5 5 14' 'word3 45 6 45 45') etc. I need: lst = ('word1 2 36' 'word2 96 5 14' 'word3 45 6')
[ "Generally:\n\nCreate a dictionary for each key wordN\nIn this key, convert item 2 through n of list to a set\nIterate through the dictionary, building a new list from each key and its set's contents\n\n", "Your question is not very clear, and as-written your \"list\" isn't a list but a string. I guess you probab...
[ 3, 0 ]
[]
[]
[ "python" ]
stackoverflow_0007712162_python.txt
Q: Error Handling in Python with SUDS I have been trying to control a camera through a wsdl file using SUDS. I have got the code working but I want to place error handling into the script. I have tried different exceptions but am unable to get the script working. When I enter an invalid coordinate I get an error. The...
Error Handling in Python with SUDS
I have been trying to control a camera through a wsdl file using SUDS. I have got the code working but I want to place error handling into the script. I have tried different exceptions but am unable to get the script working. When I enter an invalid coordinate I get an error. The code I am using is below followed by th...
[ "If you handled all exceptions and errors in your code and your code is working fine but still you are getting below message with your correct output. \nMsg : \"No handlers could be found for logger suds.client \"\nThen a simple solution is to add this line \nlogging.getLogger('suds.client').setLevel(logging.CRITIC...
[ 15, 12, 1, 0 ]
[]
[]
[ "python", "suds", "web_services" ]
stackoverflow_0002085128_python_suds_web_services.txt
Q: Broke my python build while adding numpy While trying to build my python by adding numpy to it I managed to have created problems somewhere. Now, even though I have numpy and other packages like BeautifulSoup installed, I'm unable to import them from within my mac's default python. Previously I was able to import ...
Broke my python build while adding numpy
While trying to build my python by adding numpy to it I managed to have created problems somewhere. Now, even though I have numpy and other packages like BeautifulSoup installed, I'm unable to import them from within my mac's default python. Previously I was able to import them. Where should I initially look for potent...
[ "As I understand you have build a custom python which is not same with your default python installation. \nYou should either use the newly installed python or specify the path of numpy to the default installation. There are 2 ways of doing the second choice:\nAsume that your numpy module is located at /Users/Me/pyt...
[ 1 ]
[]
[]
[ "numpy", "path", "python" ]
stackoverflow_0007712326_numpy_path_python.txt
Q: Python: how to avoid code duplication in exception catching? What is a good pattern to avoid code duplication when dealing with different exception types in Python, eg. I want to treat URLError and HTTPError simlar but not quite: try: page = urlopen(request) except URLError, err: logger.error("An error ocu...
Python: how to avoid code duplication in exception catching?
What is a good pattern to avoid code duplication when dealing with different exception types in Python, eg. I want to treat URLError and HTTPError simlar but not quite: try: page = urlopen(request) except URLError, err: logger.error("An error ocurred %s", err) except HTTPError, err: logger.error("An error o...
[ "I think that your third example is the best solution.\n\nIt's the shortest version\nIt avoids duplication\nIt is clear to read and easy to follow, much unlike the second version.\n\nYou might want to use the newer except FooError as err syntax, though, if you're on Python 2.6 or higher.\nAlso, in your example, the...
[ 10 ]
[]
[]
[ "exception", "exception_handling", "python" ]
stackoverflow_0007712651_exception_exception_handling_python.txt
Q: Why weakref doesn't support built-in types in Python? In Python weakref document( http://docs.python.org/library/weakref.html ), it says that Several built-in types such as list and dict do not directly support weak references but can add support through subclassing I think creating weakref for big dict could...
Why weakref doesn't support built-in types in Python?
In Python weakref document( http://docs.python.org/library/weakref.html ), it says that Several built-in types such as list and dict do not directly support weak references but can add support through subclassing I think creating weakref for big dict could be useful in some real cases. I'm wondering what's the rea...
[ "Most of the built-in types are not directly weak referenceable (e.g. str, int, float, list, dict, None), and there are a few that cannot even be made so by sub-classing (e.g. tuples in CPython).\nSome details about the underlying implementation of weakrefs for several built-in types can be found in this March-2005...
[ 7 ]
[ "My educated guess is that dicts and lists are used internally to implement weakrefs, so you would have an egg-chicken situation here.\n" ]
[ -1 ]
[ "python", "weak_references" ]
stackoverflow_0007711246_python_weak_references.txt
Q: Where to import modules Lets say I have a module called device which contains a class called ConfigureDevice. Lets also say that I have a module called comports which defines my com ports in a class called ComPorts (enum in C). Now, lets say that the constructor for ConfigureDevice takes an argument called comPor...
Where to import modules
Lets say I have a module called device which contains a class called ConfigureDevice. Lets also say that I have a module called comports which defines my com ports in a class called ComPorts (enum in C). Now, lets say that the constructor for ConfigureDevice takes an argument called comPorts. The question is, should I...
[ "You should generally always put import at the top of the module, where Python programmers will expect to find it, because then any import errors will happen right when the program starts, instead of happening much later when a function is finally called. We generally only put import inside a function because (a) w...
[ 5 ]
[]
[]
[ "python" ]
stackoverflow_0007712739_python.txt
Q: Control rs232 windows terminal program from python I am testing a piece of hardware which hosts an ftp server. I connect to the server in order to configure the hardware in question. My test environment is written in Python 3. To start the ftp server, I need to launch a special proprietary terminal application on ...
Control rs232 windows terminal program from python
I am testing a piece of hardware which hosts an ftp server. I connect to the server in order to configure the hardware in question. My test environment is written in Python 3. To start the ftp server, I need to launch a special proprietary terminal application on my pc. I must use this software as far as I know and I h...
[ "Have you looked at pySerial? It's been a few years since I've used it but it was quite good at handling RS-232 communications and it looks like it's compatible with Python 3.x.\n", "Sikuli might provide the kind of GUI automation you need.\n", "I was also able to solve this using WScript, but pySerial was the...
[ 1, 0, 0 ]
[]
[]
[ "automated_tests", "python", "python_3.x", "serial_port", "windows" ]
stackoverflow_0007632642_automated_tests_python_python_3.x_serial_port_windows.txt
Q: Python subprocess kill doesn't release the file handle When you start a windows executable using subprocess.Popen in shell mode and kill it (instead of letting the exe finish running), the executable remains locked for as long as the python program is running. This doesn't happen when shell=False. Anyone know a so...
Python subprocess kill doesn't release the file handle
When you start a windows executable using subprocess.Popen in shell mode and kill it (instead of letting the exe finish running), the executable remains locked for as long as the python program is running. This doesn't happen when shell=False. Anyone know a solution for this? import time import subprocess proc = subpro...
[ "You are terminating the shell and not the process it spawned. That is my guess. If that's right, have a look at this question:\nsubprocess: deleting child processes in Windows\n" ]
[ 1 ]
[]
[]
[ "python", "subprocess" ]
stackoverflow_0007713077_python_subprocess.txt
Q: python read binary from specific position I have a huge binary file from which I want to read some bytes from exact positions in the file. How can I access specific bytes from binary file not having to loop through all bytes from the beginning of the file? Thanx, A: Make sure you open the file with the "b" attri...
python read binary from specific position
I have a huge binary file from which I want to read some bytes from exact positions in the file. How can I access specific bytes from binary file not having to loop through all bytes from the beginning of the file? Thanx,
[ "Make sure you open the file with the \"b\" attribute (for example: file(\"myfile.bin\", \"rb\")). Then use the seek() method of the file object.\nLook here: http://docs.python.org/release/2.4.4/lib/bltin-file-objects.html\n" ]
[ 13 ]
[]
[]
[ "binary", "file", "python" ]
stackoverflow_0007713311_binary_file_python.txt
Q: Reading "Fn" key I'd like to find out the easiest way how to read Fn key from my keyboard in Python (Windows).I've tried to use Pygame library, but it didn't work for Fn key. A: The "Fn" key is usually a proprietary, device-specific modifier that is handled by the device driver (or the hardware itself). It's not...
Reading "Fn" key
I'd like to find out the easiest way how to read Fn key from my keyboard in Python (Windows).I've tried to use Pygame library, but it didn't work for Fn key.
[ "The \"Fn\" key is usually a proprietary, device-specific modifier that is handled by the device driver (or the hardware itself). It's not a normal button, and you can't catch it in your code. To be honest, I can't imagine why you'd ever possibly want to.\n" ]
[ 5 ]
[]
[]
[ "keyboard", "python" ]
stackoverflow_0007713539_keyboard_python.txt
Q: A Djangoic method of checking if it is an allowed subdomain I have to solve this little problem in Python/Django and I'm wondering which is the best way to go about it. I have a list of allowed domains e.g. www.google.com, mail.google.com. I would like to check if a domain is allowed or not. Now, a request from e...
A Djangoic method of checking if it is an allowed subdomain
I have to solve this little problem in Python/Django and I'm wondering which is the best way to go about it. I have a list of allowed domains e.g. www.google.com, mail.google.com. I would like to check if a domain is allowed or not. Now, a request from either www.google.com is valid, and a request from mail.google.com...
[ "First of all if i would like to use wildcard it would not be \"www\" since www is nothing but a subdomain.\nFor example if i would like to let all google domains my record would be \".google.com\".\nThis would show for example www.google.com.au as not allowed. It's possible for you to put wildcard to the end but t...
[ 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0007710002_django_python.txt