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:
fault-tolerant python based parser for WikiLeaks cables
Some time ago I started writing a BNF-based grammar for the cables which WikiLeaks released. However I now realized that my approach is maybe not the best and I'm looking for some improvement.
A cabe consists of three parts. The head has some RFC2822-style fo... | fault-tolerant python based parser for WikiLeaks cables | Some time ago I started writing a BNF-based grammar for the cables which WikiLeaks released. However I now realized that my approach is maybe not the best and I'm looking for some improvement.
A cabe consists of three parts. The head has some RFC2822-style format. This parses usually correct. The text part has a more i... | [
"Cablemap seems to do what you're searching for: http://pypi.python.org/pypi/cablemap.core/\n",
"I haven't looked at the cables but lets take a similar problem and consider the options: Lets say you wanted to write a parser for RFCs, there's an RFC for formatting of RFCs, but not all RFCs follow it. \nIf you wrot... | [
4,
1
] | [] | [] | [
"bnf",
"parsing",
"python",
"text_parsing"
] | stackoverflow_0006007229_bnf_parsing_python_text_parsing.txt |
Q:
Regex for matching optional parameters as groups in string
I am trying to read a batch script containing an input string of a command and optional parameters like
input = 'command -a field1 -b field2 -c field3'
The option parameters are set by a user in a file and I am obtaining the string by reading the file. I... | Regex for matching optional parameters as groups in string | I am trying to read a batch script containing an input string of a command and optional parameters like
input = 'command -a field1 -b field2 -c field3'
The option parameters are set by a user in a file and I am obtaining the string by reading the file. If the option is included I would need to extract the field.
I cu... | [
"In Python you can use the built in optparse or argparse modules to do this for you so you don't have to fidget with hardcore regular expressions which will fail eventually :-)\n",
"parsing command line options with regular expressions in python is very fragile - argparse will let you handle all of the arguments ... | [
5,
2,
0
] | [] | [] | [
"optional_parameters",
"python",
"regex",
"string"
] | stackoverflow_0006755443_optional_parameters_python_regex_string.txt |
Q:
TypeError: argument of type 'NoneType' is not iterable in python
I am trying to get the VM size of a running process and using the following simple script. Here initially I am trying to get the reference of that process. But getting the error as --
if "DomainManager" in c:
TypeError: argument of type 'NoneTyp... | TypeError: argument of type 'NoneType' is not iterable in python | I am trying to get the VM size of a running process and using the following simple script. Here initially I am trying to get the reference of that process. But getting the error as --
if "DomainManager" in c:
TypeError: argument of type 'NoneType' is not iterable
import wmi
computer = wmi.WMI ()
for process in... | [
"import wmi\ncomputer = wmi.WMI ()\n\nfor process in computer.Win32_Process ():\n c = process.CommandLine\n if c is not None and \"DomainManager\" in c:\n print c\n\nNotice the condition in the if statement: \nif c is not None and \"DomainManager in c\":\n\nThis will check to see if c is valid before a... | [
7,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0006762446_python.txt |
Q:
Joining Subsequent List Elements - Python
Is there a command to merge subsequent elements in a list - ie in a list ['AA', 'BB', 'C', 'D'] how would one merge the first two elements (or any others, depending on the code) in the list, leaving a list like ['AABB', 'C', 'D'] ? Thanks!
A:
>>> a = ['AA', 'BB', 'C', 'D... | Joining Subsequent List Elements - Python | Is there a command to merge subsequent elements in a list - ie in a list ['AA', 'BB', 'C', 'D'] how would one merge the first two elements (or any others, depending on the code) in the list, leaving a list like ['AABB', 'C', 'D'] ? Thanks!
| [
">>> a = ['AA', 'BB', 'C', 'D']\n>>> a[0:2] = [''.join(a[0:2])]\n>>> a\n['AABB', 'C', 'D']\n\n",
"You can try the following if you don't care about init list:\n>>> a = ['AA', 'BB', 'C', 'D']\n>>> a[0] += a.pop(1)\n\nIf you want to get new one and leave initList as is you can use something like this(note that this... | [
5,
2,
1
] | [] | [] | [
"merge",
"python"
] | stackoverflow_0006762695_merge_python.txt |
Q:
If statement for strings in python?
I am a total beginner and have been looking at http://en.wikibooks.org/wiki/Python_Programming/Conditional_Statements but I can not understand the problem here. It is pretty simple, if the user enters y it should print this will do the calculation although I get a syntax error o... | If statement for strings in python? | I am a total beginner and have been looking at http://en.wikibooks.org/wiki/Python_Programming/Conditional_Statements but I can not understand the problem here. It is pretty simple, if the user enters y it should print this will do the calculation although I get a syntax error on IF answer=="y"
answer = str(input("Is t... | [
"Even once you fixed the mis-cased if and improper indentation in your code, it wouldn't work as you probably expected. To check a string against a set of strings, use in. Here's how you'd do it (and note that if is all lowercase and that the code within the if block is indented one level).\nOne approach:\nif ans... | [
54,
13,
7,
7,
3
] | [
"Python is case sensitive and needs proper indentation. You need to use lowercase \"if\", indent your conditions properly and the code has a bug. proceed will evaluate to y\n"
] | [
-1
] | [
"conditional_statements",
"python"
] | stackoverflow_0006762959_conditional_statements_python.txt |
Q:
cleanup nested list
I have a huge mess of a nested list that looks something like this, just longer:
fruit_mess = [['watermelon,0,1.0\n'], ['apple,0,1.0\n'], ['"pineapple",0,1.0\n'], ['"strawberry, banana",0,1.0\n'], ['peach plum pear,0,1.0\n'], ['"orange, grape",0,1.0\n']]
Ultimately I want something that looks ... | cleanup nested list | I have a huge mess of a nested list that looks something like this, just longer:
fruit_mess = [['watermelon,0,1.0\n'], ['apple,0,1.0\n'], ['"pineapple",0,1.0\n'], ['"strawberry, banana",0,1.0\n'], ['peach plum pear,0,1.0\n'], ['"orange, grape",0,1.0\n']]
Ultimately I want something that looks like this:
neat_fruit = [... | [
"Use the csv module (in the standard library) to handle the double-quoted fruits with commas in their names:\nimport csv\nimport io\n\nfruit_mess = [['watermelon,0,1.0\\n'], ['apple,0,1.0\\n'], ['\"pineapple\",0,1.0\\n'], ['\"strawberry, banana\",0,1.0\\n'], ['peach plum pear,0,1.0\\n'], ['\"orange, grape\",0,1.0\\... | [
6,
1,
0
] | [] | [] | [
"nested_lists",
"python"
] | stackoverflow_0006762529_nested_lists_python.txt |
Q:
Pyinstaller Activex Attribute Error with wxPython
For some reason, when I compile my app with Pyinstaller, it gives me an error when run:
Traceback (most recent call last):
File "<string>", line 2, in <module>
AttributeError: 'module' object has no attribute 'activex'
And the top of my code (the code itself is ... | Pyinstaller Activex Attribute Error with wxPython | For some reason, when I compile my app with Pyinstaller, it gives me an error when run:
Traceback (most recent call last):
File "<string>", line 2, in <module>
AttributeError: 'module' object has no attribute 'activex'
And the top of my code (the code itself is extremely long). I've also removed a whole load of arra... | [
"Are you using the activex stuff from wxPython? By the way, you shouldn't import wx like this:\nfrom wxPython.wx import *\nfrom wx import *\n\nThe recommended way is\nimport wx\n\nAnd then prepend everything with \"wx\". wxPython is HUGE and by doing it your way, you import almost everything from it, which you don'... | [
3
] | [] | [] | [
"attributeerror",
"module",
"pyinstaller",
"python",
"wxpython"
] | stackoverflow_0006760997_attributeerror_module_pyinstaller_python_wxpython.txt |
Q:
How to wait for a list of threads to finish? (Python)
For a single thread, I would do
thread.join(60)
threadEvent.set()
How can I make it wait for all threads in the list to finish OR wait until the timeout and then issue the set() to the threading.Event()? Each thread has a corresponding threading.Event() that w... | How to wait for a list of threads to finish? (Python) | For a single thread, I would do
thread.join(60)
threadEvent.set()
How can I make it wait for all threads in the list to finish OR wait until the timeout and then issue the set() to the threading.Event()? Each thread has a corresponding threading.Event() that will be used to stop the thread. The important part is that ... | [
"import time\nendTime = time.time() + 60\nfor t in threads:\n t.join(endTime - time.time())\n t.event.set()\n\n"
] | [
3
] | [] | [] | [
"multithreading",
"python"
] | stackoverflow_0006762891_multithreading_python.txt |
Q:
How to generate a human friendly unique ID in Python?
How do I generate a unique ID value that can be easily passed on via phone or email, that can be easily remembered while still not being easily guessable.
I am using database. But as I am giving away the ID to people I do not want it to be bound to a database. ... | How to generate a human friendly unique ID in Python? | How do I generate a unique ID value that can be easily passed on via phone or email, that can be easily remembered while still not being easily guessable.
I am using database. But as I am giving away the ID to people I do not want it to be bound to a database. I could do something with the unique ID I already have in d... | [
"What you want to do is stitch together syllables to create pronounceable pseudo words. You can create syllables in any language you like to make up words that can be pronounced and communicated but don't actually mean anything.\nHere is an article about how one person created human readable UIDs for speaking them ... | [
13,
3,
2,
0,
0
] | [] | [] | [
"python",
"random",
"unique",
"uniqueidentifier"
] | stackoverflow_0006761898_python_random_unique_uniqueidentifier.txt |
Q:
odd behavior in tkinter.tk.Sizegrip
I'm currently trying to learn tkinter in Python 3 so I'm not sure if I'm looking at a bug or I'm not doing things correctly.
from tkinter import *
from tkinter import ttk
root = Tk()
grip = ttk.Sizegrip(root).grid(column=0, row=0, sticky=(S,E))
root.columnconfigure(0, weight=1)... | odd behavior in tkinter.tk.Sizegrip | I'm currently trying to learn tkinter in Python 3 so I'm not sure if I'm looking at a bug or I'm not doing things correctly.
from tkinter import *
from tkinter import ttk
root = Tk()
grip = ttk.Sizegrip(root).grid(column=0, row=0, sticky=(S,E))
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
root.main... | [
"I have the same problem on my system (Ubuntu 10.10, Python 2.6) and I think it has to do with the window manager and not Tkinter. When I use Openbox, I don't have the problem, and when I use root.overrideredirect(1), I don't have the problem either.\nWhat you can do is make a ttk.Label themed to look like a sizegr... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006208523_python_tkinter.txt |
Q:
Python regex, match more than one integer
The below code prints white space and not '11' and I can't figure out why. Replacing [0-9]* with [0-9]{1,2} prints '11'. Can any one help?
import re
test_string = 'cake_11xlfslijg'
pattern = '.*(?P<order>[0-9]*)'
result = re.compile(pattern).search(test_string)
if result:
... | Python regex, match more than one integer | The below code prints white space and not '11' and I can't figure out why. Replacing [0-9]* with [0-9]{1,2} prints '11'. Can any one help?
import re
test_string = 'cake_11xlfslijg'
pattern = '.*(?P<order>[0-9]*)'
result = re.compile(pattern).search(test_string)
if result:
print 'result'
print result.group('orde... | [
"Try [0-9]+. The * translates to \"zero or more\", and there are zero or more digits right at the start of your string.\n",
"Your regex should be this\npattern = '(?P<order>[0-9]+)'\n\n\nRemoved the first .* as it will do a greedy match of the entire string.\nMade [0-9]+ as it will match the digits only even at l... | [
9,
6,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006763589_python_regex.txt |
Q:
Python Native Arbitrary Precision
Is there any way of compiling Python's interpretter in such a way that it could use a native (c) arbitrary precision library so that Python could use arbitrary precision as if it was a normal number instead of having to use the decimal class?
EG.
>>0.00000001 + 1
1.00000001
A:
I... | Python Native Arbitrary Precision | Is there any way of compiling Python's interpretter in such a way that it could use a native (c) arbitrary precision library so that Python could use arbitrary precision as if it was a normal number instead of having to use the decimal class?
EG.
>>0.00000001 + 1
1.00000001
| [
"If you're unsatisfied with the builtin decimal, you can try several libraries that implement higher precision floating point numbers. Most of them, however, are not exactly \"native\" - you might clarify what you mean by that and why you need it.\n\nmpmath - it provides a pure-Python implementation of high-precisi... | [
3
] | [] | [] | [
"arbitrary_precision",
"python"
] | stackoverflow_0006763636_arbitrary_precision_python.txt |
Q:
ERROR Installing GeoIP-Python on windows
I am trying to install GeoIP-Python-1.2.4 on Windows 7.
Before I can do that, I need to install GeoIP-1.4.6.
I am using README.MinGW instructions for installation. I used MinGW and got through ./configure. When I do 'make', I get following error:
*** Warning: This system ... | ERROR Installing GeoIP-Python on windows | I am trying to install GeoIP-Python-1.2.4 on Windows 7.
Before I can do that, I need to install GeoIP-1.4.6.
I am using README.MinGW instructions for installation. I used MinGW and got through ./configure. When I do 'make', I get following error:
*** Warning: This system can not link to static lib archive libGeoIP.la... | [
"You may want to try\npython setup.py build_ext -cmingw32\n\n(or -cmingw, can't remember.)\nThis way it'll try to use the MinGW compiler (it defaults, as you can see from the command line, to MSVC)\n",
"better choice: pygeoip , it's pure python API for MaxMind GeoIP databases, don't need C API anymore\n",
"I g... | [
2,
2,
0
] | [] | [] | [
"geoip",
"mingw",
"python"
] | stackoverflow_0005383830_geoip_mingw_python.txt |
Q:
How to create a singleton class based on its input?
I have a class defined as
class Conditional_Singleton(object):
def __init__(self, condition=None):
self.initialization = some_func_of(condition)
Since the "initialization" step really takes a lot of time to run and the output could be huge, I would ... | How to create a singleton class based on its input? | I have a class defined as
class Conditional_Singleton(object):
def __init__(self, condition=None):
self.initialization = some_func_of(condition)
Since the "initialization" step really takes a lot of time to run and the output could be huge, I would really like that the class not be recreated over and over... | [
"class Conditional_Singleton(object):\n saved_insances = {}\n def __new__(cls, condition = None):\n if not condition in cls.saved_instances:\n cls.saved_instances[condition] = super(\n Conditional_Singleton, cls).__new__(cls)\n return cls.saved_instances[condition]\n ... | [
5,
1
] | [] | [] | [
"python"
] | stackoverflow_0006764338_python.txt |
Q:
Diagonalisation of an array of 2D arrays
I need to diagonalise a very large number of matrices.
These matrices are by themselves quite small (say a x a where a<=10) but due to
their sheer number, it takes a lot of time to diagonalise them all using a for loop
and the numpy.linalg.eig function. So I wanted to make... | Diagonalisation of an array of 2D arrays | I need to diagonalise a very large number of matrices.
These matrices are by themselves quite small (say a x a where a<=10) but due to
their sheer number, it takes a lot of time to diagonalise them all using a for loop
and the numpy.linalg.eig function. So I wanted to make an array of matrices, i.e.,
an array of 2D ar... | [
"If you have an 3D array like:\na = np.random.normal(size=(20,10,10))\n\nyou can then just loop through all 20 of the 10x10 arrays using:\nfor k in xrange(a.shape[0]):\n b = np.linalg.eig(a[k,:,:])\n\nwhere you would save b in a more sophisticated way. This may be what you are already doing, but you can't apply ... | [
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0006764600_numpy_python.txt |
Q:
Getting PyUblas sample working in Ubuntu
I would like to call C++ functions in python which return uBLAS vector/matrices.
There is a package to do this called PyUblas,
but am having trouble getting this to work in Ubuntu.
Can anyone walk me through the steps to get this sample to work?
Also, I am somewhat confused... | Getting PyUblas sample working in Ubuntu | I would like to call C++ functions in python which return uBLAS vector/matrices.
There is a package to do this called PyUblas,
but am having trouble getting this to work in Ubuntu.
Can anyone walk me through the steps to get this sample to work?
Also, I am somewhat confused with the installation instructions. I did not... | [
"I guess that wasn't so hard. Here's what I did to run the small sample on the website and in test/samply.py.\nAfter downloading and unpacking PyUblas, and having the necessary libraries installed, cd into PyUblas-VERSION\n./configure.py --help\n./configure.py --some-options\nsudo python setup.py install\ncd test/\... | [
1,
0
] | [] | [] | [
"c++",
"python",
"ublas",
"ubuntu"
] | stackoverflow_0006753788_c++_python_ublas_ubuntu.txt |
Q:
Quick way to find a true boolean, given several boolean variables?
Let's say you have 10 variables, one of which will be true and the others will be false. Other than having a ton of if/elif statements, is there a better way to find which variable is true and then do "something" based on which variable was true? E... | Quick way to find a true boolean, given several boolean variables? | Let's say you have 10 variables, one of which will be true and the others will be false. Other than having a ton of if/elif statements, is there a better way to find which variable is true and then do "something" based on which variable was true? Each "something" will be different depending on which variable is true.
| [
"bools = [False, False, False, True, False]\n# we're using constants here but you can use variables\n\n# find first True value\nwhichbool = bools.index(True)\n\n# now call a function based on that value\n[func0, func1, func2, func3, func4][whichbool]()\n\nIf there is any possibility that there might be no True valu... | [
4,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006764438_python.txt |
Q:
How does Python handle checking 'if object in list'
I'm wondering because I need to have have a function that is disgustingly fast at checking if a word is in a dictionary list - I'm considering leaving the dictionary as a large string and running regex against instead. This needs to be absurdly fast. So I just ne... | How does Python handle checking 'if object in list' | I'm wondering because I need to have have a function that is disgustingly fast at checking if a word is in a dictionary list - I'm considering leaving the dictionary as a large string and running regex against instead. This needs to be absurdly fast. So I just need a basic overview of how python handles checking if a s... | [
"If you want a blazingly fast membership test, then a list is the wrong data structure. Take a look at the implementation of list_contains in listobject.c, line 437. It iterates over the list in order, comparing the item with each element in turn. The later the item appears in the list, the longer it will take to f... | [
10,
4,
2,
2,
1,
0,
0,
0
] | [] | [] | [
"algorithm",
"list",
"performance",
"python"
] | stackoverflow_0006764063_algorithm_list_performance_python.txt |
Q:
Django easy-thumbnails MAX SIZE
is there a way to set a max size for the images uploaded in my django app using easy-thumbnails app?
In the settings list I don't see anything about it.
A:
To cap file size, you might want to do it in the webserver, rather than in Django.
Alternatively, you can specify a custom fi... | Django easy-thumbnails MAX SIZE | is there a way to set a max size for the images uploaded in my django app using easy-thumbnails app?
In the settings list I don't see anything about it.
| [
"To cap file size, you might want to do it in the webserver, rather than in Django.\nAlternatively, you can specify a custom file handler, with which you can raise an error if the file is too big:\nfrom django.core.files.uploadhandler import TemporaryFileUploadHandler, StopUpload\n\nclass SizeLimitUploadHandler(Tem... | [
-2
] | [] | [] | [
"django",
"django_apps",
"django_models",
"python"
] | stackoverflow_0006765016_django_django_apps_django_models_python.txt |
Q:
Is it possible to access the key_name of an object from inside a jinja2 template?
I'm using python google app engine with the webapp framework, substituting jinja2 templates for django templates.
I know you can get the key_name of an object from inside a handler method by calling it like so:
goody = object.key().n... | Is it possible to access the key_name of an object from inside a jinja2 template? | I'm using python google app engine with the webapp framework, substituting jinja2 templates for django templates.
I know you can get the key_name of an object from inside a handler method by calling it like so:
goody = object.key().name()
But is it possible to access the key_name from within the template logic? Someth... | [
"Jinja2 allows you to execute callables, just by using () according to the documentation here: http://jinja.pocoo.org/docs/templates/#other-operators\nSo, this should work:\n{% for instance in instance_list %}\n {{ instance.key().name() }}\n{% endfor %}\n\n",
"You can do object.key.name inside django template t... | [
10,
2
] | [] | [] | [
"google_app_engine",
"jinja2",
"python"
] | stackoverflow_0005190204_google_app_engine_jinja2_python.txt |
Q:
Finding the least busy open wireless network: which language to pick for this weekend project?
I am a web developer (PHP/Javascript) and to increase my skill set, I would like to learn a new language. I have a simple test project in mind for this, so I can learn more about (wireless) networks and Linux, something ... | Finding the least busy open wireless network: which language to pick for this weekend project? | I am a web developer (PHP/Javascript) and to increase my skill set, I would like to learn a new language. I have a simple test project in mind for this, so I can learn more about (wireless) networks and Linux, something I'm interested in as well.
I have specced out my project like this:
Look at all the open wireless n... | [
"My preference is Ruby, and that is because it is my preference. However, there are lots of libraries availble in each language. See:\nhttp://www.scribd.com/doc/56319311/Programming-Wireless-Security-32813\nalso\nWhich of these scripting languages is more appropriate for pen-testing?\n",
"I don't know much abou... | [
2,
0
] | [] | [] | [
"pcap",
"python",
"ruby",
"wireless"
] | stackoverflow_0006765036_pcap_python_ruby_wireless.txt |
Q:
Is there an equivalent to the Google Closure Compiler for Python?
I'm wondering if there is something that will scan through your code and remove any unnecessary functions.
Maybe the Python compiler already does this when it makes .pyc? It'd be nice if there was something that did this at the .py level too.
A:
... | Is there an equivalent to the Google Closure Compiler for Python? | I'm wondering if there is something that will scan through your code and remove any unnecessary functions.
Maybe the Python compiler already does this when it makes .pyc? It'd be nice if there was something that did this at the .py level too.
| [
"No, there's not such a software, because it would be extremely difficult to introspectively understand all the possible branches the code could execute based on different inputs (if you consider metaprogramming, things would become even more complicated).\nWhat you can do is to extrapolate how much / which code ha... | [
0,
0
] | [] | [] | [
"compiler_construction",
"compression",
"python"
] | stackoverflow_0006765231_compiler_construction_compression_python.txt |
Q:
Trying to pull useful info blocks from text file
I'm trying to pull all of the occurrences of a certain table out of a text file using string slices, but it keeps pulling out the first slice over and over.
Perhaps I need a dummy variable for the start and end counts?
result = ''
start = 'start of stuff I want' ... | Trying to pull useful info blocks from text file | I'm trying to pull all of the occurrences of a certain table out of a text file using string slices, but it keeps pulling out the first slice over and over.
Perhaps I need a dummy variable for the start and end counts?
result = ''
start = 'start of stuff I want'
end = 'end of stuff I want'
otn = o.read()
count ... | [
"Try this. It's more python-y and reusable:\ndef extract_delimited_data(data, begin_delimiter, end_delimiter):\n s = data.find(begin_delimiter)\n\n while s != -1:\n e = data.find(end_delimiter, s + len(begin_delimiter))\n\n s += len(begin_delimiter)\n yield data[s:e]\n\n s = data.... | [
2,
1,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0006765502_python_string.txt |
Q:
How to launch multiple other python scripts all together from one and send them arguments?
I've to launch and execute 24 independent python scripts on windows 7. I want that one script launches them all at the same time... without ruling them all (I'm not Sauron) or waiting their ends. I find os.startfile() intere... | How to launch multiple other python scripts all together from one and send them arguments? | I've to launch and execute 24 independent python scripts on windows 7. I want that one script launches them all at the same time... without ruling them all (I'm not Sauron) or waiting their ends. I find os.startfile() interesting for that. But I did not succeed in sending arguments to those 24.
coincoin1.py (one of the... | [
"You may use an indipendent process (multiprocessing.Process) and using two queues to communicate with it (multiprocessing.Queue) one for the input and the other one for the output.\nExample on starting the process:\nimport multiprocessing\n\ndef processWorker(input, result):\n work = input.get()\n ## execute... | [
4,
2,
1
] | [
"Use the call function from the subprocess module (http://docs.python.org/library/subprocess.html#module-subprocess).\nimport subprocess\nsubprocess.call([path, arg1, arg2...])\n\n"
] | [
-1
] | [
"python",
"windows"
] | stackoverflow_0006764189_python_windows.txt |
Q:
Print all properties of an App Engine Model
I'm trying to find a way to easily loop through a Google App Engine (Python) Model and to print out each property and the property name.
This is how I'm trying it, and after some research I realize I can't next variables in each other. Is there a way to do this with fil... | Print all properties of an App Engine Model | I'm trying to find a way to easily loop through a Google App Engine (Python) Model and to print out each property and the property name.
This is how I'm trying it, and after some research I realize I can't next variables in each other. Is there a way to do this with filters or a way to return all of the values of the ... | [
"Take a look at how this to_json method grabs all the property values on a Model instance, it should point you in the right direction.\n",
"Try:\nvars(user1)[property]\n\nSee Built-in Functions.html#vars for a short explanation of how vars returns a dictionary of the instance variables.\n",
"After some more res... | [
2,
1,
1
] | [] | [] | [
"django_templates",
"google_app_engine",
"properties",
"python"
] | stackoverflow_0006754994_django_templates_google_app_engine_properties_python.txt |
Q:
Reverse pretty date format
Is there a way to go from
"1 day ago", "1 week ago", "3 hours ago"
to some date format like "Tue, 19 Jul 2011 10:00:00" using Python?
A:
The answer to this question suggests http://code.google.com/p/parsedatetime/
A:
This example on the pyparsing wiki supports these cases:
today
tom... | Reverse pretty date format | Is there a way to go from
"1 day ago", "1 week ago", "3 hours ago"
to some date format like "Tue, 19 Jul 2011 10:00:00" using Python?
| [
"The answer to this question suggests http://code.google.com/p/parsedatetime/\n",
"This example on the pyparsing wiki supports these cases:\ntoday\ntomorrow\nyesterday\nin a couple of days\na couple of days from now\na couple of days from today\nin a day\n3 days ago\n3 days from now\na day ago\nin 2 weeks\nin 3 d... | [
4,
1,
0
] | [] | [] | [
"date",
"datetime",
"python"
] | stackoverflow_0006765619_date_datetime_python.txt |
Q:
Retrieve same column data from two different rows with one sqlite3 query?
I have a table profiles containing people with a primary key login_hash and a bunch of other fields (for example, age). Another table, msgs, contains src and dest fields, both of which are foreign keys to login_hash from the profiles table. ... | Retrieve same column data from two different rows with one sqlite3 query? | I have a table profiles containing people with a primary key login_hash and a bunch of other fields (for example, age). Another table, msgs, contains src and dest fields, both of which are foreign keys to login_hash from the profiles table. How do I retrieve the ages of the src and dests in one sqlite3 (from Python) qu... | [
"You can use two inner joins:\nSELECT m.*, p1.*, p2.*\n FROM msgs m\nINNER JOIN profiles p1 ON m.src = p1.login_hash\nINNER JOIN profiles p2 ON m.dest = p2.login_hash\n\n"
] | [
1
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0006765886_python_sqlite.txt |
Q:
How can I access the USB on my iPhone via Python / C?
I was wondering how to get access to the USB (kind of /dev/usb) on my jailbroken iPhone,
and how could I listen what is going on ( when I plug a device on my iPhone ) for a debug purpose (because I try to create a device that I could connect directly on my iPh... | How can I access the USB on my iPhone via Python / C? | I was wondering how to get access to the USB (kind of /dev/usb) on my jailbroken iPhone,
and how could I listen what is going on ( when I plug a device on my iPhone ) for a debug purpose (because I try to create a device that I could connect directly on my iPhone).
Thanks.
| [
"You need to be a member of the MFi Program to get access to development information for iOS Accessories.\n"
] | [
0
] | [] | [] | [
"ios",
"iphone",
"jailbreak",
"objective_c",
"python"
] | stackoverflow_0006760748_ios_iphone_jailbreak_objective_c_python.txt |
Q:
Popen.stdin with multithreading problem, does not work
I am trying to run a shell from my python program.
I have used a mltithreaded approach where an input from user is accepted and should be executed via the shell.
Everything seems right, except that the program execution just doesn't take place beyond stdin.
I ... | Popen.stdin with multithreading problem, does not work | I am trying to run a shell from my python program.
I have used a mltithreaded approach where an input from user is accepted and should be executed via the shell.
Everything seems right, except that the program execution just doesn't take place beyond stdin.
I am not sure if there is something wrong with the way I have ... | [
"could it be that it keeps hanging on process.stdout.readlines()? Perhaps no line ending can be found. Try stdout.read(1) to read one character and see what happens.\n",
"Minor things: \nIt's process.poll() not process.pole(). \nInstead of\n for i in range(nfuncs):\n t=MyThread(funcs[i],(command,output))\n ... | [
0,
0
] | [] | [] | [
"multithreading",
"python",
"stdin"
] | stackoverflow_0006765765_multithreading_python_stdin.txt |
Q:
Error while using the c code in python
I am using the following code which I have found online
def c_int_binary_search(seq,t):
# do a little type checking in Python
assert(type(t) == type(1))
assert(type(seq) == type([]))
# now the C code
code = """
#line 29 "binary_search.py"
i... | Error while using the c code in python | I am using the following code which I have found online
def c_int_binary_search(seq,t):
# do a little type checking in Python
assert(type(t) == type(1))
assert(type(seq) == type([]))
# now the C code
code = """
#line 29 "binary_search.py"
int val, m, min = 0;
int max = seq.len... | [
"That example is out of date, the Py namespace doesn't exist in recent versions.\nSome distributions ship the examples (that should be kept up to date) with scipy. On my machine, there's this:\n/usr/lib64/python2.7/site-packages/scipy/weave/examples/binary_search.py\n\nIf you don't have something like that, you can... | [
5
] | [] | [] | [
"c",
"python",
"scipy"
] | stackoverflow_0006764512_c_python_scipy.txt |
Q:
How to use a auth token from Docservice on a spreadsheetservice object
I am initially loggin into a google account using the gdata.docs.service.Docservice
At some point, I would like to manipulate a spreadsheet using the gdata.spreadsheet.service.SpreadsheetsService
I don't want to have to re-login with the new sp... | How to use a auth token from Docservice on a spreadsheetservice object | I am initially loggin into a google account using the gdata.docs.service.Docservice
At some point, I would like to manipulate a spreadsheet using the gdata.spreadsheet.service.SpreadsheetsService
I don't want to have to re-login with the new spreadsheet object, so how do I pass authentication over to the newly created ... | [
"When you request a token using ClientLogin, the service class appends an extra query param called service= to your POST request. Each service is uniquely identified.\n\nDocs: service=writely\nSpreadsheet: service=wise\n\nThe Auth token you receive is should be valid for only that particular service.\nThat aside, y... | [
1
] | [] | [] | [
"authentication",
"gdata",
"google_docs",
"google_docs_api",
"python"
] | stackoverflow_0006417524_authentication_gdata_google_docs_google_docs_api_python.txt |
Q:
How do I close a loading screen right when the other thread is finished in Python using Tk?
I have a Python GUI that uses Tkinter. I have to SSH into another place to get data. I start a new thread to do this so that the GUI doesn't hang. During this time, I want to pop up a screen that lets the user know it is lo... | How do I close a loading screen right when the other thread is finished in Python using Tk? | I have a Python GUI that uses Tkinter. I have to SSH into another place to get data. I start a new thread to do this so that the GUI doesn't hang. During this time, I want to pop up a screen that lets the user know it is loading. Once the program is finished getting the data, I want to close the loading screen. What mu... | [
"Have your thread set a flag when it is done. Have the GUI periodically check for that flag and dismiss the window when it is set.\nYou can check for the flag by creating a function that checks for the flag, and if it's not set it uses after to have itself run again a few hundred ms later. The window won't go away ... | [
0
] | [] | [] | [
"consumer",
"multithreading",
"producer",
"python",
"user_interface"
] | stackoverflow_0006764217_consumer_multithreading_producer_python_user_interface.txt |
Q:
What is the corresponding function for corrmtx (in MATLAB) in Python?
I'm translating some code from MATLAB to Python and I'm stuck with the corrmtx() MATLAB function. Is there any similar function in Python, or how could I replace it?
A:
The spectrum package has such a function.
A:
How about:
http://docs.scip... | What is the corresponding function for corrmtx (in MATLAB) in Python? | I'm translating some code from MATLAB to Python and I'm stuck with the corrmtx() MATLAB function. Is there any similar function in Python, or how could I replace it?
| [
"The spectrum package has such a function.\n",
"How about:\nhttp://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.toeplitz.html\nThe matlab docs for corrmtx state:\n\nX = corrmtx(x,m) returns an (n+m)-by-(m+1) rectangular Toeplitz matrix\n X, such that X'X is a (biased) estimate of the autocorrelation... | [
2,
1,
0
] | [] | [] | [
"matlab",
"python"
] | stackoverflow_0006766471_matlab_python.txt |
Q:
Root html (/index.html) can't be fetched. Returns 404
The dir structure is-
MyApplication (Project Dir)
-static
--inside static, I got different dirs containing images, css, htmls, etc
-some other dirs
-app.yaml
-index.py
-index.html
The content of app.yaml is-
application: MyApplicationID
version: 1
runtime:... | Root html (/index.html) can't be fetched. Returns 404 | The dir structure is-
MyApplication (Project Dir)
-static
--inside static, I got different dirs containing images, css, htmls, etc
-some other dirs
-app.yaml
-index.py
-index.html
The content of app.yaml is-
application: MyApplicationID
version: 1
runtime: python
api_version: 1
handlers:
- url: /favicon.ico
st... | [
"Requests for \"/index.html\" will be handled by index.py, given the contents of your app.yaml. Presumably you don't have a handler for \"/index.html\" in that file. \nIf you want index.html served for requests for \"/index.html\", add a mapping to app.yaml that matches the URL (or, just redirect to \"/\" instead o... | [
1,
1
] | [] | [] | [
"google_app_engine",
"http_status_code_404",
"python"
] | stackoverflow_0006766599_google_app_engine_http_status_code_404_python.txt |
Q:
Why is neither the executable nor its launcher script found despite being added to PATH
I followed the instruction to install pygmentize in order to use syntax highlight in Latex environment, however TexMaker always produces an error says pygmentize is not found. I then tested to run the .cmd file itself using com... | Why is neither the executable nor its launcher script found despite being added to PATH | I followed the instruction to install pygmentize in order to use syntax highlight in Latex environment, however TexMaker always produces an error says pygmentize is not found. I then tested to run the .cmd file itself using command prompt and the system says:
C:\Python27\Scripts>pygmentize.cmd
C:\Python27\python.exe: c... | [
"cmd.exe will prefer .exe to .cmd when choosing which pygmentize to execute, all else begin equal. python.exe will perform no magic at all and will not know what to make of C:\\Python27\\Scripts\\pygmentize unless a file with that exact name exists.\n"
] | [
1
] | [] | [] | [
"command_line",
"pygmentize",
"python",
"texmaker",
"windows"
] | stackoverflow_0006764979_command_line_pygmentize_python_texmaker_windows.txt |
Q:
Need to take average of long, strangely formatted set of data in Python
So I have a large set of data that looks like this
[('ART', [100, 234, 830, 304]), ('MATH', [600, 1400, 300, 340]), ('HISTORY', [2010, 300, 400, 600])]
How would I turn this into a set of data that I can average the numbers inside of and t... | Need to take average of long, strangely formatted set of data in Python | So I have a large set of data that looks like this
[('ART', [100, 234, 830, 304]), ('MATH', [600, 1400, 300, 340]), ('HISTORY', [2010, 300, 400, 600])]
How would I turn this into a set of data that I can average the numbers inside of and then sort? I'm using Python 2.7
| [
"for:\ninput = [('ART', [100, 234, 830, 304]), \n ('MATH', [600, 1400, 300, 340]), \n ('HISTORY', [2010, 300, 400, 600])]\n\nthis:\nprint sorted( ( (k,sum(v)/len(v)) for k,v in input ), key=lambda t: t[1] )\n\nprints:\n[('ART', 367), ('MATH', 660), ('HISTORY', 827)]\n\n"
] | [
6
] | [] | [] | [
"average",
"list",
"python",
"sorting",
"tuples"
] | stackoverflow_0006766794_average_list_python_sorting_tuples.txt |
Q:
Python PIL Image.tostring()
I'm new to Python and PIL. I am trying to follow code samples on how to load an image into to Python through PIL and then draw its pixels using openGL. Here are some line of the code:
from Image import *
im = open("gloves200.bmp")
pBits = im.convert('RGBA').tostring()
.....
glDrawPixe... | Python PIL Image.tostring() | I'm new to Python and PIL. I am trying to follow code samples on how to load an image into to Python through PIL and then draw its pixels using openGL. Here are some line of the code:
from Image import *
im = open("gloves200.bmp")
pBits = im.convert('RGBA').tostring()
.....
glDrawPixels(200, 200, GL_RGBA, GL_UNSIGNED... | [
"I think you were close. Try:\npBits = im.convert(\"RGBA\").tostring(\"raw\", \"RGBA\")\n\nThe image first has to be converted to RGBA mode in order for the RGBA rawmode packer to be available (see Pack.c in libimaging). You can check that len(pBits) == im.size[0]*im.size[1]*4, which is 200x200x4 = 160,000 bytes fo... | [
9,
1,
0
] | [] | [] | [
"pyopengl",
"python",
"python_imaging_library"
] | stackoverflow_0006756820_pyopengl_python_python_imaging_library.txt |
Q:
jpype+pdfbox class not found
I'm attempting to use JPype to call Apache Pdfbox from Python, and am having some difficulty actually importing the classes. It doesn't seem to be able to read them from the jar file in the class path.
from jpype import java, startJVM, shutdownJVM, JPackage, JClass, getDefaultJVMPath, ... | jpype+pdfbox class not found | I'm attempting to use JPype to call Apache Pdfbox from Python, and am having some difficulty actually importing the classes. It doesn't seem to be able to read them from the jar file in the class path.
from jpype import java, startJVM, shutdownJVM, JPackage, JClass, getDefaultJVMPath, nio
import sys, os, codecs
pdfbox... | [
"I figured it out. Three additional jars need to be added to the class path: fontbox-x.x.x.jar, jempbox-x.x.x.jar, and commons-logging.jar. \n"
] | [
2
] | [] | [] | [
"java",
"pdfbox",
"python"
] | stackoverflow_0006709187_java_pdfbox_python.txt |
Q:
python `in` keyword as a function used in a filter
is it possible to use the python keyword in in a filter? I know that binary, unary, assignment operations are equivalent to a function call.
such as
''!=3
is the same as
''.__ne__(3)
is there an analogous thing for the in function?
I want to do something like th... | python `in` keyword as a function used in a filter | is it possible to use the python keyword in in a filter? I know that binary, unary, assignment operations are equivalent to a function call.
such as
''!=3
is the same as
''.__ne__(3)
is there an analogous thing for the in function?
I want to do something like this. ..
filter( list1.__in__, list2 )
I guess this can b... | [
"filter( list1.__contains__, list2 )\n\nis more cleanly written as:\n[ v for v in list2 if v in list1 ]\n\nand to show equivalence:\n>>> list1 = [2, 4, 6, 8, 10]\n>>> list2 = [1, 2, 3, 4, 5]\n>>> [ v for v in list2 if v in list1 ]\n[2, 4]\n\n",
"You are looking for __contains__.\n>>> [1, 2, 3].__contains__(2)\nTr... | [
15,
8,
4,
2
] | [] | [] | [
"keyword",
"python"
] | stackoverflow_0006766243_keyword_python.txt |
Q:
How to include class from another file(in another folder) - python
I have a python file in the location 'lib/lib_add_participant.py'.And I declared a class in the file.
Now I want to call the class functions from the file call_participant.py.
I tried this code from lib/lib_add_participant.py import LibAddParti... | How to include class from another file(in another folder) - python | I have a python file in the location 'lib/lib_add_participant.py'.And I declared a class in the file.
Now I want to call the class functions from the file call_participant.py.
I tried this code from lib/lib_add_participant.py import LibAddParticipant
Its not worked.Please correct me(I am coming from Ruby).
| [
"If your file structure is as follows:\nmyproject/\n __init__.py\n call_participant.py\n lib/\n __init__.py\n lib_add_participant.py\n\nIn this case, your __init__.py files can be empty, if you like (or they can define any number of things - see this fine answer from Alex Martelli for more de... | [
4,
0
] | [] | [] | [
"class",
"python",
"python_3.x"
] | stackoverflow_0006767007_class_python_python_3.x.txt |
Q:
Python and excel reading files problem
I am sorry if this is a silly question but I have been working on this for hours and I cannot make it work. Please help!
I have a .txt file that originated from Excel. The file contains strings and numbers but I am only interested in the numbers, which is why I skip the first... | Python and excel reading files problem | I am sorry if this is a silly question but I have been working on this for hours and I cannot make it work. Please help!
I have a .txt file that originated from Excel. The file contains strings and numbers but I am only interested in the numbers, which is why I skip the first line and I only read from column 2 on.
f... | [
"convert the numbers as you read them, before creating the array:\ninfile = open('europenewMatrix.txt','r')\ninfile.readline() # skip the first line\nnumbers = []\nfor line in infile:\n numbers.append([int(val) for val in line.split(',')[2:]])\ninfile.close()\ntravelMat = array(numbers)\n\n",
"If you're workin... | [
2,
1,
0
] | [] | [] | [
"floating_point",
"python",
"string"
] | stackoverflow_0006730467_floating_point_python_string.txt |
Q:
What is the best way to give people your python program
I want to give my python program to some people, and they will run this in Linux. What is the best way to do this ? Is it better to give them every script - I have 5 of them, or make it into an installer like *.deb
Thank you.
A:
just tar (zip) it and send i... | What is the best way to give people your python program | I want to give my python program to some people, and they will run this in Linux. What is the best way to do this ? Is it better to give them every script - I have 5 of them, or make it into an installer like *.deb
Thank you.
| [
"just tar (zip) it and send it off, .deb is debian based distro's only and tedious for just some scripts:\ntar -pczf myscript.tar.gz /path/to/dir/with/scripts\n\nfor a bonus add a requirements.txt with the required external dependancies if you have external dependancies; this way people can install the requirements... | [
4,
0,
0,
0
] | [] | [] | [
"linux",
"packaging",
"python"
] | stackoverflow_0006395657_linux_packaging_python.txt |
Q:
Pythonwin - print function not working
I'm running pywin32 build 216.1 and am having trouble using the simple print function - for example:
>>> print 'Hello!'
should return:
Hello!
but instead I get:
Traceback ( File "<interactive input>", line 1
print 'Hello!'
^
SyntaxError: invalid s... | Pythonwin - print function not working | I'm running pywin32 build 216.1 and am having trouble using the simple print function - for example:
>>> print 'Hello!'
should return:
Hello!
but instead I get:
Traceback ( File "<interactive input>", line 1
print 'Hello!'
^
SyntaxError: invalid syntax
It doesn't matter what I try and use ... | [
"In Python 3, print is a function, not a statement. Call it like:\nprint(\"Hello!\")\n\n"
] | [
20
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0006767669_python_python_3.x.txt |
Q:
Calculation - numpy python bug
I am using NumPy to do some calculation on finding the Y intercept, through an Aperture between a big box and a small box. I have over 100.000 particles in the big box, and around 1000 in the small one. And it's taking a lot of time to do so. All the self.YD, self.XD are very large ... | Calculation - numpy python bug | I am using NumPy to do some calculation on finding the Y intercept, through an Aperture between a big box and a small box. I have over 100.000 particles in the big box, and around 1000 in the small one. And it's taking a lot of time to do so. All the self.YD, self.XD are very large arrays that i'm multiplying.
PS: The... | [
"Perhaps I have got the wrong end of the stick but in Numpy you can perform vectorised calculations. Remove the enclosing while loop and just run this ...\nYD_zero = self.oldYD - ((self.oldYD - self.YD) * self.oldXD) / (self.oldXD - self.XD)\nIt should be much faster.\nUpdate: Iterative root finding using the Newto... | [
3,
2,
0
] | [] | [] | [
"bug_tracking",
"matlab",
"numpy",
"python"
] | stackoverflow_0006765001_bug_tracking_matlab_numpy_python.txt |
Q:
How to get process status using pid?
If I known a process's pid, how can I tell if the process is a zombie using Python ?
A:
You could use a the status feature from psutil:
import psutil
p = psutil.Process(the_pid_you_want)
if p.status == psutil.STATUS_ZOMBIE:
....
A:
here's a quick hack using procfs (ass... | How to get process status using pid? | If I known a process's pid, how can I tell if the process is a zombie using Python ?
| [
"You could use a the status feature from psutil:\nimport psutil\np = psutil.Process(the_pid_you_want)\nif p.status == psutil.STATUS_ZOMBIE:\n ....\n\n",
"here's a quick hack using procfs (assuming you're using Linux):\ndef procStatus(pid):\n for line in open(\"/proc/%d/status\" % pid).readlines():\n ... | [
15,
15
] | [] | [] | [
"python"
] | stackoverflow_0006767649_python.txt |
Q:
NLTK - when to normalize the text?
I've finished gathering my data I plan to use for my corpus, but I'm a bit confused about whether I should normalize the text. I plan to tag & chunk the corpus in the future. Some of NLTK's corpora are all lower case and others aren't.
Can anyone shed some light on this subject, ... | NLTK - when to normalize the text? | I've finished gathering my data I plan to use for my corpus, but I'm a bit confused about whether I should normalize the text. I plan to tag & chunk the corpus in the future. Some of NLTK's corpora are all lower case and others aren't.
Can anyone shed some light on this subject, please?
| [
"By \"normalize\" do you just mean making everything lowercase? \nThe decision about whether to lowercase everything is really dependent of what you plan to do. For some purposes, lowercasing everything is better because it lowers the sparsity of the data (uppercase words are rarer and might confuse the system un... | [
9
] | [] | [] | [
"nlp",
"nltk",
"python"
] | stackoverflow_0006767770_nlp_nltk_python.txt |
Q:
How do I convert images (PSD, AI and EPS) to PDF?
Customers of my Django site can upload a print design in: PDF, PSD, AI and EPS. If the filetype they upload is not PDF I want to convert it to PDF.
So my question is: How do I convert Photoshop, Illustrator and CorelDraw files to PDF (programmatically)?
I tried Uni... | How do I convert images (PSD, AI and EPS) to PDF? | Customers of my Django site can upload a print design in: PDF, PSD, AI and EPS. If the filetype they upload is not PDF I want to convert it to PDF.
So my question is: How do I convert Photoshop, Illustrator and CorelDraw files to PDF (programmatically)?
I tried UniConvertor but it: does not support PSD, distorted my AI... | [
"One solution that does support all of those formats, as well as exporting to PDF, is Gimp. In addition, you can script Gimp with Python. \nhttp://www.gimp.org/docs/python/index.html\nIt sounds like you can install arbitrary software on the Django server, so as long as you have access to the X server (GUI) this is ... | [
6,
3
] | [] | [] | [
"django",
"gimp",
"image_conversion",
"pdf",
"python"
] | stackoverflow_0006767509_django_gimp_image_conversion_pdf_python.txt |
Q:
Redirect to a Page on 404 Error
Is it possible to redirect to a page on 404 and 500 instead of constructing a custom response? I tried-
class NotFoundPageHandler(webapp.RequestHandler):
def get(self):
#if 400
self.redirect('error/notfound.html')
#if 500 how to check
def main():... | Redirect to a Page on 404 Error | Is it possible to redirect to a page on 404 and 500 instead of constructing a custom response? I tried-
class NotFoundPageHandler(webapp.RequestHandler):
def get(self):
#if 400
self.redirect('error/notfound.html')
#if 500 how to check
def main():
application = webapp.WSGIApplica... | [
"You don't want to redirect. What you want is a custom error page. \nhttp://code.google.com/appengine/docs/python/config/appconfig.html#Custom_Error_Responses\nerror_handlers:\n - file: default_error.html\n\n - error_code: over_quota\n file: over_quota.html\n\n- error_code: 404 or - error_code: 500 should work... | [
1
] | [] | [] | [
"google_app_engine",
"http_status_code_404",
"python"
] | stackoverflow_0006767985_google_app_engine_http_status_code_404_python.txt |
Q:
Beautiful Soup extract() problem
GENERAL XML OUTLINE:
<dasbhoards>
<dashboard name="S1>
<repository-location derived-from='http://dataviz.win.compete.com/workbooks/OTCSurvey_06_15_11_16_54/RT4?rev=' id='RT4' path='/workbooks/RetailFootwear' revision='' />
<style>
</style>
<zones>
<zone h='9... | Beautiful Soup extract() problem | GENERAL XML OUTLINE:
<dasbhoards>
<dashboard name="S1>
<repository-location derived-from='http://dataviz.win.compete.com/workbooks/OTCSurvey_06_15_11_16_54/RT4?rev=' id='RT4' path='/workbooks/RetailFootwear' revision='' />
<style>
</style>
<zones>
<zone h='92975' id='4' param='horz' type='layout... | [
"Your code looks alright. It is impossible to tell why you don't get the expected result without seeing your XML file.\nYou might want to add a debug line to your loop like, such as:\nfor child in d:\n name = child.get('name', '').lower()\n print 'Name: \"{0}\"; Equal to \"s1\": {1}'.format(name, name == 's1... | [
2,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0006764149_beautifulsoup_python.txt |
Q:
Python to insert a line at a random location of a large text file with condition
I have a 30000 plus line text file that I need to modify using Python. What I want to do is the following:
There is a specific keyword1 in the file that has a certain device name following the keyword1. I need to identify keyword1 ... | Python to insert a line at a random location of a large text file with condition | I have a 30000 plus line text file that I need to modify using Python. What I want to do is the following:
There is a specific keyword1 in the file that has a certain device name following the keyword1. I need to identify keyword1 in all lines and retrieve all device names, then store them in a list for later use
I ... | [
"I ... think you should probably approach it with something like this:\nwith open('input.txt') as fhi, open('output.txt', 'w') as fho:\n for line in fhi:\n if not pattern.search(line):\n # if there is no match write the line to the output file and proceed.\n fho.write(line)\n continue\n\n # if... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006767958_python.txt |
Q:
Key to maxima of dictionary in python
I have a dictionary, "scores", of integers and I want to find the key(s) of the highest value. I used this code:
key = max(scores, key=scores.get)
however, this only gives back one key. How does this deal with ties in highest value? I only get one number back. Which is it in ... | Key to maxima of dictionary in python | I have a dictionary, "scores", of integers and I want to find the key(s) of the highest value. I used this code:
key = max(scores, key=scores.get)
however, this only gives back one key. How does this deal with ties in highest value? I only get one number back. Which is it in the case of a tie? How can I get all the ke... | [
"You could run the following, for example:\nmax_value = max(scores.values())\nkeys = [ i for (i,v) in scores.iteritems() if v == max_value ]\n\n\"keys\" would now hold all the keys which correspond to the maximum value.\n",
"The max function returns one value. You could use something like this:\nkey = max(scores,... | [
9,
1,
1,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0006768466_dictionary_python.txt |
Q:
Python - Printing Hex from a file
I have the following code:
code1 = ("\xd9\xf6\xd9\x74\x24\xf4\x5f\x29\xc9\xbd\x69\xd1\xbb\x18\xb1")
print code1
code2 = open("code.txt", 'rb').read()
print code2
code1 output:
�צ�t$פ_)�½i�»±
code2 output:
"\xd9\xf6\xd9\x74\x24\xf4\x5f\x29\xc9\xbd\x69\xd1\xbb\x18\xb1"
I need co... | Python - Printing Hex from a file | I have the following code:
code1 = ("\xd9\xf6\xd9\x74\x24\xf4\x5f\x29\xc9\xbd\x69\xd1\xbb\x18\xb1")
print code1
code2 = open("code.txt", 'rb').read()
print code2
code1 output:
�צ�t$פ_)�½i�»±
code2 output:
"\xd9\xf6\xd9\x74\x24\xf4\x5f\x29\xc9\xbd\x69\xd1\xbb\x18\xb1"
I need code2 (which I read from a file) to have ... | [
"To interpret a sequence of characters such as\nIn [125]: list(code2[:8])\nOut[125]: ['\\\\', 'x', 'd', '9', '\\\\', 'x', 'f', '6']\n\nas Python would a string with escaped characters, such as\nIn [132]: list('\\xd9\\xf6')\nOut[132]: ['\\xd9', '\\xf6']\n\nuse .decode('string_escape'):\nIn [122]: code2.decode('strin... | [
5,
3
] | [
"print eval(code2) should do the job.\n"
] | [
-3
] | [
"file",
"hex",
"printing",
"python"
] | stackoverflow_0006768246_file_hex_printing_python.txt |
Q:
How to apply a Python timings decorator to a method within a class
I am trying to apply the timing decorator described here to a method within a class instead of a standalone method. How should this be done?
I am getting this error:
TypeError: unbound method wrapper() must be called with SomeClass instance as
fir... | How to apply a Python timings decorator to a method within a class | I am trying to apply the timing decorator described here to a method within a class instead of a standalone method. How should this be done?
I am getting this error:
TypeError: unbound method wrapper() must be called with SomeClass instance as
first argument (got float instance instead)
| [
"EDIT\nThanks to your comment, I think I know what the problem is. This doesn't work:\nclass A:\n\n @timings\n @classmethod\n def a(cls, x):\n print(x)\n\nA.a(2)\n\nfor exactly the reason you said.\n TypeError: unbound method wrapper() must be called with A instance as first argument (got int inst... | [
1
] | [] | [] | [
"decorator",
"python",
"timing"
] | stackoverflow_0006764468_decorator_python_timing.txt |
Q:
python BeautifulSoup find span id name without using string\re methods
I'm trying to get the id name of my span tags.
<td vAlign="top" colSpan="2"><IMG height="25" src="images/spacer.gif" width="1"><br>
<!--start table details-->
<table cellSpacing="1" cellPadding="5" width="100%" bgColor="#a18c42" border=... | python BeautifulSoup find span id name without using string\re methods | I'm trying to get the id name of my span tags.
<td vAlign="top" colSpan="2"><IMG height="25" src="images/spacer.gif" width="1"><br>
<!--start table details-->
<table cellSpacing="1" cellPadding="5" width="100%" bgColor="#a18c42" border="0" id="compDetails">
<tr bgColor="white">
<td class="ro... | [
"You can access the attributes of tags by looking up the tag as a dict, keyed by tag name:\nfor span in spans:\n print span['id']\n\ngives what you want: lblCompanyNumber lblCompanyNameHeb lblCompanyNameEn lblStatus lblCorporationType lblGovCompanyType lblLimitType...\n\nI'm also having trouble saving the spans ... | [
1,
1
] | [] | [] | [
"beautifulsoup",
"character_encoding",
"encoding",
"html",
"python"
] | stackoverflow_0006768056_beautifulsoup_character_encoding_encoding_html_python.txt |
Q:
pygtkscintilla auto indent
I'm trying to translate the c++ code and i can't work out what "char linebuf[1000]" is, can some kind sole translate this to python or explain what linebuf is. Thanks! :) Taken from http://www.scintilla.org/ScintillaUsage.html
if (ch == '\r' || ch == '\n') {
char linebuf[10... | pygtkscintilla auto indent | I'm trying to translate the c++ code and i can't work out what "char linebuf[1000]" is, can some kind sole translate this to python or explain what linebuf is. Thanks! :) Taken from http://www.scintilla.org/ScintillaUsage.html
if (ch == '\r' || ch == '\n') {
char linebuf[1000];
int curLine = GetCu... | [
"It is a buffer for a line of input text, of type char[1000], i.e. an array of 1000 char elements (which are actually bytes, because C++ is based upon C, which in turn predates the whole idea of character encodings).\nIf we really wanted a literal translation of the algorithm, the closest fit in Python is probably ... | [
0
] | [] | [] | [
"c++",
"gtk",
"pygtk",
"python",
"scintilla"
] | stackoverflow_0006769068_c++_gtk_pygtk_python_scintilla.txt |
Q:
A replacement for python's httplib?
I have a python client which pushes a great deal of data through the standard library's httlib. Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using.
Could I improve performance by replacing httplib with somethi... | A replacement for python's httplib? | I have a python client which pushes a great deal of data through the standard library's httlib. Users are complainging that the application is slow. I suspect that this may be partly due to the HTTP client I am using.
Could I improve performance by replacing httplib with something else?
I've seen that twisted offers a... | [
"Often when I've had performance problems with httplib, the problem hasn't been with the httplib itself, but with how I'm using it. Here are a few common pitfalls:\n(1) Don't make a new TCP connection for every web request. If you are making lots of request to the same server, instead of this pattern: \n\n c... | [
22,
20,
5,
2,
1,
1,
0,
0
] | [] | [] | [
"curl",
"http",
"python",
"twisted"
] | stackoverflow_0000508817_curl_http_python_twisted.txt |
Q:
Unexpected end of Pattern : Python Regex
When I use the following python regex to perform the functionality described below, I get the error Unexpected end of Pattern.
Regex:
modified=re.sub(r'^(?i)((?:(?!http://)(?!testing[0-9])(?!example[0-9]).)*?)(?-i)
(CODE[0-9]{3})(?!</a>)',r'<a href="http://productcode/\g<1>... | Unexpected end of Pattern : Python Regex | When I use the following python regex to perform the functionality described below, I get the error Unexpected end of Pattern.
Regex:
modified=re.sub(r'^(?i)((?:(?!http://)(?!testing[0-9])(?!example[0-9]).)*?)(?-i)
(CODE[0-9]{3})(?!</a>)',r'<a href="http://productcode/\g<1>">\g<1></a>',input)
Purpose of this regex:
IN... | [
"Your main problem is the (?-i) thingy which is wishful thinking as far as Python 2.7 and 3.2 are concerned. For more details, see below.\nimport re\n# modified=re.sub(r'^(?i)((?:(?!http://)(?!testing[0-9])(?!example[0-9]).)*?)(?-i)\n# (CODE[0-9]{3})(?!</a>)',r'<a href=\"http://productcode/\\g<1>\">\\g<1></a>',inpu... | [
5,
2,
0,
0
] | [] | [] | [
"pattern_matching",
"python",
"regex"
] | stackoverflow_0006767954_pattern_matching_python_regex.txt |
Q:
argument of type 'NoneType' is not iterable
I am trying to open a directory that contains a series of XML's in one specific directory.
In the following code, I am iterating through each XML document, and I'm setting some "if statements" to read the text in the XML, find keywords and replace them and then write a n... | argument of type 'NoneType' is not iterable | I am trying to open a directory that contains a series of XML's in one specific directory.
In the following code, I am iterating through each XML document, and I'm setting some "if statements" to read the text in the XML, find keywords and replace them and then write a new file to a new location.
I am getting the follo... | [
"You will find that there are many elements in an xml document which contain no character data (i.e. text). One of the nice things about python is that None is false in a conditional, coupling that with knowledge of how conditional statements short circuit means that there's a really simple solution to your problem... | [
20,
1
] | [] | [] | [
"elementtree",
"loops",
"python",
"xml"
] | stackoverflow_0006769196_elementtree_loops_python_xml.txt |
Q:
Python Algorithm Challenge?
I have a python function (call it myFunction) that gets as input a list of numbers, and, following a complex calculation, returns back the result of the calculation (which is a number).
The function looks like this:
def myFunction( listNumbers ):
# initialize the result of the calcu... | Python Algorithm Challenge? | I have a python function (call it myFunction) that gets as input a list of numbers, and, following a complex calculation, returns back the result of the calculation (which is a number).
The function looks like this:
def myFunction( listNumbers ):
# initialize the result of the calculation
calcResult = 0
# ... | [
"You could use a generator as an input. The generator will only return when there is data available to process.\nUpdate: thanks for the brilliant comment, I wanted to remove this entry :)\nclass lazylist(object):\n def __init__(self):\n self.cnt = 0\n self.length = 5000000\n\n def __iter__(self)... | [
10,
5,
4,
1,
1,
1,
1,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0006769315_algorithm_python.txt |
Q:
Can i do an order_by on day in month?
I am trying to create a list of birth days, ordered by the dates, my query set is:
birth_days = get_list_or_404(UserProfile.objects.order_by('-birthDate'), birthDate__month=datetime.datetime.now().month)
How can i get the list ordered by the day in month so the birth days lis... | Can i do an order_by on day in month? | I am trying to create a list of birth days, ordered by the dates, my query set is:
birth_days = get_list_or_404(UserProfile.objects.order_by('-birthDate'), birthDate__month=datetime.datetime.now().month)
How can i get the list ordered by the day in month so the birth days list will be ordered, right now it is ordered ... | [
"You can extract the day as an \"extra\" field and then sort on that, for example:\nUserProfile.objects.select(extra={'birth_day': 'extract(day from birthDate)'}).order_by('-birth_day')\n\nThis should work with PostgreSQL at least.\n"
] | [
2
] | [] | [] | [
"django",
"django_queryset",
"django_views",
"python"
] | stackoverflow_0006769502_django_django_queryset_django_views_python.txt |
Q:
executing a python script on windows using java Runtime.exec
I have a python script that runs on windows and uses win32 extensions and WMI to get some information. If I run the script using the command line, it executes perfectly. But, if I try to run the same script using java Runtime.exec("python myscript.py") i... | executing a python script on windows using java Runtime.exec | I have a python script that runs on windows and uses win32 extensions and WMI to get some information. If I run the script using the command line, it executes perfectly. But, if I try to run the same script using java Runtime.exec("python myscript.py") it seems to get blocked on the waitFor(). The code is like this:
Pr... | [
"One likely reason is that your IO buffers are full and need to be flushed, so try flushing both stdout and stderr from your Process in the java code (example code).\nAlternatively, you could try redirecting all output to NUL or a text file with one of the following arguments to exec:\ncmd.exe /c python myscript.py... | [
3
] | [] | [] | [
"java",
"python",
"wmi"
] | stackoverflow_0006769565_java_python_wmi.txt |
Q:
Consume SOAP webservices using escaped xml as attribute
I am using suds to consume SOAP web services like this way:
from suds.client import Client
url = "http://www.example.com?wsdl"
client = Client(url)
client.service.example(xml_argument)
If I call the method using this xml works:
<?xml version="1.0" encoding="... | Consume SOAP webservices using escaped xml as attribute | I am using suds to consume SOAP web services like this way:
from suds.client import Client
url = "http://www.example.com?wsdl"
client = Client(url)
client.service.example(xml_argument)
If I call the method using this xml works:
<?xml version="1.0" encoding="UTF-8"?><a><b description="Foo Bar"></b></a>
But If I add a ... | [
"Mine is mostly a guess, but the error you are quoting seems to be generated from the XML well-formedness checker on the machine providing the service.\nIt seems that on that side of the cable they are getting something like:\n<a><b description=\"Foo\" Bar\"></b></a>\n\n(" converted to \") and thus they are te... | [
1
] | [] | [] | [
"python",
"soap",
"suds",
"wsdl",
"xml"
] | stackoverflow_0006769484_python_soap_suds_wsdl_xml.txt |
Q:
How to avoid packet loss on server application restart?
A typical situation with a server/web application is that the application needs to be shut down and restarted to implement an upgrade.
What are the possible/common schemes (and available software) to avoid losing data that clients sent to the server during th... | How to avoid packet loss on server application restart? | A typical situation with a server/web application is that the application needs to be shut down and restarted to implement an upgrade.
What are the possible/common schemes (and available software) to avoid losing data that clients sent to the server during the short time the application was gone?
An example scheme that... | [
"To avoid this, have multiple application servers behind a load balancer. Before bringing one down, ensure the load balancer is not sending it new clients. Bring it down, traffic will go to the other applications servers, and when it comes back up traffic will begin getting sent to it again.\nIf you have only one a... | [
3
] | [] | [] | [
"linux",
"network_programming",
"python",
"tcp",
"web_services"
] | stackoverflow_0006769405_linux_network_programming_python_tcp_web_services.txt |
Q:
Scoping rules and threads
This is the program that works (I am able to hear the text to speech in action):
import pyttsx
import threading
def saythread(location, text):
engine = pyttsx.init()
engine.say(text)
engine.runAndWait()
e = (1, "please work, oh my god")
t = threading.Thread(target=sayt... | Scoping rules and threads | This is the program that works (I am able to hear the text to speech in action):
import pyttsx
import threading
def saythread(location, text):
engine = pyttsx.init()
engine.say(text)
engine.runAndWait()
e = (1, "please work, oh my god")
t = threading.Thread(target=saythread,args=e,name='sayitthread... | [
"Global variables are almost always a bad approach. You can just pass engine as an argument to saythread:\ndef saythread(engine, location, text):\n engine.say(text)\n engine.runAndWait() \n\n# ...later...\n\nengine = pyttsx.init() #(CHANGED) ADDED VARIABLE \nt = threading.Thread(target=... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0006770084_python.txt |
Q:
Facebook Graph API: Have extended permission, need something odd
So, I have a FB app already, and when people connect I ask for the extended permission "email" and that is all well and good. I save the email and can get a list of their friends' ids and basic profiles.
I want to know if there is a way for me to fi... | Facebook Graph API: Have extended permission, need something odd | So, I have a FB app already, and when people connect I ask for the extended permission "email" and that is all well and good. I save the email and can get a list of their friends' ids and basic profiles.
I want to know if there is a way for me to figure out which of their friends have allowed their email to be visible... | [
"We don't allow access to friend email addresses for obvious privacy reasons. You have to explicitly ask for this from each user.\n"
] | [
0
] | [] | [] | [
"facebook_graph_api",
"python"
] | stackoverflow_0006755679_facebook_graph_api_python.txt |
Q:
Looking for more pythonic list comparison solution
Ok so I have two lists:
x = [1, 2, 3, 4]
y = [1, 1, 2, 5, 6]
I compare them in such a way so I get the following output:
x = [3, 4]
y = [1, 5, 6]
The basic is idea to go through each list and compare them. If they have an element in common remove that element. B... | Looking for more pythonic list comparison solution | Ok so I have two lists:
x = [1, 2, 3, 4]
y = [1, 1, 2, 5, 6]
I compare them in such a way so I get the following output:
x = [3, 4]
y = [1, 5, 6]
The basic is idea to go through each list and compare them. If they have an element in common remove that element. But only one of that element not all of them. If they don... | [
"It's possible that the data structure you are looking for is the multiset (or \"bag\"), and if so, a good way to implement it in Python is to use collections.Counter:\n>>> from collections import Counter\n>>> x = Counter([1, 2, 3, 4])\n>>> y = Counter([1, 1, 2, 5, 6])\n>>> x - y\nCounter({3: 1, 4: 1})\n>>> y - x\n... | [
7,
3,
3,
2,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0006770002_list_python.txt |
Q:
Python/Tkinter: Why is my cascade menu not working?
I'm trying to learn Tkinter though right now I'm stuck at one part. I'd like to have a cascade menu added to my main menu. The problem is I don't know what I'm doing wrong. Thanks for any help.
from Tkinter import *
import tkFileDialog
class Application(Frame):
... | Python/Tkinter: Why is my cascade menu not working? | I'm trying to learn Tkinter though right now I'm stuck at one part. I'd like to have a cascade menu added to my main menu. The problem is I don't know what I'm doing wrong. Thanks for any help.
from Tkinter import *
import tkFileDialog
class Application(Frame):
def __init__(self, master=None):
Frame.__init... | [
"You forgot to add: self.master.config(menu=self.MainMenu)\nHere's your full code listing:\nfrom Tkinter import *\nimport tkFileDialog\n\nclass Application(Frame):\n def __init__(self, master=None):\n Frame.__init__(self, master)\n self.master = master\n self.create_wgts()\n\n def create_... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006770413_python_tkinter.txt |
Q:
Change number of items per page or view all in a view using a paginator in django
I am using django 1.3 and I have a view that takes a paginated queryset (set to use 50 objects). Here is the relevant part of the get_context_data() method in the view:
#build paginator for querysets
paginated_scanned_assets ... | Change number of items per page or view all in a view using a paginator in django | I am using django 1.3 and I have a view that takes a paginated queryset (set to use 50 objects). Here is the relevant part of the get_context_data() method in the view:
#build paginator for querysets
paginated_scanned_assets = Paginator(scanned_assets_qs, 50)
#get the specified page
try:
page_n... | [
"What you want to do is add an optional parameter to the view called 'page_size' and then do something like:\ndef your_view(request, ..., page_size=50):\n scanned_assets_qs = # get your scanned_assets QuerySet\n\n if page_size == -1:\n page_size = scanned_assets_qs.count()\n\n paginator = Paginator(scanned_as... | [
3
] | [] | [] | [
"django",
"django_views",
"pagination",
"python"
] | stackoverflow_0006769782_django_django_views_pagination_python.txt |
Q:
What's the difference between pyodbc and MySQLdb?
I have some code written with pyodbc on win x64 using python 2.6 and I get no problem.
Using the same code switching to MySQLdb I get errors.
Example. Long object not iterable....
whats the difference between pyodbc and MySQLdb?
EDIT
import csv, pyodbc, os
import... | What's the difference between pyodbc and MySQLdb? | I have some code written with pyodbc on win x64 using python 2.6 and I get no problem.
Using the same code switching to MySQLdb I get errors.
Example. Long object not iterable....
whats the difference between pyodbc and MySQLdb?
EDIT
import csv, pyodbc, os
import numpy as np
cxn = pyodbc.connect('DSN=MySQL;PWD=me') ... | [
"Without seeing code, it's not obvious why you're getting errors. You can connect to MySQL databases using either one, and they both implement version 2.x of the Python DB API, though their underlying workings are totally different, as Ignacio Vazquez-Abrams commented.\nSome things to consider:\n\nAre you using ex... | [
2
] | [] | [] | [
"mysql_python",
"pyodbc",
"python"
] | stackoverflow_0006771006_mysql_python_pyodbc_python.txt |
Q:
Property as a decorator in Python 2.4?
I'm developing an application for someone who is tied down to Python 2.4. According to the Python builtins page's description of property that "the getter, setter, and deleter attributes were added" in Python 2.6. Is there still a way to use property as a decorator, or is it ... | Property as a decorator in Python 2.4? | I'm developing an application for someone who is tied down to Python 2.4. According to the Python builtins page's description of property that "the getter, setter, and deleter attributes were added" in Python 2.6. Is there still a way to use property as a decorator, or is it imperative to use the x = property(...) synt... | [
"You can use it as a decorator, but you can only specify a getter if you do so. You can delete the getter, setter, and deleter methods once you have called property() though.\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0006771120_python.txt |
Q:
copy files and folders to another path using batch
I have a directory c:/go , inside go there is tons of folders, subfolders and files.
I need to find inside go, files that start with net*.inf and oem*.inf , and copy the folder, subfolders and all files where they are to another palce at c:/
It must be something a... | copy files and folders to another path using batch | I have a directory c:/go , inside go there is tons of folders, subfolders and files.
I need to find inside go, files that start with net*.inf and oem*.inf , and copy the folder, subfolders and all files where they are to another palce at c:/
It must be something automatic using windows... like batch script, c++, python... | [
"From the command line, one way is to combine xcopy with a for loop:\nfor /D %i in (net oem) do xcopy /s c:\\go\\%i*.inf c:\\go2\\\n\nIn a batch file just replace %i with %%i.\n",
"The xcopy technique in @ars' answer is obviously simpler for your situation if it is appropriate for you. However, below is a Python... | [
4,
2
] | [] | [] | [
"batch_file",
"python",
"vbscript",
"windows"
] | stackoverflow_0006770953_batch_file_python_vbscript_windows.txt |
Q:
Update python itself using the apt module
I am writing a python script that will run on an EC2 machine as the user-data-script. I'm trying to figure out how I can upgrade the packages on the machine similar to the bash command:
$ sudo apt-get -qqy update && sudo apt-get -qqy upgrade
I know I can use the apt packa... | Update python itself using the apt module | I am writing a python script that will run on an EC2 machine as the user-data-script. I'm trying to figure out how I can upgrade the packages on the machine similar to the bash command:
$ sudo apt-get -qqy update && sudo apt-get -qqy upgrade
I know I can use the apt package in python to do this:
import apt
cache=apt.C... | [
"I think I figured it out:\ndef main():\n import argparse\n parser = argparse.ArgumentParser(description='user-data-script.py: initial python instance startup script')\n parser.add_argument('--skip-update', default=False, action='store_true', help='skip apt package updates')\n # parser.add_argument what... | [
0,
0
] | [] | [] | [
"amazon_ec2",
"apt",
"python",
"user_data"
] | stackoverflow_0006770488_amazon_ec2_apt_python_user_data.txt |
Q:
Huffman encoding: how to write binary data in Python
I have tried methods using the struct module, as shown by the lines commented out in my code, but it didn't work out. Basically I have two options: I can either write the binary data code by code (my code are sequences of bits of length varying from 3 to 13 bits... | Huffman encoding: how to write binary data in Python | I have tried methods using the struct module, as shown by the lines commented out in my code, but it didn't work out. Basically I have two options: I can either write the binary data code by code (my code are sequences of bits of length varying from 3 to 13 bits), or convert the whole string of n characters (n=25000+ i... | [
"You're looking for this:\npacked_data = ''.join(chr(int(asciiString[i:i+8], 2)) \n for i in range(0, len(asciiString), 8))\n\nIt will take 8 bits at a time from the asciiString, interpret it as an integer, and output the corresponding byte.\nYour problem here is that this requires the lengt... | [
4
] | [] | [] | [
"binary",
"binary_data",
"huffman_code",
"python"
] | stackoverflow_0006770925_binary_binary_data_huffman_code_python.txt |
Q:
c++ equivalent to python append method for lists
I'm learning c++ coming from a background in python.
I'm wondering is there a way to append items to a list in c++?
myList = []
for i in range(10):
myList.append(i)
Is there something like this in c++ that you can do to an array?
A:
You need a vector, do some... | c++ equivalent to python append method for lists | I'm learning c++ coming from a background in python.
I'm wondering is there a way to append items to a list in c++?
myList = []
for i in range(10):
myList.append(i)
Is there something like this in c++ that you can do to an array?
| [
"You need a vector, do something like this:\n#include <vector>\n\nvoid funct() {\n std::vector<int> myList;\n for(int i = 0; i < 10; i++)\n myList.push_back(10);\n}\n\nSee http://cplusplus.com/reference/stl/vector/ for more information.\n",
"For list Use std::list::push_back \nIf you are looking for ... | [
11,
2,
1,
0,
0
] | [] | [] | [
"arrays",
"c++",
"c++_standard_library",
"list",
"python"
] | stackoverflow_0006771274_arrays_c++_c++_standard_library_list_python.txt |
Q:
Odd behaviour with simple tree implementation in python
class Node:
children = {}
sequence = [1,2,3,4,5]
tree = Node()
node = tree
for item in sequence:
if item not in node.children:
node.children[item] = Node()
node = node.children[item]
print tree.children.keys()
I want the above code to ... | Odd behaviour with simple tree implementation in python | class Node:
children = {}
sequence = [1,2,3,4,5]
tree = Node()
node = tree
for item in sequence:
if item not in node.children:
node.children[item] = Node()
node = node.children[item]
print tree.children.keys()
I want the above code to output [1], however it outputs [1, 2, 3, 4, 5]. Why is this, ... | [
"Node.children is a class attribute. Make it an instance attribute instead.\nclass Node:\n def __init__(self):\n self.children = {}\n\n"
] | [
7
] | [] | [] | [
"class",
"python",
"tree"
] | stackoverflow_0006771488_class_python_tree.txt |
Q:
About Twisted Documents
I am a beginner for Twisted. Recently, I am reading the book "Twisted Network Programming Essentials".The Example 2-3 In this book as below:
class QuickDisconnectProtocol(protocol.Protocol):
def connectionMade(self):
print "Connected to %s." % self.transport.getPeer( ).host
se... | About Twisted Documents | I am a beginner for Twisted. Recently, I am reading the book "Twisted Network Programming Essentials".The Example 2-3 In this book as below:
class QuickDisconnectProtocol(protocol.Protocol):
def connectionMade(self):
print "Connected to %s." % self.transport.getPeer( ).host
self.transport.loseConnection( ... | [
"def makeConnection(self, transport): ([source][1])\n \"\"\"\n overridden in twisted.protocols.amp.BinaryBoxProtocol,\n twisted.protocols.ftp.ProtocolWrapper, twisted.protocols.ftp.SenderProtocol, \n twisted.protocols.policies.ProtocolWrapper, \n twisted.protocols.stateful.StatefulProtocol`\n\n Ma... | [
1
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0006771582_python_twisted.txt |
Q:
Python SQLite3 - Table Output Format Question & Handling IntegrityError
I have a table created using Python + Sqlite3
c.execute('CREATE TABLE IF NOT EXISTS reg(col1 TEXT PRIMARY KEY, col2 TEXT)')
I even wrote a record into it using val1 and val2 variables which have string values (URLs to be specific)
c.execute('... | Python SQLite3 - Table Output Format Question & Handling IntegrityError | I have a table created using Python + Sqlite3
c.execute('CREATE TABLE IF NOT EXISTS reg(col1 TEXT PRIMARY KEY, col2 TEXT)')
I even wrote a record into it using val1 and val2 variables which have string values (URLs to be specific)
c.execute('INSERT INTO reg VALUES(?,?)', (val1, val2))
Now when I print the table using... | [
"The u means those are Unicode strings. They can be encoded to any character set you want:\nu'http://www.someURL.com'.encode('ascii') # or 'latin-1' or 'utf-8'\n\nYou'll get back the same string without the u because they're all ASCII characters.\nSee http://docs.python.org/howto/unicode.html.\nIf the strings only ... | [
2,
1
] | [] | [] | [
"database",
"python",
"sql",
"sqlite"
] | stackoverflow_0006771757_database_python_sql_sqlite.txt |
Q:
NumPy: use 2D index array from argmin in a 3D slice
I'm trying to index large 3D arrays using a 2D array of indicies from argmin (or related argmax, etc. functions). Here is my example data:
import numpy as np
shape3d = (16, 500, 335)
shapelen = reduce(lambda x, y: x*y, shape3d)
# 3D array of [random] source inte... | NumPy: use 2D index array from argmin in a 3D slice | I'm trying to index large 3D arrays using a 2D array of indicies from argmin (or related argmax, etc. functions). Here is my example data:
import numpy as np
shape3d = (16, 500, 335)
shapelen = reduce(lambda x, y: x*y, shape3d)
# 3D array of [random] source integers
intcube = np.random.uniform(2, 50, shapelen).astype(... | [
"fancy indexing can be a little non-intuitive. Luckily the tutorial has some good examples.\nBasically, you need to define the j and k where each minidx applies. numpy doesn't deduce it from the shape.\nin your example:\ni = minax0\nk,j = np.meshgrid(np.arange(335), np.arange(500))\nothercube[i,j,k] = some2d\n\n"... | [
10
] | [] | [] | [
"indexing",
"numpy",
"python"
] | stackoverflow_0006771551_indexing_numpy_python.txt |
Q:
Organizing XML data into dictionaries
I'm trying to organize my data into a dictionary format from XML data. This will be used to run Monte Carlo simulations.
Here is an example of what a couple of entries in the XML look like:
<retirement>
<item>
<low>-0.34</low>
<high>-0.32</high>
<fr... | Organizing XML data into dictionaries | I'm trying to organize my data into a dictionary format from XML data. This will be used to run Monte Carlo simulations.
Here is an example of what a couple of entries in the XML look like:
<retirement>
<item>
<low>-0.34</low>
<high>-0.32</high>
<freq>0.0294117647058824</freq>
<varia... | [
"You have a serious indentation problem after the (unnecessary) else: pass. Fix that and try again. Does the problem occur with your sample input data? other data? First time around the loop? What is the value of thisKey that is causing the problem [hint: it's reported in the KeyError error message]? What are the c... | [
2,
0
] | [
"You have an error in your if-statement inside the for-loop. Instead of \nif thisKey in masterDictionary == False:\n\nwrite\nif (thisKey in masterDictionary) == False:\n\nGiven the rest of your original code, you will be able to access data like so:\nmasterDictionary['stock'][0].freq\n\nJohn Machin makes some valid... | [
-1
] | [
"dictionary",
"montecarlo",
"python",
"xml"
] | stackoverflow_0006770544_dictionary_montecarlo_python_xml.txt |
Q:
Python recursive crawling for urls
I have this method that when supplied with a list of links will get the child links and so on and so forth:
def crawlSite(self, linksList):
finalList = []
for link in list(linksList):
if link not in finalList:
print link
finalLi... | Python recursive crawling for urls | I have this method that when supplied with a list of links will get the child links and so on and so forth:
def crawlSite(self, linksList):
finalList = []
for link in list(linksList):
if link not in finalList:
print link
finalList.append(link)
childLinks =... | [
"You need\nfinalList.extend(self.crawlSite(childLinks))\n\nnot just \nself.crawlSite(childLinks)\n\nYou need to merge the list returned by the inner crawlSite()s with the list already extant in the outer crawlSite(). Even though they're all called finalList, you have a different list in each scope.\nThe alternative... | [
3,
2
] | [] | [] | [
"function",
"hyperlink",
"python",
"recursion",
"web_crawler"
] | stackoverflow_0006772003_function_hyperlink_python_recursion_web_crawler.txt |
Q:
How to run python scripts?
I am a PHP developer and am I want to use python for a project. What is the most common and simplest way to run python script on a server like apache or lighttpd? I am having trouble understanding how server languages that are not PHP or ASP run on servers.
A:
In Python we have somethi... | How to run python scripts? | I am a PHP developer and am I want to use python for a project. What is the most common and simplest way to run python script on a server like apache or lighttpd? I am having trouble understanding how server languages that are not PHP or ASP run on servers.
| [
"In Python we have something called WSGI. But I believe this is too much for you right now. Grab a Python web framework, like Django. It comes with a web server and with good documentation on how to deploy it later. Play with it and things will start to clear up.\n\nThe longer version is that Python is a general pu... | [
5,
0,
0
] | [] | [] | [
"apache",
"lighttpd",
"python"
] | stackoverflow_0006771848_apache_lighttpd_python.txt |
Q:
Google App Engine: task_retry_limit doesn't work?
I have a Python GAE app.
I want my tasks to stop running or just retry once if they fail. Right now, they run forever despite what my yaml file is telling them!
Here is a queue.yaml entry:
- name: globalPurchase
rate: 10/s
bucket_size: 100
retry_parameter... | Google App Engine: task_retry_limit doesn't work? | I have a Python GAE app.
I want my tasks to stop running or just retry once if they fail. Right now, they run forever despite what my yaml file is telling them!
Here is a queue.yaml entry:
- name: globalPurchase
rate: 10/s
bucket_size: 100
retry_parameters:
task_retry_limit: 1
If globalPurchase task fa... | [
"I had the same problem. The documentation and tooling in this area is lacking, but here's what I found:\n\nThe retry parameters have no effect in the development server. I tried lots of different combinations, but it was always just indefinite retries 30s apart. The parameters did take effect when I deployed to th... | [
7,
5,
2
] | [] | [] | [
"google_app_engine",
"python",
"task_queue"
] | stackoverflow_0005505416_google_app_engine_python_task_queue.txt |
Q:
Regex for word exclusion
I'm trying to write a regex that will match only the first and third words in the string:
term1 and term2
My first attempt was [^(\s|(and))]+, but it fails because
term1 anbd term2
gives me these 3 matches: ['term1','b','term2'] whereas I want it to return ['term1','anbd','term2']
A:
M... | Regex for word exclusion | I'm trying to write a regex that will match only the first and third words in the string:
term1 and term2
My first attempt was [^(\s|(and))]+, but it fails because
term1 anbd term2
gives me these 3 matches: ['term1','b','term2'] whereas I want it to return ['term1','anbd','term2']
| [
"Match only the first and third words: (\\S+)\\s+\\S+\\s+(\\S+)\nEDIT: If you mean 'match all the words except the word \"and\"' then: \\b(?!and\\b)\\S+\\b\n",
"Instead of regex, consider\nsentence.split()[:3:2]\n\neg\n>>> \"term1 and term2\".split()[:3:2]\n['term1', 'term2']\n>>> \"term1 anbd term2\".split()[:3:... | [
5,
3,
1,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006770681_python_regex.txt |
Q:
Efficient numpy / lapack routine for product of inverse and sparse matrix?
I have a matrix B that is square and dense, and a matrix A that is rectangular and sparse.
Is there a way to efficiently compute the product B^-1 * A?
So far, I use (in numpy)
tmp = B.inv()
return tmp * A
which, I believe, makes us of A'... | Efficient numpy / lapack routine for product of inverse and sparse matrix? | I have a matrix B that is square and dense, and a matrix A that is rectangular and sparse.
Is there a way to efficiently compute the product B^-1 * A?
So far, I use (in numpy)
tmp = B.inv()
return tmp * A
which, I believe, makes us of A's sparsity. I was thinking about using the sparse method
numpy.sparse.linalg.sp... | [
"Since the matrix to be inverted is dense, spsolve is not the tool you want. In addition, it is bad numerical practice to calculate the inverse of a matrix and multiply it by another - you are much better off using LU decomposition, which is supported by scipy. \nAnother point is that unless you are using the matri... | [
3
] | [] | [] | [
"lapack",
"numpy",
"python"
] | stackoverflow_0006766838_lapack_numpy_python.txt |
Q:
How to force deletion of a python object?
I am curious about the details of __del__ in python, when and why it should be used and what it shouldn't be used for. I've learned the hard way that it is not really like what one would naively expected from a destructor, in that it is not the opposite of __new__ / __ini... | How to force deletion of a python object? | I am curious about the details of __del__ in python, when and why it should be used and what it shouldn't be used for. I've learned the hard way that it is not really like what one would naively expected from a destructor, in that it is not the opposite of __new__ / __init__.
class Foo(object):
def __init__(sel... | [
"The way to close resources are context managers, aka the with statement:\nclass Foo(object):\n\n def __init__(self):\n self.bar = None\n\n def __enter__(self):\n if self.bar != 'open':\n print 'opening the bar'\n self.bar = 'open'\n return self # this is bound to the `as` part\n\n def close(s... | [
74,
8,
5,
2
] | [] | [] | [
"constructor",
"destructor",
"garbage_collection",
"python",
"reference_counting"
] | stackoverflow_0006772481_constructor_destructor_garbage_collection_python_reference_counting.txt |
Q:
How to name class instances after an iterable keys?
I'd like to create instances of classes getting their names from list values or dictionaries keys or values. Basically what I'd like to do is:
iter = ['foo', 'bar']
for a in iter:
a = Cls()
and get foo and bar instances of Cls() class instead of having insta... | How to name class instances after an iterable keys? | I'd like to create instances of classes getting their names from list values or dictionaries keys or values. Basically what I'd like to do is:
iter = ['foo', 'bar']
for a in iter:
a = Cls()
and get foo and bar instances of Cls() class instead of having instance referenced by a updated at each loop.
Thanks in advan... | [
"Maybe with a dictionnary : \niter = ['foo', 'bar']\nresult = {}\nfor a in iter:\n result[a] = Cls()\n\nAnd in result you'll have { 'foo' : instance_of_Cls, 'bar' : instance_of_Cls}\n"
] | [
7
] | [
"You could use dynamic code evaluation.\ninst1 = eval(\"foo()\")\ninst2 = eval(a + \"()\")\ninst3 = eval(a)()\n\n"
] | [
-1
] | [
"class",
"instance",
"loops",
"python"
] | stackoverflow_0006773002_class_instance_loops_python.txt |
Q:
Importing fixtures with foreign keys and SQLAlchemy?
I've been experimenting with using fixture to load test data sets into my Pylons / PostgreSQL app. This works great except that it fails to properly create foreign keys if they reference an auto increment id field.
My fixture looks like this:
class AuthorsData(D... | Importing fixtures with foreign keys and SQLAlchemy? | I've been experimenting with using fixture to load test data sets into my Pylons / PostgreSQL app. This works great except that it fails to properly create foreign keys if they reference an auto increment id field.
My fixture looks like this:
class AuthorsData(DataSet):
class frank_herbert:
first_name = "F... | [
"Referencing not yet inserted rows is not supported by SQL expression layer in SQLAlchemy because it's meaningless: all queries are executed explicitly. ORM layer does support references to new objects, it even uses unit of work pattern to organize insertion order properly. To solve this problem fixture uses ref() ... | [
1,
1,
0
] | [] | [] | [
"fixture",
"postgresql",
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0002962330_fixture_postgresql_pylons_python_sqlalchemy.txt |
Q:
parameter transferring in the wmi
hello everyone I have some problem with understanding this piece of the code:
import wmi
c = wmi.WMI ()
process_id, return_value = c.Win32_Process.Create (CommandLine="notepad.exe")
for process in c.Win32_Process (ProcessId=process_id):
print process.ProcessId, process.Name
re... | parameter transferring in the wmi | hello everyone I have some problem with understanding this piece of the code:
import wmi
c = wmi.WMI ()
process_id, return_value = c.Win32_Process.Create (CommandLine="notepad.exe")
for process in c.Win32_Process (ProcessId=process_id):
print process.ProcessId, process.Name
result = process.Terminate ()
I can't un... | [
"It is sent as part of **kwargs of def new (self, **kwargs): as you can see in the wmi.py. The convention is always what Microsoft has defined for the process creation and you can find that in the MSDN documentation.\n"
] | [
0
] | [] | [] | [
"python",
"wmi"
] | stackoverflow_0006773155_python_wmi.txt |
Q:
python styling ** question
I'm working on my first project using Python 2.7. We're coming from a Java background and our first instinct was to write python code in a Java-esque way. But now we're trying to adapt as much as possible. So far we are using pylint to adapt our code.
Now I keep running into a situation... | python styling ** question | I'm working on my first project using Python 2.7. We're coming from a Java background and our first instinct was to write python code in a Java-esque way. But now we're trying to adapt as much as possible. So far we are using pylint to adapt our code.
Now I keep running into a situation with pylint. Every time I use s... | [
"** can introduce some more tricky bug because it will accept anything. Usually you want code that breaks when called wrong. Here is a example:\ndef dostuff(**kwargs):\n force = 3\n if kwargs.get('reallyhard', False):\n force += 5 \n # and so on\n\n# Now you need luck to find this bug ...\ndostuff(fancy=True, ... | [
4,
2,
2
] | [] | [] | [
"coding_style",
"pylint",
"python"
] | stackoverflow_0006773287_coding_style_pylint_python.txt |
Q:
Mock an object in a method that is not a parameter in python
(i'm a python newbie)
I was looking at: Mocking out objects and methods
And I was wondering if i can replace an object in a python method which is not passed as a parameter, lets say my method is like this:
def mypymethod(param1)
myresult = os.path.som... | Mock an object in a method that is not a parameter in python | (i'm a python newbie)
I was looking at: Mocking out objects and methods
And I was wondering if i can replace an object in a python method which is not passed as a parameter, lets say my method is like this:
def mypymethod(param1)
myresult = os.path.something
return myresult
and i wish to test mypymethod however i ... | [
"You should use Michael Foord's Mock module for the same.\nFrom the documentation:\n>>> from mock import Mock\n>>> real = ProductionClass()\n>>> real.method = Mock(return_value=3)\n>>> real.method(3, 4, 5, key='value')\n3\n>>> real.method.assert_called_with(3, 4, 5, key='value')\n\n"
] | [
1
] | [] | [] | [
"mocking",
"python",
"python_unittest"
] | stackoverflow_0006773234_mocking_python_python_unittest.txt |
Q:
Django - Multiple optional ForeignKey
class Truc(models.Model):
name = models.CharField(max_length=50, unique=True)
machin1 = models.ForeignKey(Machin1, blank=True, null=True)
machin2 = models.ForeignKey(Machin2, blank=True, null=True)
machin3 = models.ForeignKey(Machin3, blank=True, null=True)
I would li... | Django - Multiple optional ForeignKey | class Truc(models.Model):
name = models.CharField(max_length=50, unique=True)
machin1 = models.ForeignKey(Machin1, blank=True, null=True)
machin2 = models.ForeignKey(Machin2, blank=True, null=True)
machin3 = models.ForeignKey(Machin3, blank=True, null=True)
I would like Truc to be linked to one machin, either ... | [
"If it is only ever linked to one use a generic relation:\nclass Truc(models.Model):\n name = models.CharField(max_length=50, unique=True)\n content_type = models.ForeignKey(ContentType)\n object_id = models.PositiveIntegerField()\n machin_object = generic.GenericForeignKey('content_type', 'object_id')\... | [
0
] | [] | [] | [
"django",
"foreign_keys",
"model",
"python",
"validation"
] | stackoverflow_0006773659_django_foreign_keys_model_python_validation.txt |
Q:
Django + uWSGI + Websocket client connection
We are trying to integrate Socket.io with our website. All messages are sent with uWSGI workers (Django). My problem is, that every message does all connection magic. It looks now like that:
Request -> HTTP Handshake with Socket.io -> Websocket connection -> Data send -... | Django + uWSGI + Websocket client connection | We are trying to integrate Socket.io with our website. All messages are sent with uWSGI workers (Django). My problem is, that every message does all connection magic. It looks now like that:
Request -> HTTP Handshake with Socket.io -> Websocket connection -> Data send -> Connection close
And repeat for every message th... | [
"If someone has similar problem, check out Roberto (dev of uWSGI) response to my e-mail on mailing list here: http://lists.unbit.it/pipermail/uwsgi/2011-July/002436.html :)\n"
] | [
4
] | [] | [] | [
"django",
"python",
"socket.io",
"uwsgi"
] | stackoverflow_0006761430_django_python_socket.io_uwsgi.txt |
Q:
problem with closing python pypdf - writing. getting a valueError: I/O operation on closed file
can't figure this up
this function (part of class for scraping internet site into a pdf) supposed to merge the pdf file generated from web pages using pypdf.
this is the method code:
def mergePdf(self,mainname,inputlis... | problem with closing python pypdf - writing. getting a valueError: I/O operation on closed file | can't figure this up
this function (part of class for scraping internet site into a pdf) supposed to merge the pdf file generated from web pages using pypdf.
this is the method code:
def mergePdf(self,mainname,inputlist=0):
"""merging the pdf pages
getting an inputlist to merge or defaults to the class instanc... | [
"OK, I found your problem. You were right to call file(). Don't try to call open() at all.\nYour problem is the input file still needs to be open when you call self.pdfoutput.write(self._pdfstream), so you need to remove the line self._filestream.close().\nEdit: This script will trigger the problem. The first write... | [
7
] | [] | [] | [
"pypdf",
"python"
] | stackoverflow_0006773631_pypdf_python.txt |
Q:
Python equivalent of php's virtual()
Do you know if there is a python equivalent of php's virtual() ?
My configuration is python, djanogo, mod_wsgi, apache
Trying to include a script that has only examples for php using the above include and also needs to be included in all website's pages.
Thanks
LE: I'm includi... | Python equivalent of php's virtual() | Do you know if there is a python equivalent of php's virtual() ?
My configuration is python, djanogo, mod_wsgi, apache
Trying to include a script that has only examples for php using the above include and also needs to be included in all website's pages.
Thanks
LE: I'm including a .cgi script
| [
"The only reference to this I see is\nhttp://www.modpython.org/pipermail/mod_python/2004-January/014834.html\n\nWhich states In theroy you can use the Apache 2.x chain handlers feature, where more\nthan one content handler can process the request. I say in theroy\nbecause I've read about it, but never tried it =)\... | [
0
] | [] | [] | [
"equivalent",
"php",
"python",
"virtual"
] | stackoverflow_0006774166_equivalent_php_python_virtual.txt |
Q:
Python eval integer in string, and return integer instead of ascii char
I'm getting some data from a file, which looks like this:
[200, "Hello", "World"]
Now, since this is a file, this array is inside a string; I turn it into an array using eval().
This works fine BUT the integer at the start is converted to an ... | Python eval integer in string, and return integer instead of ascii char | I'm getting some data from a file, which looks like this:
[200, "Hello", "World"]
Now, since this is a file, this array is inside a string; I turn it into an array using eval().
This works fine BUT the integer at the start is converted to an ascii char, instead of an integer as I want it to (the euro sign).
How can I ... | [
"You could use the simplejson module. E.g.\n>>> import simplejson\n>>> a = simplejson.loads('[200, \"Hello\", \"World\"]')\n>>> print a\n[200, 'Hello', 'World']\n\nThis way \"malicious\" data such as os.execvp() would not be evaluated but an JSONDecodeErrorwould be thrown.\n",
"You can use literal_eval. Really de... | [
2,
2
] | [] | [] | [
"ascii",
"eval",
"integer",
"python"
] | stackoverflow_0006773374_ascii_eval_integer_python.txt |
Q:
Python get start and end date of the week
How to get the start date and end date of a week, and also if the following dates below comes under a particular range of start and end dates of the week how to show only those weeks start and end date.I am using python 2.4
2011-03-07 0:27:41
2011-03-06 0:13:41
2011-03-0... | Python get start and end date of the week | How to get the start date and end date of a week, and also if the following dates below comes under a particular range of start and end dates of the week how to show only those weeks start and end date.I am using python 2.4
2011-03-07 0:27:41
2011-03-06 0:13:41
2011-03-05 0:17:40
2011-03-04 0:55:40
2011-05-16 0:55... | [
"from datetime import datetime\nfrom time import strptime\n\nNow\ndatetime(*strptime('2011-03-08 0:27:41', '%Y-%m-%d %H:%M:%S')[0:6]).weekday()\n\nreturns the day of the week for the first date \"as an integer, where Monday is 0 and Sunday is 6\", so selecting those dates for which weekday() in [0, 6] will give y... | [
1,
0
] | [] | [] | [
"python",
"python_2.4"
] | stackoverflow_0006774428_python_python_2.4.txt |
Q:
Unknown specifier in URL when using Django-Tagging
Hi I am getting the following error;
error at /
unknown specifier: ?P[
This is what my URLS file looks like;
urlpatterns = patterns('mainpage.views',
(r'^$', 'index'),
(r'^post/(?P<id>\d+)/$', 'post'),
(r'^projects/$', 'projects'),
(r'^about/$', 'about'),... | Unknown specifier in URL when using Django-Tagging | Hi I am getting the following error;
error at /
unknown specifier: ?P[
This is what my URLS file looks like;
urlpatterns = patterns('mainpage.views',
(r'^$', 'index'),
(r'^post/(?P<id>\d+)/$', 'post'),
(r'^projects/$', 'projects'),
(r'^about/$', 'about'),
(r'^tags/$', 'tags'),
(r'^tag/(?P[-_A-Za-z0-9]+)/$', 'w... | [
"This is not related to django-tagging, it's a regex syntax error. ?P indicates a named group, and requires a name after it: ?P<foo>. So, either add names to your groups, or make them numbered (i.e. remove ?P part).\n"
] | [
9
] | [] | [] | [
"django",
"django_tagging",
"python"
] | stackoverflow_0006774557_django_django_tagging_python.txt |
Q:
Can I bind a tixBalloon Widget to a Text widget tag?
I am wanting to mimic the behavior of the 'abbr' tag of HTML in a tkinter Text widget. The Tix Balloon widget looks like it would be a perfect fit, but I can't figure out how to bind it to a text tag instead of a whole widget. Any suggestions welcome.
A:
you m... | Can I bind a tixBalloon Widget to a Text widget tag? | I am wanting to mimic the behavior of the 'abbr' tag of HTML in a tkinter Text widget. The Tix Balloon widget looks like it would be a perfect fit, but I can't figure out how to bind it to a text tag instead of a whole widget. Any suggestions welcome.
| [
"you might be better off writing your own balloon widget in plain Tkinter\nsee http://tkinter.unpythonic.net/wiki/ToolTip for an example\nre: binding to a tag in a text widget: Pmw balloon can do it\n"
] | [
1
] | [] | [] | [
"balloon",
"python",
"text",
"tix",
"tkinter"
] | stackoverflow_0006597327_balloon_python_text_tix_tkinter.txt |
Q:
Python script executes another script and resumes after second script completes its job
Is there a way to check if a subprocess has finished its job? My python script executes an 123.exe from cmd. 123.exe then does some things and in the end it writes 1 or 0 to a txt file. Python script then reads the txt file and... | Python script executes another script and resumes after second script completes its job | Is there a way to check if a subprocess has finished its job? My python script executes an 123.exe from cmd. 123.exe then does some things and in the end it writes 1 or 0 to a txt file. Python script then reads the txt file and continues with the job if '1' and stops if '0'. At the moment all that I can think of, is to... | [
"Use:\nretcode = subprocess.call([\"123.exe\"])\n\nThis will execute the command, wait until it finishes, and you get its return code into retcode (this way you could also avoid the need of checking the output status file, if the command returns a proper return code).\nIf you need to instantiate manually the subpro... | [
3,
1,
0
] | [] | [] | [
"python",
"subprocess",
"timeout",
"wait"
] | stackoverflow_0006774809_python_subprocess_timeout_wait.txt |
Q:
wxpython: return value from Mainloop
If I create a wx.app in a script and call the method MainLoop.
how return a value from wx.app to the script ?
print myApp.MainLoop()
A:
Actually, from within the frame you can reference the app using wx.GetApp() hence removing the need to pass it in via the init of your Ma... | wxpython: return value from Mainloop | If I create a wx.app in a script and call the method MainLoop.
how return a value from wx.app to the script ?
print myApp.MainLoop()
| [
"Actually, from within the frame you can reference the app using wx.GetApp() hence removing the need to pass it in via the init of your MainWindow\n",
"If there's a way to directly access the wx.App object from within a wx.Frame, I don't know what it is, so it's possible I'm doing this the hard way:\nclass MainWi... | [
1,
0
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004820772_python_wxpython.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.