content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Python Pickle EOFerror when using Pickler (but not with pickle.dump())
So, I'm trying to save some objects to disk on Windows 7 using Python's pickle. I'm using the code below, which fails on pretty much any arbitrary object (the contents of saveobj aren't important, it fails regardless). Below is my test code:
im... | Python Pickle EOFerror when using Pickler (but not with pickle.dump()) | So, I'm trying to save some objects to disk on Windows 7 using Python's pickle. I'm using the code below, which fails on pretty much any arbitrary object (the contents of saveobj aren't important, it fails regardless). Below is my test code:
import pickle, os, time
outfile = "foo.pickle"
f = open(outfile, 'wb')
p = pic... | [
"Pickler.save() is a lower level method, that you're not supposed to call directly.\nIf you call p.dump(saveobj) instead of p.save(saveobj), it works as expected.\nPerhaps it should be called _save to avoid confusion. But dump is the method described in the documentation, and it neatly matches up with the module-le... | [
2,
1
] | [] | [] | [
"pickle",
"python",
"serialization"
] | stackoverflow_0006617348_pickle_python_serialization.txt |
Q:
Use django sorl-thumbnail with django form-utils
How do I implement sorl thumbnailing in django form utils?
So the form utils documentation says this about its ImageWidget:
(Thumbnails only available if
sorl-thumbnail is installed; otherwise
the full-size image is displayed).
However, I can't seem to impleme... | Use django sorl-thumbnail with django form-utils | How do I implement sorl thumbnailing in django form utils?
So the form utils documentation says this about its ImageWidget:
(Thumbnails only available if
sorl-thumbnail is installed; otherwise
the full-size image is displayed).
However, I can't seem to implement it. I tried using sorl's ImageField in models, it b... | [
"It looks like in your form class definition you are naming the ImageField as pic, but then in your template you are attempting to refer to the field with form.image.\nTry just using the standard Django form renderer for now by putting {{form}} in your template--if that works then you know it's just a problem with ... | [
1
] | [] | [] | [
"django",
"django_forms",
"python",
"sorl_thumbnail"
] | stackoverflow_0006543282_django_django_forms_python_sorl_thumbnail.txt |
Q:
Potential database systems for portable/standalone web applications?
I'm in the process of developing a portable web app using python/cherrypy, which I'd like to ideally be able to simply extract to a folder and not have to install anything. One of the things potentially preventing this is my database back end. Mo... | Potential database systems for portable/standalone web applications? | I'm in the process of developing a portable web app using python/cherrypy, which I'd like to ideally be able to simply extract to a folder and not have to install anything. One of the things potentially preventing this is my database back end. Most similar set ups seem to use SQLite, however I have a few concerns, as I... | [
"There are some pure python databases out there, not sure how good or stable they are:\n\nPyDbLite\nBuzHug\nSnakeSQL\nKirbyBase\n\nIf you are worried about licenses for distribution, then check out stuff with an Apache license. One of the currently hosted top tier database projects is CouchDB. Main issue I see is t... | [
2
] | [] | [] | [
"database",
"python",
"sqlite",
"web_applications"
] | stackoverflow_0006617753_database_python_sqlite_web_applications.txt |
Q:
Convert list of positions [4, 1, 2] of arbitrary length to an index for a nested list
Assuming this list
nestedList = ["a", "b", [1, 2, 3], "c",[4, 5, 6, [100, 200, 300]], "d"]
I have a function that returns a position list for a nested list of arbitrary depth.
Examples:
[2, 1] -> "2"
[5] -> "d"
[4, 3, 2] -> "300... | Convert list of positions [4, 1, 2] of arbitrary length to an index for a nested list | Assuming this list
nestedList = ["a", "b", [1, 2, 3], "c",[4, 5, 6, [100, 200, 300]], "d"]
I have a function that returns a position list for a nested list of arbitrary depth.
Examples:
[2, 1] -> "2"
[5] -> "d"
[4, 3, 2] -> "300"
As you can see it is not clear in the beginning how many levels of nesting there are.
A... | [
"The first part is easy enough.\n>>> reduce(lambda x, y: x[y], [4, 3, 2], nestedList)\n300\n\nThe second part requires much more effort, but is still doable. Hint:\n>>> a = [1, 2, 3]\n>>> a[slice(1, None)] = [4, 5]\n>>> a\n[1, 4, 5]\n\n",
"I finally had some time to fiddle around with this. I got a little carried... | [
7,
1
] | [] | [] | [
"eval",
"generated_code",
"nested_lists",
"python",
"recursion"
] | stackoverflow_0006558365_eval_generated_code_nested_lists_python_recursion.txt |
Q:
How to get the selected option in a Python CGI script from a html select/option
I have been working on getting a python CGI script to work all day, and I am now at near the final hurdle, but I have run into a problem that I cant seem to find an answer for...
Its in 2 parts so here goes:
I am generating the followi... | How to get the selected option in a Python CGI script from a html select/option | I have been working on getting a python CGI script to work all day, and I am now at near the final hurdle, but I have run into a problem that I cant seem to find an answer for...
Its in 2 parts so here goes:
I am generating the following html code:
<form action="selections.cgi" enctype="multipart/form-data" method="PO... | [
"If you want the form to automatically submit whenever the user changes the option then javascript is mandatory. It would be very simple:\n<select name=\"cboOptions\" onchange=\"this.form.submit();\">\n\nI suspect that what is preventing you from reading the selected value is the enctype atribute. Just take it out:... | [
1
] | [] | [] | [
"cgi",
"html",
"python",
"webforms"
] | stackoverflow_0006615883_cgi_html_python_webforms.txt |
Q:
Python, matching two list's elements
x= [0,2,3,5,6];
y= [64,384,1024,4096,384];
The above are two arrays I'm using. Im trying to match the elements together in a pythonic way
example:
if xType is 2 i want to compute a variable called yType to correspond to its value(position wise) in y. so i should get y = 384. i... | Python, matching two list's elements | x= [0,2,3,5,6];
y= [64,384,1024,4096,384];
The above are two arrays I'm using. Im trying to match the elements together in a pythonic way
example:
if xType is 2 i want to compute a variable called yType to correspond to its value(position wise) in y. so i should get y = 384. if xType = 3 i should get 1024.
How would i... | [
"If your specific aim is to generate a dict from the two lists you've given, use zip:\n>>> x = [0,2,3,5,6]\n>>> y = [64,384,1024,4096,384]\n>>> dict(zip(x, y))\n{0: 64, 2: 384, 3: 1024, 5: 4096, 6: 384}\n\nAnd get rid of those semicolons!\nIf you don't need a mapping type, but just want to create pairs of items, zi... | [
6,
5,
3,
2,
2
] | [] | [] | [
"elements",
"list",
"matching",
"python"
] | stackoverflow_0006618578_elements_list_matching_python.txt |
Q:
How to get the users with birth day that happen at this month?
I am trying to get all the user with birth day of this month:
Did this but getting errors, Can any one help with what am i doing wrong?
birth_days = get_list_or_404(UserProfile, birthDate.month() == datetime.date.month())
I've tried many other things,... | How to get the users with birth day that happen at this month? | I am trying to get all the user with birth day of this month:
Did this but getting errors, Can any one help with what am i doing wrong?
birth_days = get_list_or_404(UserProfile, birthDate.month() == datetime.date.month())
I've tried many other things, but can't make it work...
thank you,
Erez
| [
"There are several problems\n\ndatetime.date.month() does not exist, i think you mean datetime.datetime.now().month\nYou are not using the right criteria, again birtDay.month() does not exist, i think you should use \nbirth_days = get_list_or_404(UserProfile, birthDate__month=datetime.datetime.now().month)\n\nJFTR ... | [
2
] | [] | [] | [
"django",
"django_models",
"django_views",
"python",
"python_datetime"
] | stackoverflow_0006618658_django_django_models_django_views_python_python_datetime.txt |
Q:
C++ callback with python through SWIG when the function takes non-trivial arguments?
I just read the following section of the "SWIG and Python" tutorial:
http://www.swig.org/Doc1.1/HTML/Python.html#n11
I understand what they do in the example, basically you write a C function that calls python. However, the exampl... | C++ callback with python through SWIG when the function takes non-trivial arguments? | I just read the following section of the "SWIG and Python" tutorial:
http://www.swig.org/Doc1.1/HTML/Python.html#n11
I understand what they do in the example, basically you write a C function that calls python. However, the example provided takes only a double in the argument list, making it rather trivial to build an ... | [
"I do not think your question is actually about SWIG; it is purely about Python. At this level, your problem is simply calling in to Python from C, so you need to study \"Parsing arguments and building values\" in the Python documentation. (Also \"Extending and Embedding the Python interpreter\".)\n"
] | [
0
] | [] | [] | [
"c++",
"callback",
"pyobject",
"python",
"swig"
] | stackoverflow_0006553396_c++_callback_pyobject_python_swig.txt |
Q:
AVAudioRecorder doesn't write out proper WAV File Header
I'm working on a project on the iPhone where I'm recording audio from the device mic using AVAudioRecorder, and then will be manipulating the recording.
To ensure that I'm reading in the samples from the file correctly, I'm using python's wave module to see ... | AVAudioRecorder doesn't write out proper WAV File Header | I'm working on a project on the iPhone where I'm recording audio from the device mic using AVAudioRecorder, and then will be manipulating the recording.
To ensure that I'm reading in the samples from the file correctly, I'm using python's wave module to see if it returns the same samples.
However, python's wave module ... | [
"Apple software often creates WAVE files with a non-standard (but \"spec\" conformant) \"FLLR\" subchunk after the \"fmt \" subchunk and before the \"data\" subchunk. I assume \"FLLR\" stands for \"filler\", and I assume the purpose of the subchunk is to enable some sort of data alignment optimization. The subchu... | [
40,
1
] | [] | [] | [
"avaudiorecorder",
"ios",
"python",
"wave"
] | stackoverflow_0006284651_avaudiorecorder_ios_python_wave.txt |
Q:
readline() is skipping lines in source file
I have a .txt file that I created with multiple lines.
When I run a for loop, with a count accumulator, it skips lines.
It skips the top line, and starts with the second, prints the fourth, the sixth, etc.
What is it I'm missing?
def main():
# Open file line_numbers.... | readline() is skipping lines in source file | I have a .txt file that I created with multiple lines.
When I run a for loop, with a count accumulator, it skips lines.
It skips the top line, and starts with the second, prints the fourth, the sixth, etc.
What is it I'm missing?
def main():
# Open file line_numbers.txt
data_file = open('line_numbers.txt', 'r')... | [
"Try removing the \"line=data_file.readline()\" altogether? I suspect the \"for line in data_file:\" is also a readline operation.\n",
"You for loop is iterating over the data_file and your readline() is competing with it. Erase the line = data_file.readline() line of your code for this result:\n# Read all lines ... | [
12,
11,
4
] | [] | [] | [
"accumulator",
"python",
"readline"
] | stackoverflow_0006618882_accumulator_python_readline.txt |
Q:
Compiling python from source error with shared library loading error
When I try to run python I get the error:
python2.6: error while loading shared libraries: libpython2.6.so.1.0: cannot open shared object file: No such file or directory
I had previously compiled python with no issues and ran it fine. I didn't en... | Compiling python from source error with shared library loading error | When I try to run python I get the error:
python2.6: error while loading shared libraries: libpython2.6.so.1.0: cannot open shared object file: No such file or directory
I had previously compiled python with no issues and ran it fine. I didn't enable --with-threads or --enable-shared. Now that I enabled these two compi... | [
"sudo ldconfig -n $HOME/lib\nought to fix the problem. otherwise, strace python and pastebin the results.\n"
] | [
0
] | [] | [] | [
"compiler_construction",
"python",
"shared_libraries"
] | stackoverflow_0006619099_compiler_construction_python_shared_libraries.txt |
Q:
Where I can download django-tracker?
Possible Duplicate:
How to use django-tracker ?
Is anyone know where I can download django-tracker and the module from tracker.models import Tracker?
I mean this django-tracker http://pypi.python.org/pypi/django-tracker/0.0.1.
A:
As you are being rather vague I'll assume t... | Where I can download django-tracker? |
Possible Duplicate:
How to use django-tracker ?
Is anyone know where I can download django-tracker and the module from tracker.models import Tracker?
I mean this django-tracker http://pypi.python.org/pypi/django-tracker/0.0.1.
| [
"As you are being rather vague I'll assume that you mean this one here:\nhttp://code.google.com/p/django-tracking/\nI hope this helps.\n"
] | [
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006619627_django_python.txt |
Q:
why do wrapper classes NOT inherit basic datatypes?
I was looking at the UserDict class source and I am kind of perturbed to see:
class UserDict:
def __init__(self, dict=None, **kwargs):
self.data = {}
if dict is not None:
self.update(dict)
...
and then methods like:
def keys(self): return se... | why do wrapper classes NOT inherit basic datatypes? | I was looking at the UserDict class source and I am kind of perturbed to see:
class UserDict:
def __init__(self, dict=None, **kwargs):
self.data = {}
if dict is not None:
self.update(dict)
...
and then methods like:
def keys(self): return self.data.keys()
def items(self): return self.data.items()
... | [
"Because they're older than the ability to inherit from the basic datatypes. Modifying them to do so could have broken existing programs in various ways.\n",
"Before Python 2.2 you couldn't subclass dict. UserDict only exists for backwards compatibility.\nSee http://docs.python.org/library/userdict.html\n"
] | [
5,
4
] | [] | [] | [
"design_patterns",
"python"
] | stackoverflow_0006619978_design_patterns_python.txt |
Q:
uWSGI libxml2 headers unavailable
Every now and again a problem comes up that just seems it shouldn't have to be this exasperating. Or else I'm missing something simple (perhaps more likely).
I'm on a CentOS box trying to get uWSGI installed & configured to host a django site. I'm using python2.7 installed @ /opt/... | uWSGI libxml2 headers unavailable | Every now and again a problem comes up that just seems it shouldn't have to be this exasperating. Or else I'm missing something simple (perhaps more likely).
I'm on a CentOS box trying to get uWSGI installed & configured to host a django site. I'm using python2.7 installed @ /opt/python2.7/lib/python2.7.
Ran: pip insta... | [
"yum install libxml2-devel\nlibxml2 is a c library there is no way to load it from python without a binding.\n"
] | [
4
] | [] | [] | [
"django",
"libxml2",
"python",
"uwsgi"
] | stackoverflow_0006618575_django_libxml2_python_uwsgi.txt |
Q:
How do I access JSON data passed via AJAX in my django application?
{
"data": [
{
"name": "Kill Bill",
"category": "Movie",
"id": "179403312117362",
"created_time": "2011-06-21T17:40:15+0000"
},
{
"name": "In Search of a Midnight Kiss",
"ca... | How do I access JSON data passed via AJAX in my django application? | {
"data": [
{
"name": "Kill Bill",
"category": "Movie",
"id": "179403312117362",
"created_time": "2011-06-21T17:40:15+0000"
},
{
"name": "In Search of a Midnight Kiss",
"category": "Movie",
"id": "105514816149992",
"created_tim... | [
"It'll come as a string that needs to be desearialized.\nimport json\n\ndef some_http_call(request)\n json_string = request.GET.get('http_parameter_key', '')\n json_object = json.loads(json_string)\n\n data = json_object[\"data\"]\n for x in data:\n print x[\"name\"]\n\nAssuming some_http_call is your... | [
2,
1
] | [] | [] | [
"django",
"json",
"python"
] | stackoverflow_0006620558_django_json_python.txt |
Q:
Explain what this is for me?
So, I've seen this type thing on several occasions, but I've never been able to find out anything about it. Can someone please explain what these "r' foo(*)'" things are and link me to the python docs for them? I think they have to do with finding key words in strings. Am I right?
(r'w... | Explain what this is for me? | So, I've seen this type thing on several occasions, but I've never been able to find out anything about it. Can someone please explain what these "r' foo(*)'" things are and link me to the python docs for them? I think they have to do with finding key words in strings. Am I right?
(r'why (.*) i (.*)\?',
( "You%1%2?", ... | [
"Those appear to be regular expressions. Regular expressions let you search for patterns in strings in a fairly powerful and sophisticated way. They can be a bit cryptic though. These appear to be the basis of some kind of primitive chatterbot. \n>>> import re\n>>> regex, phrases = (r'why (.*) i (.*)\\?', \n... ( \... | [
3,
3,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0006620701_python_string.txt |
Q:
"No child processes" on os.waitpid
I'm trying to simulate behavior of os.system with Popen and waitpid on Ubuntu and I'm getting
OSError: [Errno 10] No child processes
here's how I'm using it
p = Popen(args, stdout = PIPE, stderr = PIPE)
stdout, stderr = p.communicate()
returncode = os.waitpid(p.pid, 0)[1]
I tr... | "No child processes" on os.waitpid | I'm trying to simulate behavior of os.system with Popen and waitpid on Ubuntu and I'm getting
OSError: [Errno 10] No child processes
here's how I'm using it
p = Popen(args, stdout = PIPE, stderr = PIPE)
stdout, stderr = p.communicate()
returncode = os.waitpid(p.pid, 0)[1]
I tried to get return code out of p.returnco... | [
"communicate already waits on the child process to terminate, and collects the return code itself. Therefore, when you call os.waitpid, you're calling it referencing a process ID that has already been removed from the OS tables. Therefore, you get the \"No child process\" error. \nThe return code you're looking for... | [
7,
2
] | [] | [] | [
"python",
"ubuntu",
"unix"
] | stackoverflow_0006620693_python_ubuntu_unix.txt |
Q:
obtain current status of Wikipedia articles?
I am using Python and MySQL to query mediawiki database to get the current status of articles (i.e. whether the article is FA, GA, GAN etc.) but have been unable to do so.
I know current status is stored in the old_text field of the text table. I was trying to somethin... | obtain current status of Wikipedia articles? | I am using Python and MySQL to query mediawiki database to get the current status of articles (i.e. whether the article is FA, GA, GAN etc.) but have been unable to do so.
I know current status is stored in the old_text field of the text table. I was trying to something like:
loc = select (locate('currentstatus', old_... | [
"For Wikipedia, it would be more to the point to examine the categories the article is in. Or if processing raw wikitext, look for the corresponding template:\n\nFeatured articles (FA) are in [[category:Featured articles]] and use {{featured article}}, which references [[template:featured article]]\nGood articles ... | [
0
] | [] | [] | [
"milestone",
"mysql",
"python",
"wikipedia"
] | stackoverflow_0006600693_milestone_mysql_python_wikipedia.txt |
Q:
Django vs Grails vs Lift for Comet support?
I am going to be developing a real-time web application that will make heavy use of Ajax and Comet programming techniques. I am wondering which web framework will be best to use for this type of application.
I already know Python and Django, I have built a smaller app i... | Django vs Grails vs Lift for Comet support? | I am going to be developing a real-time web application that will make heavy use of Ajax and Comet programming techniques. I am wondering which web framework will be best to use for this type of application.
I already know Python and Django, I have built a smaller app in Grails, and have experience with Scala but not ... | [
"You should also consider Tornado in the list of web frameworks. Together with tornad.io, a tornado version of socket.io javascript lib, it makes Comet techniques easy.\nI hope it helps\n",
"if you consider to go with grails , there are some plugins which might help\n\nAtmosphere\nCometd\nPusher\n\n"
] | [
0,
0
] | [] | [] | [
"comet",
"django",
"grails",
"python"
] | stackoverflow_0006620150_comet_django_grails_python.txt |
Q:
Django/python and Apache Solr: pysolr or solrpy?
brand new on this forum and this is my first post!
At work we're starting a project which uses Apache Solr and i'm in charge of the frontend system (Django-based).
Our solr database isn't related to any other db engine nor to any models' class, so Haystack isn't goo... | Django/python and Apache Solr: pysolr or solrpy? | brand new on this forum and this is my first post!
At work we're starting a project which uses Apache Solr and i'm in charge of the frontend system (Django-based).
Our solr database isn't related to any other db engine nor to any models' class, so Haystack isn't good for us (since its strictly related to the models).
I... | [
"We have used 'solrpy', but encountered some problems with it.\nSunburnt is actually an interesting API:\nhttps://github.com/tow/sunburnt/\nActively developed, and easy to use. Unfortunately it introduces some additional dependencies.\n"
] | [
6
] | [] | [] | [
"django",
"pysolr",
"python",
"solr"
] | stackoverflow_0006466188_django_pysolr_python_solr.txt |
Q:
Behavior of buggy parameter passing
I have a function:
def greeter(name, greeting, punc):
print greeting+', '+name+punc
I have a dictionary with parameters:
params={'name':'Mark','greeting':'How are you','punc':'?'}
When I call the function as greeter(**params), I get the expected output How are you, Mark?. ... | Behavior of buggy parameter passing | I have a function:
def greeter(name, greeting, punc):
print greeting+', '+name+punc
I have a dictionary with parameters:
params={'name':'Mark','greeting':'How are you','punc':'?'}
When I call the function as greeter(**params), I get the expected output How are you, Mark?. But When I call like this greeter(*params... | [
"\nLooks like a list of keys from params has been passed to greeter. What is actually happening here?\n\nThat is indeed what is happening, more or less.\n*x expects x to be an iterable, and iterates over it, interpreting the results as arguments one by one. Iterating over a dict, by default, iterates over its keys.... | [
5,
2
] | [] | [] | [
"parameter_passing",
"python"
] | stackoverflow_0006622088_parameter_passing_python.txt |
Q:
Using python to write a daemon instead of C++
I am about to start into a daemon project with a friend, he will do the design and I will do the coding
I am confused between Python and C++
I know C++, but I need to learn Python if I will go with it
The daemon I am about to write will be more than 1 daemon actually, ... | Using python to write a daemon instead of C++ | I am about to start into a daemon project with a friend, he will do the design and I will do the coding
I am confused between Python and C++
I know C++, but I need to learn Python if I will go with it
The daemon I am about to write will be more than 1 daemon actually, each one is responsible for a function, such as acc... | [
"Use the right tool for the right job. If you want a process that keeps on running for a long time you will want a proof of some of it's correctness (not a complete one, but at least something). This proof is given to you by the compiler or interpreter accepting the language. It depends a lot on the language, what ... | [
1
] | [] | [] | [
"daemon",
"linux",
"python"
] | stackoverflow_0006621501_daemon_linux_python.txt |
Q:
What is the performance hit of this order_by django query?
MyModel.objects.all().order_by('-timestamp')
There is a unique key on timestamp and another column:
`code` varchar(3) NOT NULL,
`timestamp` date NOT NULL,
UNIQUE KEY `exchangerate_currency_70883b95_uniq` (`code`,`timestamp`)
All I want is to obtain the ... | What is the performance hit of this order_by django query? | MyModel.objects.all().order_by('-timestamp')
There is a unique key on timestamp and another column:
`code` varchar(3) NOT NULL,
`timestamp` date NOT NULL,
UNIQUE KEY `exchangerate_currency_70883b95_uniq` (`code`,`timestamp`)
All I want is to obtain the latest row in the table.
The query achieves that but I am thinki... | [
"Without seeing your full query, and your schema, it's impossible to do more than speculate.\nBut... I believe the order of columns in a multi-column index in MySQL is important. This would mean that your index on (code,timestamp) is likely unusable for ordering by timestamp. If you changed the order to instead b... | [
0,
0
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0006622153_django_mysql_python.txt |
Q:
Problem with IF statement in mako template
I have mako template where i check conditions from a simple dict in for loop, like:
% for el in seq:
% if el["attr"] == 1:
...
elif:
....
else:
.....
% endif
And if i want add another IF statement in this loop, like:
%if el["a... | Problem with IF statement in mako template | I have mako template where i check conditions from a simple dict in for loop, like:
% for el in seq:
% if el["attr"] == 1:
...
elif:
....
else:
.....
% endif
And if i want add another IF statement in this loop, like:
%if el["attr1"] == 1:
....
%endif
I have error: "... | [
"You're missing the %endfor and the % from elif and else statements:\n%for el in seq:\n %if foo:\n pass\n %elif bar:\n pass\n %else:\n pass\n %endif\n%endfor\n\n"
] | [
11
] | [] | [] | [
"mako",
"pylons",
"python"
] | stackoverflow_0006621401_mako_pylons_python.txt |
Q:
Java class list like in Python
I have classes which are inherited from abstract Packet( this class has abstract method named read which reads from ByteBuffer).
in Python i would do something like...
class Blabla(Packet):
pass
class Blabla2(Packet):
pass
and then i would init each class in list like this
_... | Java class list like in Python | I have classes which are inherited from abstract Packet( this class has abstract method named read which reads from ByteBuffer).
in Python i would do something like...
class Blabla(Packet):
pass
class Blabla2(Packet):
pass
and then i would init each class in list like this
_packets = [Blabla, Blabla2]
and whe... | [
"Yes, it is possible to do something very similar in Java.\nYou could have a list of Class objects and then call list.get(packetId).newInstance() to create an instance of the correct class.\nSee the Javadoc.\n",
"This is what you should do:\nArrayList<Class> list = new ArrayList<Class>();\nlist.add(Class.forName(... | [
4,
3,
2
] | [] | [] | [
"class",
"java",
"list",
"python"
] | stackoverflow_0006622407_class_java_list_python.txt |
Q:
Storing python dates in sqlite3
is not there any way to store python dates or pyqt4 dates (QDate) in sqlite3 ? I'd not like to use sqlite's date types since i'll need to find the difference between dates that i'll store.That's what i'm trying :
record = QtCore.QDate.currentDate()
latest = self.calendar.se... | Storing python dates in sqlite3 | is not there any way to store python dates or pyqt4 dates (QDate) in sqlite3 ? I'd not like to use sqlite's date types since i'll need to find the difference between dates that i'll store.That's what i'm trying :
record = QtCore.QDate.currentDate()
latest = self.calendar.selectedDate()
db = sql.connect(":... | [
"No. Convert it to a timestamp first.\n"
] | [
2
] | [] | [] | [
"pyqt",
"python",
"sqlite"
] | stackoverflow_0006623125_pyqt_python_sqlite.txt |
Q:
Django: Context processors in views, bad practice?
In my Django project, I have a context processor which returns a FacebookUser object based on the cookies present in the request (using Facebook's Python SDK). This means that when the user is logged in, their corresponding FacebookUser object is always available ... | Django: Context processors in views, bad practice? | In my Django project, I have a context processor which returns a FacebookUser object based on the cookies present in the request (using Facebook's Python SDK). This means that when the user is logged in, their corresponding FacebookUser object is always available in my templates.
However, what should I do when I want t... | [
"If you need your FacebookUser object a lot then use middleware. Documentation is here\nFor a sample middleware class:\nclass FacebookApiIntegrator(object):\n\n def process_request(self, request):\n if request.user.is_authenticated():# check if user has logged in\n request.facebook = <your prof... | [
3,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006622630_django_python.txt |
Q:
How to reverse engineer a program which has no documentation
I have a source of python program which doesn't have any documentation or comments.
I did tried twice to understand it but most of the times I am losing my track, because there are many files.
What should be the steps to understand that program fully a... | How to reverse engineer a program which has no documentation | I have a source of python program which doesn't have any documentation or comments.
I did tried twice to understand it but most of the times I am losing my track, because there are many files.
What should be the steps to understand that program fully and quickly.
| [
"Michael Feathers' \"Working Effectively with Legacy Code\" is a superb starting point for such endeavors -- not particularly language-dependent (his examples are in several non-python languages, but the techniques and mindset DO extend pretty well to Python and just about any other language).\nThe key focus is, th... | [
11,
5,
5,
3,
2,
1,
0,
0
] | [] | [] | [
"open_source",
"python"
] | stackoverflow_0001397572_open_source_python.txt |
Q:
boost.python "DLL load failed" on WinXP, VisualStudio 2005
I have problems importing a boost-python module on WinXP-32.
I'm using python 2.6.6, boost.python 1.41 precompiled libs by boostpro and VC++8 (VisualStudio 2005).
After compiling the piece of code below, I tried to import the resulting pyHELLO.pyd from the... | boost.python "DLL load failed" on WinXP, VisualStudio 2005 | I have problems importing a boost-python module on WinXP-32.
I'm using python 2.6.6, boost.python 1.41 precompiled libs by boostpro and VC++8 (VisualStudio 2005).
After compiling the piece of code below, I tried to import the resulting pyHELLO.pyd from the python command line and always get:
"ImportError: DLL load fai... | [
"Resolved:\nThe correct version of the MSVC80CRT dll on which the boost.python dll depends was missing on my machine. I downloaded the corresponding redist package from MS and installed it. Now it works. \nThe dependencywalker did not show a missing dependency for this dll.\nAfter reading about manifests and SxS I ... | [
0
] | [] | [] | [
"boost_python",
"python",
"visual_studio_2005",
"windows_xp"
] | stackoverflow_0006492602_boost_python_python_visual_studio_2005_windows_xp.txt |
Q:
Python subprocess module: parent child communication not working
I'm trying to run the following code as a subprocess
#include<stdio.h>
int main()
{
int a;
printf("Hello\n");
fprintf(stderr, "Hey\n");
scanf("%d", &a);
printf("%d\n", a);
return 0;
}
This script works fine: write to stdin, r... | Python subprocess module: parent child communication not working | I'm trying to run the following code as a subprocess
#include<stdio.h>
int main()
{
int a;
printf("Hello\n");
fprintf(stderr, "Hey\n");
scanf("%d", &a);
printf("%d\n", a);
return 0;
}
This script works fine: write to stdin, read from stdout and from stderr.
#!/usr/bin/python
import subprocess
... | [
"You need to flush the stream first. This will make sure all data is actually written to the stream.\n#include<stdio.h>\nint main()\n{\n int a;\n printf(\"Hello\\n\");\n fprintf(stderr, \"Hey\\n\");\n fflush(stdout); // <--\n scanf(\"%d\", &a);\n printf(\"%d\\n\", a);\n return 0;\n}\n\nBy defau... | [
2,
0
] | [] | [] | [
"popen",
"python",
"subprocess"
] | stackoverflow_0006621799_popen_python_subprocess.txt |
Q:
Python Pyramid - Add multiple chameleon base templates
I am using this procedure to use a base template which the other templates can derive from.
How can I create multiple base templates?
A:
Just register them both:
from pyramid.renderers import get_renderer
def add_base_template(event):
base = get_render... | Python Pyramid - Add multiple chameleon base templates | I am using this procedure to use a base template which the other templates can derive from.
How can I create multiple base templates?
| [
"Just register them both:\nfrom pyramid.renderers import get_renderer\n\ndef add_base_template(event):\n base = get_renderer('templates/base.pt').implementation()\n base2 = get_renderer('templates/base2.pt').implementation()\n event.update({'base': base, 'base2': base2})\n\nAnd then choose which to use in ... | [
3
] | [] | [] | [
"chameleon",
"pyramid",
"python",
"template_metal",
"template_tal"
] | stackoverflow_0006623420_chameleon_pyramid_python_template_metal_template_tal.txt |
Q:
String slicing in python
I want to slice word from the end.Suppose, I have some line with case sensitives(Upper/lower case)
Abc Defg Hijk Lmn
Xyz Lmn jkf gkjhg
I want to slice them as like below :
Abc Defg Hijk
Abc Defg
Abc
Then I need to take each sliced line in variables so that I can use them to search in ... | String slicing in python | I want to slice word from the end.Suppose, I have some line with case sensitives(Upper/lower case)
Abc Defg Hijk Lmn
Xyz Lmn jkf gkjhg
I want to slice them as like below :
Abc Defg Hijk
Abc Defg
Abc
Then I need to take each sliced line in variables so that I can use them to search in some text file & return the wh... | [
"Use rsplit function:\n>>> s = 'Abc Defg Hijk Lmn'\n>>> s.rsplit(' ', 1)[0]\n'Abc Defg Hijk'\n>>> s = s.rsplit(' ', 1)[0]\n>>> s.rsplit(' ', 1)[0]\n'Abc Defg'\n\nand so on...\nAnother variant:\n>>> words = s.split()\n>>> [' '.join(words[:i]) for i in range(len(words), 0, -1)]\n['Abc Defg Hijk Lmn', 'Abc Defg Hijk',... | [
5,
1,
0
] | [] | [] | [
"python",
"slice",
"substring"
] | stackoverflow_0006623887_python_slice_substring.txt |
Q:
python setuptools and easy_install numpy question
So I'm having a bit of a dillema here. Doesn't setuptools use easy_install to get the additional dependencies you specify in a setup.py ? I'm asking because say I have a setup.yp and in the install_requires = ["numpy"]. Now if I run python setup.py install that g... | python setuptools and easy_install numpy question | So I'm having a bit of a dillema here. Doesn't setuptools use easy_install to get the additional dependencies you specify in a setup.py ? I'm asking because say I have a setup.yp and in the install_requires = ["numpy"]. Now if I run python setup.py install that gives a error:
_configtest.c:1:20: error: Python.h: No s... | [
"The kind of error you're receiving is usually because you don't have the Python development package installed. If you're using an Ubuntu based distribution, go to Synaptic, and search for python-dev ( the name may not be 100% accurate, do a little browsing there ).\nIt could be that easy_install works with prebuil... | [
5
] | [] | [] | [
"numpy",
"python",
"setuptools"
] | stackoverflow_0006623973_numpy_python_setuptools.txt |
Q:
Using sqlalchemy.sql.functions.char_length as a filter condition
I'm using Elixir and sqla 0.6, and I'm trying to query my model:
class Document(Entity):
using_options(shortnames=True, order_by='doc_date')
doc_number = Field(Unicode(20),index=True)
...for Documents having numbers of a given length.
I wa... | Using sqlalchemy.sql.functions.char_length as a filter condition | I'm using Elixir and sqla 0.6, and I'm trying to query my model:
class Document(Entity):
using_options(shortnames=True, order_by='doc_date')
doc_number = Field(Unicode(20),index=True)
...for Documents having numbers of a given length.
I was thinking about something like this:
Document.query.filter(Document.d... | [
"Ok, found an answer:\nfrom sqlalchemy import func\nDocument.query.filter(func.char_length(Document.doc_number)==5).all()\n\n"
] | [
6
] | [] | [] | [
"python",
"python_elixir",
"sqlalchemy"
] | stackoverflow_0006600008_python_python_elixir_sqlalchemy.txt |
Q:
Send XML using urllib
Following this link I tried sending a XML file to my web service using GET:
import urllib
from createfile import XML
URL = "http://http://localhost:8080/mywebservice
parameter = urllib.urlencode({'XML': XML})
response = urllib.urlopen(URL + "?%s" % parameter)
print response.read()
But it... | Send XML using urllib | Following this link I tried sending a XML file to my web service using GET:
import urllib
from createfile import XML
URL = "http://http://localhost:8080/mywebservice
parameter = urllib.urlencode({'XML': XML})
response = urllib.urlopen(URL + "?%s" % parameter)
print response.read()
But it gives me this error:
Trac... | [
"Sending a XML file through a GET request is bare nonsense.\nUse POST instead.\n"
] | [
3
] | [] | [] | [
"python",
"urllib"
] | stackoverflow_0006623900_python_urllib.txt |
Q:
Issue with removing newline character from unicode string in python
I have a piece of Unicode text. I wanted to remove all newline characters from the text before printing the output. My code looks something like this:
input_string = u'\u3010JK\u3011\u9032\u5b66\u306b\u56f0\u3063\u305f\uff2a\uff2b\u304c\u5148\u751... | Issue with removing newline character from unicode string in python | I have a piece of Unicode text. I wanted to remove all newline characters from the text before printing the output. My code looks something like this:
input_string = u'\u3010JK\u3011\u9032\u5b66\u306b\u56f0\u3063\u305f\uff2a\uff2b\u304c\u5148\u751f\u306b\u52a9\u3051\u3066\u3082\u3089\u3046\u305f\u3081\u306b\uff33\uff25... | [
"According to my Python, your string contains no characters of category Cc (control character):\n>>> unicodedata.category(u'\\n') in map(unicodedata.category, input_string)\nFalse\n\nso there is no newline in this string. unicodedata.name confirms this:\n>>> for c in s: print unicodedata.name(c)\n... \nLEFT BLACK L... | [
6,
1
] | [] | [] | [
"newline",
"python",
"unicode",
"unicode_string"
] | stackoverflow_0006624680_newline_python_unicode_unicode_string.txt |
Q:
django-mptt and ForeignKey with blank=True
I am using django-mptt in my project
models.py:
class Category(models.Model):
name = models.TextField()
parent = models.ForeignKey("self", blank=True, null=True,
related_name="sub_category")
image = models.ImageField(upload_to="c... | django-mptt and ForeignKey with blank=True | I am using django-mptt in my project
models.py:
class Category(models.Model):
name = models.TextField()
parent = models.ForeignKey("self", blank=True, null=True,
related_name="sub_category")
image = models.ImageField(upload_to="categories", blank=True)
mptt.register(Category)... | [
"Use required=False when initializing the TreeNodeChoiceField object.\nfield = TreeNodeChoiceField(\n required=False,\n queryset=Category.objects.all(),\n level_indicator = u'+--',\n )\n\nDjango form ... | [
1
] | [] | [] | [
"django",
"foreign_keys",
"mptt",
"python"
] | stackoverflow_0006623608_django_foreign_keys_mptt_python.txt |
Q:
Django psycopg2 template return
i am searching some words in remote database with python psycopg2 module and than append them in list then taking it django template .. i have problem with how can i get third and eight object from list
my view.py:
result=[]
....
rows = cur.fetchall()
for row in rows:
result.appe... | Django psycopg2 template return | i am searching some words in remote database with python psycopg2 module and than append them in list then taking it django template .. i have problem with how can i get third and eight object from list
my view.py:
result=[]
....
rows = cur.fetchall()
for row in rows:
result.append(row)
return render_to_response("s... | [
"Sorry misread the question.\nTry starting from this\ndef fields(cursor):\n results = {}\n column = 0\n for d in cursor.description:\n results[d[0]] = column\n column = column + 1\n\n return results \n\nas you can see you can modify my code to get out your 3rd and 8th columns as list\nalso... | [
2,
1
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0006623855_django_django_templates_python.txt |
Q:
matching a multiline make-line variable assignment with a python regexp
I am trying to extract from a multiline make-line variable assignment the multiline value. The following testcase fails to find a match in the input string and I have to confess that I fail to see why. Help on making this sample code print "a ... | matching a multiline make-line variable assignment with a python regexp | I am trying to extract from a multiline make-line variable assignment the multiline value. The following testcase fails to find a match in the input string and I have to confess that I fail to see why. Help on making this sample code print "a \ b" on stdout would be most welcome.
#!/usr/bin/env python ... | [
"re.M means re.MULTILINE, but it doesn't concern the symbolism of dot, it concerns the symbolism of ^ and $\nYou need to specify re.DOTALL to make the dot able to match even with '\\n'\ndef test():\n s = r\"\"\" \n\nFOO=a \\ \n\n b\n\n \"\"\"\n import re\n print repr(s)\n print '----------------... | [
2,
1,
0,
0
] | [] | [] | [
"multiline",
"python",
"regex"
] | stackoverflow_0006624152_multiline_python_regex.txt |
Q:
Django - QuerySet to multi-dimensional list
I have the following models:
class Fixture(models.Model):
id = models.AutoField(primary_key=True)
home_team = models.ForeignKey(Player, related_name="home")
away_team = models.ForeignKey(Player, related_name="away")
game_week = models.PositiveSmallInteger... | Django - QuerySet to multi-dimensional list | I have the following models:
class Fixture(models.Model):
id = models.AutoField(primary_key=True)
home_team = models.ForeignKey(Player, related_name="home")
away_team = models.ForeignKey(Player, related_name="away")
game_week = models.PositiveSmallIntegerField(max_length=2, default=0)
What I want to do... | [
"Easiest way to do it is to use a dictionary:\n fixtures = Fixture.objects.all()\n fixture_dict = {}\n for fixture in fixtures:\n fixture_dict.setdefault(fixture.game_week, []).append(fixture)\n\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006625287_django_python.txt |
Q:
Installing/uninstalling my module with pip
I am going through the Learn Python the Hard Way, 2nd Edition book, and I am stuck on this problem: "Use your setup.py to install your own module and make sure it works, then use pip to uninstall it."
If I type
setup.py install
in the command line, I can install the modu... | Installing/uninstalling my module with pip | I am going through the Learn Python the Hard Way, 2nd Edition book, and I am stuck on this problem: "Use your setup.py to install your own module and make sure it works, then use pip to uninstall it."
If I type
setup.py install
in the command line, I can install the module.
But when I type
pip uninstall setup.py
it... | [
"You're giving pip a Python file and not a package name, so it doesn't know what to do. If you want pip to remove it, try providing the name of the package this setup.py file is actually part of.\nThere are some good suggestions in this related thread:\npython setup.py uninstall\n"
] | [
38
] | [] | [] | [
"installation",
"pip",
"python",
"uninstallation"
] | stackoverflow_0006625597_installation_pip_python_uninstallation.txt |
Q:
Solution to storing 300MB in memory for Google App Engine
I am using Google App Engine in Python. I have 5000 people in my database. The entire list of 5000 people objects takes up 300 MB of memory.
I have been trying to store this in memory using blobcache, a module written [here][1].
I am running into pickle "O... | Solution to storing 300MB in memory for Google App Engine | I am using Google App Engine in Python. I have 5000 people in my database. The entire list of 5000 people objects takes up 300 MB of memory.
I have been trying to store this in memory using blobcache, a module written [here][1].
I am running into pickle "OutOfMemory" issues, and am looking for a solution that involves... | [
"You should not have all 5000 users in memory at once. Only retrieve the one you need.\n",
"For this size of data why not use a blobstore and memcache?\nIn terms of performance (from highest to lowest):\n\nlocal instance memory (your data set is too large)\nmemcache (partition your data into several keys and you... | [
2,
0,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"memcached",
"python"
] | stackoverflow_0006540769_google_app_engine_google_cloud_datastore_memcached_python.txt |
Q:
Turn a pyqt application into a client-server application
I am developping an application using PyQt.
I didn't plan in from the start but I would need to turn this application into a client-server application : centralize the code and have potentially many clients connected to it.
The thing is, I'm very bad in netw... | Turn a pyqt application into a client-server application | I am developping an application using PyQt.
I didn't plan in from the start but I would need to turn this application into a client-server application : centralize the code and have potentially many clients connected to it.
The thing is, I'm very bad in network programming.
Do you know what would be the steps to follow... | [
"I would suggest using Twisted.\nIt can easily be integrated into PyQt4 and it's a comprehensive network programming library.\nTwisted documentation: http://twistedmatrix.com/trac/wiki/Documentation\nReactor that can integrate with PyQt4's event loop: http://twistedmatrix.com/trac/attachment/ticket/1770/qt4reactor.... | [
1
] | [] | [] | [
"client_server",
"network_programming",
"pyqt",
"python"
] | stackoverflow_0006625442_client_server_network_programming_pyqt_python.txt |
Q:
Does someone use Django-Socialauth successful
I am using Django-Socialauth , my site is here
But I'm not successful now, I think Django-Socialauth lacks a method that get user data from openid_response.
Can anyone give me successful demo about it?
A:
I have not used Django-Socialauth, but the same functionalit... | Does someone use Django-Socialauth successful | I am using Django-Socialauth , my site is here
But I'm not successful now, I think Django-Socialauth lacks a method that get user data from openid_response.
Can anyone give me successful demo about it?
| [
"I have not used Django-Socialauth, but the same functionality is offered by a package with a similar name called:\ndjango-social-auth\nwhich I find to be very well documented.\nYou can find it here: https://github.com/omab/django-social-auth\nYou can find documentation and examples here:\nhttp://django-social-auth... | [
2
] | [] | [] | [
"django",
"django_socialauth",
"openid",
"python"
] | stackoverflow_0004476492_django_django_socialauth_openid_python.txt |
Q:
Dynamically building up types in python
Suppose I am building a composite set of types:
def subordinate_type(params):
#Dink with stuff
a = type(myname, (), dict_of_fields)
return a()
def toplevel(params)
lots_of_types = dict(keys, values)
myawesomedynamictype = type(toplevelname, (), lots_of_type... | Dynamically building up types in python | Suppose I am building a composite set of types:
def subordinate_type(params):
#Dink with stuff
a = type(myname, (), dict_of_fields)
return a()
def toplevel(params)
lots_of_types = dict(keys, values)
myawesomedynamictype = type(toplevelname, (), lots_of_types)
#Now I want to edit some of the value... | [
"This is an ancient question, and because it's not clear what the code is trying to do (being a code gist rather than working code), it's a little hard to answer. \nBut it sounds like you want a reference to the dynamically created class \"myawesomedynamictype\" on the class itself. A copy of (I believe a copy of)... | [
1
] | [] | [] | [
"metaprogramming",
"python",
"types"
] | stackoverflow_0003398586_metaprogramming_python_types.txt |
Q:
selected value in Django forms.ChoiceField
Here i have the form
vote = forms.ChoiceField(widget=forms.Select(), choices=(('1', '1',), ('2', '2',), ('3', '3',)), initial='2')
Django1.3 create from it the code
<option value="1">1</option>
<option value="2" selected="selected">2</option>
<option value="3">3</option>... | selected value in Django forms.ChoiceField | Here i have the form
vote = forms.ChoiceField(widget=forms.Select(), choices=(('1', '1',), ('2', '2',), ('3', '3',)), initial='2')
Django1.3 create from it the code
<option value="1">1</option>
<option value="2" selected="selected">2</option>
<option value="3">3</option>
This selected-tag does not work. Should be
<op... | [
"Occasionally, I've seen browsers not select the appropriate option, even with selected=\"selected\" when doing an F5 or Command + R (on Mac). However, doing a full refresh of the page (Ctrl + F5) in FF on Windows, or reloading the url from the address bar, will correctly select the selected option. FireFox does so... | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006625857_django_python.txt |
Q:
Check if path accessible by non-root user
I have an installation script written in Python (in Linux) that runs as root and needs to check whether certain files are readable by a non-root user.
For this reason I can't use os.path.exists() or open(filename) (and catch any exceptions).
Currently I'm thinking of chec... | Check if path accessible by non-root user | I have an installation script written in Python (in Linux) that runs as root and needs to check whether certain files are readable by a non-root user.
For this reason I can't use os.path.exists() or open(filename) (and catch any exceptions).
Currently I'm thinking of checking the permission bit on each of the files, b... | [
"You could use os.seteuid to change the effective user to some non-root user. Then try opening the file. An IOError will be raised if permission is denied.\nimport os\nos.seteuid(65534) # user 65534 is `nobody`\nfilename='/etc/passwd-'\ntry:\n open(filename,'r')\nexcept IOError as err:\n print(err)\n\n# [Err... | [
4
] | [] | [] | [
"file_permissions",
"linux",
"python"
] | stackoverflow_0006625919_file_permissions_linux_python.txt |
Q:
How do I get the stack trace from an Exception Object in Python 2.7?
How can I get the full stack trace from the Exception object itself?
Consider the following code as reduced example of the problem:
last_exception = None
try:
raise Exception('foo failed')
except Exception as e:
print "Exception Stack Tra... | How do I get the stack trace from an Exception Object in Python 2.7? | How can I get the full stack trace from the Exception object itself?
Consider the following code as reduced example of the problem:
last_exception = None
try:
raise Exception('foo failed')
except Exception as e:
print "Exception Stack Trace %s" % e
| [
"The stack trace itself is not stored in the exception object itself. However, you can print the stack trace of the last recent exception using sys.exc_info() and the traceback module. Example:\nimport sys\nimport traceback\n\ntry:\n raise Exception('foo failed')\nexcept Exception as e:\n traceback.print_tb(*... | [
5
] | [] | [] | [
"exception_handling",
"python"
] | stackoverflow_0006626342_exception_handling_python.txt |
Q:
replace/modify tail of a gz file with gzip.open
I have a gz file that with a huge size, is it possible to replace the tail without touching the rest of the file? I tried gzip.open( filePath, mode = 'r+' ) but the write method was blocked .... saying it is a read-only object ... any idea?
what I am doing now is...... | replace/modify tail of a gz file with gzip.open | I have a gz file that with a huge size, is it possible to replace the tail without touching the rest of the file? I tried gzip.open( filePath, mode = 'r+' ) but the write method was blocked .... saying it is a read-only object ... any idea?
what I am doing now is... gzip.open as r and once I get the offset of the star... | [
"Not possible - you can not replace parts of a compressed file without decompressing it first. At least not with the common compression algorithms.\n"
] | [
2
] | [] | [] | [
"gzip",
"python",
"tail"
] | stackoverflow_0006626629_gzip_python_tail.txt |
Q:
Build a PyObject* from a C function?
I am embedding Python in a C++ library which I am making. I would like users to be able to pass C functions in the form of function pointers PyObject* (fpFunc*)(PyObject*,PyObject*); so that I can use those functions in the embedded Python.
So I have a function pointer and I kn... | Build a PyObject* from a C function? | I am embedding Python in a C++ library which I am making. I would like users to be able to pass C functions in the form of function pointers PyObject* (fpFunc*)(PyObject*,PyObject*); so that I can use those functions in the embedded Python.
So I have a function pointer and I know that it is possible to put this functio... | [
"Found it. Though it's not in the docs and it's hardly explicit in the source.\nPyObject* (*fpFunc)(PyObject*,PyObject*) = someFunction;\nPyMethodDef methd = {\"methd\",fpFunc,METH_VARARGS,\"A new function\"};\nPyObject* name = PyString_FromString(methd.ml_name);\nPyObject* pyfoo = PyCFunction_NewEx(&methd,NULL,nam... | [
26
] | [] | [] | [
"c",
"python",
"python_c_api"
] | stackoverflow_0006626167_c_python_python_c_api.txt |
Q:
How to pass a variable to an exception when raised and retrieve it when excepted?
Right now I just have a blank exception class. I was wondering how I can give it a variable when it gets raised and then retrieve that variable when I handle it in the try...except.
class ExampleException (Exception):
pass
A:
G... | How to pass a variable to an exception when raised and retrieve it when excepted? | Right now I just have a blank exception class. I was wondering how I can give it a variable when it gets raised and then retrieve that variable when I handle it in the try...except.
class ExampleException (Exception):
pass
| [
"Give its constructor an argument, store that as an attribute, then retrieve it in the except clause:\nclass FooException(Exception):\n def __init__(self, foo):\n self.foo = foo\n\ntry:\n raise FooException(\"Foo!\")\nexcept FooException as e:\n print e.foo\n\n"
] | [
72
] | [
"You can do this.\ntry:\n ex = ExampleException()\n ex.my_variable= \"some value\"\n raise ex\nexcept ExampleException, e:\n print( e.my_variable )\n\nWorks fine.\n"
] | [
-2
] | [
"exception",
"python"
] | stackoverflow_0006626816_exception_python.txt |
Q:
Is using a giant OR regex inefficent in python?
Simple question, is using a giant OR regex inefficent in python. I am building a script to search for bad files. I have a source file that contains 50 or so "signatures" so far. The list is in the form of:
Djfsid
LJflsdflsdf
fjlsdlf
fsdf
.
.
.
There are no... | Is using a giant OR regex inefficent in python? | Simple question, is using a giant OR regex inefficent in python. I am building a script to search for bad files. I have a source file that contains 50 or so "signatures" so far. The list is in the form of:
Djfsid
LJflsdflsdf
fjlsdlf
fsdf
.
.
.
There are no real "consistancies" so optomizing the list by remov... | [
"\nAlso is this a good way to multithread? \n\nNot really.\n\nWill disk access basically bottelneck me to the point where multithreading is useless?\n\nCorrect.\nYou might want to look closely at multiprocessing.\n\nA worker Process should do the OS.walk and put the file names into a Queue.\nA pool of worker Proces... | [
3,
0,
0
] | [] | [] | [
"multithreading",
"performance",
"python",
"regex",
"string"
] | stackoverflow_0006626798_multithreading_performance_python_regex_string.txt |
Q:
Update numbers in the middle of a string
I'm looking at diff-style output, but I need to update the line numbers. So I see:
*** 1,2 *****
Actual line 1
Actual line 2
--- 1,2 -----
Expected line 1
Expected line 2
and in my results file, I'm at resline. So if resline=line 90, I'd want to change the second "1,2" t... | Update numbers in the middle of a string | I'm looking at diff-style output, but I need to update the line numbers. So I see:
*** 1,2 *****
Actual line 1
Actual line 2
--- 1,2 -----
Expected line 1
Expected line 2
and in my results file, I'm at resline. So if resline=line 90, I'd want to change the second "1,2" to "91,92".
In perl, I'd use the following on t... | [
"You would use re.sub and pass in a callable instead of a string as the replacement:\nimport re\nre.sub(r'\\d+?', lambda m: str(int(m.group(0))+resline), YOUR_STR)\n\n"
] | [
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006627010_python_regex.txt |
Q:
How to delete a s3 version from a bucket using boto and python
When I try to delete a bucket using the lines:
conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
print conn.delete_Bucket('BucketNameHere').message
It tells me the bucket I tried to delete is not empty.
The bucket has no keys in it. B... | How to delete a s3 version from a bucket using boto and python | When I try to delete a bucket using the lines:
conn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
print conn.delete_Bucket('BucketNameHere').message
It tells me the bucket I tried to delete is not empty.
The bucket has no keys in it. But it does have versions.
How can I delete the versions?
I can see t... | [
"Boto does support versioned buckets after version 1.9c. Here's how it works:\nimport boto\n\ns3 = boto.connect_s3()\n\n#Create a versioned bucket\nbucket = s3.create_bucket(\"versioned.example.com\")\nbucket.configure_versioning(True)\n\n#Create a new key and make a few versions\nkey = bucket.new_key(\"versioned_... | [
22
] | [] | [] | [
"amazon_s3",
"boto",
"python",
"versions"
] | stackoverflow_0006525270_amazon_s3_boto_python_versions.txt |
Q:
possibilities for fast dynamic code execution in Python
I have some code available in some form of AST and I would like to execute it.
I can think of several ways to do this, e.g.:
Just straight-forwardly interpret it.
Translate it into a Python AST (the ast module) and
Python-compile that or
Python-eval that.
... | possibilities for fast dynamic code execution in Python | I have some code available in some form of AST and I would like to execute it.
I can think of several ways to do this, e.g.:
Just straight-forwardly interpret it.
Translate it into a Python AST (the ast module) and
Python-compile that or
Python-eval that.
Translate it into Python source code (e.g. a pure string) and... | [
"Another possibility: translate to Cython code, write out to a file, compile with Cython then a C compiler with optimization turned on, load the resulting module and execute it.\nIf the code has type annotations that can be translated to Cython/C types, this can be blazing fast. Watch out, though, as Cython is in b... | [
1,
0
] | [] | [] | [
"abstract_syntax_tree",
"jit",
"python",
"scripting",
"vm_implementation"
] | stackoverflow_0006626901_abstract_syntax_tree_jit_python_scripting_vm_implementation.txt |
Q:
Reshaping a numpy array in python
I have a 48x365 element numpy array where each element is a list containing 3 integers. I want to be able to turn it into a 1x17520 array with all the lists intact as elements. Using
np.reshape(-1)
seems to break the elements into three separate integers and makes a 1x52560 array... | Reshaping a numpy array in python | I have a 48x365 element numpy array where each element is a list containing 3 integers. I want to be able to turn it into a 1x17520 array with all the lists intact as elements. Using
np.reshape(-1)
seems to break the elements into three separate integers and makes a 1x52560 array. So I either need a new way of rearran... | [
"Is there a reason you can't do it explicitly? As in:\n>>> a = numpy.arange(17520 * 3).reshape(48, 365, 3)\n>>> a.reshape((17520,3))\narray([[ 0, 1, 2],\n [ 3, 4, 5],\n [ 6, 7, 8],\n ..., \n [52551, 52552, 52553],\n [52554, 52555, 52556],\n [52557... | [
6
] | [] | [] | [
"multidimensional_array",
"numpy",
"python",
"reshape"
] | stackoverflow_0006627647_multidimensional_array_numpy_python_reshape.txt |
Q:
Pymongo gives db assertion failure while trying to access remote server
I am getting the following error:
db assertion failure, assertion: 'unauthorized db:db1 lock type:-1 client:', assertionCode: 10057
I am able to access the MongoDB database by running python on the shell of my server. But when I try to acces... | Pymongo gives db assertion failure while trying to access remote server | I am getting the following error:
db assertion failure, assertion: 'unauthorized db:db1 lock type:-1 client:', assertionCode: 10057
I am able to access the MongoDB database by running python on the shell of my server. But when I try to access my site i get this unauthorised errors.
Any fix for this error?
| [
"This means that your database is using authentication. In such a setup, you must authenticate a valid user before you can perform any operations (queries, commands, updates, etc). You can do so with the db.auth(username, password) helper in the mongo shell (described in the MongoDB docs), and with Python, you can ... | [
5
] | [] | [] | [
"django",
"mongodb",
"pymongo",
"python"
] | stackoverflow_0006627611_django_mongodb_pymongo_python.txt |
Q:
syntax error on line: `if x.isupper() and not in y`
I'm getting "invalid syntax" errors pointing to the "in" statement. What's my mistake?
while(notes > 1):
note = choice(scale)
if note[0].isupper() and not in patternNotes:
patternNotes.append(note)
notes -= 1
elif note is not rootNote... | syntax error on line: `if x.isupper() and not in y` | I'm getting "invalid syntax" errors pointing to the "in" statement. What's my mistake?
while(notes > 1):
note = choice(scale)
if note[0].isupper() and not in patternNotes:
patternNotes.append(note)
notes -= 1
elif note is not rootNote and note not in patternNotes:
patternNotes.appen... | [
"You probably want \nif note[0].isupper() and note not in patternNotes:\n\nrather than \nif note[0].isupper() and not in patternNotes:\n\nNote the lacking note in the second one.\n",
"It should be note[0].isupper() and note not in patternNotes: (notice the second note before not)\nAfter that your syntax is fine:\... | [
5,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006626176_python.txt |
Q:
How do I bind an existing instance method in one class to another class?
I'm trying to do a limited form of dynamic mixin on a class, taking methods from a third-party library class and binding them to my class. But nothing I've tried has worked correctly. All examples I've seen elsewhere bind a unbound function t... | How do I bind an existing instance method in one class to another class? | I'm trying to do a limited form of dynamic mixin on a class, taking methods from a third-party library class and binding them to my class. But nothing I've tried has worked correctly. All examples I've seen elsewhere bind a unbound function to a class but, in my case, I need to bind an already bound method to a differe... | [
"Add it as a parent class dynamically, by modifying YourClass.__bases__:\n>>> class Base: pass\n>>> class Foo(Base): pass\n>>> class Bar(Base): attr = True\n>>> Foo.__bases__ = (Bar,) + Foo.__bases__\n>>> Foo.attr\nTrue\n\nAlternatively, get the bound method object and extract the original function, then attach tha... | [
8,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0006627387_python.txt |
Q:
Is JSON syntax a strict subset of Python syntax?
JSON is very similar to Python syntax. Can all JSON objects directly convert to Python without error?
Example
The following is a valid JSON object:
// Valid JSON
{"foo":"bar"}
This object will directly translate to a Python dictionary with key "foo" and value "bar"... | Is JSON syntax a strict subset of Python syntax? | JSON is very similar to Python syntax. Can all JSON objects directly convert to Python without error?
Example
The following is a valid JSON object:
// Valid JSON
{"foo":"bar"}
This object will directly translate to a Python dictionary with key "foo" and value "bar":
# Python
json_dict = eval('{"foo":"bar"}')
| [
"No. In particular, true, false, and null are not Python, although they do have direct equivalents in Python (True, False, and None respectively).\n// Valid JSON\n{\"sky_is_blue\":true}\n\nBut when used in Python...\n# Python\n>>> json_dict = eval('{\"sky_is_blue\":true}')\nTraceback (most recent call last):\n Fil... | [
19,
6
] | [] | [] | [
"javascript",
"json",
"python",
"syntax"
] | stackoverflow_0006627635_javascript_json_python_syntax.txt |
Q:
group by multiple fileds and order by count of group in python/django
Please help me in getting the result of below in django/python
SELECT u,v,x,y,z,count(1) FROM table1 group by u,v,x,y,z order by 5,6;
A:
Not sure what you mean by order by 5,6, I assume you have columns with that name...
Anyway, it should wo... | group by multiple fileds and order by count of group in python/django | Please help me in getting the result of below in django/python
SELECT u,v,x,y,z,count(1) FROM table1 group by u,v,x,y,z order by 5,6;
| [
"Not sure what you mean by order by 5,6, I assume you have columns with that name...\nAnyway, it should work like this:\nresults = MyModelForTable1.objects.values('u', 'v', 'x', 'y', 'z').annotate(Count('u')).order_by('5', '6')\n\n"
] | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0006627510_django_django_models_python.txt |
Q:
Which file is used in import statement for 'MultipleObjectsReturne' exception
I am using this code
except MultipleObjectsReturned:
return HttpResponse('some error')
but i get this error
global name 'MultipleObjectsReturned' is not defined
A:
You can do either:
from django.core.exceptions import MultipleObje... | Which file is used in import statement for 'MultipleObjectsReturne' exception | I am using this code
except MultipleObjectsReturned:
return HttpResponse('some error')
but i get this error
global name 'MultipleObjectsReturned' is not defined
| [
"You can do either:\nfrom django.core.exceptions import MultipleObjectsReturned\n\nexcept MultipleObjectsReturned as e:\n return HttpResponse(e)\n\nOr:\nexcept yourmodel.MultipleObjectsReturned as e:\n return HttpResponse(e)\n\nhttps://docs.djangoproject.com/en/1.3/ref/exceptions/#django.core.exceptions.Multi... | [
10,
3
] | [] | [] | [
"exception_handling",
"python"
] | stackoverflow_0006628272_exception_handling_python.txt |
Q:
Django's Admin Interface for Read-Only Model?
I have a Django model whose fields are read-only, populated from a database.
I have found that the admin interface is a great way to visualize my data, but whenever I try using it, I run into a problem: It seems to require write access to the database, which I don't ha... | Django's Admin Interface for Read-Only Model? | I have a Django model whose fields are read-only, populated from a database.
I have found that the admin interface is a great way to visualize my data, but whenever I try using it, I run into a problem: It seems to require write access to the database, which I don't have.
(i.e. it tries to create tables called auth_use... | [
"I figured out how to do this:\n\nCreate an in-memory sqlite database (use :memory: as the database) for the internal data\nUse a database router for redirecting the reads to the other database\n\n"
] | [
0
] | [] | [] | [
"database",
"django",
"model",
"python",
"readonly"
] | stackoverflow_0006379749_database_django_model_python_readonly.txt |
Q:
Open a script on workspace with just a link
Automater sends out an automated e-mail message that contains several links.
The links provided will call a script with different command line arguments depending on which link they clicked on.
So for example an e-mail would look like this:
Zipped contents located at... | Open a script on workspace with just a link | Automater sends out an automated e-mail message that contains several links.
The links provided will call a script with different command line arguments depending on which link they clicked on.
So for example an e-mail would look like this:
Zipped contents located at this link \\intranet\nightbuild: click1
Click on... | [
"Opening links it Microsoft Outlook automatically open the file in the correct manner, however, I still had one problem, according to this link. Microsoft outlook does NOT allow you edit html in the outlook viewer, it follows the WYSIWYG (what you see is what you get) philosophy.\nThus all html must be handled by ... | [
0
] | [] | [] | [
"html",
"python"
] | stackoverflow_0006554165_html_python.txt |
Q:
Python logical NOT operator for regular expressions
I tried searching for this answer online but I haven't found any luck. I am wondering if python supports a logical not operator (usually '!') in other languages for an if statement, or any control statement really. For example, I am looking to achieve this functi... | Python logical NOT operator for regular expressions | I tried searching for this answer online but I haven't found any luck. I am wondering if python supports a logical not operator (usually '!') in other languages for an if statement, or any control statement really. For example, I am looking to achieve this functionality.
if !(re.search('[0-9]', userInputVariable):
... | [
"You're looking for the not operator.\nBut that's not how you check for a number.\ntry:\n int(userInputVariable)\nexcept ValueError:\n print \"Not a number\"\n\n...\nif not userInputVariable.isdigit():\n\n"
] | [
6
] | [] | [] | [
"logical_operators",
"python"
] | stackoverflow_0006628780_logical_operators_python.txt |
Q:
Referencing Django login name from within a model
I'll start by saying that my database skills are weak, and it's quite possible I'm just designing this wrong.
I'm working on a Django 1.3 application that would allow customers to log in to view various aspects of their "account". One of the models is "Customer"... | Referencing Django login name from within a model | I'll start by saying that my database skills are weak, and it's quite possible I'm just designing this wrong.
I'm working on a Django 1.3 application that would allow customers to log in to view various aspects of their "account". One of the models is "Customer", and it makes sense to me that I add a field in that m... | [
"You are probably looking for a ForeignKey relationship.\nprojects = models.ManyToManyField('Project')\nwebsite = models.URLField()\nuser = models.ForeignKey('User')\n\nThen from within your view:\nproject = Project.objects.all()[0]\nusername = project.user.username ## Or whatever you want to do with it.\n\nTo read... | [
4
] | [] | [] | [
"authentication",
"database_schema",
"django",
"python"
] | stackoverflow_0006628807_authentication_database_schema_django_python.txt |
Q:
Python or WPF reporting application
I have an existing VS-2008 Windows application with back-end MySQL Server 5.5. The existing application uses Crystal Reports for reporting. I want to get rid of Crystal Reports and want to use another tool that seamlessly integrates with VS-2010 Express. I want to remove reporti... | Python or WPF reporting application | I have an existing VS-2008 Windows application with back-end MySQL Server 5.5. The existing application uses Crystal Reports for reporting. I want to get rid of Crystal Reports and want to use another tool that seamlessly integrates with VS-2010 Express. I want to remove reporting options from my existing application a... | [
"For WPF you can use http://wpfreports.codeplex.com/ for simple reports or follow this article instructions to make you own: http://janrep.blog.codeplant.net/post/WPF-Multipage-Reports-Part-I.aspx\nI've used SSRS, but only the RDLC part (you can use it with any datasource), but not very happy with the results and W... | [
1,
0
] | [] | [] | [
"python",
"visual_studio_2008",
"visual_studio_2010",
"wpf"
] | stackoverflow_0006628157_python_visual_studio_2008_visual_studio_2010_wpf.txt |
Q:
Comparing elements of numpy arrays in python
I want to compare two 1x3 arrays such as:
if output[x][y] != [150,25,75]
(output here is a 3x3x3 so output[x][y] is only a 1x3).
I'm getting an error that says:
ValueError: The truth value of an array with more than one element is ambiguous.
Does that mean I need to ... | Comparing elements of numpy arrays in python | I want to compare two 1x3 arrays such as:
if output[x][y] != [150,25,75]
(output here is a 3x3x3 so output[x][y] is only a 1x3).
I'm getting an error that says:
ValueError: The truth value of an array with more than one element is ambiguous.
Does that mean I need to do it like:
if output[y][x][0] == 150 and output[y... | [
"The numpy way is to use np.allclose:\nnp.allclose(a,b)\n\nThough for integers, \nnot (a-b).any()\n\nis quicker.\n",
"You should also get the message:\n\nUse a.any() or a.all()\n\nThis means that you can do the following:\nif (output[x][y] != [150,25,75]).all():\n\nThat is because the comparison of 2 arrays or an... | [
7,
4,
3,
0
] | [] | [] | [
"arrays",
"comparison",
"numpy",
"python"
] | stackoverflow_0006628793_arrays_comparison_numpy_python.txt |
Q:
Python MySQL Syntax Error
I've been trying to work out where I've been going for most of the day, and still can't work it out, been staring at it too long and I'm sqill very early in my learning of Python & MySQL.
The query I've built is:
query = "UPDATE `db`.`%s" % table + "` SET %s" % table + "`.`%s" % field + "... | Python MySQL Syntax Error | I've been trying to work out where I've been going for most of the day, and still can't work it out, been staring at it too long and I'm sqill very early in my learning of Python & MySQL.
The query I've built is:
query = "UPDATE `db`.`%s" % table + "` SET %s" % table + "`.`%s" % field + "` = `%s" % daychangeperc + "` W... | [
"That's pretty messy, perhaps try doing it like this instead:\nquery = \"\"\"UPDATE db.%s SET %s.%s = %s WHERE db.%s.id = %s LIMIT 1\"\"\" % (table,table,field,daychangeperc,table,rowid)\n\n",
"First, here is your query re-written so that all of the arguments for your format string come at the end:\nquery = \"UPD... | [
2,
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0006629186_mysql_python.txt |
Q:
Markup language instead of HTML
I'm building a website, but don't want to write any HTML (or XML). I was thinking that I could use a nicer markup language instead.
I've looked at Markdown and reStructuredText, but they don't support all the HTML "features" I need. Are there any markup languages that I could use in... | Markup language instead of HTML | I'm building a website, but don't want to write any HTML (or XML). I was thinking that I could use a nicer markup language instead.
I've looked at Markdown and reStructuredText, but they don't support all the HTML "features" I need. Are there any markup languages that I could use instead of writing a lot of intricate H... | [
"As far as I know, there aren't really many alternatives for writing actual website structural markup in other languages than HTML.\nThe only thing that I've heard of is Haml, HTML Abstraction Markup Language. It's a short and concise markup language which translates directly into HTML markup, so perhaps it's worth... | [
1,
0
] | [] | [] | [
"html",
"markdown",
"markup",
"python"
] | stackoverflow_0006629201_html_markdown_markup_python.txt |
Q:
Django, query question
I have a mysql table full of geo data like so:
locations
- city
- state
- zipcode
- lat
- lon
Since major towns have more than one zip code, there are multiple records for each town.
example:
"city": "BOULDER", "state": "CO", "zipcode": "80310"
"city": "BOULDER", "state": "CO", "... | Django, query question | I have a mysql table full of geo data like so:
locations
- city
- state
- zipcode
- lat
- lon
Since major towns have more than one zip code, there are multiple records for each town.
example:
"city": "BOULDER", "state": "CO", "zipcode": "80310"
"city": "BOULDER", "state": "CO", "zipcode": "80322"
"city": "B... | [
"The best solution is to change your table, but this would get you a dictionary with all the information you need:\ndef location_query(my_city, my_state):\n my_dict = {'city':my_city,'state':my_state}\n zips = Location.objects.filter(city = my_city, state = my_state).values_list('zip', flat = True)\n my_di... | [
1,
0,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0005149036_django_django_models_python.txt |
Q:
How to make Python warn about bad practice and likely mistakes?
Perl has the strict and warnings pragmas and a couple of CPAN modules for encouraging good style and reducing errors. Is there a Python counterpart that can help me avoid such problems and bad practices while it encourages me to use a more Pythonic st... | How to make Python warn about bad practice and likely mistakes? | Perl has the strict and warnings pragmas and a couple of CPAN modules for encouraging good style and reducing errors. Is there a Python counterpart that can help me avoid such problems and bad practices while it encourages me to use a more Pythonic structure?
I should make it clear that I do not know what I want to avo... | [
"I believe pylint (http://www.logilab.org/857) is the most most common tool used for this purpose.\n",
"The classic style guide for Python is PEP8. If you are interested in style errors, a checker for PEP8 can be found at http://pypi.python.org/pypi/pep8.\n",
"googling for Python lint yielded this: http://pyche... | [
10,
6,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0006629277_python.txt |
Q:
how to define IronPython static property?
I have found previous discussing about defining Static Methods in (Iron)Python, however, I didn't find any about Static Properties. I assume you can definitively create Static Properties since properties are just methods for the .NET CLR and that's what I did in the code b... | how to define IronPython static property? | I have found previous discussing about defining Static Methods in (Iron)Python, however, I didn't find any about Static Properties. I assume you can definitively create Static Properties since properties are just methods for the .NET CLR and that's what I did in the code below, however, it looks like by calling the Sta... | [
"this answer is for python in general, and not specific to IronPython.\nproperty is a convenience for creating a descriptor, an object which supplies a __get__ and optionally __set__ and __del__ methods. The __get__ method accepts arguments for the target instance and also the associated class, but __set__ is neve... | [
1
] | [] | [] | [
"ironpython",
"properties",
"python",
"static_members"
] | stackoverflow_0006629326_ironpython_properties_python_static_members.txt |
Q:
Numpy: How to map f: (shape (3) ndarray) --> (float) over an ndarray of shape (...,3) to get ndarray of shape (...)?
I have an function that maps an ndarray of shape (3) to a float, and I have an ndarray of shape (...,3). What's the best way to map that function over that array to get an array of shape (...)?
Than... | Numpy: How to map f: (shape (3) ndarray) --> (float) over an ndarray of shape (...,3) to get ndarray of shape (...)? | I have an function that maps an ndarray of shape (3) to a float, and I have an ndarray of shape (...,3). What's the best way to map that function over that array to get an array of shape (...)?
Thanks.
| [
"You want numpy.apply_along_axis.\ndef f(a):\n return a[0] + a[1] + a[2]\nmm = numpy.random.randn(5, 3)\nnumpy.apply_along_axis(f, 1, mm)\n\noutput: array([-1.75875289, -0.34689792, 0.66092486, -0.21626001, -0.14125476])\n"
] | [
4
] | [] | [] | [
"functional_programming",
"numpy",
"python"
] | stackoverflow_0006629546_functional_programming_numpy_python.txt |
Q:
perform different splits based off different criteria to create a distinct output
When I execute the below python code I have written, (I am trying to create a user name based off three distinct scenarios (1.user enters First, middle, and last name, 2. user enters first and last name, 3. user enters only last name... | perform different splits based off different criteria to create a distinct output | When I execute the below python code I have written, (I am trying to create a user name based off three distinct scenarios (1.user enters First, middle, and last name, 2. user enters first and last name, 3. user enters only last name. I am attempting to create a username based off the first 4 characters of the last nam... | [
"Or you could write something simpler like:\ndef get_id():\n print \"Hello! This program will contruct a new userid for you.\\n\"\n name = raw_input('Please enter your full name: ').lower().split(' ')\n userid = name[-1][:4] # first 4 chars of last name\n if len(name) > 1:\n userid += name[0][0] ... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006618766_python.txt |
Q:
search for before and after values in a long sorted list
What would be the fastest way to search for a number (eg. 12.31) in long sorted list and get the values one before and after my "search" value when the exact value isn't found (eg. 11.12 and 12.03 in the list below)?
Many thanks in advance.
long_list = [10.1... | search for before and after values in a long sorted list | What would be the fastest way to search for a number (eg. 12.31) in long sorted list and get the values one before and after my "search" value when the exact value isn't found (eg. 11.12 and 12.03 in the list below)?
Many thanks in advance.
long_list = [10.11, 11.12, 13.03, 14.2 .. 12345.67]
| [
"The fastest is probably to use built-in support in python. Here I'm thinking about the bisect module. Below I'm using a dictionary to quickly check in O(1) if a value is in the list; if not, bisect is used to find values smaller than and larger than the sought value.\n#!/usr/bin/env python\n\nimport bisect\n\ndef ... | [
5,
2,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006628744_python.txt |
Q:
SWIG: String not being fully copied or displayed?
I need to send a pointer to a character array to one of my functions. To produce this char*, I use this function in one of my c files such that is called like this
charPtr = myProj.strAll ( 8 );
where strAll is:
char * strAll ( int size ) {
return malloc( size... | SWIG: String not being fully copied or displayed? | I need to send a pointer to a character array to one of my functions. To produce this char*, I use this function in one of my c files such that is called like this
charPtr = myProj.strAll ( 8 );
where strAll is:
char * strAll ( int size ) {
return malloc( sizeof( char ) * size );
}
I then pass charPtr into a func... | [
"ABCD1234 has 8 characters. But you should also provide an extra byte for the termination character \\0. Every C string should be terminated by \\0.\nmyProj.Populate ( \"ABCD1234\", charPtr, 8 );\n\ncharPtr should be pointing to a location which can accommodate 9 characters out of which the last is to place the ter... | [
0
] | [] | [] | [
"c",
"memcpy",
"python",
"string",
"swig"
] | stackoverflow_0006630230_c_memcpy_python_string_swig.txt |
Q:
Import Python modules with the same name
I have several Python projects and they all have a conf package:
/some_folder/project_1/
conf/
__init__.py
some_source_file.py
/another_folder/project_2/
conf/
__init__.py
another_source_file.py
For each project, I have created a .pth file in the site-... | Import Python modules with the same name | I have several Python projects and they all have a conf package:
/some_folder/project_1/
conf/
__init__.py
some_source_file.py
/another_folder/project_2/
conf/
__init__.py
another_source_file.py
For each project, I have created a .pth file in the site-packages folder with this contents:
.../site-p... | [
"No. You will need to either rename one of them or turn the project directory into a package and import via that.\n"
] | [
9
] | [] | [] | [
"import",
"module",
"python"
] | stackoverflow_0006630394_import_module_python.txt |
Q:
Running a python package
Running Python 2.6.1 on OSX, will deploy to CentOS. Would like to have a package to be invoked from a command line like this:
python [-m] tst
For that, here is the directory structure made:
$PYTHONPATH/
tst/
__init__.py # empty
__main__.py # below
dep.p... | Running a python package | Running Python 2.6.1 on OSX, will deploy to CentOS. Would like to have a package to be invoked from a command line like this:
python [-m] tst
For that, here is the directory structure made:
$PYTHONPATH/
tst/
__init__.py # empty
__main__.py # below
dep.py # below
The follow... | [
"The feature to run the __main__ module of a package when using the command line -m option was introduced in Python 2.7. For 2.6 you need to specify the package module name to run; -m test.__main__ should work. See the documentation here.\n"
] | [
43
] | [] | [] | [
"module",
"package",
"program_entry_point",
"python",
"python_2.6"
] | stackoverflow_0006630822_module_package_program_entry_point_python_python_2.6.txt |
Q:
How to download python from command-line?
I'm on windows, but I'm using a putty shell to connect to a linux machine, and want to install python 2.7. Can't figure out how to do it. How can I download python from command line?
A:
wget --no-check-certificate https://www.python.org/ftp/python/2.7.11/Python-2.7.11.tg... | How to download python from command-line? | I'm on windows, but I'm using a putty shell to connect to a linux machine, and want to install python 2.7. Can't figure out how to do it. How can I download python from command line?
| [
"wget --no-check-certificate https://www.python.org/ftp/python/2.7.11/Python-2.7.11.tgz\ntar -xzf Python-2.7.11.tgz \ncd Python-2.7.11\n\nNow read the README file to figure out how to install, or do the following with no guarantees from me that it will be exactly what you need.\n./configure \nmake \nsudo make in... | [
82,
4,
0
] | [] | [] | [
"command_line",
"download",
"linux",
"python"
] | stackoverflow_0006630873_command_line_download_linux_python.txt |
Q:
Drag drop support for a GtkTreeView where the model is filtered and sorted
As the title suggests, I have a gtk.TreeView whose model is sorted and filtered. According to the documentation: "Drag and drop reordering of rows only works with unsorted stores.". The only other information given relates to using external... | Drag drop support for a GtkTreeView where the model is filtered and sorted | As the title suggests, I have a gtk.TreeView whose model is sorted and filtered. According to the documentation: "Drag and drop reordering of rows only works with unsorted stores.". The only other information given relates to using external sources, which in this case I don't need.
I tried implementing it anyway, provi... | [
"I got a bit confused as I already had a \"drag-drop\" handler but was sorted once I implemented the following:\ndef __init__(self):\n self.treeview.connect(\"drag_data_received\", self.on_drag_data_received)\n\ndef on_drag_data_received(self, widget, drag_context, x, y, selection_data, info, timestamp):\n wi... | [
4,
1,
0
] | [] | [] | [
"gtktreeview",
"pygtk",
"python"
] | stackoverflow_0003079485_gtktreeview_pygtk_python.txt |
Q:
convert pdf to image with imageMagick
Any Idea what I am doing wrong here? The convert never seems to even open the pdf:
a = r"\\server\gis\agsResources\resources\map4.pdf"
b = r"\\server\gis\agsResources\resources\map4.png"
boutput = Popen([
r'C:\Program Files\ImageMagick-6.7.0-Q16\convert.exe',
'-density=... | convert pdf to image with imageMagick | Any Idea what I am doing wrong here? The convert never seems to even open the pdf:
a = r"\\server\gis\agsResources\resources\map4.pdf"
b = r"\\server\gis\agsResources\resources\map4.png"
boutput = Popen([
r'C:\Program Files\ImageMagick-6.7.0-Q16\convert.exe',
'-density=400',
'-scale=2000x1000',
'-sOutputFi... | [
"The option syntax does not look right. When I try your code (with just paths changed), convert: unrecognized option '-density=400' is written to the boutput variable.\nThis works for me:\nboutput = Popen([\n '/bin/convert',\n '-density', '400',\n '-scale', '2000x1000',\n '%s' % a,\n '%s' % b \n], st... | [
4
] | [] | [] | [
"imagemagick",
"pdf",
"popen",
"python"
] | stackoverflow_0006630407_imagemagick_pdf_popen_python.txt |
Q:
Gzipping all HTTP traffic with Pyramid
I am creating a mobile service based on Pyramid framework. Because it's mobile everything to reduce bandwidth usage is plus. I am considering gzipping all the traffic, even dynamic HTML pages.
What kind of hooks Pyramid framework provides for this? Or is there WSGI middleware... | Gzipping all HTTP traffic with Pyramid | I am creating a mobile service based on Pyramid framework. Because it's mobile everything to reduce bandwidth usage is plus. I am considering gzipping all the traffic, even dynamic HTML pages.
What kind of hooks Pyramid framework provides for this? Or is there WSGI middleware for the task? I'd like to do this still on ... | [
"First of all I should stress that you should do this on the web server level (nginx or apache). There are several reasons for this:\n\nPerformance - If you do this in Python you are using one of your threads that could be handling requests to do cpu-intensive compression. This is way less efficient than allowing y... | [
24,
5,
1
] | [] | [] | [
"gzip",
"http",
"pyramid",
"python"
] | stackoverflow_0006618985_gzip_http_pyramid_python.txt |
Q:
Why does \w+ match a trailing newline?
I am curious why the following would output that there was a match:
import re
foo = 'test\n'
match = re.search('^\w+$', foo)
if match == None:
print "It did not match"
else:
print "Match!"
The newline is before the end of the string, yes? Why is this matching?
A:
Fro... | Why does \w+ match a trailing newline? | I am curious why the following would output that there was a match:
import re
foo = 'test\n'
match = re.search('^\w+$', foo)
if match == None:
print "It did not match"
else:
print "Match!"
The newline is before the end of the string, yes? Why is this matching?
| [
"From Python's re documentation.\n\n'$'\n Matches the end of the string or just before the newline at the end of the string, and in MULTILINE mode also matches before a newline. foo matches both ‘foo’ and ‘foobar’, while the regular expression foo$ matches only ‘foo’. More interestingly, searching for foo.$ in 'f... | [
9,
8
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006631481_python_regex.txt |
Q:
Scikits-learn: Use custom vocabulary together with Pipeline
In my scikits-learn Pipeline, I would like to pass a custom vocabulary to CountVectorizer():
text_classifier = Pipeline([
('count', CountVectorizer(vocabulary=myvocab)),
('tfidf', TfidfTransformer()),
('clf', LinearSVC(C=1000))
])
However, as... | Scikits-learn: Use custom vocabulary together with Pipeline | In my scikits-learn Pipeline, I would like to pass a custom vocabulary to CountVectorizer():
text_classifier = Pipeline([
('count', CountVectorizer(vocabulary=myvocab)),
('tfidf', TfidfTransformer()),
('clf', LinearSVC(C=1000))
])
However, as far as I understand when I call
text_classifier.fit(X_train, y_t... | [
"This was a bug in scikit-learn that I fixed five minutes ago. Thanks for spotting it. I suggest you either upgrade to the newest version from Github, or separate the vectorizer from the pipeline as a workaround:\ncount = CountVectorizer(vocabulary=myvocab)\nX_vectorized = count.transform(X_train)\n\ntext_classifie... | [
9
] | [] | [] | [
"machine_learning",
"python",
"scikit_learn",
"scikits"
] | stackoverflow_0006608241_machine_learning_python_scikit_learn_scikits.txt |
Q:
Worst Case Analysis for Regular Expressions
Are there any tools that will take a particular regular expression and return the worst case scenario in terms of the number of operations required for a certain number of characters that the regular expression is matched against?
So for example, given a (f|a)oo.*[ ]baz,... | Worst Case Analysis for Regular Expressions | Are there any tools that will take a particular regular expression and return the worst case scenario in terms of the number of operations required for a certain number of characters that the regular expression is matched against?
So for example, given a (f|a)oo.*[ ]baz, how many steps might the engine possibly go thou... | [
"Regexbuddy's debugger shows how many steps engine would take to conclude match or not on a given sample. More information on catastrophic backtracking and debugging regular expressions.\n\nPS: It is not free but they offer a 3-month money-back guarantee.\n",
"Note that it depends on the engine. While regex theor... | [
21,
10,
7
] | [] | [] | [
"analysis",
"optimization",
"perl",
"python",
"regex"
] | stackoverflow_0004731104_analysis_optimization_perl_python_regex.txt |
Q:
Numpy masked arrays - indicating missing values
import numpy as np
import numpy.ma as ma
"""This operates as expected with one value masked"""
a = [0., 1., 1.e20, 9.]
error_value = 1.e20
b = ma.masked_values(a, error_value)
print b
"""This does not, all values are masked """
d = [0., 1., 'NA', 9.]
error_value = ... | Numpy masked arrays - indicating missing values | import numpy as np
import numpy.ma as ma
"""This operates as expected with one value masked"""
a = [0., 1., 1.e20, 9.]
error_value = 1.e20
b = ma.masked_values(a, error_value)
print b
"""This does not, all values are masked """
d = [0., 1., 'NA', 9.]
error_value = 'NA'
e = ma.masked_values(d, error_value)
print e
Ho... | [
"Are you getting your data from a text file or similar? If so, I'd suggest using the genfromtxt function directly to specify your masked value:\nIn [149]: f = StringIO('0.0, 1.0, NA, 9.0')\n\nIn [150]: a = np.genfromtxt(f, delimiter=',', missing_values='NA', usemask=True)\n\nIn [151]: a\nOut[151]:\nmasked_array(da... | [
4,
0
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0006555101_arrays_numpy_python.txt |
Q:
How to access a database initialized in a class from another class in python?
How would I go about implementing the MainPage class?
import cgi
import os
import logging
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from goog... | How to access a database initialized in a class from another class in python? | How would I go about implementing the MainPage class?
import cgi
import os
import logging
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
class Greeting(db.Model): #setting up database
a = d... | [
"You could pass a Downloader object to MainPage on initialization:\nclass MainPage(webapp.RequestHandler):\n def __init__(self, downloader):\n self.downloader = downloader\n\n def get(self):\n self.downloader.get()\n\n",
"This is solved by basically naming the database, and refer to it from an... | [
0,
0
] | [] | [] | [
"database",
"google_app_engine",
"python",
"web_applications"
] | stackoverflow_0006549970_database_google_app_engine_python_web_applications.txt |
Q:
Installing PyOpenGL with MacPorts
I'm trying to install PyOpenGL with macports, and I'd like to use Python 2.7, which I have also installed with macports. However, only Python 2.4 seems to have access to PyOpenGL when I install it with: sudo port install py-opengl
Anyone know what is going on? How can I get python... | Installing PyOpenGL with MacPorts | I'm trying to install PyOpenGL with macports, and I'd like to use Python 2.7, which I have also installed with macports. However, only Python 2.4 seems to have access to PyOpenGL when I install it with: sudo port install py-opengl
Anyone know what is going on? How can I get python 2.7 to see PyOpenGL?
| [
"Use sudo port py27-opengl instead.\nIn general, with MacPorts python-related ports, the Python version to which it applies is encoded in its name: py25-, py26-, py27-, py31-, py32-. They started doing this after Python 2.4, so py- are generally the legacy Python 2.4 versions. There are other ports that use varia... | [
4
] | [] | [] | [
"macports",
"pyopengl",
"python"
] | stackoverflow_0006631492_macports_pyopengl_python.txt |
Q:
Pycharm warns about Unexpected type in a SqlAlchemy model
In a SqlAlchemy model I am getting a warning from pycharm saying that a column has an unexpected type.
The simplified code that produces the warning is as follows:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Intege... | Pycharm warns about Unexpected type in a SqlAlchemy model | In a SqlAlchemy model I am getting a warning from pycharm saying that a column has an unexpected type.
The simplified code that produces the warning is as follows:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
Base = declarative_base()
class Peptide(Base):
... | [
"Currently PyCharm is unaware of SQLAlchemy ORM conventions, so usually it doesn't know the real types of model fields. If you'd like to get special support for SQLAlchemy in PyCharm, feel free to vote for the issue PY-4186 in the PyCharm issue tracker.\nUpdate: PY-4536 was fixed in 2013. As the comments mention be... | [
12
] | [] | [] | [
"pycharm",
"python",
"sqlalchemy"
] | stackoverflow_0006574446_pycharm_python_sqlalchemy.txt |
Q:
Any way to get a figure from Python's matplotlib into Matlab?
I'm processing some data for a research project, and I'm writing all my scripts in python. I've been using matplotlib to create graphs to present to my supervisor. However, he is a die-hard MATLAB user and he wants me to send him MATLAB .fig files rathe... | Any way to get a figure from Python's matplotlib into Matlab? | I'm processing some data for a research project, and I'm writing all my scripts in python. I've been using matplotlib to create graphs to present to my supervisor. However, he is a die-hard MATLAB user and he wants me to send him MATLAB .fig files rather than SVG images.
I've looked all over but can't find anything to ... | [
"Without access to (or experience with matlab) this is going to be a bit tricky. As Amro stated, .fig files store the underlying data, and not just an image, and you're going to have a hard time saving .fig files from python. There are however a couple of things which might work in your favour, these are: \n\nnumpy... | [
2
] | [] | [] | [
"matlab",
"matplotlib",
"python"
] | stackoverflow_0006618132_matlab_matplotlib_python.txt |
Q:
Django, simple way to query one to many relationships?
So I want to return a dict in javascript of two tables a Category table and a Sub_category table with category = models.ForeignKey(Category). The dictionary so be 'Category1': 'Sub_cat1, Sub_cat2, ...'. I did the following code, but it seems very inefficient... | Django, simple way to query one to many relationships? | So I want to return a dict in javascript of two tables a Category table and a Sub_category table with category = models.ForeignKey(Category). The dictionary so be 'Category1': 'Sub_cat1, Sub_cat2, ...'. I did the following code, but it seems very inefficient, so could you guys help me find another way to do this?
Tha... | [
"Sub_category.objects.filter(category__name=category).values('name')\n\n",
"So you're implementing a hierarchy in your database? I just started working on the same thing, only a user hierarchy. hierarchies are, as you seem to have realized, inefficient to model with a simple foreign key. Their is another way o... | [
1,
0
] | [] | [] | [
"django",
"javascript",
"json",
"python",
"sql"
] | stackoverflow_0006631639_django_javascript_json_python_sql.txt |
Q:
How to send a file through Soap in python?
I want to send a zip file through SOAP (from a SOAP client to a SOAP server) in python.
Following the reading of this SO question, I choose to use suds as my python client.
But according to this, suds do not support sending attachment. A method is given to circumvent the ... | How to send a file through Soap in python? | I want to send a zip file through SOAP (from a SOAP client to a SOAP server) in python.
Following the reading of this SO question, I choose to use suds as my python client.
But according to this, suds do not support sending attachment. A method is given to circumvent the problem but I've not been able to make it work. ... | [
"Download the provided wrapper, and then where you would normally say something like...\nclient.service.fooMethod(fooParam1,fooParam2,...)\n\n...instead do...\nsoap_attachments.with_soap_attachment(client.service.fooMethod,binaryParam,fooParam1,fooParam2,...)\n\nWhere binaryParam is of the type expected by soap_att... | [
7,
3,
1
] | [] | [] | [
"python",
"soap"
] | stackoverflow_0006601107_python_soap.txt |
Q:
Real time text processing using Python
Real time text processing using Python. For e.g. consider this sentance
I am going to schol today
I want to do the following (real time):
1) tokenize
2) check spellings
3) stem(nltk.PorterStemmer())
4) lemmatize (nltk.WordNetLemmatizer())
Currently I am using NLTK libra... | Real time text processing using Python | Real time text processing using Python. For e.g. consider this sentance
I am going to schol today
I want to do the following (real time):
1) tokenize
2) check spellings
3) stem(nltk.PorterStemmer())
4) lemmatize (nltk.WordNetLemmatizer())
Currently I am using NLTK library to do these operations, but its not real ... | [
"NLTK's WordNetLemmatizer uses a lazily-loaded WordNetCorpusReader (using a LazyCorpusLoader). The first call to lemmatize() may take significantly longer than later calls if it triggers the corpus loading. \nYou could place a dummy call to lemmatize() to trigger the loading when your application starts up.\n",
... | [
3,
1,
1
] | [] | [] | [
"nlp",
"nltk",
"performance",
"python",
"text_processing"
] | stackoverflow_0006621666_nlp_nltk_performance_python_text_processing.txt |
Q:
passing game pointer to units (cyclical includes, python)
edit: I'm asking for advice / correct structure for code
The current layout (which is probably wrong), is:
Game stores player, screen, and units.
Game handles top level logic, user input, etc
screen and player are used entire-program-scope
units list is m... | passing game pointer to units (cyclical includes, python) | edit: I'm asking for advice / correct structure for code
The current layout (which is probably wrong), is:
Game stores player, screen, and units.
Game handles top level logic, user input, etc
screen and player are used entire-program-scope
units list is modified (added+removed) in game
If I want access to units list... | [
"Is there any reason not to keep a reference to game within each unit - ie adding a line to Unit.__init__(...) like self.game = game and then using this in your teleport method.\nThe only reason I can think of is that you might be worried about creating cyclic references which won't be garbage collected, in which c... | [
0
] | [] | [] | [
"logic",
"program_entry_point",
"python"
] | stackoverflow_0006617334_logic_program_entry_point_python.txt |
Q:
How can I solve this without list comprehensions
I´m new in python and I´m trying to find the best way to approach this problem , I need to understand if this can be made only with loops and functions (whithout lists comprehensions).
I also need to find the more elegant way to solve this kind or problems,
simple ... | How can I solve this without list comprehensions | I´m new in python and I´m trying to find the best way to approach this problem , I need to understand if this can be made only with loops and functions (whithout lists comprehensions).
I also need to find the more elegant way to solve this kind or problems,
simple functions? recursivity? lists comprehensions? Generato... | [
"Try the following:\ndef calc(base, alist, blist):\n for num in range(1, 4):\n result = []\n for b in base:\n result.append(b + sum(alist[:num]) - sum(blist[:num]))\n print result\n\nHere is the result with the data you gave:\n>>> calc(base, alist, blist)\n[-1, 0]\n[-1, 0]\n[1, 2]... | [
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006627487_python.txt |
Q:
Get 's title-attribute with lxml in Python
I want to extract the onel-iner-texts from this website using Python. The messages in HTML look like this:
<div class="olh_message">
<p>foobarbaz <img src="/static/emoticons/support-our-fruits.gif" title=":necta:" /></p>
</div>
My code looks like this so far:
impo... | Get 's title-attribute with lxml in Python | I want to extract the onel-iner-texts from this website using Python. The messages in HTML look like this:
<div class="olh_message">
<p>foobarbaz <img src="/static/emoticons/support-our-fruits.gif" title=":necta:" /></p>
</div>
My code looks like this so far:
import lxml.html
url = "http://www.scenemusic.net/de... | [
"try this\n import lxml.html\n url = \"http://www.scenemusic.net/demovibes/oneliner/\"\n parser = lxml.etree.HTMLParser()\n tree = lxml.etree.parse(url, parser)\n texts = tree.xpath(\"//div[@class='olh_message']/p/img/@title\")\n\n",
"Use:\n//div[@class='olh_message']/p/node()\n\nhis selects all children nod... | [
1,
0
] | [] | [] | [
"dom",
"html_parsing",
"lxml",
"python",
"xpath"
] | stackoverflow_0006628231_dom_html_parsing_lxml_python_xpath.txt |
Q:
Django view gets called twice... sometimes
I have several logging.debug statements in the home view of a web site, mainly to log the start time and the end time of a bunch of sql queries.
However, sometimes, I see those sets of debug statements pop up twice in a row in the debug log. Of course, during that time on... | Django view gets called twice... sometimes | I have several logging.debug statements in the home view of a web site, mainly to log the start time and the end time of a bunch of sql queries.
However, sometimes, I see those sets of debug statements pop up twice in a row in the debug log. Of course, during that time only one user has made ONE request (as in refresh,... | [
"It's possible your view function is called once, but you are logging twice. I've had problems before where my logging add_handler call was being run twice, so the log had the same handler twice, so one log.debug() call would result in the same message in the log twice.\n"
] | [
0
] | [] | [] | [
"django",
"http",
"python",
"request"
] | stackoverflow_0006631601_django_http_python_request.txt |
Q:
python array_walk() alternative
i have a list that looks like this:
list = [1,2,3,4]
I would like to add 12 to each value. In PHP you can use array_walk to process each item in the array. Is there a similar function or easier way than doing a for loop such as:
for i in list:
Thanks
A:
Use list comprehensions. ... | python array_walk() alternative | i have a list that looks like this:
list = [1,2,3,4]
I would like to add 12 to each value. In PHP you can use array_walk to process each item in the array. Is there a similar function or easier way than doing a for loop such as:
for i in list:
Thanks
| [
"Use list comprehensions. Try this:\nlist = [i+12 for i in list]\n\n",
"my_list = [e+12 for e in my_list]\n\nor:\nfor i in range(len(my_list)):\n my_list[i] += 12\n\n",
"alist = map(lambda i: i + 12, alist)\n\n\nUpdate: @Daenyth says in the comments that this is slower than a list comprehension because of t... | [
10,
4,
4
] | [] | [] | [
"python"
] | stackoverflow_0006632315_python.txt |
Q:
Are there good Tutorials on how to make web apps with Python?
I think I'm gonna start learning Python web development from scratch. So if someone knows good tutorials on this, please post links.
A:
Assuming you mean "learn from scratch" and not "build from scratch", these are books for popular frameworks:
Djang... | Are there good Tutorials on how to make web apps with Python? | I think I'm gonna start learning Python web development from scratch. So if someone knows good tutorials on this, please post links.
| [
"Assuming you mean \"learn from scratch\" and not \"build from scratch\", these are books for popular frameworks:\n\nDjango Book\nPylons Book\nZope Book\n\nThere are many others, so do some searching around.\n",
"You have a couple of choices, just to name a few:\nFrameworks\n\nWerkzeug / Screencast (building a wi... | [
5,
3,
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0001936109_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.