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:
of tornado and blocking code
I am trying to move away from CherryPy for a web service that I am working on and one alternative that I am considering is Tornado. Now, most of my requests look on the backend something like:
get POST data
see if I have it in cache (database access)
if not make multiple HTTP requests... | of tornado and blocking code | I am trying to move away from CherryPy for a web service that I am working on and one alternative that I am considering is Tornado. Now, most of my requests look on the backend something like:
get POST data
see if I have it in cache (database access)
if not make multiple HTTP requests to some other web service which c... | [
"Tornado comes shipped with an asynchronous (actually two iirc) http client (AsyncHTTPClient). Use that one if you need to do additional http requests.\nThe database lookup should also be done using an asynchronous client in order to not block the tornado ioloop/mainloop. I know there are a couple of tornado tailor... | [
1
] | [] | [] | [
"python",
"tornado"
] | stackoverflow_0004647974_python_tornado.txt |
Q:
Python - How to sort a list, by an attribute from another class
I have some elements in a list in one class. I want them sorted in a new list, and they have to be sorted by an attribute from another class.
Can anyone give an example?
My code so far looks like this:
class Carcompany:
def __init__(self, model, pr... | Python - How to sort a list, by an attribute from another class | I have some elements in a list in one class. I want them sorted in a new list, and they have to be sorted by an attribute from another class.
Can anyone give an example?
My code so far looks like this:
class Carcompany:
def __init__(self, model, production_number):
self.model = model
self.production_number =... | [
"To sort a list of objects that have the attribute bar:\nanewlist = sorted(list, key=lambda x: x.bar)\n\n",
"You say that you have classes already (show them!) so you can make them sortable by defining __lt__:\nclass Car(object):\n def __init__(self, year, plate):\n self.year = year\n self.plate ... | [
4,
2
] | [] | [] | [
"python",
"sorting"
] | stackoverflow_0004648608_python_sorting.txt |
Q:
Get a letter out of a word
a = ['cat','dog']
random.choice(a)
How can I choose a random word, and pull out a letter?
I've searched and experimented and whatnot but can't find an answer.
thanks.
I don't want a random letter,
for instances
I want it to choose a word, cat.
then I want someone to guess either c a or... | Get a letter out of a word | a = ['cat','dog']
random.choice(a)
How can I choose a random word, and pull out a letter?
I've searched and experimented and whatnot but can't find an answer.
thanks.
I don't want a random letter,
for instances
I want it to choose a word, cat.
then I want someone to guess either c a or t.
Kind of like hangman
| [
"If you want to choose a random character from the randomly selected word:\nrandom.choice(random.choice(a))\n\nOr, if you want the first letter (for example) of the randomly chosen word:\nrandom.choice(a)[0]\n\n",
"First to pick the word, you use what you published.Then you can make a set from the word to get the... | [
6,
5
] | [] | [] | [
"python"
] | stackoverflow_0004649236_python.txt |
Q:
Python: Having "not-yet-defined" class-names as default-arguments
I have a "class1" which must be able to create an object of a
different class-name. The class-name is passed as an argument called "friend".
I want the "friend"-argument to default to a class-name called "class2".
Additionally I need to have the sam... | Python: Having "not-yet-defined" class-names as default-arguments | I have a "class1" which must be able to create an object of a
different class-name. The class-name is passed as an argument called "friend".
I want the "friend"-argument to default to a class-name called "class2".
Additionally I need to have the same behavior for the class "class2".
So "class2" should have "class1" as ... | [
"You can push it to later:\nclass class1(object):\n def __init__(self, friend=None):\n if friend is None:\n friend = class2\n self.friendInstance = friend()\n\nEdit: Actually, don't do that. It will create a class2 instance that creates a class1 instance that creates a class2 instance, e... | [
3,
1
] | [] | [] | [
"arguments",
"class",
"default_parameters",
"parameters",
"python"
] | stackoverflow_0004648396_arguments_class_default_parameters_parameters_python.txt |
Q:
Releasing a wxPython App: Give out scripts or compile in Exe, etc?
I have a wxPython application that is almost done & I would like to place it in my portfolio. I have to consider when someone attempts to run my app that they may not have Python, or wxPython, so if they just click the main script/python file its n... | Releasing a wxPython App: Give out scripts or compile in Exe, etc? | I have a wxPython application that is almost done & I would like to place it in my portfolio. I have to consider when someone attempts to run my app that they may not have Python, or wxPython, so if they just click the main script/python file its not going to run, right?
How should I distribute my app (how do you distr... | [
"Use Gui2exe and compress with UPX to get unpacked size down.\nFor a setup file(exe) with uinstall info Inno-Setup is good.\nI have use this with wxpython several times and got it to work on all windows versions.\nFor Gui2exe use optimize(2) - compressed(2) - Bundle files(3)\nBundle files(3) is the most stable,\nBu... | [
3,
2,
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004643247_python_wxpython.txt |
Q:
Using a prefix in RDFLIB
I would like to use a short prefix to designate a namespace in rdflib but I am having trouble. I think the answer must be very simple. Here is the offending code:
g = rdflib.parse("some_rdf.rdf")
rdf=rdflib.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
print "Name Spaces:"
fo... | Using a prefix in RDFLIB | I would like to use a short prefix to designate a namespace in rdflib but I am having trouble. I think the answer must be very simple. Here is the offending code:
g = rdflib.parse("some_rdf.rdf")
rdf=rdflib.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#")
print "Name Spaces:"
for ns in g.namespaces():
pr... | [
"They way you are trying to use it in your second case is not supported by RDFLib.\nYou could do like ...\nrdf=rdflib.Namespace(\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\")\nand\nrdflib.term.URIRef(rdf+'type')\nor\nrdflib.term.URIRef(rdf['type'])\nI quite like they way it's expressed in your third case, why not... | [
5
] | [] | [] | [
"python",
"rdf",
"rdflib"
] | stackoverflow_0004648873_python_rdf_rdflib.txt |
Q:
Using a wx.Timer, always sends the wx.EVT_PAINT msg & not wx.EVT_TIMER
I have a wx.Dialog, that I have subclassed. In this dialog, I perform my own painting on the DC & I also have my own wx.Timer that loops every 100 clock steps.
Now what happens is when I initiate my wx.Timer by saying, self.timer.Start(100), it... | Using a wx.Timer, always sends the wx.EVT_PAINT msg & not wx.EVT_TIMER | I have a wx.Dialog, that I have subclassed. In this dialog, I perform my own painting on the DC & I also have my own wx.Timer that loops every 100 clock steps.
Now what happens is when I initiate my wx.Timer by saying, self.timer.Start(100), it loops every 100 clock steps correctly BUT it sends the wx.EVT_PAINT msg to ... | [
"If you are on Windows then the problem is that you do not create a wx.PaintDC in the EVT_PAINT handler. When control returns to widows after sending that event it senses that the window still has invalidated areas and so it immediately sends another paint event with a higher priority, this ends up starving out al... | [
1
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0004643172_python_wxpython.txt |
Q:
Cross-platform video conversion tool + Python ( Gstreamer ? )
I'm looking for a tool to do the following:
Convert video/audio from multiple formats to WebM format.
Needs to be command-line or Python-binded.
Cross-platform.
No royalty licenses - Thus, all FFMpeg-based tools are out - See this for an explanation.
... | Cross-platform video conversion tool + Python ( Gstreamer ? ) | I'm looking for a tool to do the following:
Convert video/audio from multiple formats to WebM format.
Needs to be command-line or Python-binded.
Cross-platform.
No royalty licenses - Thus, all FFMpeg-based tools are out - See this for an explanation.
The best framework I've found so far is GStreamer, But I'm not sure... | [
"you can try FFMPEG for format conversion. FFMPEG v.0.6 adds support for VP8 (WebM)\n"
] | [
0
] | [] | [] | [
"gstreamer",
"macos",
"python",
"video"
] | stackoverflow_0004648325_gstreamer_macos_python_video.txt |
Q:
Creating Custom WPF Controls in IronPython: a control made up out of standard controls
I've looked at the other custom control creation questions on here, as well as other online resources, but I'm lost as to how to create a custom control that doesn't require a C# code-behind file. Since my project is pure IronPy... | Creating Custom WPF Controls in IronPython: a control made up out of standard controls | I've looked at the other custom control creation questions on here, as well as other online resources, but I'm lost as to how to create a custom control that doesn't require a C# code-behind file. Since my project is pure IronPython, I don't know how I would integrate the C# code behind with it.
What I'm trying to do ... | [
"I still feel like there's a better way, so I'll leave this question open, but the way I ended up doing run-time addition of custom controls in IronPython is by simply placing the XAML in a seperate file, loading it with XamlReader.Load() and storing the return value in a new object. That object becomes the control... | [
1
] | [] | [] | [
"composite_controls",
"custom_controls",
"ironpython",
"python",
"wpf"
] | stackoverflow_0004382123_composite_controls_custom_controls_ironpython_python_wpf.txt |
Q:
How can I check pooled connections in SQLAlchemy before handing them off to my application code?
We have a slightly unreliable database server, for various reasons, and as a consequence sometimes the database connections used by my application vanish out from under it. The connections are SQLAlchemy 0.6.5 connect... | How can I check pooled connections in SQLAlchemy before handing them off to my application code? | We have a slightly unreliable database server, for various reasons, and as a consequence sometimes the database connections used by my application vanish out from under it. The connections are SQLAlchemy 0.6.5 connections to a PostgreSQL db in a Pylons 1.0 web runtime.
What I want is some way to catch most of these wi... | [
"You could use a pool listener:\nclass ConnectionChecker(sqlalchemy.interfaces.PoolListener):\n def checkout(self, dbapi_con, con_record, con_proxy):\n if not is_valid_connection(dbapi_con):\n # a new connection will be used\n raise sqlalchemy.exc.DisconnectionError \n\nLeft for you ... | [
4
] | [] | [] | [
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0004649397_pylons_python_sqlalchemy.txt |
Q:
Django templates: how do I use key to access value?
I don't want to iterate through the dictionary. I have a key, and simply want to return the value for that key if it exists.
I'm not getting any results.
users // a dictionary of user_ids and values
user.key // a user id.
{{ users.user.key }}
This displays not... | Django templates: how do I use key to access value? | I don't want to iterate through the dictionary. I have a key, and simply want to return the value for that key if it exists.
I'm not getting any results.
users // a dictionary of user_ids and values
user.key // a user id.
{{ users.user.key }}
This displays nothing when I know the value for the key passed exists.
| [
"The problem is that Django interprets users.user.key as users.user[key], which of course is not what you want.\nYou can use with directive to work around this.\n {% with user.key as user_key %}\n {{users.user_key}} \n {% endwith %}\n\n"
] | [
4
] | [] | [] | [
"dictionary",
"django",
"python",
"templates"
] | stackoverflow_0004649747_dictionary_django_python_templates.txt |
Q:
Which one of these GAE Datastore queries is more efficient?
Suppose I have defined my data models the following way:
class Newsportal(db.Model):
name = db.StringProperty()
#... blah blah blah
class Article(db.Model):
newsportal = db.ReferenceProperty(Newsportal)
url = db.StringProperty()
date = db.DateTi... | Which one of these GAE Datastore queries is more efficient? | Suppose I have defined my data models the following way:
class Newsportal(db.Model):
name = db.StringProperty()
#... blah blah blah
class Article(db.Model):
newsportal = db.ReferenceProperty(Newsportal)
url = db.StringProperty()
date = db.DateTimeProperty()
#... blah blah blah
Now I want to determine wheth... | [
"Assuming you have a custom index for the first query, they should have the same efficiency, although the datastore won't enforce uniqueness for you unless you use the URL as a key_name, in which case you don't need to query at all, and can use the much more efficient get_by_key_name.\n",
"I would think that both... | [
2,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004583949_google_app_engine_python.txt |
Q:
Call a url that writes to a file on a server (free)
What I'm asking may sound strange, but I really need it..
What I need is a url that I can setup (like a free server with php support, but something reliable) and call that url from python with the arguments I need and it would write the values to a file.
I don't ... | Call a url that writes to a file on a server (free) | What I'm asking may sound strange, but I really need it..
What I need is a url that I can setup (like a free server with php support, but something reliable) and call that url from python with the arguments I need and it would write the values to a file.
I don't know if what I really need is a server with php (I hope n... | [
"You need a script that you can execute on the server. This can be written in any language you want. Python works fine. Unless loads of people call the URL at once you can use CGI (it's a bit slow when using Python).\n"
] | [
2
] | [] | [] | [
"html",
"python",
"url"
] | stackoverflow_0004649343_html_python_url.txt |
Q:
Python: HTML regex not matching
I have this code:
reg = re.search('<div class="col result_name">(.*)</div>', html)
print 'Value is', reg.group()
Where 'html' contains something like this:
<div class="col result_name">
<h4>Blah</h4>
<p>
blah
</p>
... | Python: HTML regex not matching | I have this code:
reg = re.search('<div class="col result_name">(.*)</div>', html)
print 'Value is', reg.group()
Where 'html' contains something like this:
<div class="col result_name">
<h4>Blah</h4>
<p>
blah
</p>
</div>
But it's not returning anythi... | [
"Don't use regex to parse html. Use a html parser\nimport lxml.html\ndoc = lxml.html.fromstring(your_html)\nresult = doc.xpath(\"//div[@class='col result_name']\")\nprint result\n\nObligatory link:\nRegEx match open tags except XHTML self-contained tags\n",
"The dot does not neccessarily match newlines in REs, yo... | [
6,
3,
2
] | [] | [] | [
"html",
"python",
"regex"
] | stackoverflow_0004650163_html_python_regex.txt |
Q:
Django model i18n of content
In my design there are some models where I need to store certain fields in different languages. Has it be done before? I saw some Django modules that help do model translations but some of them did not work properly.
Any best practices out there? Below is my code.
My model,
class Looku... | Django model i18n of content | In my design there are some models where I need to store certain fields in different languages. Has it be done before? I saw some Django modules that help do model translations but some of them did not work properly.
Any best practices out there? Below is my code.
My model,
class Lookup_I18n(models.Model):
i18n_cod... | [
"I used recently django_modeltranslation. It will create extra fields in each table for for translation of a field in a certain language. You can provide the translation through Django admin panel. Here are some applications for Django that translate the models. I had to translate just a field in the model and it w... | [
5
] | [] | [] | [
"django",
"django_models",
"internationalization",
"localization",
"python"
] | stackoverflow_0004627004_django_django_models_internationalization_localization_python.txt |
Q:
How can I get consistent behavior on my wxPython StyledTextControl?
I am having a problem with wxPython. I am attempting to have a scrollable window without a visible scroll bar. I still want to be able to use the mouse wheel to scroll as well as use the keyboard shortcuts that I have written.
I have the followin... | How can I get consistent behavior on my wxPython StyledTextControl? | I am having a problem with wxPython. I am attempting to have a scrollable window without a visible scroll bar. I still want to be able to use the mouse wheel to scroll as well as use the keyboard shortcuts that I have written.
I have the following simplified code:
import wx
import wx.stc
app = wx.App(0)
frame = wx.Fr... | [
"ScrollToLine seems to work consistently on Windows and Linux, so you could replace the ScrollLines call with something like this:\nfirst = textViewer.GetFirstVisibleLine()\ntextViewer.ScrollToLine(first + n)\n\nwhere n is the number of lines to scroll down.\n"
] | [
1
] | [] | [] | [
"python",
"scroll",
"user_interface",
"wxpython"
] | stackoverflow_0004607805_python_scroll_user_interface_wxpython.txt |
Q:
Parse Python file and evaluate selected functions
I have a file that contains several python functions, each with some statements.
def func1():
codeX...
def func2():
codeY...
codeX and codeY can be multiple statements. I want to be able to parse the file, find a function by name, then evaluate the code i... | Parse Python file and evaluate selected functions | I have a file that contains several python functions, each with some statements.
def func1():
codeX...
def func2():
codeY...
codeX and codeY can be multiple statements. I want to be able to parse the file, find a function by name, then evaluate the code in that function.
With the ast module, I can parse the f... | [
"\nI want to be able to grab any block of code given the name and then execute that code ... (providing my own local/global scope objects). \n\nA naive solution looks like this. This is based on the assumption that the functions don't all depend on global variables.\nfrom file_that_contains_several_python_functio... | [
2,
1,
1
] | [] | [] | [
"abstract_syntax_tree",
"parsing",
"python"
] | stackoverflow_0004650110_abstract_syntax_tree_parsing_python.txt |
Q:
Replacing leading text in Python
I use Python 2.6 and I want to replace each instance of certain leading characters (., _ and $ in my case) in a string with another character or string. Since in my case the replacement string is the same, I came up with this:
def replaceLeadingCharacters(string, old, new = ''):
... | Replacing leading text in Python | I use Python 2.6 and I want to replace each instance of certain leading characters (., _ and $ in my case) in a string with another character or string. Since in my case the replacement string is the same, I came up with this:
def replaceLeadingCharacters(string, old, new = ''):
t = string.lstrip(old)
return n... | [
"re.sub(r'^[._$]+', lambda m: 'Y' * m.end(0), '._.!$XXX$._')\n\nBut IMHO your first solution is good enough.\n",
"Your replaceLeadingCharacters() seems fine as is.\nHere's replaceLeadingString() implementation that uses re module (without the while loop):\n#!/usr/bin/env python\nimport re\n\ndef lreplace(s, old, ... | [
1,
1
] | [] | [] | [
"python",
"string"
] | stackoverflow_0004649997_python_string.txt |
Q:
Python: Convert Unicode to ASCII without errors for CSV file
I've been reading all questions regarding conversion from Unicode to CSV in Python here in StackOverflow and I'm still lost. Everytime I receive a "UnicodeEncodeError: 'ascii' codec can't encode character u'\xd1' in position 12: ordinal not in range(128)... | Python: Convert Unicode to ASCII without errors for CSV file | I've been reading all questions regarding conversion from Unicode to CSV in Python here in StackOverflow and I'm still lost. Everytime I receive a "UnicodeEncodeError: 'ascii' codec can't encode character u'\xd1' in position 12: ordinal not in range(128)"
buffer=cStringIO.StringIO()
writer=csv.writer(buffer, csv.excel)... | [
"Correct, ñ is not a valid ASCII character, so you can't encode it to ASCII. So you can, as your code does above, ignore them. Another way, namely to remove the accents, you can find here: \nWhat is the best way to remove accents in a Python unicode string?\nBut note that both techniques can result in bad effects, ... | [
13
] | [] | [] | [
"ascii",
"csv",
"diacritics",
"python",
"unicode"
] | stackoverflow_0004650639_ascii_csv_diacritics_python_unicode.txt |
Q:
Python : How to handle multiple clients and a server
I am implementing a program with a server and multiple clients. All clients send data to the server and a server check out the step of each client. If all client's steps are the same, a server sends new data to all clients to do next step. And it continues this ... | Python : How to handle multiple clients and a server | I am implementing a program with a server and multiple clients. All clients send data to the server and a server check out the step of each client. If all client's steps are the same, a server sends new data to all clients to do next step. And it continues this procedure again and again.
However, when I run my program,... | [
"A server must perform the sequence socket(), bind(), listen(), accept() (possibly repeating the accept() to service more than one client), while a client only needs the sequence socket(), connect(). \nYour missing listen() i saw first. Listen for connections made to the socket.\nMore on this here: link text\n",
... | [
1,
1
] | [] | [] | [
"client",
"python",
"sockets"
] | stackoverflow_0004650329_client_python_sockets.txt |
Q:
Accessing model field attributes in Django
I have a model in Django 1.2.4:
class MyModel():
foo = IntegerField(verbose_name="bar")
def printFoo(self):
print("Value of %s is %d" % (foo.verbose_name, foo))
I'm trying to get both the value and verbose name of a field. How can I do this?
I've looked ... | Accessing model field attributes in Django | I have a model in Django 1.2.4:
class MyModel():
foo = IntegerField(verbose_name="bar")
def printFoo(self):
print("Value of %s is %d" % (foo.verbose_name, foo))
I'm trying to get both the value and verbose name of a field. How can I do this?
I've looked at myModel._meta.fields, but I'm not sure if tha... | [
"Probably like this:\nMyModel._meta.get_field('foo').verbose_name\n\nSee How can I programmatically obtain the max_length of a Django model field? for a very similar question.\n"
] | [
14
] | [] | [] | [
"django",
"models",
"python"
] | stackoverflow_0004651098_django_models_python.txt |
Q:
python - performance difference between the two implementations
How are the following two implementations have different performance in Python?
from cStringIO import StringIO
from itertools import imap
from sys import stdin
input = imap(int, StringIO(stdin.read()))
print '\n'.join(imap(str, sorted(input)))
AND
im... | python - performance difference between the two implementations | How are the following two implementations have different performance in Python?
from cStringIO import StringIO
from itertools import imap
from sys import stdin
input = imap(int, StringIO(stdin.read()))
print '\n'.join(imap(str, sorted(input)))
AND
import sys
for line in sys.stdin:
l.append(int(line.strip('\n')))
... | [
">>> dis.dis(first)\n 2 0 LOAD_GLOBAL 0 (imap)\n 3 LOAD_GLOBAL 1 (int)\n 6 LOAD_GLOBAL 2 (StringIO)\n 9 LOAD_GLOBAL 3 (stdin)\n 12 LOAD_ATTR 4 (read)\n 15 CALL_FUNCTION ... | [
3,
2,
1
] | [] | [] | [
"performance",
"python",
"sorting"
] | stackoverflow_0004649703_performance_python_sorting.txt |
Q:
Simple alarm clock and checking time every second
I'm creating an alarm clock in python and have a simple question:
My alarm clock's resolution needs to be down to the second. Currently I have a thread that wakes every 0.5 seconds, and checks whether its time to start making noise.
My only concern is that somehow ... | Simple alarm clock and checking time every second | I'm creating an alarm clock in python and have a simple question:
My alarm clock's resolution needs to be down to the second. Currently I have a thread that wakes every 0.5 seconds, and checks whether its time to start making noise.
My only concern is that somehow the system gets completely overloaded at some point and... | [
"That's not the best solution. It's no guarantee you are locked out for more than one second. \nYou should stick to 0.5 second resolution (or worse if no lives depend on it) and fire the event whenever it is at or past the due time, and keep a flag per event if it has been fired. Then it will always be fired at exa... | [
2,
2
] | [] | [] | [
"python",
"scheduler"
] | stackoverflow_0004651239_python_scheduler.txt |
Q:
Why is MutableString deprecated in Python?
Why was the MutableString class deprecated in Python 2.6;
and why was it removed in Python 3?
A:
The MutableString class was meant to be educational, and not to be used in real programs. If you look at the implementation, you'd see that you can't really use this in a se... | Why is MutableString deprecated in Python? | Why was the MutableString class deprecated in Python 2.6;
and why was it removed in Python 3?
| [
"The MutableString class was meant to be educational, and not to be used in real programs. If you look at the implementation, you'd see that you can't really use this in a serious application requiring mutable strings.\nIf you need mutable bytestrings, you might consider using bytearray that's available in Python 2... | [
26,
5
] | [] | [] | [
"deprecated",
"mutable",
"python",
"python_3.x",
"string"
] | stackoverflow_0004651344_deprecated_mutable_python_python_3.x_string.txt |
Q:
python algorithm: how to efficiently find if two integer sets are intersected?
Given a set [2004, 2008], what is the fastest way to find if this set is intersected with other sets?
Actually I am dealing a problem with database, the table has 2 columns, one is the lower bound, the other one is the higher bound. The... | python algorithm: how to efficiently find if two integer sets are intersected? | Given a set [2004, 2008], what is the fastest way to find if this set is intersected with other sets?
Actually I am dealing a problem with database, the table has 2 columns, one is the lower bound, the other one is the higher bound. The task is to find all the intersected rows with the given 2 tuple(like [2004,2008]).
... | [
"I don't know MongoDB at all, but you're basically looking for \nSELECT * from the_table where not (lower_bound > 2008 or upper_bound < 2004).\n",
"Try this, assuming low and high are your bound fields:\ndb.ranges.find({'low': {'$lt': self.high}, 'high': {'$gt': self.low}})\n\nSubstitute $lte and $gte if you want... | [
4,
3,
2,
1,
1
] | [] | [] | [
"algorithm",
"data_structures",
"mongodb",
"python"
] | stackoverflow_0004646089_algorithm_data_structures_mongodb_python.txt |
Q:
Python and xml : Reading data from xml file
I have a simple python, in which i have defined styledoc as follows
styledoc = libxml2.parseDoc("""
<xsl:stylesheet version='1.0'
xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
xmlns:foo='http://example.com/foo'
xsl:exclude-result-prefixes='foo'>
<xsl:param na... | Python and xml : Reading data from xml file | I have a simple python, in which i have defined styledoc as follows
styledoc = libxml2.parseDoc("""
<xsl:stylesheet version='1.0'
xmlns:xsl='http://www.w3.org/1999/XSL/Transform'
xmlns:foo='http://example.com/foo'
xsl:exclude-result-prefixes='foo'>
<xsl:param name='bar'>failure</xsl:param>
<xsl:template matc... | [
"parseDoc takes a string containing XML, as shown in your first example. To parse a file use parseFile instead:\nstyledoc = libxml2.parseFile(\"read.xml\")\n\n"
] | [
2
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0004651569_python_xml.txt |
Q:
Optimized method for calculating cosine distance in Python
I wrote a method to calculate the cosine distance between two arrays:
def cosine_distance(a, b):
if len(a) != len(b):
return False
numerator = 0
denoma = 0
denomb = 0
for i in range(len(a)):
numerator += a[i]*b[i]
... | Optimized method for calculating cosine distance in Python | I wrote a method to calculate the cosine distance between two arrays:
def cosine_distance(a, b):
if len(a) != len(b):
return False
numerator = 0
denoma = 0
denomb = 0
for i in range(len(a)):
numerator += a[i]*b[i]
denoma += abs(a[i])**2
denomb += abs(b[i])**2
resu... | [
"If you can use SciPy, you can use cosine from spatial.distance:\nhttp://docs.scipy.org/doc/scipy/reference/spatial.distance.html\nIf you can't use SciPy, you could try to obtain a small speedup by rewriting your Python (EDIT: but it didn't work out like I thought it would, see below).\nfrom itertools import izip\n... | [
7,
6,
2,
1,
1,
1,
0,
0
] | [] | [] | [
"arrays",
"distance",
"optimization",
"python"
] | stackoverflow_0001823293_arrays_distance_optimization_python.txt |
Q:
Pysmell install error with Textmate?
I'm trying to install PySmell with Textmate -
I'm using TextMate on Mac OS, and to complicate things a bit, I'm using Brew and several virtual environments. In my case, I'm just trying to install Pysmell in my default version of Python.
I've followed the instructions for the i... | Pysmell install error with Textmate? | I'm trying to install PySmell with Textmate -
I'm using TextMate on Mac OS, and to complicate things a bit, I'm using Brew and several virtual environments. In my case, I'm just trying to install Pysmell in my default version of Python.
I've followed the instructions for the install - and can import pysmell through a ... | [
"Doh! \nI accidentally created my TM_PYTHON link to pysmell and not python. Working fine now...\n"
] | [
1
] | [] | [] | [
"python",
"textmate"
] | stackoverflow_0004651693_python_textmate.txt |
Q:
How do I get hgweb to actually display the repository I want?
I am having an infuriating experience with IIS7, Python 2.6, Mercurial 1.7.2, and hgweb.cgi.
After battling for an afternoon getting hgweb.cgi to work, I finally got it to render in the browser using hgweb.cgi and IIS7. I can now see a blank rendering ... | How do I get hgweb to actually display the repository I want? | I am having an infuriating experience with IIS7, Python 2.6, Mercurial 1.7.2, and hgweb.cgi.
After battling for an afternoon getting hgweb.cgi to work, I finally got it to render in the browser using hgweb.cgi and IIS7. I can now see a blank rendering of the web server, that is, a header with no repositories listed. ... | [
"I had about the same luck with hgweb.cgi, and ended up going a different route with wsgi and a \"pure python\" mercurial install.\nI wrote a pretty comprehensive answer here.\n",
"I'll answer my own question:\nThe solution is that the path listed in the [paths] section is relative to the directory where the hgwe... | [
1,
1
] | [] | [] | [
"hgweb",
"iis_7",
"mercurial",
"python"
] | stackoverflow_0004476106_hgweb_iis_7_mercurial_python.txt |
Q:
How do I change the Django login to allow for emails as well?
Currently, this is how I do my login:
(r'^login/?$','django.contrib.auth.views.login',{'template_name':'login.html'}),
I'm using Django's built in contrib.
What do I have to do so that people can type in their email or their username to login?
A:
Y... | How do I change the Django login to allow for emails as well? | Currently, this is how I do my login:
(r'^login/?$','django.contrib.auth.views.login',{'template_name':'login.html'}),
I'm using Django's built in contrib.
What do I have to do so that people can type in their email or their username to login?
| [
"You would want to use a custom authentication backend, like this:\nhttp://djangosnippets.org/snippets/1001/\n"
] | [
1
] | [] | [] | [
"authentication",
"django",
"python",
"url"
] | stackoverflow_0004651901_authentication_django_python_url.txt |
Q:
Examining then updating rows in sqlite with Python
I've decided that I'm not fond of the automatic filing and renaming provided by Mendeley, but have found that it keeps track of everything in an sqlite database that I can easily read and modify from Python.
My question is, if I'm going to iterate over the rows of... | Examining then updating rows in sqlite with Python | I've decided that I'm not fond of the automatic filing and renaming provided by Mendeley, but have found that it keeps track of everything in an sqlite database that I can easily read and modify from Python.
My question is, if I'm going to iterate over the rows of a table containing file paths and hashes that are servi... | [
"I don't think there's a way to modify the rows in the table other than via SQL -- UPDATE, or INSERT OR REPLACE. (It's tempting to think that the sqlite3.Row object might allow assignment, and write back to the row it represents, but no.)\nAs for doing UPDATEs (via a 2nd cursor) while there's an outstanding cursor... | [
2
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0003926606_python_sqlite.txt |
Q:
How to: Click button, then do stuff, then show confirmation in Django
Basic question, but I can't find a simple answer anywhere.
What is the best way to do the following in Django:
User pushes button
Some Python code gets crunched server-side
User sees confirmation page
All the user needs to know is that the ser... | How to: Click button, then do stuff, then show confirmation in Django | Basic question, but I can't find a simple answer anywhere.
What is the best way to do the following in Django:
User pushes button
Some Python code gets crunched server-side
User sees confirmation page
All the user needs to know is that the server did what he told it to. No input other than the button click.
Thanks i... | [
"That's what a Form is for. You can create a small HTML form with just the button.\nThe form's action is the URI to which a request is sent.\nDjango parse the URI and calls a view function.\nThe function does the work and returns the resulting page. \n"
] | [
4
] | [] | [] | [
"button",
"django",
"django_forms",
"post",
"python"
] | stackoverflow_0004652048_button_django_django_forms_post_python.txt |
Q:
user inheritance in django
I saw a couple of ways extending user information of users and decided to adopt the model inheritance method.
for instance, I have :
class Parent(User):
contact_means = models.IntegerField()
is_staff = False
objects = userManager()
Now it is done, I've downloaded django_reg... | user inheritance in django | I saw a couple of ways extending user information of users and decided to adopt the model inheritance method.
for instance, I have :
class Parent(User):
contact_means = models.IntegerField()
is_staff = False
objects = userManager()
Now it is done, I've downloaded django_registration to help me out with se... | [
"It's probably something like:\np = Parent()\np.user_ptr = user\np.contact_means = ...\np.save()\n\n(Django creates the foreign key for you when doing model inheritance, plus the attribute ending in _ptr)\n"
] | [
2
] | [] | [] | [
"django",
"django_models",
"django_registration",
"python"
] | stackoverflow_0004648598_django_django_models_django_registration_python.txt |
Q:
redirection in django
In my home page i have a profile pic on changing the profile pic i update the DB and redirevt the page to /home . But now when i redirect the old picture remains the same till refresh button is hit.Ami doing anything wrong here
This is in the python code
return HttpResponseRedirect('/home')
... | redirection in django | In my home page i have a profile pic on changing the profile pic i update the DB and redirevt the page to /home . But now when i redirect the old picture remains the same till refresh button is hit.Ami doing anything wrong here
This is in the python code
return HttpResponseRedirect('/home')
This is in the base html p... | [
"Maybe the profile picture is cached by the browser. There are multiple ways to avoid it:\n\ndisable caching for the by changing the response headers for it. This is a bad idea for production because the picture would never be cached, so every page-request would fetch the picture, which massively increases the traf... | [
1,
1
] | [] | [] | [
"django",
"django_templates",
"django_views",
"python"
] | stackoverflow_0004646151_django_django_templates_django_views_python.txt |
Q:
Wikipedia deletion log download
I need wikipedia deletion log for my project. I was able to find deletion logs here
http://en.wikipedia.org/w/index.php?title=Special:Log&type=delete&user=&page=&year=&month=-1&tagfilter=&hide_review_log=1
I can download 5000 entries at a time, but it will take lot of time, due to ... | Wikipedia deletion log download | I need wikipedia deletion log for my project. I was able to find deletion logs here
http://en.wikipedia.org/w/index.php?title=Special:Log&type=delete&user=&page=&year=&month=-1&tagfilter=&hide_review_log=1
I can download 5000 entries at a time, but it will take lot of time, due to large number of pages. Is there a dum... | [
"Why not ask at Wikipedia? There are various dumps available, including tools on the toolserver that may be of use. Your best bet is asking at the technical pump.\n"
] | [
4
] | [] | [] | [
"dump",
"information_retrieval",
"java",
"python",
"wikipedia"
] | stackoverflow_0004652530_dump_information_retrieval_java_python_wikipedia.txt |
Q:
What is a VM and why do dynamic languages need one?
So, for example, Python and Java have a VM, C and Haskell do not. (Correct me if I'm wrong)
Thinking about what languages on both sides of the line have, I can't find the reason. Java is static in a lot of ways, while Haskell provides a lot of dynamic features.
... | What is a VM and why do dynamic languages need one? | So, for example, Python and Java have a VM, C and Haskell do not. (Correct me if I'm wrong)
Thinking about what languages on both sides of the line have, I can't find the reason. Java is static in a lot of ways, while Haskell provides a lot of dynamic features.
| [
"It's nothing to do with static vs. dynamic.\nRather, it's about becoming independent from the underlying hardware platform (\"build once, run everywhere\" - in theory...)\nActually, it's nothing to do with the language, either. One could write a C compiler that generates bytecode for the JVM. One could write a J... | [
29,
23,
4,
4,
3,
2,
2,
2
] | [] | [] | [
"c",
"haskell",
"java",
"python",
"vm_implementation"
] | stackoverflow_0004640809_c_haskell_java_python_vm_implementation.txt |
Q:
reference to lxml node
i'm iterating xml node values, which i get from xpath query. And i need to assign a reference to some node value.
Here what i want to to:
from lxml import etree
doc = etree.fromstring(some_xml)
nodes = doc.xpath('some_query')
for node in nodes:
if node.text == 'smth':
#there i n... | reference to lxml node | i'm iterating xml node values, which i get from xpath query. And i need to assign a reference to some node value.
Here what i want to to:
from lxml import etree
doc = etree.fromstring(some_xml)
nodes = doc.xpath('some_query')
for node in nodes:
if node.text == 'smth':
#there i need to assign reference
... | [
"store a reference to the actual node instead:\nfrom lxml import etree\n\ndoc = etree.fromstring(some_xml)\nnodes = doc.xpath('some_query')\nfor node in nodes:\n if node.text == 'smth':\n reference = node\n\nreference.text = 'hello world'\n\n"
] | [
1
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0004652756_lxml_python.txt |
Q:
What is the Pythonic way of reordering a list consisting of dicts?
I have the the following list:
list = [{'nr' : 2, 'name': 'streamname'}, {'nr' : 3,'name': 'streamname'}, {'nr' : 1, 'name': 'streamname'}]
So how would I reorder it to become like this in an efficient way in python?
list = [{'nr' : 1, 'name': 's... | What is the Pythonic way of reordering a list consisting of dicts? | I have the the following list:
list = [{'nr' : 2, 'name': 'streamname'}, {'nr' : 3,'name': 'streamname'}, {'nr' : 1, 'name': 'streamname'}]
So how would I reorder it to become like this in an efficient way in python?
list = [{'nr' : 1, 'name': 'streamname'}, {'nr' : 2,'name': 'streamname'}, {'nr' : 3, 'name': 'stream... | [
"No, using cmp= is not efficient. Use key= instead. Like so:\nsorted(list, key=lambda x: x['nr'])\n\nThe reason is simple: cmp compares two objects. If your list is long, there are many combinations of two objects you can have to compare, so a list that is twice as long takes much more than twice as long to sort.\n... | [
12,
3
] | [] | [] | [
"lambda",
"python",
"sorting"
] | stackoverflow_0004647524_lambda_python_sorting.txt |
Q:
running external commands with control over the input/output in jython 2.1
I have an application using jython2.1 and I need to run external applications, (lets say some .exe for now). I also need to capture the input and output such as logs from that program.
Jython 2.1 seems to not have the support for popen().
A... | running external commands with control over the input/output in jython 2.1 | I have an application using jython2.1 and I need to run external applications, (lets say some .exe for now). I also need to capture the input and output such as logs from that program.
Jython 2.1 seems to not have the support for popen().
ANy idea how I do that , apart from depending on standard Java libraries? Just tr... | [
"You can just use Java's classes that do this.\nfrom java.lang import Runtime\nprocess = Runtime.getRuntime().exec(\"ls -l\")\noutput = process.getInputStream() # process' output is our input\n# read output somehow, while the process is generating it\n\n",
"Any reason you're using jython 2.1? I mean, it's ancient... | [
1,
0
] | [] | [] | [
"jakarta_ee",
"jython",
"python"
] | stackoverflow_0004652512_jakarta_ee_jython_python.txt |
Q:
Can someone tell me why I'm not installing this Django backend correctly?
My project is "fable". So I created this:
/home/myuser/fable/backends/EmailOrUsernameModelBackend.py
And also __init__.py inside there.
Inside this file, I pasted this snipplet in there: http://djangosnippets.org/snippets/1001/
Now, I cha... | Can someone tell me why I'm not installing this Django backend correctly? | My project is "fable". So I created this:
/home/myuser/fable/backends/EmailOrUsernameModelBackend.py
And also __init__.py inside there.
Inside this file, I pasted this snipplet in there: http://djangosnippets.org/snippets/1001/
Now, I change add this to my settings.py:
AUTHENTICATION_BACKENDS = (
'fable.backends... | [
"Solved. Simple spelling mistake in my file.\n"
] | [
1
] | [] | [] | [
"authentication",
"django",
"python"
] | stackoverflow_0004652818_authentication_django_python.txt |
Q:
RegEx - Match optional groups
I know RegEx is not the best way to scrape HTMLs, but this is it...
I have some something like:
<td> Writing: <a href="creator.php?c=CCh">Carlo Chendi</a> Art: <a href="creator.php?c=LBo">Luciano Bottaro</a> </td>
And I need to match the Writing and Art parts. But it is not said the... | RegEx - Match optional groups | I know RegEx is not the best way to scrape HTMLs, but this is it...
I have some something like:
<td> Writing: <a href="creator.php?c=CCh">Carlo Chendi</a> Art: <a href="creator.php?c=LBo">Luciano Bottaro</a> </td>
And I need to match the Writing and Art parts. But it is not said they're there, and there could be othe... | [
"Maybe there are two patterns to recognise.\n\nyour keywords exist within a <td>...</td>\nyour keywords are followed by a <a>...</a> section\n\nSo.. first extract everything within <td>s... (psuedo code)\nwhile ( match( \"<td[^>]*>(.*?)</td[^>]*>\" ) ) {\n inner = match[1];\n ...\n}\n\nThe (.*?) means match n... | [
2,
1,
1,
0,
0
] | [] | [] | [
"html_parsing",
"python",
"regex"
] | stackoverflow_0004637688_html_parsing_python_regex.txt |
Q:
tokyo-python Install Issues
I'm trying to use Tokyo Cabinet in Python via the tokyo-python package. I've installed Cabinet, and the Cabinet development library. However, whenever I try to install tokyo-python with pip or easy_install, I get this ugliness.
matt@amalgam:~/$ bin/pip install tokyo-python
Downloading/u... | tokyo-python Install Issues | I'm trying to use Tokyo Cabinet in Python via the tokyo-python package. I've installed Cabinet, and the Cabinet development library. However, whenever I try to install tokyo-python with pip or easy_install, I get this ugliness.
matt@amalgam:~/$ bin/pip install tokyo-python
Downloading/unpacking tokyo-python
Downloading... | [
"Did you try asking the developer? (Though I guess this question is out of date as current version is already 0.7.)\n"
] | [
0
] | [] | [] | [
"easy_install",
"linux",
"pip",
"python",
"tokyo_cabinet"
] | stackoverflow_0003225494_easy_install_linux_pip_python_tokyo_cabinet.txt |
Q:
Importing a class and calling a method
I am using Eclipse for Python programming.
In my project, I have a file: main.py. This file is located in the root of the project files hierarchy. In the root itself, I created a folder with the name Classes in which I have a class file named: PositionWindow.py. This file con... | Importing a class and calling a method | I am using Eclipse for Python programming.
In my project, I have a file: main.py. This file is located in the root of the project files hierarchy. In the root itself, I created a folder with the name Classes in which I have a class file named: PositionWindow.py. This file contains a class PositionWindow and the class i... | [
"You seem to be programming in java, still. I understand that you used java for a long time, but this is no longer java. This is python...\n\nPython doesn't have directories. It has packages\nPython doesn't have class files. It has modules.\nYou can have multiple classes in a module.\nYou can have multiple modules ... | [
5,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004652984_python.txt |
Q:
android python full integration
Is there a way to fully integrate Python with Java code on Android platform?
Yes, I saw the question about running Python on Android and Android Scripting Environment (ASE).
But that doesn't seem to be enough (correct me if I am wrong). I wanted to be able not only to invoke a Pytho... | android python full integration | Is there a way to fully integrate Python with Java code on Android platform?
Yes, I saw the question about running Python on Android and Android Scripting Environment (ASE).
But that doesn't seem to be enough (correct me if I am wrong). I wanted to be able not only to invoke a Python script from within Java code, but h... | [
"ASE is probably the way to go.\nI'm not a Jython expert, but I expect part of the problem with trying to go that route is that Android isn't really Java -- while the base language is the same, Android Java code does not share any of the \"standard\" Java libraries and it compiles into its own bytecode language.\nH... | [
0
] | [] | [] | [
"android",
"ase",
"java",
"jython",
"python"
] | stackoverflow_0004641625_android_ase_java_jython_python.txt |
Q:
Problems with Getting Remote Contents using Google App Engine
Here is the client side code. It is running insdide a Google Gadgets
var params = {};
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
var url = "http://invplatformtest.appspot.com/getrecent/";
gadgets.io.makeRequ... | Problems with Getting Remote Contents using Google App Engine | Here is the client side code. It is running insdide a Google Gadgets
var params = {};
params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
var url = "http://invplatformtest.appspot.com/getrecent/";
gadgets.io.makeRequest(url, response, params);
The response function is:
function res... | [
"The problem is that you're not encoding JSON at all - you're just passing a Python dictionary to self.request.out.write, and expecting it to know what to do with it. Import django.utils.simplejson, and call simplejson.dumps() on the dictionary to convert it to JSON.\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"json",
"python"
] | stackoverflow_0004652314_google_app_engine_json_python.txt |
Q:
Reading input from raw_input() without having the prompt overwritten by other threads in Python
I'm trying to let the user input commands at a console using raw_input(), this works fine. The problem is I have background threads that occasionally output log-information to the screen and when they do they mess up th... | Reading input from raw_input() without having the prompt overwritten by other threads in Python | I'm trying to let the user input commands at a console using raw_input(), this works fine. The problem is I have background threads that occasionally output log-information to the screen and when they do they mess up the input prompt (since the output go wherever the cursor happens to be at the moment).
This is a small... | [
"I recently encountered this problem, and would like to leave this solution here for future reference.\nThese solutions clear the pending raw_input (readline) text from the terminal, print the new text, then reprint to the terminal what was in the raw_input buffer.\nThis first program is pretty simple, but only wor... | [
26,
3,
1,
0
] | [] | [] | [
"multithreading",
"python",
"raw_input"
] | stackoverflow_0002082387_multithreading_python_raw_input.txt |
Q:
Adding a sub-menu in Windows context-menu
I want to add a sub-menu to the right-click menu of Windows. Whenever a user right-clicks on a file or a folder, my application name with the sub-menu must appear there.
How to handle this?
A:
You want to edit the Windows Explorer context menu. You can do this in a coupl... | Adding a sub-menu in Windows context-menu | I want to add a sub-menu to the right-click menu of Windows. Whenever a user right-clicks on a file or a folder, my application name with the sub-menu must appear there.
How to handle this?
| [
"You want to edit the Windows Explorer context menu. You can do this in a couple of different ways:\n\nThere is a utility at http://www.ghacks.net/2010/08/15/add-custom-items-to-windows-explorer-context-menu/ which provides a bit of hand-holding. It looks like it will also let you add sub-menus directly.\nManually ... | [
2
] | [] | [] | [
"python",
"registry",
"windows_explorer"
] | stackoverflow_0004653094_python_registry_windows_explorer.txt |
Q:
Add a custom link to hudson project page
I'm using Hudson to generate the documentation for a Python project using Sphinx. This generates HTML documentation in the folder project/_build/html, which I set up to be used as an build artifact. Now after running the job, I can navigate to the documentation by clicking ... | Add a custom link to hudson project page | I'm using Hudson to generate the documentation for a Python project using Sphinx. This generates HTML documentation in the folder project/_build/html, which I set up to be used as an build artifact. Now after running the job, I can navigate to the documentation by clicking on the "Artifacts" link, then on the folder, a... | [
"I know the question is closed, but I thought you could try this. You don't need a separate http server just to serve HTML documentation, artifact or not. You can use the plugin:\nhttp://wiki.hudson-ci.org/display/HUDSON/HTML+Publisher+Plugin\n",
"The Project Description allows HTML, just edit it and place the li... | [
4,
2,
1
] | [] | [] | [
"continuous_integration",
"hudson",
"python",
"python_sphinx"
] | stackoverflow_0004645581_continuous_integration_hudson_python_python_sphinx.txt |
Q:
How to check a List for a match in Django?
Assuming:
strings = ["abc", "a", "bc"]
str = "bc"
I want to:
{% if str is in strings %}
Doesn't look like this is allowed in Django. If not what is the proper syntax or a method for checking a value in a List?
A:
This is an app running on Google App Engine. Here is ... | How to check a List for a match in Django? | Assuming:
strings = ["abc", "a", "bc"]
str = "bc"
I want to:
{% if str is in strings %}
Doesn't look like this is allowed in Django. If not what is the proper syntax or a method for checking a value in a List?
| [
"This is an app running on Google App Engine. Here is a custom filter that will do the trick:\nfrom google.appengine.ext.webapp import template\nfrom django import template as django_template\n\ndef in_list(value, arg):\n \"\"\"\n Given an item and a list, check if the item is in the list.\n Usage:\n {% if ite... | [
4,
1
] | [] | [] | [
"django",
"if_statement",
"list",
"python"
] | stackoverflow_0004643545_django_if_statement_list_python.txt |
Q:
python writing a list-of-tuples to a file
I need to write a list to a file in python. I know the list should be converted to a string with the join method, but since I have a tuple I got confused. I tried a lot to change my variables to strings etc, this is one of my first attempts:
def perform(text):
reposito... | python writing a list-of-tuples to a file | I need to write a list to a file in python. I know the list should be converted to a string with the join method, but since I have a tuple I got confused. I tried a lot to change my variables to strings etc, this is one of my first attempts:
def perform(text):
repository = [("","")]
fdist = nltk.FreqDist(some_v... | [
"Convert the tuples to strings before passing them to join()\nI have fairly drastically rearranged this, such that:\n\nyour function is now a generator (lower memory requirements)\nthe desired format is passed in - it returns whatever format you ask it to return\nI am guessing that some_variable is a reportable sub... | [
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004653480_python.txt |
Q:
Equivalent C++ nested print in python
I'm trying to run this C++ statement in python and I'm having trouble placing the print in the loop.
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
for (int k = 0; k < 3; k++)
{
cout<<_3x3x3[i][j][k]<<" ";
}
}
//p... | Equivalent C++ nested print in python | I'm trying to run this C++ statement in python and I'm having trouble placing the print in the loop.
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
for (int k = 0; k < 3; k++)
{
cout<<_3x3x3[i][j][k]<<" ";
}
}
//print here in python
cout<<endl;
}
in ... | [
"for i in range(3):\n for j in range(3):\n for k in range(3):\n # something here\n print _3x3x3[i][j][k],\n print\n\n",
"For variety, and future-proofing:\nfrom __future__ import print_function\n\nfor i in range(3):\n print(*(_3x3x3[i][j][k] for j in range(3) for k in range(3... | [
4,
0
] | [] | [] | [
"c++",
"equivalent",
"nested_loops",
"printing",
"python"
] | stackoverflow_0004653507_c++_equivalent_nested_loops_printing_python.txt |
Q:
Deliver to a specific version via Inbound Mail service
I have an app that services inbound mail and I have deployed a new development version to Google App Engine. The default is currently set to the previous version.
Is there a way to specify that inbound mail should be delivered to a particular version?
This is ... | Deliver to a specific version via Inbound Mail service | I have an app that services inbound mail and I have deployed a new development version to Google App Engine. The default is currently set to the previous version.
Is there a way to specify that inbound mail should be delivered to a particular version?
This is well documented using URLs but I can't find any reference to... | [
"No, this isn't currently supported. You could write some code for your default version that routes mail to other versions via URLFetch, though.\n",
"There is an easier way to do this than writing code that routes between different versions using URLFetch.\nIf you have a large body of code that is email oriented ... | [
5,
0
] | [] | [] | [
"email",
"google_app_engine",
"python"
] | stackoverflow_0004567769_email_google_app_engine_python.txt |
Q:
Unbelievable python boolean feature
>>> a = False
>>> b = False
>>> a | b
True
>>> a
True
>>> b
True
I get this in a python interpreter.
I just don't think so. Is there any detailed material about python boolean type?
I use Python 2.6.6, thanks!
A:
I can see only one context in which your problem makes sense:... | Unbelievable python boolean feature | >>> a = False
>>> b = False
>>> a | b
True
>>> a
True
>>> b
True
I get this in a python interpreter.
I just don't think so. Is there any detailed material about python boolean type?
I use Python 2.6.6, thanks!
| [
"I can see only one context in which your problem makes sense:\n>>> False = True\n>>> a = False\n>>> b = False\n>>> a | b\nTrue\n>>> a\nTrue\n>>> b\nTrue\n>>> \n\nTo start debugging - what's the result of print int(False)? If the above happened, you should get 1. Try:\n>>> False = bool(0)\n>>> a = False\n>>> b = Fa... | [
7,
4,
2
] | [] | [] | [
"boolean",
"python",
"python_2.6"
] | stackoverflow_0004653711_boolean_python_python_2.6.txt |
Q:
Python: pass more than one keyword argument?
is there possible to pass more than one keyword argument to a function in python?
foo(self, **kwarg) # Want to pass one more keyword argument here
A:
You only need one keyword-arguments parameter; it receives any number of keyword arguments.
def foo(**kwargs):
... | Python: pass more than one keyword argument? | is there possible to pass more than one keyword argument to a function in python?
foo(self, **kwarg) # Want to pass one more keyword argument here
| [
"You only need one keyword-arguments parameter; it receives any number of keyword arguments.\ndef foo(**kwargs):\n return kwargs\n\n>>> foo(bar=1, baz=2)\n{'baz': 2, 'bar': 1}\n\n",
"I would write a function to do this for you\n def partition_mapping(mapping, keys):\n \"\"\" Return two dicts. The first one h... | [
5,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004653603_python.txt |
Q:
Python: Replace tags but preserve inner text V2
I've got a script to do search and replace. it's based on a script here.
It was modified to accept file as input but it does not seem to recognize regex well.
The script:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os
import re
import glob
_replacement... | Python: Replace tags but preserve inner text V2 | I've got a script to do search and replace. it's based on a script here.
It was modified to accept file as input but it does not seem to recognize regex well.
The script:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os
import re
import glob
_replacements = {
'[B]': '**',
'[/B]': '**',
'[I]': '... | [
"For starters, you're escaping the patterns on this line:\ntext = replace_tags(text, re.compile('|'.join(re.escape(r) for r in _replacements)))\n\nre.escape takes a string and escapes it in such a way that if the new string were used as a regex it would match exactly the input string.\nRemoving the re.escape won't ... | [
1,
0
] | [] | [] | [
"python",
"regex",
"replace"
] | stackoverflow_0004394526_python_regex_replace.txt |
Q:
Python TypeError: unsupported operand type(s) for *: 'Vector2' and 'int'
I am trying to create a Vector2 class.
When I try to type
vec1 = Vector2()
vec2 = vec1 * 5
it gives me the error:
TypeError: unsupported operand type(s) for *: 'Vector2' and 'int'
Is there something wrong with my operator overloading?
class... | Python TypeError: unsupported operand type(s) for *: 'Vector2' and 'int' | I am trying to create a Vector2 class.
When I try to type
vec1 = Vector2()
vec2 = vec1 * 5
it gives me the error:
TypeError: unsupported operand type(s) for *: 'Vector2' and 'int'
Is there something wrong with my operator overloading?
class Vector2(object):
def __init__(self, x = 0.0, y = 0.0):
self.X = x
se... | [
"Isn't it __mul__ and not __mull__ ? Replace your __mull__ with __mul__ and try again.\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0004654688_python.txt |
Q:
Which of two methods of using python within erlang should I use?
I have a project where I use erlang to aggregate RSS, and I use python to process the RSS feeds.
Method 1:
Use an erlang port, using erlport.org, to call python.
I'm not sure how to design the python code to be asyncrhonous using erlport.
Method 2... | Which of two methods of using python within erlang should I use? | I have a project where I use erlang to aggregate RSS, and I use python to process the RSS feeds.
Method 1:
Use an erlang port, using erlport.org, to call python.
I'm not sure how to design the python code to be asyncrhonous using erlport.
Method 2:
Use erlang to call on a RESTful interface with Tornado that does the... | [
"I haven't worked Erlang<->Python before but erlport.org seems promising. I would try that first before getting into greasiness with REST and what not. I.e. I didn't provide and answer but a recommendation :)\n"
] | [
1
] | [] | [] | [
"erlang",
"python"
] | stackoverflow_0004653361_erlang_python.txt |
Q:
Many-to-Many Relationships: Querying for Objects with a Single Value
I have two models. An Artist model, and a Album model. There's a ManyToManyField connecting the two, since an album can have more than one artist (collaborations and the like).
The problem I'm having is when I do a simple Album.objects.filter(art... | Many-to-Many Relationships: Querying for Objects with a Single Value | I have two models. An Artist model, and a Album model. There's a ManyToManyField connecting the two, since an album can have more than one artist (collaborations and the like).
The problem I'm having is when I do a simple Album.objects.filter(artists=1)-type query, it expectedly shows all of the Album objects that have... | [
"Album.objects.annotate(n_artists=Count(\"artists')).filter(n_artists=1).filter(artist=some_awesome_artist)\n\nBasically the idea is to find all the albums who have exactly 1 artist (by annotating and filtering), and then filter down.\n"
] | [
4
] | [] | [] | [
"django",
"django_orm",
"django_queryset",
"python"
] | stackoverflow_0004654914_django_django_orm_django_queryset_python.txt |
Q:
In my Django template, how do I display the check boxes and notification types?
If this is the view in Django_notification (https://github.com/pinax/django-notification/blob/master/notification/views.py), how do I display the check box? It doesn't seem like there are form objects here. Usually, I'm used to doing ... | In my Django template, how do I display the check boxes and notification types? | If this is the view in Django_notification (https://github.com/pinax/django-notification/blob/master/notification/views.py), how do I display the check box? It doesn't seem like there are form objects here. Usually, I'm used to doing this: {{ myform.thefield }}
@login_required
def notice_settings(request):
"""
... | [
"The default template for this view is checked into github: https://github.com/pinax/pinax/blob/master/pinax/templates/default/notification/notice_settings.html\nUPDATE: Pinax removed their themes, the last checkin with templates can still be found here.\nThere is no form defined for the notification settings objec... | [
3,
0
] | [] | [] | [
"css",
"django",
"html",
"python",
"templates"
] | stackoverflow_0004633264_css_django_html_python_templates.txt |
Q:
Automatically Convert PNG to JPG with Python
I've written a Python program to retrieve an image from a URL using
msgImage = MIMEImage( urllib2.urlopen(chartURL).read() )
msgRoot.attach(msgImage)
The image that I get from the URL is in PNG format, but I would like to embed a JPG version of it. Is there a simple ... | Automatically Convert PNG to JPG with Python | I've written a Python program to retrieve an image from a URL using
msgImage = MIMEImage( urllib2.urlopen(chartURL).read() )
msgRoot.attach(msgImage)
The image that I get from the URL is in PNG format, but I would like to embed a JPG version of it. Is there a simple way to automatically convert the PNG msgImage into... | [
"You can use PIL: http://www.pythonware.com/products/pil/\nIt is easy and it has a lot of documentation.\n"
] | [
1
] | [] | [] | [
"image",
"jpeg",
"mime",
"python"
] | stackoverflow_0004655562_image_jpeg_mime_python.txt |
Q:
How to split a multistring in python?
Given a multistring returned by a function I'm accessing using ctypes of the form:
"the quick brown fox\x00jumped over the lazy\00programmer\00\00"
What's the best way to turn this into a python list like this:
["the quick brown fox", "jumped over the lazy", "programmer"]
I ... | How to split a multistring in python? | Given a multistring returned by a function I'm accessing using ctypes of the form:
"the quick brown fox\x00jumped over the lazy\00programmer\00\00"
What's the best way to turn this into a python list like this:
["the quick brown fox", "jumped over the lazy", "programmer"]
I tried using foo.split('\x00'), but that did... | [
"Given\nsentence = \"the quick brown fox\\x00jumped over the lazy\\00programmer\\00\\00\"\n[phrase for phrase in sentence.split(\"\\x00\") if phrase != \"\"]\n\n\nEDIT\nStraight from the horse's mouth:\n>>> sentence = \"the quick brown fox\\x00jumped over the lazy\\00programmer\\00\\00\"\n>>> [phrase for phrase in ... | [
5,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0004654495_python.txt |
Q:
Why can I not access this class member in python?
I have the following code
class Transcription(object):
WORD = 0
PHONE = 1
STATE = 2
def __init__(self):
self.transcriptions = []
def align_transcription(self,model,target=Transcription.PHONE):
pass
The important part here is t... | Why can I not access this class member in python? | I have the following code
class Transcription(object):
WORD = 0
PHONE = 1
STATE = 2
def __init__(self):
self.transcriptions = []
def align_transcription(self,model,target=Transcription.PHONE):
pass
The important part here is that I would like to have a class member as default valu... | [
"You can't access it because Transcription isn't defined at the time that the def statement is running.\n def align_transcription(self,model,target=PHONE):\n pass\n\nwill do the trick. The PHONE name is available in the namespace which will become the Transcription class after the class statement finishes ex... | [
11,
2,
1
] | [] | [] | [
"class_members",
"python"
] | stackoverflow_0004655745_class_members_python.txt |
Q:
Django: persistent database-backed settings
I want to have some database stored settings for my Django app - just some key-value pairs. Does Django have a conventional way of doing this / something built in for it, or should I implement it myself?
class Setting(models.Model):
key = models.TextField()
val... | Django: persistent database-backed settings | I want to have some database stored settings for my Django app - just some key-value pairs. Does Django have a conventional way of doing this / something built in for it, or should I implement it myself?
class Setting(models.Model):
key = models.TextField()
value = models.TextField()
Of course, I'd want to b... | [
"I've just been playing with the django-satchmo e-store application. Satchmo uses satchmo-livesettings or just livesettings to achieve this goal. In addition to that it is possible to change the settings using the admin interface.\nThe only problem is that I didn't find a tutorial on how to use livesettings. But if... | [
0
] | [] | [] | [
"database",
"django",
"python"
] | stackoverflow_0004655084_database_django_python.txt |
Q:
Sort list of strings by length and alphabetically
I need to sort a list of words based on two criteria given. I need to return a list with the same words in order of length (longest to shortest) and the second sort criteria should be alphabetical.
Example list :
l = ['aa','aaa','aaaa','b','bb','z','ccc']
Desired ... | Sort list of strings by length and alphabetically | I need to sort a list of words based on two criteria given. I need to return a list with the same words in order of length (longest to shortest) and the second sort criteria should be alphabetical.
Example list :
l = ['aa','aaa','aaaa','b','bb','z','ccc']
Desired output:
['aaaa', 'aaa', 'ccc', 'aa', 'bb', 'b', 'z']
| [
"You only need one call to sort, because Python automatically sorts tuples lexicographically. That is, if you ask Python to compare two tuples it will order them by their first element, except if those compare equal in which case it will order them by their second element, except if those compare equal in which cas... | [
9,
6,
2,
1,
0
] | [] | [] | [
"algorithm",
"python",
"sorting"
] | stackoverflow_0004655591_algorithm_python_sorting.txt |
Q:
Creating a SQL Server database from Python
I'm using Python with pywin32's adodbapi to write a script to create a SQL Server database and all its associated tables, views, and procedures. The problem is that Python's DBAPI requires that cursor.execute() be wrapped in a transaction that is only committed by cursor... | Creating a SQL Server database from Python | I'm using Python with pywin32's adodbapi to write a script to create a SQL Server database and all its associated tables, views, and procedures. The problem is that Python's DBAPI requires that cursor.execute() be wrapped in a transaction that is only committed by cursor.commit(), and you can't execute a drop or creat... | [
"\"The problem is that Python's DBAPI requires that cursor.execute() be wrapped in a transaction that is only committed by cursor.commit()\"\n\"and you can't execute a drop or create database statement in a user transaction.\"\nI'm not sure all of this is actually true for all DBAPI interfaces.\nSince you don't sho... | [
2,
1,
0,
0
] | [] | [] | [
"adodbapi",
"python",
"pywin32",
"sql_server"
] | stackoverflow_0000854008_adodbapi_python_pywin32_sql_server.txt |
Q:
Python: How to know if two dictionary have the same keys
dic1 = {'a':'a','b':'c','c':'d'}
dic2 = {'b':'a','a':'c','c':'d'}
dic1.keys() =>['a', 'b', 'c']
dic2.keys() =>['b', 'a', 'c']
dic1 and dic2 have the same keys, but in different order.
How to tell they have same keys(do not consider the order)?
A:
p... | Python: How to know if two dictionary have the same keys | dic1 = {'a':'a','b':'c','c':'d'}
dic2 = {'b':'a','a':'c','c':'d'}
dic1.keys() =>['a', 'b', 'c']
dic2.keys() =>['b', 'a', 'c']
dic1 and dic2 have the same keys, but in different order.
How to tell they have same keys(do not consider the order)?
| [
"python 2.7\ndict views:\nSupports direct set operations, etc.\n>>> dic1 = {'a':'a','b':'c','c':'d'}\n>>> dic2 = {'b':'a','a':'c','c':'d'}\n>>> dic1.viewkeys() == dic2.viewkeys()\nTrue\n>>> dic1.viewkeys() - dic2.viewkeys()\nset([])\n>>> dic1.viewkeys() | dic2.viewkeys()\nset(['a', 'c', 'b'])\n\nsimilarly in 3.x: ... | [
30,
12,
1,
0
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0004656329_dictionary_python.txt |
Q:
Including If In Arrays Formed Using For
In Python I have this statement:
blog_ids = [c.blog_id for c in connections]
Which basically tells Python to create an array of all the blog IDs in the connections. Unfortunately, if the connections object has some None types, c.blog_id would cause an exception. Is there an... | Including If In Arrays Formed Using For | In Python I have this statement:
blog_ids = [c.blog_id for c in connections]
Which basically tells Python to create an array of all the blog IDs in the connections. Unfortunately, if the connections object has some None types, c.blog_id would cause an exception. Is there any syntax to solve this problem? I tried this ... | [
"blog_ids = [c.blog_id for c in connections if c is not None]\n\n",
"The thing here probably is to ask what kind of objects you have in your connections object. Are they either valid objects with blog_id attribute or None objects. Or is there possibility that among those objects there are also some other objects ... | [
8,
0
] | [] | [] | [
"python"
] | stackoverflow_0004656590_python.txt |
Q:
pythonpath and omniORB
In README file of omniORBpy-3.4 is written that I have to set PYTHONPATH as
set PYTHONPATH=%PYTHONPATH%;%TOP%\lib\python;%TOP%\lib\x86_win32
Where %TOP% is the top-level omniORBpy directory. (Windows machine)
I have done that and reboot my machine but when I try to run *.py files which have... | pythonpath and omniORB | In README file of omniORBpy-3.4 is written that I have to set PYTHONPATH as
set PYTHONPATH=%PYTHONPATH%;%TOP%\lib\python;%TOP%\lib\x86_win32
Where %TOP% is the top-level omniORBpy directory. (Windows machine)
I have done that and reboot my machine but when I try to run *.py files which have a line like
import omniORB ... | [
"I think you will find that the README file of omniORBpy says that TOP must be set to the \"the root of your omniORB tree\" and not omniORBpy.\n",
"Not sure here, but I don't think, that changes made to the environment via a batch script will persist across reboots. Try setting the variable via the Workstation pr... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004439568_python.txt |
Q:
Socket error "IP address not valid in its context" - Python
I'm using Python 2.6 and Windows Server 2008.
The server has two IP addresses 1 internal, 1 external.
I need Python to use the external IP address, but while doing so I get this:
socket.error: [Error 10049] The requested address is not valid in its cont... | Socket error "IP address not valid in its context" - Python | I'm using Python 2.6 and Windows Server 2008.
The server has two IP addresses 1 internal, 1 external.
I need Python to use the external IP address, but while doing so I get this:
socket.error: [Error 10049] The requested address is not valid in its context
To be more precise I'm using Django's runserver command for... | [
"That's an error Windows gives when you're trying to bind to an address on the local machine that's not assigned to any of the adapters on the machine. If ipconfig doesn't show it, you can't bind to it. \nIf the external address is on a router that is NAT'ing requests from it to the server's internal address, you c... | [
17
] | [] | [] | [
"django",
"networking",
"python",
"windows",
"windows_server_2008"
] | stackoverflow_0004657347_django_networking_python_windows_windows_server_2008.txt |
Q:
Python, geometry and visualisation
I'm looking for a Python library that would allow me to visualise geometrical data. Nothing extremely complicated, just a bunch of points in the plane or space and a few basic shapes that I would generate.
I had a look at this question and the answers to it, but the focus over t... | Python, geometry and visualisation | I'm looking for a Python library that would allow me to visualise geometrical data. Nothing extremely complicated, just a bunch of points in the plane or space and a few basic shapes that I would generate.
I had a look at this question and the answers to it, but the focus over there seems to be on computation.
| [
"How about Matplotlib/mplot3D?\n"
] | [
7
] | [] | [] | [
"geometry",
"python",
"visualization"
] | stackoverflow_0004657541_geometry_python_visualization.txt |
Q:
Python Regex - Works in Expresso not in IronPython
Back to the same HTML thing as I posted already. Trying to learn a bit RegEx, even if I know there are other ways. I'm not dumb, just like challenges...
My expression is:
publisher.php\?c=.*?\">(.*?)</a>(?:.*?)<br\s\\>(?:[\s\r\n]*?)Date:\s<time\sdatetime="(.*?)\">... | Python Regex - Works in Expresso not in IronPython | Back to the same HTML thing as I posted already. Trying to learn a bit RegEx, even if I know there are other ways. I'm not dumb, just like challenges...
My expression is:
publisher.php\?c=.*?\">(.*?)</a>(?:.*?)<br\s\\>(?:[\s\r\n]*?)Date:\s<time\sdatetime="(.*?)\">(?:.*?)(?:[\s\r\n]*?)Pages:\s*?(\d*?)<br\s\\>
To match ... | [
"\nAll implementations of regexp has subtle differences. That it works in expresso doesn't mean it works in Python. It could also be a question of having dfferent flags defaults, like for whitespace, etc.\nDon't use regexp to match HTML or XML unless the case is trivial. Use a library made for HTML/XML like lxml or... | [
2,
0
] | [] | [] | [
"ironpython",
"python",
"regex"
] | stackoverflow_0004657505_ironpython_python_regex.txt |
Q:
Django: ManagementForm data is missing ... Formset will not validate. Why?
For some reason my formset will not validate, after I submit it. Any ideas as to way this may be happening?
#models.py
class Department(models.Model):
department = models.CharField(verbose_name = "Department Name", max_length=100)
desc... | Django: ManagementForm data is missing ... Formset will not validate. Why? | For some reason my formset will not validate, after I submit it. Any ideas as to way this may be happening?
#models.py
class Department(models.Model):
department = models.CharField(verbose_name = "Department Name", max_length=100)
description = models.TextField(verbose_name = "Description", blank=True, null=True)
... | [
"Your problem is here:\n if request.method=='POST':\n if 'add_department' in request.POST:\n cp = request.POST.copy()\n cp['department-TOTAL_FORMS'] = int(cp['department-TOTAL_FORMS'])+ 1\n new_department = AddDepartmentFormSet(cp, prefix='department', i... | [
6,
3
] | [] | [] | [
"django",
"formset",
"inline_formset",
"python",
"validation"
] | stackoverflow_0004638693_django_formset_inline_formset_python_validation.txt |
Q:
How to evaluate simple math expressions in config files
I would like to use a configuration file with some simple math expressions like adding or substracting.
For example:
[section]
a = 10
b = 15
c = a-5
d = b+c
Is there any way to do this using a ConfigParser module? I found some examples of using strings as a ... | How to evaluate simple math expressions in config files | I would like to use a configuration file with some simple math expressions like adding or substracting.
For example:
[section]
a = 10
b = 15
c = a-5
d = b+c
Is there any way to do this using a ConfigParser module? I found some examples of using strings as a kind of variables in config files, but if i'm using it i get ... | [
"Why use ConfigParser? Why not just\nconfig.py:\na = 10\nb = 15\nc = a-5\nd = b+c\n\nscript.py:\nimport config\nprint(config.c)\n# 5\nprint(config.d)\n# 20\n\n",
"One approach that some projects use is to make your configuration file a Python module. Then simply import it (or use exec) to run the contents. That g... | [
9,
2,
2
] | [] | [] | [
"configparser",
"configuration_files",
"python"
] | stackoverflow_0004658033_configparser_configuration_files_python.txt |
Q:
best way to store code for later execution (python)
I have some tasks stored in db for later execution. For example i can fix task of sending email. And by cron exec task (send it). I search for best way to store code in db for later execution. For ex store it in raw string of python code and than do eval, but als... | best way to store code for later execution (python) | I have some tasks stored in db for later execution. For example i can fix task of sending email. And by cron exec task (send it). I search for best way to store code in db for later execution. For ex store it in raw string of python code and than do eval, but also i must store relative imports here..
for example for s... | [
"What you're doing is a bad idea mainly because you allow for way too much variability in what code will be executed. A code string can do anything, and I'm guessing there are only a few kinds of tasks you want to store for later execution.\nSo, figure out what the variables in those tasks are (variables in a non-p... | [
5,
2,
2,
1,
0
] | [] | [] | [
"python",
"queue",
"serialization",
"task"
] | stackoverflow_0004652444_python_queue_serialization_task.txt |
Q:
pygccxml on python 3.0+ or Python 2.7+?
I will be using pygccxml to parse C++ header files.
Does this module work with Python 3.0+ (i.e. have you used it without issues on this version of python)?
The reason I ask is that python 3.0+ is backwards-incompatible and i want to know if I need to run python 2.7+ or if... | pygccxml on python 3.0+ or Python 2.7+? | I will be using pygccxml to parse C++ header files.
Does this module work with Python 3.0+ (i.e. have you used it without issues on this version of python)?
The reason I ask is that python 3.0+ is backwards-incompatible and i want to know if I need to run python 2.7+ or if I can go with the newer 3.0+.
Thank You
| [
"Why don't you try it? If it hasn't been ported it's unlikely to even install.\nThe lack of mention of Python 3 is however a pretty big indication that it hasn't been ported, and since it hasn't had one single release since Python 3 was released I'd say you probably have to use Python 2.\n(Edit: I downloaded it and... | [
2
] | [] | [] | [
"python",
"python_2.7",
"python_3.x"
] | stackoverflow_0004658259_python_python_2.7_python_3.x.txt |
Q:
python: Python script knows user that started this script last time?
Is it possible to store name of the user that started my script last?
I want to have something like this:
user1 launched script
user2 launched script
python myscr.py
Last started by: user1
...
A:
Look at getpass.getuser()
>>> import getpass
... | python: Python script knows user that started this script last time? | Is it possible to store name of the user that started my script last?
I want to have something like this:
user1 launched script
user2 launched script
python myscr.py
Last started by: user1
...
| [
"Look at getpass.getuser()\n>>> import getpass\n\n>>> getpass.getuser()\n'me'\n\nEDIT : \nWell in general case to log each time the scripts runs and the user i will definitely use logging for that; something like this maybe:\nimport logging\nimport getpass\n\nFORMAT = \"DATE : %(asctime)-15s USER : %(message)s FIL... | [
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0004658688_python.txt |
Q:
Subclassing Satchmo's Category model, but then getting the error "'Manager' object has no attribute 'root_categories'"
I'm using Satchmo as part of a website I'm currently building. At the moment I'm trying add more functions to the Satchmo Category class, but obviously I'm not going to make any changes to the Sa... | Subclassing Satchmo's Category model, but then getting the error "'Manager' object has no attribute 'root_categories'" | I'm using Satchmo as part of a website I'm currently building. At the moment I'm trying add more functions to the Satchmo Category class, but obviously I'm not going to make any changes to the Satchmo files. So, I thought that subclassing the Category class would give me a new class which contains all the Satchmo Cat... | [
"You should read the docs on custom managers and model inheritance.\nIn any case, you should probably be defining the MyCategory class as a Proxy model, which does inherit the parent class's Manager.\n"
] | [
1
] | [] | [] | [
"django",
"python",
"satchmo",
"subclassing"
] | stackoverflow_0004658844_django_python_satchmo_subclassing.txt |
Q:
how to imitate a link click in QTextBrowser
Actualy, i have different tabs.
what I wanted to achieve is,
- user clicked a link from tab 1
- and it will immediately display QTextBrowser in tab 2, at the html anchor i set.
Is there a way of doing this?
I've managed to switch tab by using tabWidget.setCurrentWidget(... | how to imitate a link click in QTextBrowser | Actualy, i have different tabs.
what I wanted to achieve is,
- user clicked a link from tab 1
- and it will immediately display QTextBrowser in tab 2, at the html anchor i set.
Is there a way of doing this?
I've managed to switch tab by using tabWidget.setCurrentWidget()
now the question is, how to set the focus to th... | [
"Here's an example:\nfrom tabwidget import Ui_MainWindow\nimport sys\nfrom PyQt4 import QtGui, QtCore\n\nclass MyApp(QtGui.QMainWindow):\n def __init__(self, parent=None):\n QtGui.QWidget.__init__(self, parent)\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n\n QtCore.QObject.con... | [
2
] | [] | [] | [
"pyqt4",
"python"
] | stackoverflow_0003286451_pyqt4_python.txt |
Q:
How to save html elements to jpeg/png or pdf using python
So I have an html-page:
<html>
<b>Bold text</b>
<table><tr><td>abc</td></tr></table>
</html>
How I can save <b>Bold text</b> or any html tag to jpeg/png or pdf.
Thanks.
A:
For converting HTML to PDF in Python try pisa.
A:
Is HTML/CSS to PDF con... | How to save html elements to jpeg/png or pdf using python | So I have an html-page:
<html>
<b>Bold text</b>
<table><tr><td>abc</td></tr></table>
</html>
How I can save <b>Bold text</b> or any html tag to jpeg/png or pdf.
Thanks.
| [
"For converting HTML to PDF in Python try pisa.\n",
"Is HTML/CSS to PDF converter written in Python the right tool for you?\n"
] | [
2,
1
] | [] | [] | [
"html",
"jpeg",
"pdf",
"png",
"python"
] | stackoverflow_0004659058_html_jpeg_pdf_png_python.txt |
Q:
Py_INCREF/DECREF: When
Is one correct in stating the following:
If a Python object is created in a C function, but the function doesn't return it, no INCREF is needed, but a DECREF is.
[false]If the function does return it, you do need to INCREF, in the function that receives the return value.[/false]
When assign... | Py_INCREF/DECREF: When | Is one correct in stating the following:
If a Python object is created in a C function, but the function doesn't return it, no INCREF is needed, but a DECREF is.
[false]If the function does return it, you do need to INCREF, in the function that receives the return value.[/false]
When assigning C typed variables as att... | [
"First, read this more carefully, specifically the last paragraph, http://docs.python.org/extending/extending.html#ownership-rules\nEasy way to think about it is thinking about the reference counts.\n\nYour first statement is correct. If you create a new Python object (say PyLong) then it already has a reference co... | [
51
] | [] | [] | [
"python",
"python_c_api"
] | stackoverflow_0004657764_python_python_c_api.txt |
Q:
Beautiful soup question
I want to fetch specific rows in an HTML document
The rows have the following attributes set: bgcolor and vallign
Here is a snippet of the HTML table:
<table>
<tbody>
<tr bgcolor="#f01234" valign="top">
<!--- td's follow ... -->
</tr>
<tr bgcolor="#c01234" valig... | Beautiful soup question | I want to fetch specific rows in an HTML document
The rows have the following attributes set: bgcolor and vallign
Here is a snippet of the HTML table:
<table>
<tbody>
<tr bgcolor="#f01234" valign="top">
<!--- td's follow ... -->
</tr>
<tr bgcolor="#c01234" valign="top">
<!--- td's f... | [
"Don't use regex to parse html. Use a html parser\nimport lxml.html\ndoc = lxml.html.fromstring(your_html)\nresult = doc.xpath(\"//tr[(@bgcolor='#f01234' or @bgcolor='#c01234') \"\n \"and @valign='top']\")\nprint result\n\nThat will extract all tr elements that match from your html, you can do further operation ... | [
5,
4
] | [] | [] | [
"beautifulsoup",
"html_parsing",
"python"
] | stackoverflow_0004658686_beautifulsoup_html_parsing_python.txt |
Q:
changing django default model settings
I'm just starting with the django creating your own app tutorial (creating a Poll) I'm deviating slightly as I'm wanting to create an app using my own database model that already exists.
And in the tutorial it says
Table names are automatically
generated by combining the nam... | changing django default model settings | I'm just starting with the django creating your own app tutorial (creating a Poll) I'm deviating slightly as I'm wanting to create an app using my own database model that already exists.
And in the tutorial it says
Table names are automatically
generated by combining the name of
the app (polls) and the lowercase
name ... | [
"You can override Model behavior in Django largely through the use of an inner Meta class\n\ndb_table allows you to rename the table name\nspecifying another field as the primary key will have it use that rather than a surrogate key (not in the Meta class, just in the model itself)\n\n",
"You should try and work ... | [
3,
1
] | [] | [] | [
"django",
"mysql",
"mysql_error_1146",
"python",
"sql"
] | stackoverflow_0004659229_django_mysql_mysql_error_1146_python_sql.txt |
Q:
Python create a loop if condition not verified
I'm using python 2.6.6 and I can't solve my problem.
I have this code:
file = raw_input('Enter the name of the file: ')
try:
text_file = open(file,'r')
except IOError:
print 'File not found'
file = raw_input('Enter the name of the file: ')
text_file = ... | Python create a loop if condition not verified | I'm using python 2.6.6 and I can't solve my problem.
I have this code:
file = raw_input('Enter the name of the file: ')
try:
text_file = open(file,'r')
except IOError:
print 'File not found'
file = raw_input('Enter the name of the file: ')
text_file = open(file,'r')
How can i turn this into a loop so t... | [
"while True:\n file = raw_input('Enter the name of the file: ')\n try:\n text_file = open(file,'r')\n break\n except IOError:\n print 'File not found'\n\n"
] | [
7
] | [] | [] | [
"python"
] | stackoverflow_0004659323_python.txt |
Q:
Puzzling Parallel Python Problem - TRANSPORT_SOCKET_TIMEOUT
The following code doesn't appear to work properly for me. It requires starting a ppserver on another computer on your network, for example with the following command:
ppserver.py -r -a -w 4
Once this server is started, on my machine I run this code:
im... | Puzzling Parallel Python Problem - TRANSPORT_SOCKET_TIMEOUT | The following code doesn't appear to work properly for me. It requires starting a ppserver on another computer on your network, for example with the following command:
ppserver.py -r -a -w 4
Once this server is started, on my machine I run this code:
import pp
import time
job_server = pp.Server(ppservers = ("*",))
jo... | [
"Answer from Bagira of the Parallel Python forum:\n\nHow long does the calculation of every\n job take? Have a look at the variable\n TRANSPORT_SOCKET_TIMEOUT in\n /usr/local/lib/python2.6/dist-packages/pptransport.py.\nMaybe your job takes longer than the\n time in the variable above. Increase\n the value of ... | [
2,
1
] | [] | [] | [
"parallel_processing",
"parallel_python",
"python"
] | stackoverflow_0004102380_parallel_processing_parallel_python_python.txt |
Q:
Python: Automating Emails
Here is what I want to achieve :
1) An email should be sent to using "email address & details" mentioned in a Google docs/excel file.
2) The email should also pick up some content from a web page .i.e Title, URL etc. & include in the email sent.
Do let me know, how or where do I begin?
... | Python: Automating Emails | Here is what I want to achieve :
1) An email should be sent to using "email address & details" mentioned in a Google docs/excel file.
2) The email should also pick up some content from a web page .i.e Title, URL etc. & include in the email sent.
Do let me know, how or where do I begin?
| [
"Start reading this http://docs.python.org/library/email\n",
"You might want to start by writing something that just downloads the document and writes it to file. Python has a module for using most of its services: Youtube, gmail, docs, etc.\nYou could get the gdata client here: http://code.google.com/p/gdata-pyt... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004659618_python.txt |
Q:
scan through a list with dictionary in python
Hi i have been trying this for some time now no result yet.
i have a dict = {'Å':'a', 'Ä':'a', 'Ö':'0', 'å':'a', 'ä':'a', 'ö':'o'}
input = lxml.etree.parse(inputxml)
for block in input.xpath('//PAGE/BLOCK/TEXT'):
J = block.xpath('TOKEN/text()')
current = 0
... | scan through a list with dictionary in python | Hi i have been trying this for some time now no result yet.
i have a dict = {'Å':'a', 'Ä':'a', 'Ö':'0', 'å':'a', 'ä':'a', 'ö':'o'}
input = lxml.etree.parse(inputxml)
for block in input.xpath('//PAGE/BLOCK/TEXT'):
J = block.xpath('TOKEN/text()')
current = 0
line = ""
while current < len(J):
A... | [
"Not what you asked about, but it looks like you might be interested in it: Unidecode is a module specifically intended to reduce any series of characters to the most similar ASCII characters.\n>>> import unidecode # to install: `pip install unidecode`\n>>> line = u\"Flyttbara hyllplan anpassar förvaringen så\"\n>>... | [
3,
2,
2
] | [] | [] | [
"dictionary",
"list",
"python"
] | stackoverflow_0004659335_dictionary_list_python.txt |
Q:
Deleting a Windows Registry Value with Python
I would like to delete values from the registry in Windows using Python, but I don't understand what is the sub_key in the python documentation:
I have the following code, which I would like to use:
def del_env(name):
key = OpenKey(HKEY_CURRENT_USER, 'Environment',... | Deleting a Windows Registry Value with Python | I would like to delete values from the registry in Windows using Python, but I don't understand what is the sub_key in the python documentation:
I have the following code, which I would like to use:
def del_env(name):
key = OpenKey(HKEY_CURRENT_USER, 'Environment', 0, KEY_ALL_ACCESS)
#SetValueEx(key, name, 0, RE... | [
"Use DeleteValue instead of DeleteKey as @Philipp mentioned in the comments:\ndef del_env(name):\n key = OpenKey(HKEY_CURRENT_USER, 'Environment', 0, KEY_ALL_ACCESS)\n DeleteValue(key, name) \n CloseKey(key)\n SendMessage(\n win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')\n\n",
... | [
9,
0
] | [
"OK, \nNot A Pythonic Solution, but it works:\n C:\\Documents and Settings\\admin>reg add \"%REGISTRY_KEY%\\Environment\" /v AME /t\n REG_EXPAND_SZ /d \"%AME%\" /f\n\n\n #REG DELETE KeyName [/v ValueName | /ve | /va] [/f]\n\n C:\\Documents and Settings\\admin>reg delete \"%REGISTRY_KEY%\\Environment\" /v AME... | [
-1
] | [
"python",
"registry",
"winreg"
] | stackoverflow_0004657721_python_registry_winreg.txt |
Q:
How to make a bitmap of the current mouse pointer?
I'd like to write a screenshot tool in Python. Right now i'm studying how I could do. I've got a script making a screenshot using win32 api like here, but want to include the mouse pointer in the screenshot.
With win32gui.GetCursorInfo() i get its state (shown/hid... | How to make a bitmap of the current mouse pointer? | I'd like to write a screenshot tool in Python. Right now i'm studying how I could do. I've got a script making a screenshot using win32 api like here, but want to include the mouse pointer in the screenshot.
With win32gui.GetCursorInfo() i get its state (shown/hidden), its handle and its position. My goal is to use the... | [
"Does the python win32 api include DrawIconEx:\nhttp://msdn.microsoft.com/en-us/library/ms648065%28v=vs.85%29.aspx\nyou need to make a drawable context to write it on, and then pass that and the cursor handle...\n(or plain DrawIcon)\n",
"Anther option is to actually use Python Imaging Library (PIL)\nyou can easil... | [
3,
0,
0
] | [] | [] | [
"python",
"windows"
] | stackoverflow_0004660194_python_windows.txt |
Q:
How to see traceback on xmlrpc server, not client?
I have simple xmlrpc server code:
from SimpleXMLRPCServer import SimpleXMLRPCServer
port = 9999
def func():
print 'Hi!'
print x # error!
print 'Bye!'
if __name__ == '__main__':
server = SimpleXMLRPCServer(("localhost", port))
print "Listenin... | How to see traceback on xmlrpc server, not client? | I have simple xmlrpc server code:
from SimpleXMLRPCServer import SimpleXMLRPCServer
port = 9999
def func():
print 'Hi!'
print x # error!
print 'Bye!'
if __name__ == '__main__':
server = SimpleXMLRPCServer(("localhost", port))
print "Listening on port %s..." % port
server.register_function(fun... | [
"You can do something like this:\nfrom SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler\n\nport = 9999\n\ndef func():\n print 'Hi!'\n print x # error!\n print 'Bye!'\n\nclass Handler(SimpleXMLRPCRequestHandler):\n def _dispatch(self, method, params):\n try: \n ... | [
13
] | [] | [] | [
"multithreading",
"python",
"simplexmlrpcserver",
"xmlrpcclient",
"xmlrpclib"
] | stackoverflow_0004659579_multithreading_python_simplexmlrpcserver_xmlrpcclient_xmlrpclib.txt |
Q:
Python, comtypes and ArcObjects: Error creating AppROT object
I am experimenting with comtypes and ArcObjects under Python 2.6.5 and ArcGIS 10 SP1. I'm using the pure Python method to wrap the ArcObjects OLBs described in this answer, but getting an error in the comtypes.CoCreateInstance method.
Here is the code I... | Python, comtypes and ArcObjects: Error creating AppROT object | I am experimenting with comtypes and ArcObjects under Python 2.6.5 and ArcGIS 10 SP1. I'm using the pure Python method to wrap the ArcObjects OLBs described in this answer, but getting an error in the comtypes.CoCreateInstance method.
Here is the code I am running:
def WrapModules():
#force wrapping of all ArcObjec... | [
"For completeness, this solution was posted by Jason Scheirer over on the GIS Stack Exchange:\n\nImport arcpy first, you aren't doing any license checkout or setting up the ArcObjects 10.0 runtime as-is so it won't find the CoClass.\n\n"
] | [
1
] | [] | [] | [
"arcobjects",
"comtypes",
"python"
] | stackoverflow_0004652911_arcobjects_comtypes_python.txt |
Q:
displaying message in PyQt4
I am developing an application using PyQt4 .
Currently I am in need of a message box ie if I am on a current screen and user presses a function the callback function should display message whether by a message box or any other way you can suggest ......However when the user cancels it t... | displaying message in PyQt4 | I am developing an application using PyQt4 .
Currently I am in need of a message box ie if I am on a current screen and user presses a function the callback function should display message whether by a message box or any other way you can suggest ......However when the user cancels it the flow should go to the current ... | [
"If I have understood your question, I believe your scenario is the common one.\nIn order to show a message, the easiest way is:\nmy_msg = \"Hello world\"\nQtGui.QMessageBox.information(None, 'My Title', my_msg)\n\nThis code should be in the callback function you have mention.\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0004660302_python.txt |
Q:
how to write in stdout after to call a method (doing a system of notifications automatic (Iphone))
I'm trying to do a system of notifications automatic (Iphone) using https://github.com/simonwhitaker/PyAPNs. When you want to send a notification you call "apns.gateway_server.send_notification(key, payload)" and you... | how to write in stdout after to call a method (doing a system of notifications automatic (Iphone)) | I'm trying to do a system of notifications automatic (Iphone) using https://github.com/simonwhitaker/PyAPNs. When you want to send a notification you call "apns.gateway_server.send_notification(key, payload)" and you have to enter the PEM pass phrase. Is there a way to enter this phrase through code?
Something like: c... | [
"import apns\n\ngate = apns.APNs('keyfile','certfile').gateway_server()\ngate.send_notification(key,payload)\n\nIs there a problem when you run this?\n"
] | [
0
] | [] | [] | [
"iphone",
"push_notification",
"python",
"stdout"
] | stackoverflow_0004657900_iphone_push_notification_python_stdout.txt |
Q:
Passing window name as parameter to a class
I created a class containing a method to position a window anywhere on the screen. I am using PyQt4 for GUI programming. I wrote following class:
from PyQt4 import QtGui
class setWindowPosition:
def __init__(self, xCoord, yCoord, windowName, parent = None):
... | Passing window name as parameter to a class | I created a class containing a method to position a window anywhere on the screen. I am using PyQt4 for GUI programming. I wrote following class:
from PyQt4 import QtGui
class setWindowPosition:
def __init__(self, xCoord, yCoord, windowName, parent = None):
self.x = xCoord
self.y = yCoord
s... | [
"It is not entirely clear what you are trying to ask, But, you access the values in the method the same way you set them in the constructor.\nfrom PyQt4 import QtGui\n\nclass setWindowPosition:\n def __init__(self, xCoord, yCoord, windowName, parent = None):\n self.x = xCoord\n self.y = yCoord\n ... | [
1
] | [] | [] | [
"pyqt4",
"python"
] | stackoverflow_0004660987_pyqt4_python.txt |
Q:
What's the rationale of not preserving case (by default) in configparser?
If I want to preserve key names in a config file, I must add configparser.optionxform = str. I was surprised by this (configparser) behaviour, expecting case-preservation to be the default (if not the only) option.
Does this make sense to yo... | What's the rationale of not preserving case (by default) in configparser? | If I want to preserve key names in a config file, I must add configparser.optionxform = str. I was surprised by this (configparser) behaviour, expecting case-preservation to be the default (if not the only) option.
Does this make sense to you? What's the rationale behind this decision?
| [
"This only affects the case of the option names, the case of values is always preserved. It can be argued, whether this is a sane choice, but the choice has been made and must now be followed in order to maintain compatibility with old sources.\nI don't see any big problem, since you obviously found a workaround f... | [
1,
0
] | [] | [] | [
"configparser",
"python"
] | stackoverflow_0003176254_configparser_python.txt |
Q:
Google maps reverse geocoding always responds with 602 (Unknown Address) on server side
I have server-side code that calls the Google geocoding API, like this:
http://maps.google.com/maps/geo?q=40.714224,-73.961452&output=json&sensor=false&key=API_KEY
where API_KEY is my API key. I get a JSON reply, as expected, ... | Google maps reverse geocoding always responds with 602 (Unknown Address) on server side | I have server-side code that calls the Google geocoding API, like this:
http://maps.google.com/maps/geo?q=40.714224,-73.961452&output=json&sensor=false&key=API_KEY
where API_KEY is my API key. I get a JSON reply, as expected, but the reponse is always 602 (Unknown Address). Is my URL wrong? (I've also tried the URL in... | [
"Try using a HTTP watcher to make sure that this is the actual URL that is being sent within your application. There could be a chance that it isn't being encoded correctly or maybe is being incorrectly assembled. Since you aren't getting request denied and we were able to get a good response when we viewed it di... | [
1,
1
] | [] | [] | [
"django",
"google_maps",
"python"
] | stackoverflow_0004660426_django_google_maps_python.txt |
Q:
Using win32service module with IronPython
Hey,so I'm trying to take an existing IronPython script I have and convert it into a windows service that runs on one of our servers at all times. Unfortunately I can't seem to get the modules I need. I downloaded the pywin32 extensions (http://sourceforge.net/projects/pyw... | Using win32service module with IronPython | Hey,so I'm trying to take an existing IronPython script I have and convert it into a windows service that runs on one of our servers at all times. Unfortunately I can't seem to get the modules I need. I downloaded the pywin32 extensions (http://sourceforge.net/projects/pywin32/) but I can't install them because I only ... | [
"I don't think that you can use pywin32 to create a Windows Service with IronPython. If an IronPython Windows Service is what you want, this project might help:\nhttp://dlrhostservice.codeplex.com/\nGood Luck!\n"
] | [
1
] | [] | [] | [
"ironpython",
"python",
"pywin32"
] | stackoverflow_0003160437_ironpython_python_pywin32.txt |
Q:
Efficient way to do a large number of search/replaces in Python?
I'm fairly new to Python, and am writing a series of script to convert between some proprietary markup formats. I'm iterating line by line over files and then basically doing a large number (100-200) of substitutions that basically fall into 4 catego... | Efficient way to do a large number of search/replaces in Python? | I'm fairly new to Python, and am writing a series of script to convert between some proprietary markup formats. I'm iterating line by line over files and then basically doing a large number (100-200) of substitutions that basically fall into 4 categories:
line = line.replace("-","<EMDASH>") # Replace single character ... | [
"str.replace() is more efficient if you're going to do basic search and replaces, and re.sub is (obviously) more efficient if you need complex pattern matching (because otherwise you'd have to use str.replace several times).\nI'd recommend you use a combination of both. If you have several patterns that all get rep... | [
4,
0,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004661041_python_regex.txt |
Q:
How to access a superclass's class attributes in Python?
Have a look at the following code:
class A(object):
defaults = {'a': 1}
def __getattr__(self, name):
print('A.__getattr__')
return self.get_default(name)
@classmethod
def get_default(cls, name):
# some debug output
... | How to access a superclass's class attributes in Python? | Have a look at the following code:
class A(object):
defaults = {'a': 1}
def __getattr__(self, name):
print('A.__getattr__')
return self.get_default(name)
@classmethod
def get_default(cls, name):
# some debug output
print('A.get_default({}) - {}'.format(name, cls))
... | [
"Not really an answer but an observation:\nThis looks overengineered to me, a common trap when looking for excuses to use python magic.\nIf you can be bothered to define a defaults dict for a class why not just define the attributes instead? the effect is the same.\nclass A:\n a = 1\n\nclass B(A):\n b = 2\n\n... | [
8,
2,
1,
1,
0,
0
] | [] | [] | [
"python",
"super",
"superclass"
] | stackoverflow_0004608968_python_super_superclass.txt |
Q:
Auth-System easy way to do it like Amazon?
is there an easy way to configure the authentication system in Django like amazon
does it?
If you are going to login in your amazon-account and the you are going to close your browser, even after two days when you are going on the webpage again, amazon is greeting you wi... | Auth-System easy way to do it like Amazon? | is there an easy way to configure the authentication system in Django like amazon
does it?
If you are going to login in your amazon-account and the you are going to close your browser, even after two days when you are going on the webpage again, amazon is greeting you with your name. When you are going to shop, you st... | [
"See the documentation on sessions, in particular the section titled Browser-length sessions vs. persistent sessions.\nThey explain precisely how to achieve what you're asking: request.session.set_expiry(...).\n",
"I think most likely what Amazon does is based on time and not on whether you close the browser or n... | [
1,
0
] | [] | [] | [
"authentication",
"django",
"python",
"web"
] | stackoverflow_0004659791_authentication_django_python_web.txt |
Q:
python convert sql result to tree hierarchy
i have a sql query that returns 3 levels of a data chain on each row (ie. Country, County, City). There may be more than 1 county per country and more than 1 city per county.
resultset:
"UK" "Lancashire" "Burnley"
"UK" "Lancashire" "Blackburn"
"UK" "Merseysid... | python convert sql result to tree hierarchy | i have a sql query that returns 3 levels of a data chain on each row (ie. Country, County, City). There may be more than 1 county per country and more than 1 city per county.
resultset:
"UK" "Lancashire" "Burnley"
"UK" "Lancashire" "Blackburn"
"UK" "Merseyside" "Liverpool"
"UK" "West Yorkshire" "Leeds"
... | [
"This isn't ideal because it's kind of obscure.\nccc = defaultdict( lambda: defaultdict( list ) )\nfor row in cursor.fetchall():\n country, county, city = row\n ccc[country][county].append(city)\n\nThere are probably cleaner ways to do this.\n"
] | [
2
] | [] | [] | [
"iteration",
"python"
] | stackoverflow_0004661164_iteration_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.