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: Regular expression to parse a commented configuration file Edit: I'm really just curious as to how I can get this regex to work. Please don't tell me there are easier ways to do it. That's obvious! :P I'm writing a regular expression (using Python) to parse lines in a configuration file. Lines could look like this...
Regular expression to parse a commented configuration file
Edit: I'm really just curious as to how I can get this regex to work. Please don't tell me there are easier ways to do it. That's obvious! :P I'm writing a regular expression (using Python) to parse lines in a configuration file. Lines could look like this: someoption1 = some value # some comment # this line is only a ...
[ "The reason your regular expression isn't matching as you want is because of the greedy matching behaviour of regular expressions: each part will match the longest substring such that the rest of the string can still be matched with the remainder of the regular expression\nWhat this means in the case of one of your...
[ 2, 2, 2, 1, 0, 0 ]
[]
[]
[ "parsing", "python", "regex" ]
stackoverflow_0003783626_parsing_python_regex.txt
Q: Python: How can I modify dictionary values in a for loop alternating the keys? I am new to Python (and to programming). I'd like to modify a dictionary in a for loop by alternating the key of the dictionary. I wrote the following code, which was unsccessful, however: #coding: utf-8 dict1 = {'key1': 'value1', 'key2...
Python: How can I modify dictionary values in a for loop alternating the keys?
I am new to Python (and to programming). I'd like to modify a dictionary in a for loop by alternating the key of the dictionary. I wrote the following code, which was unsccessful, however: #coding: utf-8 dict1 = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'} dict2 = dict.fromkeys(dict1.values(),[]) for key in ...
[ "All values of dict2 are actually the same list instance, since passing [] to dict.fromkeys() only creates one list instance. Try\ndict2 = {v: [] for v in dict1.values()}\n\n", "The problem is you used a mutable object as the value initializer. It is the very same object for each value.\nPython2> dict1 = {'key1'...
[ 7, 2, 0, 0, 0 ]
[]
[]
[ "dictionary", "for_loop", "key", "loops", "python" ]
stackoverflow_0005281834_dictionary_for_loop_key_loops_python.txt
Q: Python Web/UI Options We are in the process of standing up a UI on top of a python system. This is all throw away code, so we want something quick, yet presentable. We will have a couple of "interfaces" but they will be of two types. One will be control, it will basically be sitting on top of a python thread, ...
Python Web/UI Options
We are in the process of standing up a UI on top of a python system. This is all throw away code, so we want something quick, yet presentable. We will have a couple of "interfaces" but they will be of two types. One will be control, it will basically be sitting on top of a python thread, and accepting requests from...
[ "I like wxPython. The demo application is excellent and lets you browse, tweak and re-run the code right in the demo.\n", "We have found the DJango meets our needs. It is a pretty slick mvc style python web stack. Really is easy to use, and very quick to develop in. I will say that the ORM layer is a little yo...
[ 3, 2, 0, 0 ]
[]
[]
[ "python", "user_interface" ]
stackoverflow_0005205062_python_user_interface.txt
Q: python: my package import fails on 3.1, but works on 2.6 I decided to develop my home project in python 3.x rather than 2.x. So I decided to check, if it works under 3.1. I run python3.1 above my package directory and then: >>> import fathom Traceback (most recent call last): File "<stdin>", line 1, in <module> ...
python: my package import fails on 3.1, but works on 2.6
I decided to develop my home project in python 3.x rather than 2.x. So I decided to check, if it works under 3.1. I run python3.1 above my package directory and then: >>> import fathom Traceback (most recent call last): File "<stdin>", line 1, in <module> File "fathom/__init__.py", line 3, in <module> from sche...
[ "Did you try a relative import?\nfrom . import schema\nfrom .inspectors import PostgresInspector\n\nWorks in Python 2.6 as well.\nThe 2to3 script can help you pinpoint more of these problems.\n" ]
[ 0 ]
[]
[]
[ "import", "python", "python_3.x" ]
stackoverflow_0005286573_import_python_python_3.x.txt
Q: Django FeinCMS and page extensions issue I'm experimenting with Page extensions and FeinCMS 1.2.1. I'd like to create this simple page extension: from django.db import models def register(cls, admin_cls): cls.add_to_class(models.TextField()) but I keep getting this error: AttributeError: 'module' object has...
Django FeinCMS and page extensions issue
I'm experimenting with Page extensions and FeinCMS 1.2.1. I'd like to create this simple page extension: from django.db import models def register(cls, admin_cls): cls.add_to_class(models.TextField()) but I keep getting this error: AttributeError: 'module' object has no attribute 'TextField' The package contain...
[ "Maybe models is getting reassigned somewhere to another module before your register function gets run? \nTry changing your code to this:\nfrom django.db import models as django_models\n\ndef register(cls, admin_cls):\n cls.add_to_class('field_name_here', django_models.TextField())\n\n" ]
[ 3 ]
[]
[]
[ "content_management_system", "django", "feincms", "python" ]
stackoverflow_0005286182_content_management_system_django_feincms_python.txt
Q: using cPickle returns only the first entry in the file I am storing a dictionary object into file using cPickle, and not able to get any other entry other than the first one. Initially the file tweets.pkl is empty, and the EOFError is raised. I am sure it has something to do with it. Thanks #!/usr/bin/env python ...
using cPickle returns only the first entry in the file
I am storing a dictionary object into file using cPickle, and not able to get any other entry other than the first one. Initially the file tweets.pkl is empty, and the EOFError is raised. I am sure it has something to do with it. Thanks #!/usr/bin/env python ...
[ "You're constructing a new dictionary (feed = defaultdict()) every time appendfeed is called, so that new dictionary loses all previous references. You're then appending the new (single-entry) dict to the file.\nIf you want to restore multiple separate calls to dump like this, then you will need multiple matching c...
[ 2 ]
[]
[]
[ "eoferror", "pickle", "python" ]
stackoverflow_0005286658_eoferror_pickle_python.txt
Q: How to delete all instance names in a list? Possible Duplicate: Remove all occurences of a value from a Python list mylist = ['dogs', 'cats', 'cats'] If I type mylist.remove('cats'), it deletes only one cats in my list, but I want to delete all cats in my list without loops, because loops are going to crash the...
How to delete all instance names in a list?
Possible Duplicate: Remove all occurences of a value from a Python list mylist = ['dogs', 'cats', 'cats'] If I type mylist.remove('cats'), it deletes only one cats in my list, but I want to delete all cats in my list without loops, because loops are going to crash the way I want to. EDIT: it's a little trick to exp...
[ "You can create a new list with a list comprehension to avoid an explicit loop:\nmylist = [item for item in mylist if item != 'cats']\n\n", "There is no built-in method for removing all elements from a list. You have to use a loop. What is wrong with:\nIn [129]: x=['dog','cat','cat']\nIn [136]: [elt for elt in x ...
[ 6, 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005286725_python.txt
Q: Django Models, tables in InnoDB In order to get Django to output innodb tables in MySQL, you either need to output ALL tables as innodb or selectively issue alter table commands The first is sub-optimal (MyISAM is faster for query-dominant tables) and the second is a pain and hack-ish. Are there any other ways?...
Django Models, tables in InnoDB
In order to get Django to output innodb tables in MySQL, you either need to output ALL tables as innodb or selectively issue alter table commands The first is sub-optimal (MyISAM is faster for query-dominant tables) and the second is a pain and hack-ish. Are there any other ways? UPDATE: Adding more clarity to my qu...
[ "This page should be good starting point: http://code.djangoproject.com/wiki/AlterModelOnSyncDB\nIt documents a way to hook into the post_syncdb hook to dynamically issue ALTER SQL commands to change the engine for the tables. (Note that this was written 4 years ago, and may need to be updated to the current vers...
[ 2 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0005269585_django_django_models_python.txt
Q: python code ,need help. name not defined error from gasp import * GRID_SIZE = 30 MARGIN = GRID_SIZE BACKGROUND_COLOR = (0,0,0) # Colors we use WALL_COLOR = (0.6 * 255, 0.9 * 255, 0.9 * 255) # The shape of the maze. Each character # represents a different type of object # % - Wall # . - Food # o - Caps...
python code ,need help. name not defined error
from gasp import * GRID_SIZE = 30 MARGIN = GRID_SIZE BACKGROUND_COLOR = (0,0,0) # Colors we use WALL_COLOR = (0.6 * 255, 0.9 * 255, 0.9 * 255) # The shape of the maze. Each character # represents a different type of object # % - Wall # . - Food # o - Capsule # G - Ghost # P - Chomp # Other characters a...
[ "Why is the module named gasp.py, but your opening statement is \"from gasp import *\"?\n", "You probably have an indentation problem just before the line for x in range( width ): causing Python to think that that line is at the same level as the def lines. Rid your sourcefile of tabs and try again.\n", "Do you...
[ 2, 1, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005286287_python.txt
Q: Total object deletion in python Is there any way to ensure that when an object is deleted, it is deleted fully from wherever it is? For example, if you did something like: A = NewObject() B = NewObject() C = NewObject() List1 = [A,B,C] List2 = [1,2,3,C] del A del List2[3] and have the objects deleted wherever t...
Total object deletion in python
Is there any way to ensure that when an object is deleted, it is deleted fully from wherever it is? For example, if you did something like: A = NewObject() B = NewObject() C = NewObject() List1 = [A,B,C] List2 = [1,2,3,C] del A del List2[3] and have the objects deleted wherever they are, meaning that List1 would onl...
[ "You can use weak references in some cases. If you don't care if C remains alive in List2, you can wrap it in a weakref, and when the reference to C expires from List1, the garbage collector will collect any memory associated with it.\nPython uses reference counting to decide whether or not an object should be coll...
[ 4, 2, 1 ]
[]
[]
[ "class", "global", "python" ]
stackoverflow_0005286912_class_global_python.txt
Q: How can I check if a SOCKS server is working? I'd like to periodicity check if my SOCKS 5 server is working fine. Just pinging the server or successfully connecting to the SOCKS service is not enough for me. I'd like to check that the server is actually working, by successfully downloading an HTML file, for exampl...
How can I check if a SOCKS server is working?
I'd like to periodicity check if my SOCKS 5 server is working fine. Just pinging the server or successfully connecting to the SOCKS service is not enough for me. I'd like to check that the server is actually working, by successfully downloading an HTML file, for example (Or any other reasonable way). How should I check...
[ "Try the pycyurl library, as it supports SOCKS 5 proxies. Another answer shows how to use it. You could then use smtplib to send you an email if your proxy is down, and drop the finished script in your crontab (or some other means of automating it).\n" ]
[ 4 ]
[]
[]
[ "python", "socks" ]
stackoverflow_0005286209_python_socks.txt
Q: Determining Nearest Neighbour in Dijkstra Ok, I have changed my code a little, but I am getting confused on what variable names should be passed to my nearestNeighbour function. These two functions work ok: infinity = 1000000 invalid_node = -1 startNode = 0 #Values to assign to each node class Node: def __in...
Determining Nearest Neighbour in Dijkstra
Ok, I have changed my code a little, but I am getting confused on what variable names should be passed to my nearestNeighbour function. These two functions work ok: infinity = 1000000 invalid_node = -1 startNode = 0 #Values to assign to each node class Node: def __init__(self): self.distFromSource = infini...
[ "I think you want nodeTable[node], not node[nodeTable], and similarly with theNetwork[node].\n" ]
[ 1 ]
[]
[]
[ "dijkstra", "python" ]
stackoverflow_0005286920_dijkstra_python.txt
Q: Get the GET query in a Python CGI script (Apache, mod_cgi) I am trying to get the query string in a CGI python script because for some reason the .FieldStorage and .getvalue functions are returning "None". The query is being generated correctly. I checked it in Wireshark and it is correctly produced. Any ideas on ...
Get the GET query in a Python CGI script (Apache, mod_cgi)
I am trying to get the query string in a CGI python script because for some reason the .FieldStorage and .getvalue functions are returning "None". The query is being generated correctly. I checked it in Wireshark and it is correctly produced. Any ideas on how I can just get the string itself correctly? I was trying to ...
[ "I think I figured it out. I need to use the environ variable passed to the application function by mod_wsgi.\nThanks!\n" ]
[ 1 ]
[]
[]
[ "apache", "cgi", "python" ]
stackoverflow_0005287113_apache_cgi_python.txt
Q: How to accept value from textctrl in wxpython Here is a python pgm. It contains a text ctrl and a button. Please help me to modify so that on pressing the button I need the string user entered in textctrl to be stored to a variable. #! /usr/bin/env python #Boa:Frame:Frame1 import wx def create(parent): retu...
How to accept value from textctrl in wxpython
Here is a python pgm. It contains a text ctrl and a button. Please help me to modify so that on pressing the button I need the string user entered in textctrl to be stored to a variable. #! /usr/bin/env python #Boa:Frame:Frame1 import wx def create(parent): return Frame1(parent) [wxID_FRAME1, wxID_FRAME1BUTTON1...
[ "There's a method attached to a wxTextCtrl object called getValue, so in OnButton1Button(), you call\nvar = self.text1.GetValue()\n\nAnd then do what you want with var afterwards.\n" ]
[ 4 ]
[]
[]
[ "python", "wxpython", "wxwidgets" ]
stackoverflow_0005287204_python_wxpython_wxwidgets.txt
Q: Python NameError: name -- syntax error Possible Duplicate: I have a compiler error “not defined” although there is a definition from gasp import * GRID_SIZE = 30 MARGIN = GRID_SIZE BACKGROUND_COLOR = color.BLACK # Colors we use WALL_COLOR = (0.6 * 255, 0.9 * 255, 0.9 * 255) # The shape of the maze. Each...
Python NameError: name -- syntax error
Possible Duplicate: I have a compiler error “not defined” although there is a definition from gasp import * GRID_SIZE = 30 MARGIN = GRID_SIZE BACKGROUND_COLOR = color.BLACK # Colors we use WALL_COLOR = (0.6 * 255, 0.9 * 255, 0.9 * 255) # The shape of the maze. Each character # represents a different type of...
[ "You never close the function call to Circle() two lines about line 122, that's probably it. You're probably missing an argument based on the trailing comma.\ndot_size = GRID_SIZE * 0.2\nCircle(self.screen_point, dot_size, # No closing parentheses\n(x, y) = self.place\nneighbors = [ (x+1, y), (x-1, y)]\nfor neighbo...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005287524_python.txt
Q: Finding the position of a pattern using the re module in Python I looked through a bunch of methods the re module provides, but I couldn't seem to find one that gives the position of a pattern. For example, consider the following code: import re text = '23132102301211213302' x=re.findall(r'21',text) print x Ou...
Finding the position of a pattern using the re module in Python
I looked through a bunch of methods the re module provides, but I couldn't seem to find one that gives the position of a pattern. For example, consider the following code: import re text = '23132102301211213302' x=re.findall(r'21',text) print x Output: ['21', '21', '21'] I just get a list of 21's as my output, wh...
[ "re.finditer() gives you MatchObjects which among other things make the position available.\nThe beginning of the match object m is given by m.start(), and the end by m.end() if you want that too.\n" ]
[ 2 ]
[]
[]
[ "position", "python", "regex" ]
stackoverflow_0005287536_position_python_regex.txt
Q: Modelling a robotic arm motion in 3D, ideas? I hope you don't mind if I ask for a bit of advice regarding modelling robotic systems. I've recently become rather interested in using inverse kinematics (IK) to control a 5 dof robotic manipulator. I have a solid foundation in IK but what I'm having trouble with is a ...
Modelling a robotic arm motion in 3D, ideas?
I hope you don't mind if I ask for a bit of advice regarding modelling robotic systems. I've recently become rather interested in using inverse kinematics (IK) to control a 5 dof robotic manipulator. I have a solid foundation in IK but what I'm having trouble with is a way to visualize how the manipulator moves with re...
[ "Well the great thing about Blender is that its API is actually in python!\nIn addition, it supports inverse kinematics (IK) quite well in addition to many other modeling tools.\nBlender Cookie is a great resource.\nHere is a tutorial on making IK rigs in Blender.\nBlenders python api is documented quite extensivel...
[ 2, 0, 0 ]
[]
[]
[ "inverse_kinematics", "modeling", "python", "robot", "robotics" ]
stackoverflow_0005287575_inverse_kinematics_modeling_python_robot_robotics.txt
Q: (Only) generate SQL-Code with SqlAlchemy Can i use the SqlAlchemy ORM-Mapper to only generate the SQL-Code? With simple tables i can use code like print users_table.select() print users_table.insert() print users_table.update() print users_table.delete() But with the ORM i have only found a way for SELECT-Statem...
(Only) generate SQL-Code with SqlAlchemy
Can i use the SqlAlchemy ORM-Mapper to only generate the SQL-Code? With simple tables i can use code like print users_table.select() print users_table.insert() print users_table.update() print users_table.delete() But with the ORM i have only found a way for SELECT-Statements: TestUser = User("John", "Doe") print ses...
[ "Perhaps you want the SQLAlchemy core expression language, instead of the ORM?\nhttp://www.sqlalchemy.org/docs/core/index.html\nThe ORM is designed to be very tightly data-bound, and thus to not really be decoupled from its DB sessions. The expression language, on the other hand, can be directly translated to SQL. ...
[ 9, 3, 3 ]
[]
[]
[ "orm", "python", "sqlalchemy" ]
stackoverflow_0005238275_orm_python_sqlalchemy.txt
Q: I have a compiler error "not defined" although there is a definition from gasp import * GRID_SIZE = 30 MARGIN = GRID_SIZE BACKGROUND_COLOR = color.BLACK # Colors we use WALL_COLOR = (0.6 * 255, 0.9 * 255, 0.9 * 255) # The shape of the maze. Each character # represents a different type of object # % - Wal...
I have a compiler error "not defined" although there is a definition
from gasp import * GRID_SIZE = 30 MARGIN = GRID_SIZE BACKGROUND_COLOR = color.BLACK # Colors we use WALL_COLOR = (0.6 * 255, 0.9 * 255, 0.9 * 255) # The shape of the maze. Each character # represents a different type of object # % - Wall # . - Food # o - Capsule # G - Ghost # P - Chomp # Other charact...
[ "The unfinished call to Circle() is probably the result of an error trying to format the code properly. Please check that you post the code that you actually ran, and the traceback is the one that you actually got (there's some of this one missing!).\nThe error reported in the (horribly formatted) traceback is that...
[ 1, 1 ]
[]
[]
[ "debugging", "python" ]
stackoverflow_0005287702_debugging_python.txt
Q: Port Python v2 function to v3 This v2 function gives a "NameError: global name 'file' is not defined" error when run in v3. def from_file(filename, sep='\n'): "Parse a file into a list of strings, separated by sep." return file(filename).read().strip().split(sep) Could someone please provide a v3 ...
Port Python v2 function to v3
This v2 function gives a "NameError: global name 'file' is not defined" error when run in v3. def from_file(filename, sep='\n'): "Parse a file into a list of strings, separated by sep." return file(filename).read().strip().split(sep) Could someone please provide a v3 version?
[ "Change the file call to open.\n" ]
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0005287812_python.txt
Q: Apache, mod_*, PHP, Perl, Python, Ruby; Learning backwards I started web development some time ago, but have invested essentially all my time in learning PHP, MySQL/SQLite, (X)HTML/XML (XPath, XQuery, XSL), etc. I went with an out-of-the-box XAMPP install, everything was pretty straightforward, and I could focus m...
Apache, mod_*, PHP, Perl, Python, Ruby; Learning backwards
I started web development some time ago, but have invested essentially all my time in learning PHP, MySQL/SQLite, (X)HTML/XML (XPath, XQuery, XSL), etc. I went with an out-of-the-box XAMPP install, everything was pretty straightforward, and I could focus my learning on languages. Now, however, I'm looking to learn Ruby...
[ "I would recommend the following:\nMake your home in the Ubuntu environment within the VM you mentioned\nEssentially all of the technologies you mentioned started out in Unix-based systems, and, while the playing field is leveling, there are still significant advantages to developing with these technologies in a Un...
[ 3, 2 ]
[]
[]
[ "apache", "perl", "php", "python", "ruby" ]
stackoverflow_0005286419_apache_perl_php_python_ruby.txt
Q: Linker settings I'm trying to link boost.python with my application in cmake build-system. The most important parts in my CMakeList.txt: set(Boost_USE_STATIC_LIBS OFF) set(Boost_USE_MULTITHREADED ON) set(Boost_USE_STATIC_RUNTIME OFF) find_package(Boost COMPONENTS filesystem system date_time python REQUIRED) add_...
Linker settings
I'm trying to link boost.python with my application in cmake build-system. The most important parts in my CMakeList.txt: set(Boost_USE_STATIC_LIBS OFF) set(Boost_USE_MULTITHREADED ON) set(Boost_USE_STATIC_RUNTIME OFF) find_package(Boost COMPONENTS filesystem system date_time python REQUIRED) add_definitions(-Wall -g ...
[ "You did not show the code that uses the Boost libraries, so I assume it's just:\ntarget_link_libraries(foo ${Boost_LIBRARIES})\n\nCould you please add \nmessage(\"XXX ${Boost_LIBRARIES}\")\n\naround that point? I suspect that will print a list of libraries with .a extension, which CMake then converts into that -Wl...
[ 0 ]
[]
[]
[ "boost", "c++", "cmake", "linker", "python" ]
stackoverflow_0005276973_boost_c++_cmake_linker_python.txt
Q: re do not work, strange characters textfields="""Conjugation of suorittaa """ stry2= """Conjugation""" stryc=re.compile(stry2, re.DOTALL) print 'textfields=', textfields, ' stry2=', stry2 LtryM=re.search(stryc, textfields); print 'LtryM', LtryM I could not find with re word """Conjugation""" in string """Conju...
re do not work, strange characters
textfields="""Conjugation of suorittaa """ stry2= """Conjugation""" stryc=re.compile(stry2, re.DOTALL) print 'textfields=', textfields, ' stry2=', stry2 LtryM=re.search(stryc, textfields); print 'LtryM', LtryM I could not find with re word """Conjugation""" in string """Conjugation of suorittaa """. I the end i pr...
[ "Your problem is not reproducible, based on the information that you have supplied:\n>>> import re\n>>> textfields=\"\"\"Conjugation of suorittaa \"\"\"\n>>> stry2= \"\"\"Conjugation\"\"\"\n>>> stryc=re.compile(stry2, re.DOTALL)\n>>> print 'textfields=', textfields, ' stry2=', stry2\ntextfields= Conjugation of suo...
[ 1, 0, 0 ]
[]
[]
[ "python", "regex", "string" ]
stackoverflow_0005288149_python_regex_string.txt
Q: Python: comparing dates and print out the first one This is probably very simple, but I am a beginner in python and I wanted to compare birthday dates by prompting a user to enter a date in MM-DD format. No year because year is current year (2011). It will then prompt the user to enter another date, and then the p...
Python: comparing dates and print out the first one
This is probably very simple, but I am a beginner in python and I wanted to compare birthday dates by prompting a user to enter a date in MM-DD format. No year because year is current year (2011). It will then prompt the user to enter another date, and then the program compares it to see which one is first. Then it pri...
[ "There are a few problems I can see in the code you've posted. I hope it will be helpful to point some of these out, and provide a somewhat rewritten version:\n\nIndentation is broken, but I guess this might just be problems pasting it into Stack Overflow\nstrftime is for formatting times, not parsing them. You w...
[ 4, 1, 1 ]
[]
[]
[ "date", "datetime", "python", "strftime" ]
stackoverflow_0005288329_date_datetime_python_strftime.txt
Q: Distinguishing overriding and overloading I have two classes in python Drunk Usual Drunk The usual drunk class inherits from the drunk and provides a new implementation for its move method as shown below class Drunk: def __init__(self,name): self.name = name def move(self,field,cp,dist=1): ...
Distinguishing overriding and overloading
I have two classes in python Drunk Usual Drunk The usual drunk class inherits from the drunk and provides a new implementation for its move method as shown below class Drunk: def __init__(self,name): self.name = name def move(self,field,cp,dist=1): if field.getDrunk().name!= self.name: ...
[ "It's overriding. Python does not support overloading.\nThat said, overriding a method with one that accepts different arguments, especially when it accepts fewer arguments than the base class method, is a Bad Idea. Consider:\nsome_drunk.move(field, cp)\n\nIf some_drunk is a regular Drunk, this works. But if it's a...
[ 9 ]
[]
[]
[ "python" ]
stackoverflow_0005288601_python.txt
Q: matching siblings according to tag attributes in xml using Python and libxml2 I am new to programming and thus maybe lacking basics somewhere. I have an xml: <mother> <daughter nr='1' state='nice' name='Ada'> <daughter nr='2' state='naughty' name='Beta'> <daughter nr='3' state='nice' name='Cecilia'> <daughter nr='...
matching siblings according to tag attributes in xml using Python and libxml2
I am new to programming and thus maybe lacking basics somewhere. I have an xml: <mother> <daughter nr='1' state='nice' name='Ada'> <daughter nr='2' state='naughty' name='Beta'> <daughter nr='3' state='nice' name='Cecilia'> <daughter nr='4' state='neither' name='Dora'> <daughter nr='5' state='naughty' name='Elis'> </mo...
[ "Use:\n /*/daughter[@state = 'nice'][1]\n| \n /*/daughter[@state = 'nice'][1]\n /following-sibling::daughter[@state='naughty'] [1]\n\nThis selects the pair of the first nice daughter and its nearest naughty daughter.\nTo select the second such pair use:\n /*/daughter[@state = 'nice'][2]\n| \n /*/daughter[@sta...
[ 3, 0, 0 ]
[]
[]
[ "attributes", "libxml2", "python", "xpath" ]
stackoverflow_0005286548_attributes_libxml2_python_xpath.txt
Q: flip bytes using Python's struct module I would like to flip from big to little endian this string: \x00\x40 to have it like this: \x40\x00 I guess the proper function to use would be struct.pack, but I can't find a way to make it properly work. A small help would be very appreciated ! Thanks A: You're not show...
flip bytes using Python's struct module
I would like to flip from big to little endian this string: \x00\x40 to have it like this: \x40\x00 I guess the proper function to use would be struct.pack, but I can't find a way to make it properly work. A small help would be very appreciated ! Thanks
[ "You're not showing the whole code, so the simplest solution would be:\ndata = data[1] + data[0]\n\nIf you insist on using struct:\n>>> from struct import pack, unpack\n>>> unpack('<H', '\\x12\\x13')\n(4882,)\n>>> pack('>H', *unpack('<H', '\\x12\\x13'))\n'\\x13\\x12'\n\nWhich first unpacks the string as a little-en...
[ 6, 5, 0, 0 ]
[]
[]
[ "endianness", "flip", "python", "struct" ]
stackoverflow_0002189600_endianness_flip_python_struct.txt
Q: Identify the number of elements in a python struct/pack fmt string? When using the python struct module on can specify a format string that declares how binary data should be interpreted: >>> from struct import * >>> fmt = 'hhl' >>> values = [1,2,3] >>> blob = pack(fmt, values) It is easily possible to calculate ...
Identify the number of elements in a python struct/pack fmt string?
When using the python struct module on can specify a format string that declares how binary data should be interpreted: >>> from struct import * >>> fmt = 'hhl' >>> values = [1,2,3] >>> blob = pack(fmt, values) It is easily possible to calculate the amount of bytes needed to store an instance of that format: >>> calcs...
[ "I'm afraid there's no such function in the struct API, but you can define it yourself without parsing the format string:\ndef calcentries(fmt):\n return len(struct.unpack(fmt, '\\0' * struct.calcsize(fmt)))\n\n" ]
[ 5 ]
[]
[]
[ "binary_data", "python", "struct" ]
stackoverflow_0005289069_binary_data_python_struct.txt
Q: Why would Python give me a "TypeError: argument of type 'UserAgent' is not iterable" in a non-iteration type of operation? I have a BaseHandler class that subclasses the Tipfy RequestHandler in my AppEngine site. In it, I have setup a "poor man's" browser sniffer for mobile devices with a class attribute (a tuple)...
Why would Python give me a "TypeError: argument of type 'UserAgent' is not iterable" in a non-iteration type of operation?
I have a BaseHandler class that subclasses the Tipfy RequestHandler in my AppEngine site. In it, I have setup a "poor man's" browser sniffer for mobile devices with a class attribute (a tuple) containing device names. In a subsequent method, I loop through the device names in the tuple and check them against the user a...
[ "The expression\ndevice in self.request.user_agent\n\nwill first try to call\nself.request.user_agent.__contains__(device)\n\nIf this method does not exist, Python tries to iterate over self.request.user_agent and compares each item it encounters to device. Obviously, the type of self.request.user_agent neither al...
[ 5 ]
[]
[]
[ "google_app_engine", "python", "tipfy" ]
stackoverflow_0005289206_google_app_engine_python_tipfy.txt
Q: How to index and automate processing of list using input csv file I have csv input file, lets call it heights.csv. my example file has only four lines but it cannot be limited. The first column contains just irrelevant name, the second one contains values I want to process as integers. 1000,57020, 2003,56095, 2007...
How to index and automate processing of list using input csv file
I have csv input file, lets call it heights.csv. my example file has only four lines but it cannot be limited. The first column contains just irrelevant name, the second one contains values I want to process as integers. 1000,57020, 2003,56095, 2007,55964, 3001,57020, I would like to perform action like this: first_rea...
[ "Well, I hope you worked with success on your problem. \nDid you find how to manage with '.' in the values ? That was simple: \nreplace('.','')\n\nFor me, I think the following code fulfills all the requirements. I hope it wasn't a homework and you learned something.\nimport csv\nimport random\nfrom sys import exit...
[ 3, 1, 1 ]
[]
[]
[ "csv", "python" ]
stackoverflow_0005227466_csv_python.txt
Q: How do I increment an attribute at runtime using getattr/setattr? I have a class with ten different counters. I need to increment one or another of these at runtime, and the increment method is told the name of the counter to increment. I'm wondering if there's a cleaner way than this: def increment(self, name): ...
How do I increment an attribute at runtime using getattr/setattr?
I have a class with ten different counters. I need to increment one or another of these at runtime, and the increment method is told the name of the counter to increment. I'm wondering if there's a cleaner way than this: def increment(self, name): """Increments a counter specified by the 'name' argument.""" set...
[ "You could store the counters in a dictionary instead of in attributes.\nAlternatively, you could use\ndef increment(self, name):\n \"\"\"Increments a counter specified by the 'name' argument.\"\"\"\n self.__dict__[name] += 1\n\nIt's up to you to decide if this is \"cleaner\".\n" ]
[ 7 ]
[]
[]
[ "python" ]
stackoverflow_0005289259_python.txt
Q: Init method for subclass of PyQt QTableWidgetItem I'd like to subclass the QTableWidgetItem so that my subclass can have an additional 'id' attribute. Unfortunately, I'm a little confused because the PyQt docs here show four different init methods. To create my own init method for my "QTableWidgetItemWithId" subcl...
Init method for subclass of PyQt QTableWidgetItem
I'd like to subclass the QTableWidgetItem so that my subclass can have an additional 'id' attribute. Unfortunately, I'm a little confused because the PyQt docs here show four different init methods. To create my own init method for my "QTableWidgetItemWithId" subclass (which would also pass in an extra 'id' argument), ...
[ "I'd say that depends a little on your taste and what you consider readable and also how flexible you want to keep your subclass.\nYou can add whatever you wish to your constructor and just hand what's needed to QTableWidgetItem's constructor. There are many ways of doing it. I personally try to avoid *args and **k...
[ 3, 1 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0005284648_pyqt_python.txt
Q: In Python, what operator to override for "if object:"? I find it very handy to check if an object is "empty" with the following construct: l=[] if l: do_stuff() For a standard python list, the if will be executed only if the list is not empty. My question is, how can I implement the same idea for my own obje...
In Python, what operator to override for "if object:"?
I find it very handy to check if an object is "empty" with the following construct: l=[] if l: do_stuff() For a standard python list, the if will be executed only if the list is not empty. My question is, how can I implement the same idea for my own objects?
[ "Define a method __bool__ (Python 3.x) or __nonzero__ (2.x). Or define both for portability, with one returning the result of the other.\n", "Implement __nonzero__ for Python 2 and __bool__ for Python 3:\nclass AlwaysTrueObject:\n def __bool__(self):\n return True\n __nonzero__ = __bool__\n\n", "If...
[ 32, 19, 10 ]
[]
[]
[ "object", "operator_overloading", "python" ]
stackoverflow_0005288990_object_operator_overloading_python.txt
Q: Dependencies Tree Implementation For those who used apt-get, you know that everytime you install / uninstall something, you get the notificatons saying you need / no longer need certain dependencies. I'm trying to understand the theory behinds this and potentially implement my own version of this. I've done some g...
Dependencies Tree Implementation
For those who used apt-get, you know that everytime you install / uninstall something, you get the notificatons saying you need / no longer need certain dependencies. I'm trying to understand the theory behinds this and potentially implement my own version of this. I've done some googling, came up with mostly coupling ...
[ "Graph theory is the way to go.\nA graph is just a bunch of places (vertices) with roads (edges) between them, and in particular we're talking about a directed graph, which means one-way roads. Figuring out dependencies means, basically, finding out all the places that can reach a particular town along the one-way...
[ 9, 9, 5, 0, 0 ]
[]
[]
[ "computer_science", "python" ]
stackoverflow_0005287516_computer_science_python.txt
Q: Learn a scripting language besides Python Someone told me once, that programmers tend to learn one scripting language properly and ignore or dislike other scripting languages. Do you have similar experiences? I'm using Python as my choice for scripting for few years, however, I'm sure that there are many existin...
Learn a scripting language besides Python
Someone told me once, that programmers tend to learn one scripting language properly and ignore or dislike other scripting languages. Do you have similar experiences? I'm using Python as my choice for scripting for few years, however, I'm sure that there are many existing and emerging languages that could impress the...
[ "Look, Python pretty much has all you need (in my opinion) for application programming. You can write anything from a protocol stack to YouTube, from media players to 3D games and graphics and you get excellent performance.\nIt occupies the same niche as some of these other mentioned languages:\n\nC, you have acces...
[ 22, 6, 6, 5, 4, 3, 3, 3, 3, 2, 1, 1, 1 ]
[]
[]
[ "programming_languages", "python", "scripting" ]
stackoverflow_0003243529_programming_languages_python_scripting.txt
Q: multiple try/except in a single function does not work def creating_folder_for_csv_files(cwd): try: os.makedirs(cwd+'\\migration_data\\trade') except os.error, e: print "Could not create the destination folder for CSV files" # end of first try/except block try: os.ma...
multiple try/except in a single function does not work
def creating_folder_for_csv_files(cwd): try: os.makedirs(cwd+'\\migration_data\\trade') except os.error, e: print "Could not create the destination folder for CSV files" # end of first try/except block try: os.makedirs(cwd+'\\migration_data\\voucher') except os.error...
[ "The voucher might already exist. \n" ]
[ 0 ]
[]
[]
[ "python" ]
stackoverflow_0005087819_python.txt
Q: Python multithreaded extension - thread lock recovery I have a multithreaded C extension for Python. It outputs data to the class in Python using 3 threads. I am using PyGILState_Ensure / PyGILState_Release API to sync interpreter calls. There are possible cases in the extension where some threads stuck and get te...
Python multithreaded extension - thread lock recovery
I have a multithreaded C extension for Python. It outputs data to the class in Python using 3 threads. I am using PyGILState_Ensure / PyGILState_Release API to sync interpreter calls. There are possible cases in the extension where some threads stuck and get terminated before they call PyGILState_Release. Is there anyw...
[ "I am not entirely sure how you terminate your threads, but in the implementation I have in my head, you would be destructing a thread object would you not? In this case you release the lock in the destructor...\n", "I'd suggest to change the pattern of interaction between threads.\nYour current implementation se...
[ 0, 0 ]
[]
[]
[ "python", "python_multithreading" ]
stackoverflow_0005286447_python_python_multithreading.txt
Q: Persistent ssh session to Cisco router I have search on this site and multiple other locations but I have been unable to resolve my problem of connecting and maintaining ssh session after one command. Below is my current code: #!/opt/local/bin/python import os import pexpect import paramiko import hashlib i...
Persistent ssh session to Cisco router
I have search on this site and multiple other locations but I have been unable to resolve my problem of connecting and maintaining ssh session after one command. Below is my current code: #!/opt/local/bin/python import os import pexpect import paramiko import hashlib import StringIO while True: cisco_cmd...
[ "I used Exscript instead of paramiko and I am now able to get persistent session on IOS device.\n#!/opt/local/bin/python\nimport hashlib\nimport Exscript\n\nfrom Exscript.util.interact import read_login\nfrom Exscript.protocols import SSH2\n\naccount = read_login() # Prompt the user for his name and pa...
[ 7, 1, 1, 1 ]
[]
[]
[ "cisco", "paramiko", "python" ]
stackoverflow_0005238000_cisco_paramiko_python.txt
Q: Python thread synchronisation I have 3 tasks : t1, t2 and t3. I want to run t1 and t2 in two parallels threads. And I want to wait for the end of t1 and t2 execution before running t3. t1 =========> | t2 ====>           | t3......................|=======> -----------------------------------------------------------...
Python thread synchronisation
I have 3 tasks : t1, t2 and t3. I want to run t1 and t2 in two parallels threads. And I want to wait for the end of t1 and t2 execution before running t3. t1 =========> | t2 ====>           | t3......................|=======> -------------------------------------------------------------(time)--> I have some basis about...
[ "You can wait on threads with join:\n# start the two threads\nt1.start()\nt2.start()\n\n# wait until both ended\nt1.join()\nt2.join()\n\n# then start the third\nt3.start()\n\n", "I would advise you to have a look at the module threading. It provides lock objects, condition objects and semaphore objects.\n" ]
[ 6, 1 ]
[]
[]
[ "multithreading", "python", "synchronization" ]
stackoverflow_0005289817_multithreading_python_synchronization.txt
Q: How to tweet from Django? I want to create a manage.py command that takes an object from a queryset and posts it on my Twitter. I was going to use the curl method as described in here. But Twitter has since disabled basic authentication. I don't want to install an overkill library like Tweepy that lets people auth...
How to tweet from Django?
I want to create a manage.py command that takes an object from a queryset and posts it on my Twitter. I was going to use the curl method as described in here. But Twitter has since disabled basic authentication. I don't want to install an overkill library like Tweepy that lets people authenticate to my site with oAuth,...
[ "from twitter api page:\n\nFor applications with single-user use cases, we now offer the ability to issue an access token for your own account (and your own applications). You can generate these keys from your application details pages. Find out more about using a single access token.\n\ngo to https://dev.twitter.c...
[ 6 ]
[]
[]
[ "django", "oauth", "python", "twitter" ]
stackoverflow_0005289473_django_oauth_python_twitter.txt
Q: Safe Python Environment in Linux Is it possible to create an environment to safely run arbitrary Python scripts under Linux? Those scripts are supposed to be received from untrusted people and may be too large to check them manually. A very brute-force solution is to create a virtual machine and restore its initia...
Safe Python Environment in Linux
Is it possible to create an environment to safely run arbitrary Python scripts under Linux? Those scripts are supposed to be received from untrusted people and may be too large to check them manually. A very brute-force solution is to create a virtual machine and restore its initial state after every launch of an untru...
[ "Consider using a chroot jail. Not only is this very secure, well-supported and tested but it also applies to external applications you run from python.\n", "There are 4 things you may try:\n\nAs you already mentioned, using a virtual machine or some other form of virtualisation (perhaps solaris zones are lightwe...
[ 4, 4, 2, 1, 1 ]
[]
[]
[ "linux", "python", "restriction", "runtime", "sandbox" ]
stackoverflow_0000886895_linux_python_restriction_runtime_sandbox.txt
Q: Using MySQLdb execute method I'm having some trouble passing in dynamic variables into my query. Please ignore the poor style. This is what I'm trying to run: > sql = "SELECT COUNT(*) FROM artifacts WHERE " \ > "url = '%s' AND " \ > "source_id = '%s'" > self.db.execute(sql, (url, source_id)) I get the...
Using MySQLdb execute method
I'm having some trouble passing in dynamic variables into my query. Please ignore the poor style. This is what I'm trying to run: > sql = "SELECT COUNT(*) FROM artifacts WHERE " \ > "url = '%s' AND " \ > "source_id = '%s'" > self.db.execute(sql, (url, source_id)) I get the error: self.db.execute(sql) Attri...
[ "Just for clarification is your self.db attribute a connection or a cursor. Because you can only call the execute on a cursor!\nIf your following this example then you can see that there is create a cursor from the connection attribute and this cursor contains the execute method.\nhere is a small example:\nimport M...
[ 3 ]
[]
[]
[ "mysql", "python" ]
stackoverflow_0005290022_mysql_python.txt
Q: How to write a program that mimics Fiddler by using tcpdump or from scratch? When Fiddler is not on Mac OS X or Ubuntu, and if we don't install/use Wireshark or any other more heavy duty tools, what is a way to use tcpdump so that 1) It can print out GET /foo/bar HTTP/1.1 [request content in RAW text] [res...
How to write a program that mimics Fiddler by using tcpdump or from scratch?
When Fiddler is not on Mac OS X or Ubuntu, and if we don't install/use Wireshark or any other more heavy duty tools, what is a way to use tcpdump so that 1) It can print out GET /foo/bar HTTP/1.1 [request content in RAW text] [response content in RAW text] POST /foo/... HTTP/1.1 this should be able to be done ...
[ "Here are two tcpdump filters for HTTP GET & HTTP POST:\n# tcpdump filter for HTTP GET \nsudo tcpdump -s 0 -A 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'\n\n# tcpdump filter for HTTP POST \nsudo tcpdump -s 0 -A 'tcp dst port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354)'\n\n" ]
[ 1 ]
[]
[]
[ "bash", "python", "ruby", "shell", "tcpdump" ]
stackoverflow_0005285016_bash_python_ruby_shell_tcpdump.txt
Q: Creating a custom widget using django for use on external sites I have a new site that I am putting together and part of it has statistics for the site's users. I would like to create a widget that others can use on another website by invoking javascript that reads data from my server and shows that statistics for...
Creating a custom widget using django for use on external sites
I have a new site that I am putting together and part of it has statistics for the site's users. I would like to create a widget that others can use on another website by invoking javascript that reads data from my server and shows that statistics for a given user, but I am having a hard time finding specific tutorials...
[ "This is not matter of Django, you can solve this by using the most common solution. Javascript.\nGive your users this to put on their websites.\n<script type=\"text/javascript\" src=\"http://mysite.com/widget/user/124546465\"></script>\n\nOn a django view, render the next template:\n(function(){\ndocument.write('<...
[ 7, 2 ]
[]
[]
[ "django", "javascript", "python", "widget" ]
stackoverflow_0005290085_django_javascript_python_widget.txt
Q: Spoofing Python operator precedence I know that when I compare two objects lhs == rhs and both define __eq__, just lhs.__eq__ is called unless it returns NotImplemented or rhs is a subclass of lhs. However I would like to implement a class, instances of which while comparing to arbitrary objects will be given a ch...
Spoofing Python operator precedence
I know that when I compare two objects lhs == rhs and both define __eq__, just lhs.__eq__ is called unless it returns NotImplemented or rhs is a subclass of lhs. However I would like to implement a class, instances of which while comparing to arbitrary objects will be given a chance to say what they want to say, regard...
[ "I don't know if this will suite your need, but why not test the two operation by that i mean test if : object1 == object2 and object2 == object1 and usually you should end up with the same value unless one of the object have overwrote the __eq__ method so you will execute this new __eq__ method and return the one ...
[ 1 ]
[]
[]
[ "magic_methods", "metaclass", "operator_overloading", "python" ]
stackoverflow_0005290044_magic_methods_metaclass_operator_overloading_python.txt
Q: Splitting a GPS Point into Latitude and Longitude Regular Given the following string representation of a GPS point... (40.714353, -74.005973) How can I perform a string split to obtain both the latitude and longitude as separate tokens - without any superfluous characters (spaces and brackets) using Python? A: ...
Splitting a GPS Point into Latitude and Longitude Regular
Given the following string representation of a GPS point... (40.714353, -74.005973) How can I perform a string split to obtain both the latitude and longitude as separate tokens - without any superfluous characters (spaces and brackets) using Python?
[ "You may use ast.literal_eval() to parse the string:\n>>> import ast\n>>> coord = \"(40.714353, -74.005973)\"\n>>> ast.literal_eval(coord)\n(40.714353000000003, -74.005972999999997)\n\n", "You don't need regular expressions:\n>>> str = \"(40.714353, -74.005973)\"\n>>> tuple(float(x) for x in str.strip('()').split...
[ 8, 6 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005290508_python_regex.txt
Q: SystemError: The connection has been disabled This is a really nebulous error that I can't seem to get a lot of context for so please ask any questions that might help clarify. I'll try to give you as much context as I can. I'm currently creating a whole bunch of insert statements for mysql using a comma separated...
SystemError: The connection has been disabled
This is a really nebulous error that I can't seem to get a lot of context for so please ask any questions that might help clarify. I'll try to give you as much context as I can. I'm currently creating a whole bunch of insert statements for mysql using a comma separated list of parantheses delineated values (i.e. insert...
[ "I'm not sure why you are getting the error you are getting. Perhaps it has to do with creating very long SQL statements? Whatever the case, you should\nalways use parametrized SQL statements; avoid composing SQL (with arguments) manually:\nsql = 'INSERT INTO table (a,b,c) VALUES (%s,%s,%s)'\nargs = [(1,2,3),(4,5,6...
[ 1, 0 ]
[]
[]
[ "ironpython", "mysql", "python" ]
stackoverflow_0005264521_ironpython_mysql_python.txt
Q: Complex transforming nested dictionaries into objects in python It hasn't been long since I started learning python, but I really want to dig in it. And dig it hard. So here is a task I've been studying for a while but haven't cracked yet: I am given a mixed combination of nested dictionaries and lists (let's call...
Complex transforming nested dictionaries into objects in python
It hasn't been long since I started learning python, but I really want to dig in it. And dig it hard. So here is a task I've been studying for a while but haven't cracked yet: I am given a mixed combination of nested dictionaries and lists (let's call it "combination"), and I need to implement function that will allow ...
[ "How about:\nclass ComboParser(object):\n def __init__(self,data):\n self.data=data\n def __getattr__(self,key):\n try:\n return ComboParser(self.data[key])\n except TypeError:\n result=[]\n for item in self.data:\n if key in item:\n ...
[ 6, 3, 1, 1 ]
[]
[]
[ "python" ]
stackoverflow_0005290715_python.txt
Q: How to a split a list in parts that have size less than 1MByte I have a sorted list of dictionaries returned by a remote API call (tipically the response is less than 4 MByte. I would like to split this list in chunks where the MAX allowed size of the resulted single chunk is 1 MByte.* The resulted list of chunks ...
How to a split a list in parts that have size less than 1MByte
I have a sorted list of dictionaries returned by a remote API call (tipically the response is less than 4 MByte. I would like to split this list in chunks where the MAX allowed size of the resulted single chunk is 1 MByte.* The resulted list of chunks need to preserve the initial sorting; these chunks then will be seri...
[ "Following up on my comment. You could use this extension.\nAnd the following script. Assume that this won't optimize the size of the chunks. It only assures that none of them are larger than MAX\nfrom sizeof import asizeof\n\nmatrix=[]\nnew_chunk = []\nsize_of_current_chunk = 0\nfor x in your_sorted_list:\n s =...
[ 1, 0 ]
[]
[]
[ "python" ]
stackoverflow_0004139977_python.txt
Q: How to specify data in models.ManyToManyField(Foo,Bar) I'm working on an application were I want the user roles to be entered into a table in the database. class Role(models.Model): name = models.CharField(max_length = 40) details = models.TextField() class Foo(models.Model): name = models.CharField(max_lengt...
How to specify data in models.ManyToManyField(Foo,Bar)
I'm working on an application were I want the user roles to be entered into a table in the database. class Role(models.Model): name = models.CharField(max_length = 40) details = models.TextField() class Foo(models.Model): name = models.CharField(max_length = 40) details = models.TextField() class Bar(models.Mode...
[ "I don't understand what exactly you are trying to do, but reading this line: {|id|Foo_id|Bar_id|Role_id|}\nmakes me think you could either define a model with those fields, or set up a through model with that extra field.\n", "To simplify this so you can think of it more clearly, don't use many-to-many associati...
[ 1, 0 ]
[]
[]
[ "database", "django", "python" ]
stackoverflow_0005291072_database_django_python.txt
Q: Python Map Function I need some help with Python's map function. I am trying to execute this code, though I get an error: Updated Post This is my exact code, along with the outputs of each function: infinity = 1000000 invalid_node = -1 startNode = 0 #Values to assign to each node class Node: def __init__(sel...
Python Map Function
I need some help with Python's map function. I am trying to execute this code, though I get an error: Updated Post This is my exact code, along with the outputs of each function: infinity = 1000000 invalid_node = -1 startNode = 0 #Values to assign to each node class Node: def __init__(self): self.distFromS...
[ "for nodeIndex in theNetwork:\n\ndoes not make nodeIndex iterate over indices in theNetwork, but over the values of its elements. You should use\nfor nodeIndex,node in enumerate(theNetwork):\n # theNetwork[nodeIndex] is now known as node\n\n", "Check your theNetwork variable by printing it at your console:\npr...
[ 4, 0, 0 ]
[]
[]
[ "dijkstra", "python" ]
stackoverflow_0005291182_dijkstra_python.txt
Q: Remove and Replace Printed items I was wondering if it was possible to remove items you have printed in Python - not from the Python GUI, but from the command prompt. e.g. a = 0 for x in range (0,3): a = a + 1 b = ("Loading" + "." * a) print (a) so it prints >>>Loading >>>Loading. >>>Loading.. ...
Remove and Replace Printed items
I was wondering if it was possible to remove items you have printed in Python - not from the Python GUI, but from the command prompt. e.g. a = 0 for x in range (0,3): a = a + 1 b = ("Loading" + "." * a) print (a) so it prints >>>Loading >>>Loading. >>>Loading.. >>>Loading... But, my problem is I wa...
[ "Just use CR to go to beginning of the line.\nimport time\nfor x in range (0,5): \n b = \"Loading\" + \".\" * x\n print (b, end=\"\\r\")\n time.sleep(1)\n\n", "One way is to use ANSI escape sequences:\nimport sys\nimport time\nfor i in range(10):\n print(\"Loading\" + \".\" * i)\n sys.stdout.write...
[ 259, 137, 38 ]
[]
[]
[ "printing", "python", "python_3.2", "python_3.x" ]
stackoverflow_0005290994_printing_python_python_3.2_python_3.x.txt
Q: Pyramid Framework - Help with creating a view function I have the following code for the view: def pages_view(request): path = request.path.split('/')[1] dbsession = DBSession() page = dbsession.query(PagesTable).from_statement( 'SELECT * FROM pages WHERE path=:page_path').params(page_path=path).fi...
Pyramid Framework - Help with creating a view function
I have the following code for the view: def pages_view(request): path = request.path.split('/')[1] dbsession = DBSession() page = dbsession.query(PagesTable).from_statement( 'SELECT * FROM pages WHERE path=:page_path').params(page_path=path).first() pages_dir = os.getcwd() + '/myblog/templates/pages...
[ "You would have been better off following through on this question rather than starting the other one. Based on information here and in the comment you provided in the other question, the following is taking place:\nView:\n\ndef view1(request)\n args1 = 'a string'\n return render_to_response('page.mak',{'args...
[ 1, 0, 0, 0 ]
[]
[]
[ "pylons", "pyramid", "python" ]
stackoverflow_0005282786_pylons_pyramid_python.txt
Q: Share Session between Play framework and Django How can I create a single sign on application that will let me move from one section of my site to another. One section of my site uses play framework and the other is on django. My SSO know-how is very limited so be nice to me :) A: as stated by mandubian the best...
Share Session between Play framework and Django
How can I create a single sign on application that will let me move from one section of my site to another. One section of my site uses play framework and the other is on django. My SSO know-how is very limited so be nice to me :)
[ "as stated by mandubian the best option is to have a central service that provides authentication tokens that all applications recognize and use to authenticate the user. And example of such a service is CAS, if as you say you are not experienced with SSO I would read about it to get the grasp of how it should work...
[ 3, 1, 1 ]
[]
[]
[ "django", "java", "playframework", "python", "single_sign_on" ]
stackoverflow_0005282764_django_java_playframework_python_single_sign_on.txt
Q: Explanations some Python Code this is a basic example of a barrier, of how some threads are waited to enter a barrier for an entrance and another barrier for an exit. Although the code is fine, I don't really understand in depth how it works... For instance, I don't understand why a thread that enters the barrier(...
Explanations some Python Code
this is a basic example of a barrier, of how some threads are waited to enter a barrier for an entrance and another barrier for an exit. Although the code is fine, I don't really understand in depth how it works... For instance, I don't understand why a thread that enters the barrier() function, after it does n = n-1, ...
[ "n is the number of threads that still have to reach the rendezvous point. region is a mutex, protecting access to n. bar1 and bar2 are semaphores, indicating the number of threads that can proceed, initialized to 0.\nIn the first part of barrier(), each thread enters in turn, decreases n, and blocks on the bar1 se...
[ 2 ]
[]
[]
[ "multithreading", "python" ]
stackoverflow_0005291564_multithreading_python.txt
Q: Desktop WiFi app to Sync with Mobile app I need your help! I want to create a desktop app and a mobile app to sync data between them. Imagine a simple TO-DO list app. I also want to know if you think this is the best solution. My first idea is to create a python app in order to target all possible operative syste...
Desktop WiFi app to Sync with Mobile app
I need your help! I want to create a desktop app and a mobile app to sync data between them. Imagine a simple TO-DO list app. I also want to know if you think this is the best solution. My first idea is to create a python app in order to target all possible operative systems, and then create the mobile ones to sync be...
[ "Do you intend the desktop app to be the server for the mobile app client? Or are both the desktop app and mobile app clients of some server on the web?\nEither are entirely possible and workable; however if the server is at a known location on the web, any mobile client instance can know where to find it - if it i...
[ 0 ]
[]
[]
[ "iphone", "mobile", "python", "wifi" ]
stackoverflow_0005291723_iphone_mobile_python_wifi.txt
Q: How do I create a tree view (with checkbox) inside a combo box - PyQt I'm using PYQT for developing an application. my requirement is to insert a tree view with checkbox inside a combobox items. I would like to know how to achieve this? I have the following code but this does not work. class CheckboxInsideListbox(...
How do I create a tree view (with checkbox) inside a combo box - PyQt
I'm using PYQT for developing an application. my requirement is to insert a tree view with checkbox inside a combobox items. I would like to know how to achieve this? I have the following code but this does not work. class CheckboxInsideListbox(QWidget): def __init__(self, parent = None): super(CheckboxInsideListbo...
[ "If you really mean to apply a layout to a layout, try adding your widget to your cb_layout. Otherwise get rid of your sublayout.\n", "You should create a model that support Qt.CheckStateRole in data and SetData methods and the flag Qt.ItemIsUserCheckable in the flags method.\nI Paste you here an example i am usi...
[ 0, 0 ]
[]
[]
[ "pyqt", "python" ]
stackoverflow_0005219946_pyqt_python.txt
Q: Specifying installed native library paths during pypy translate I am trying to build the latest pypy repo on a Mac machine. One of the needed libraries, libintl, is installed in $HOME/opt/local/lib. I run (using a previously built pypy-c), pypy-c translate.py -Ojit --ldflags=-L~/opt/local/lib --cflags=-L~/opt/loca...
Specifying installed native library paths during pypy translate
I am trying to build the latest pypy repo on a Mac machine. One of the needed libraries, libintl, is installed in $HOME/opt/local/lib. I run (using a previously built pypy-c), pypy-c translate.py -Ojit --ldflags=-L~/opt/local/lib --cflags=-L~/opt/local/lib However, after about half an hour, it stalls with [translatio...
[ "New Environment Variable\nTalk about timing — I just added support for this! You can now set a PYPY_LOCALBASE environment variable when you translate, e.g.\nPYPY_LOCALBASE=/Users/tav/local pypy-c translate.py -Ojit\n\nIt will then add the lib and include directories inside PYPY_LOCALBASE to the library/include pat...
[ 3 ]
[]
[]
[ "dynamic_linking", "pypy", "python", "rpython", "static_linking" ]
stackoverflow_0005287050_dynamic_linking_pypy_python_rpython_static_linking.txt
Q: allowing user to cast one vote anonymously with GAE I have a GAE app for voting, where each voter is sent a unique key via email and then uses that key to vote at a web page. I'd like to ensure that each voter can only cast one vote, and also that the vote remains anonymous. I have a Voter class with an attribute...
allowing user to cast one vote anonymously with GAE
I have a GAE app for voting, where each voter is sent a unique key via email and then uses that key to vote at a web page. I'd like to ensure that each voter can only cast one vote, and also that the vote remains anonymous. I have a Voter class with an attribute has_voted and a Vote class with an attribute for the vot...
[ "As you observed, since voter and vote are in separate entity groups you cannot update them in the same transaction. However, you can update voter in the transaction (as you are now), and record their vote in a transactional task associated with this transaction.\n", "You could assign the vote item to the voter ...
[ 1, 1 ]
[]
[]
[ "google_app_engine", "google_cloud_datastore", "python", "transactions" ]
stackoverflow_0005291638_google_app_engine_google_cloud_datastore_python_transactions.txt
Q: Python: Problem closing files in a while loop I've ran into an error while dealing with a while loop. I am able to input the number I want to run, and the results are written correctly to the corresponding .CSV. Once the section for that number is done running, it will ask if I want to try again with a new number....
Python: Problem closing files in a while loop
I've ran into an error while dealing with a while loop. I am able to input the number I want to run, and the results are written correctly to the corresponding .CSV. Once the section for that number is done running, it will ask if I want to try again with a new number. It runs the new numbers code and creates the new ....
[ "It would be nice to know what you are exactly doing with the file descriptor you opened at the beginning of the loop (f1, f2, f3). Nevertheless I believe that the issue you have is related with the fact that you are trying to read twice from one of those file descriptors but you are not resetting their position wh...
[ 4, 0 ]
[]
[]
[ "csv", "python", "while_loop" ]
stackoverflow_0005291018_csv_python_while_loop.txt
Q: CRC16 in Python How do I calculate CRC16 in Python? In Perl I would write something like: use Digest::CRC "crc16"; $result = crc16($str); How do I do same thing in Python? A: There is a library for calculating CRC16 here http://pypi.python.org/pypi/crc16/0.1.0
CRC16 in Python
How do I calculate CRC16 in Python? In Perl I would write something like: use Digest::CRC "crc16"; $result = crc16($str); How do I do same thing in Python?
[ "There is a library for calculating CRC16 here http://pypi.python.org/pypi/crc16/0.1.0\n" ]
[ 3 ]
[]
[]
[ "crc", "crc16", "perl", "python" ]
stackoverflow_0005292290_crc_crc16_perl_python.txt
Q: Where to start with parsing JSON? If I have JSON data stored in a string called 'data' (e.g. the example below) how do I access specific information (such as messages->unread or pokes->most_recent)? { "messages": { "unread": 0, "most_recent": 1300047276 }, "pokes": { "unread": 0, "most_recent...
Where to start with parsing JSON?
If I have JSON data stored in a string called 'data' (e.g. the example below) how do I access specific information (such as messages->unread or pokes->most_recent)? { "messages": { "unread": 0, "most_recent": 1300047276 }, "pokes": { "unread": 0, "most_recent": 0 }, "shares": { "unread": 0...
[ "JSON parser is bundled with Python since 2.6: json module. To unserialize a string, use json.loads, e.g.\nimport json\ndata = json.loads(...)\n\nYou can also load directly from a file-like object with json.load.\n", "You run the string through a JSON parser to turn it into a suitable data structure for whatever ...
[ 5, 0 ]
[]
[]
[ "facebook", "json", "python" ]
stackoverflow_0005292397_facebook_json_python.txt
Q: Django and GeoSpatial Queries on Google App Engine - How to overcome the 'one inequality per query' issue? I've just began to use the GAE and I have stumbled upon an issue which has let me questioning the feasibility of using Django on GAE. All I'm trying to do is a simple query with Django's ORM: addresses = Addr...
Django and GeoSpatial Queries on Google App Engine - How to overcome the 'one inequality per query' issue?
I've just began to use the GAE and I have stumbled upon an issue which has let me questioning the feasibility of using Django on GAE. All I'm trying to do is a simple query with Django's ORM: addresses = Address.objects.filter(lat__gte=form.cleaned_data['north_east_lat']) addresses = addresses.filter(lat__lte=form.clea...
[ "Unfortunately, I don't know of an easy way to use Django's ORM to get around this issue. However, you can do geospatial queries on GAE (including bounding box queries like you're doing in your example). For details, please check out the Geospatial Queries with Google App Engine using GeoModel article.\n" ]
[ 3 ]
[]
[]
[ "django", "django_nonrel", "google_app_engine", "google_cloud_datastore", "python" ]
stackoverflow_0005292402_django_django_nonrel_google_app_engine_google_cloud_datastore_python.txt
Q: Is there a C# equivalent of python's os.path.normpath? In python, I take a raw string, and then pass it to os.path.normpath to make it a proper pathname. It escapes all the stuff I need escaped and I don't have to worry about it. Is there an equivalent in C#? Here is a python snippet. myClassProjectPath = os.pat...
Is there a C# equivalent of python's os.path.normpath?
In python, I take a raw string, and then pass it to os.path.normpath to make it a proper pathname. It escapes all the stuff I need escaped and I don't have to worry about it. Is there an equivalent in C#? Here is a python snippet. myClassProjectPath = os.path.normpath(r"C:\Users\Documents\SharpDevelop Projects\Projec...
[ "Also check out:\nstring normalizedPath = Path.GetDirectoryName(path);\n\nThis will fix / vs \\ as well.\n", "You can always add an @ in front to create a verbatim string literal.\nWhat's the @ in front of a string in C#?\n", "Try to Path.Combine the path with nothing, or Path.ChangeExtension it to Path.GetExte...
[ 3, 2, 2, 1 ]
[]
[]
[ "c#", "escaping", "path", "python" ]
stackoverflow_0005292305_c#_escaping_path_python.txt
Q: How to eliminate {} brackets from message box I have script like this:rp_1st_name = 1000 rp_last_name = 2000 rp_1st_val = 5555 rp_last_val = 6666 fdh = 200 dif = (rp_1st_val - rp_last_val) - fdh teor = rp_1st_val - rp_last_val m1='wysokosc reperu poczatkowego:',rp_1st_val,'mm \n' m2='wysokosc reperu koncowego:',rp...
How to eliminate {} brackets from message box
I have script like this:rp_1st_name = 1000 rp_last_name = 2000 rp_1st_val = 5555 rp_last_val = 6666 fdh = 200 dif = (rp_1st_val - rp_last_val) - fdh teor = rp_1st_val - rp_last_val m1='wysokosc reperu poczatkowego:',rp_1st_val,'mm \n' m2='wysokosc reperu koncowego:',rp_last_val, 'mm \n' m3='przwyzszenie na ciagu: \n' m...
[ "You seem to think that\nmyvar = \"String\",value,\"more string\"\n\nresults in a string (String 5 more string) but it doesn't -\nit gives you a tuple ((\"String\", 5, \"more string\"))\nInstead, try one of\nmyvar = \"String \" + str(value) + \" more string\" # string concatenation\nmyvar = \"String %d more string...
[ 7 ]
[]
[]
[ "msgbox", "python" ]
stackoverflow_0005292462_msgbox_python.txt
Q: How to spawn Python2.5 process through Apache and return immediately under Windows I have two Python scripts, one launches the other with subprocess invoke.py: import subprocess p = subprocess.Popen(['python', 'long.py']) print "Content-Type: text/plain\n" print "invoked (%d)" % (p.pid) longtime.py: import time i...
How to spawn Python2.5 process through Apache and return immediately under Windows
I have two Python scripts, one launches the other with subprocess invoke.py: import subprocess p = subprocess.Popen(['python', 'long.py']) print "Content-Type: text/plain\n" print "invoked (%d)" % (p.pid) longtime.py: import time import os print "start (%d)" %(os.getpid()) time.sleep(10) print "end (%d)" %(os.getpid()...
[ "I've tested the code below on Windows XP and on OSX 10.6.6 (shell) and it exits without waiting for the child process to finish.\ninvoke.py:\nfrom subprocess import Popen, PIPE\nimport platform\n\n\nif platform.system() == 'Windows':\n close_fds=False\nelse: \n close_fds=True\n\np = Popen('python long.py', s...
[ 0 ]
[]
[]
[ "apache2", "python", "subprocess" ]
stackoverflow_0005285890_apache2_python_subprocess.txt
Q: Python: Removing a single element from a nested list I'm having trouble figuring out how to remove something from within a nested list. For example, how would I remove 'x' from the below list? lst = [['x',6,5,4],[4,5,6]] I tried del lst[0][0], but I get the following result: TypeError: 'str' object doesn't sup...
Python: Removing a single element from a nested list
I'm having trouble figuring out how to remove something from within a nested list. For example, how would I remove 'x' from the below list? lst = [['x',6,5,4],[4,5,6]] I tried del lst[0][0], but I get the following result: TypeError: 'str' object doesn't support item deletion. I also tried a for loop, but got the...
[ "Use the pop(i) function on the nested list. For example:\nlst = [['x',6,5,4],[4,5,6]]\nlst[0].pop(0)\nprint lst #should print [[6, 5, 4], [4, 5, 6]]\n\nDone.\n", "Your code works fine. Are you sure lst is defined as [['x',6,5,4],[4,5,6]]? Because if it is, del lst[0][0] effectively deletes 'x'.\nPerhaps you hav...
[ 4, 3, 0 ]
[]
[]
[ "del", "nested_lists", "python" ]
stackoverflow_0005292573_del_nested_lists_python.txt
Q: sqlautocode : primary key required in tables? This relates to primary key constraint in SQLAlchemy & sqlautocode. I have SA 0.5.1 & sqlautocode 0.6b1 I have a MySQL table without primary key. sqlautocode spits traceback that "could not assemble any primary key columns". Can I rectify this with a patch sothat it wi...
sqlautocode : primary key required in tables?
This relates to primary key constraint in SQLAlchemy & sqlautocode. I have SA 0.5.1 & sqlautocode 0.6b1 I have a MySQL table without primary key. sqlautocode spits traceback that "could not assemble any primary key columns". Can I rectify this with a patch sothat it will reflect tables w/o primary key? Thanks, Vineet D...
[ "I don't think so. How an ORM is suposed to persist an object to the database without any way to uniquely identify records? \nHowever, most ORMs accept a primary_key argument so you can indicate the key if it is not explicitly defined in the database.\n", "We've succeeded in faking sqa if the there's combination ...
[ 0, 0, 0 ]
[]
[]
[ "python", "turbogears", "turbogears2", "web_applications" ]
stackoverflow_0005003475_python_turbogears_turbogears2_web_applications.txt
Q: Maze not being random Hey there, I am building a program that generates a maze so I can later translate the path to my graphical part. I have most of it working, however, every time you can just take the east and south routes, and you'll get to the end. Even if I set the width as high as 64, so the maze is 64*64, ...
Maze not being random
Hey there, I am building a program that generates a maze so I can later translate the path to my graphical part. I have most of it working, however, every time you can just take the east and south routes, and you'll get to the end. Even if I set the width as high as 64, so the maze is 64*64, I'm able to choose those 2 ...
[ "You're using an iterative approach, not a recursive one like your code states!\nCheck out this series of great articles on maze generation (starting with recursive backtracking):\nhttp://weblog.jamisbuck.org/2010/12/27/maze-generation-recursive-backtracking\n", "You've got an iterative maze generator, not a recu...
[ 2, 1 ]
[]
[]
[ "backtracking", "depth_first_search", "maze", "python" ]
stackoverflow_0005292758_backtracking_depth_first_search_maze_python.txt
Q: Python O(1) member data access possible? In C++, for access to 'named' member data, we constantly do: const unsigned int CHEESE_CAKE = 0; const unsigned int CHOCOLATE_CAKE = 1; ... const unsigned int CHERRY_PIE = 1050; Then, when we want to access some specific resource matched to the string, we can simply do: mR...
Python O(1) member data access possible?
In C++, for access to 'named' member data, we constantly do: const unsigned int CHEESE_CAKE = 0; const unsigned int CHOCOLATE_CAKE = 1; ... const unsigned int CHERRY_PIE = 1050; Then, when we want to access some specific resource matched to the string, we can simply do: mResource[MyClass::CHEESE_CAKE]; // constant tim...
[ "Proper hash table implementations give amortized O(1) lookup time. You're thinking of binary search trees when you mention O(log n) time. Python name lookup is O(1).\n", "I think it's your lucky day: python dictionaries have an average complexity O(1) (see TimeComplexity on python wiki). You do not have to mod...
[ 4, 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0005293057_python.txt
Q: How to store two different values returned from query into list data types to be used later(plpy python) I need to store two values, "id" and "name" returned from sql query into a variable which I can use later. Can I use list for this purpose. I want to store values from sql at once and then only to refer to the ...
How to store two different values returned from query into list data types to be used later(plpy python)
I need to store two values, "id" and "name" returned from sql query into a variable which I can use later. Can I use list for this purpose. I want to store values from sql at once and then only to refer to the stored value. I was able to do so but with only one value (id), but now I need to store both id and name toge...
[ "I'm not sure I understand your question completely. But if you were previously storing a list of \"id\"s:\nmylist = []\nmylist.append(id1) # or however you get your id values\nmylist.append(id2)\n# ..\n\nso mylist is something like [1, 2, 3], then you can simply use tuples to store more than one element that are...
[ 1 ]
[]
[]
[ "plpy", "postgresql", "python" ]
stackoverflow_0005292952_plpy_postgresql_python.txt
Q: Python urllib2 crawler crashes router I have threaded urllib2 to pull quotes from google finance. By the time the request queue is finished and output stored about as second has elapsed before sending out the new requests, at the moment I'm just checking 10 stocks, so the thread count is 10 per sec. Although my ro...
Python urllib2 crawler crashes router
I have threaded urllib2 to pull quotes from google finance. By the time the request queue is finished and output stored about as second has elapsed before sending out the new requests, at the moment I'm just checking 10 stocks, so the thread count is 10 per sec. Although my router may not be the best, it crashes under ...
[ "I wouldn't suggest crawling anything from Google except for API's or you can expect a ban, filter or law suit (though unlikely), especially not when making something commercial and/or publicly released.\nThis seems interesting though: http://yken.org/2009/01/05/how-to-get-a-real-time-stock-quote-using-google-api/\...
[ 0 ]
[]
[]
[ "multithreading", "python", "urllib2", "web_crawler" ]
stackoverflow_0005293183_multithreading_python_urllib2_web_crawler.txt
Q: How to make it more Pythonic? I'm learning Python. I found this problem from Google Code Jam. And solved it by writing this code. It works correctly But What are the other possibilities to make this code more Pythonic, Increase Speed or in anyway better. Thanks. import sys def split_path(f,c): result_list = [...
How to make it more Pythonic?
I'm learning Python. I found this problem from Google Code Jam. And solved it by writing this code. It works correctly But What are the other possibilities to make this code more Pythonic, Increase Speed or in anyway better. Thanks. import sys def split_path(f,c): result_list = [] for i in range(c): l ...
[ "import sys\n\ndef getInts(s):\n \"Convert string to list of integers\"\n return [int(i) for i in s.strip().split()]\n\ndef getPath(s, sep='/'):\n \"Convert string to list of directory names\"\n dirs = s.strip().split(sep)\n dirs.pop(0) # remove empty root-dir string\n return dirs\n\ndef addPath(...
[ 2, 1, 1 ]
[]
[]
[ "path", "python" ]
stackoverflow_0005292968_path_python.txt
Q: Vim extension (via Python)? is it possible to extend vim functionality via custom extension (preferably, written in Python)? What I need ideally is custom command when in command mode. E.g. ESC :do_this :do_that A: vim supports scripting in python (and in perl as well, I think). You just have to make sure that t...
Vim extension (via Python)?
is it possible to extend vim functionality via custom extension (preferably, written in Python)? What I need ideally is custom command when in command mode. E.g. ESC :do_this :do_that
[ "vim supports scripting in python (and in perl as well, I think).\nYou just have to make sure that the vim distribution you are using has been compiled with python support.\nIf you are using a Linux system, you can download the source and then compile it with\n./configure --enable-pythoninterp \nmake\nsudo make ins...
[ 20, 5, 4 ]
[]
[]
[ "python", "vim" ]
stackoverflow_0000138680_python_vim.txt
Q: Download JSON data and convert it to CSV using Python I'm currently using Yahoo Pipes which provides me with a JSON file from an URL. I would like to be able to fetch it and convert it into a CSV file, and I have no idea where to begin (I'm a complete beginner in Python). How can I fetch the JSON data from the URL...
Download JSON data and convert it to CSV using Python
I'm currently using Yahoo Pipes which provides me with a JSON file from an URL. I would like to be able to fetch it and convert it into a CSV file, and I have no idea where to begin (I'm a complete beginner in Python). How can I fetch the JSON data from the URL? How can I transform it to CSV? Thank you
[ "import urllib2\nimport json\nimport csv\n\ndef getRows(data):\n # ?? this totally depends on what's in your data\n return []\n\nurl = \"http://www.yahoo.com/something\"\ndata = urllib2.urlopen(url).read()\ndata = json.loads(data)\n\nfname = \"mydata.csv\"\nwith open(fname,'wb') as outf:\n outcsv = csv.wri...
[ 6 ]
[]
[]
[ "csv", "json", "python", "yahoo_pipes" ]
stackoverflow_0005293534_csv_json_python_yahoo_pipes.txt
Q: Django User M2M relationship When trying to syncdb with the following models: class Contact(models.Model): user_from = models.ForeignKey(User,related_name='from_user') user_to = models.ForeignKey(User, related_name='to_user') class Meta: unique_together = (('user_from', 'user_to'),) User.add_...
Django User M2M relationship
When trying to syncdb with the following models: class Contact(models.Model): user_from = models.ForeignKey(User,related_name='from_user') user_to = models.ForeignKey(User, related_name='to_user') class Meta: unique_together = (('user_from', 'user_to'),) User.add_to_class('following', models.ManyT...
[ "See Carl's answer to this question Django: Model name clash\n" ]
[ 0 ]
[]
[]
[ "django", "django_models", "python" ]
stackoverflow_0002592187_django_django_models_python.txt
Q: Django Connect to MS SQL along side postgres I have a standard django setup using postgres, but I also want to access data from a mssql database. I have installed pyodbc and was in the process of installing django-pyodbc but the instructions tell me how to make the mssql the default database which is not what I wa...
Django Connect to MS SQL along side postgres
I have a standard django setup using postgres, but I also want to access data from a mssql database. I have installed pyodbc and was in the process of installing django-pyodbc but the instructions tell me how to make the mssql the default database which is not what I want. I was hoping somebody could point me in the ri...
[ "If you're using Django 1.2 or later, you can use Django's built-in multi-database support. You can follow the django-pyodbc directions, and give your database a name other than 'default'.\n" ]
[ 2 ]
[]
[]
[ "django", "pyodbc", "python", "sql" ]
stackoverflow_0005293544_django_pyodbc_python_sql.txt
Q: Importing module-under-test per test rather than module level imports? I've recently come across some unit testing code that imports the modules to test in the function to test, rather than a module level import. Then, after Googling it, I found that Pylons/Pyramid best practices reason that "import failures...sho...
Importing module-under-test per test rather than module level imports?
I've recently come across some unit testing code that imports the modules to test in the function to test, rather than a module level import. Then, after Googling it, I found that Pylons/Pyramid best practices reason that "import failures...should never prevent those tests from being run." Should that be standard prac...
[ "If you import all the modules tested at the top of the file, instead of in the unittest functions, then an import error will prevent any of your tests from running. I have two opinions about this. It depends how you're running your unittests.\nIf you're running tests on the commandline, or from Hudson or Jenkins...
[ 1 ]
[]
[]
[ "pylons", "python", "unit_testing" ]
stackoverflow_0005293791_pylons_python_unit_testing.txt
Q: Economically deleting data from app engine I have a popular social game, for which I was storing every user action as an Event entity in the data store and then once per day exporting these events from GAE for processing. Now I'd like to delete all of these entities from the data store, all 300 million of them. I ...
Economically deleting data from app engine
I have a popular social game, for which I was storing every user action as an Event entity in the data store and then once per day exporting these events from GAE for processing. Now I'd like to delete all of these entities from the data store, all 300 million of them. I started using the "datastore admin" for this. In...
[ "Presuming your goal is to delete for the cheapest cost, rather than face migration, I would launch a self-scheduling task, that would clean up several hundred/thousand keys in each run, then re-schedules itself. I would purposefully throttle this task on a separate queue so that the task ran only often enough to a...
[ 3, 3, 1, 0, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005252477_google_app_engine_python.txt
Q: Role of semi-colon in sql injection and xss attacks I've been told to use (python's) cgi.escape() function to avoid sql injections and xss attacks, although I'm sure that django automatically escapes variables. Reading about such attacks, it seems to me that the role of the semi-colon is crucial to both injecting...
Role of semi-colon in sql injection and xss attacks
I've been told to use (python's) cgi.escape() function to avoid sql injections and xss attacks, although I'm sure that django automatically escapes variables. Reading about such attacks, it seems to me that the role of the semi-colon is crucial to both injecting sql and javascript. Yet, cgi.escape doesn't seem to enc...
[ "cgi.escape is used to convert text that might contain &, <, and > characters, which generally aren't visible in HTML documents, into HTML entities that will be displayed. It has nothing whatsoever to do with preventing SQL injection, although it might help prevent XSS attacks by displaying HTML codes as text rath...
[ 3, 1 ]
[]
[]
[ "escaping", "python", "sql_injection", "xss" ]
stackoverflow_0005294185_escaping_python_sql_injection_xss.txt
Q: Socket Program Hangs I'm trying to get some basic networking going in python. Here's the snippet of the program that does the actual communication: Client Side # open socket and connect to port sock = socket(AF_INET, SOCK_STREAM) sock.connect((regHost, regPort)) # prepare f...
Socket Program Hangs
I'm trying to get some basic networking going in python. Here's the snippet of the program that does the actual communication: Client Side # open socket and connect to port sock = socket(AF_INET, SOCK_STREAM) sock.connect((regHost, regPort)) # prepare flos for data o...
[ "The error was that I forgot to add a \\n at the end of one of my strings. Due to that, the program was hanging on the call to inFlo.readline().\n" ]
[ 1 ]
[]
[]
[ "networking", "python", "sockets" ]
stackoverflow_0005294020_networking_python_sockets.txt
Q: Python: Get number of years that have passed from date string Given that I start with a string, like '3/6/2011' which is month/day/year, and the current day is 3/13/2011 (7 days later), how can I find the number of years that have passed since that time (7/365 = 0.0191780821917808) in Python? Note that I want to b...
Python: Get number of years that have passed from date string
Given that I start with a string, like '3/6/2011' which is month/day/year, and the current day is 3/13/2011 (7 days later), how can I find the number of years that have passed since that time (7/365 = 0.0191780821917808) in Python? Note that I want to be able to handle any input date. Not any format though, you can as...
[ "You can get the timedelta by subtracting two datetimes, which gives you a lot of cool ways to operate on the time difference.\n>>> import datetime\n>>> before = datetime.datetime.strptime('3/6/2011','%m/%d/%Y')\n>>> now = datetime.datetime.now()\n>>> type(now-before)\n<type 'datetime.timedelta'>\n>>> (now-before)....
[ 11, 1 ]
[]
[]
[ "datetime", "python", "string", "string_conversion", "time" ]
stackoverflow_0005294314_datetime_python_string_string_conversion_time.txt
Q: String parsing with Python I can't seem to find any docs on the parse() method for strings. Is there a good reference? I want to parse the following: frame 0 rows {3 2 3 3 3 3 2 3 2 3 3 3 2 3 2 3 4 3 3 4 3 2 2 3 3 3 2 2 2 2 3 3 3 2 3 2 3 3 3 3 4 3 4 3 3 3 3 4 3 2 3 3 3 3 2 2 2 4 4 3 3 3 3 3 4 4 4 3 2 4 3 4 3 3 3...
String parsing with Python
I can't seem to find any docs on the parse() method for strings. Is there a good reference? I want to parse the following: frame 0 rows {3 2 3 3 3 3 2 3 2 3 3 3 2 3 2 3 4 3 3 4 3 2 2 3 3 3 2 2 2 2 3 3 3 2 3 2 3 3 3 3 4 3 4 3 3 3 3 4 3 2 3 3 3 3 2 2 2 4 4 3 3 3 3 3 4 4 4 3 2 4 3 4 3 3 3 4 3 3 4 3 3 4 4 3 3 3 4 4 3 4 3...
[ "Python strings' parse() won't help you here (it has a very obscure use). In this case, I'd do it the obvious way: With regexes! If 's' is your string above,\nimport re\nlists = [\n [int(i) for i in match.split()]\n for match in re.findall(r'{(.*?)}', s)\n]\n\nprint lists\n\n", ">>> a=\"frame 0 rows {3 2 ...
[ 5, 1, 1, 0, 0 ]
[]
[]
[ "parsing", "python", "string" ]
stackoverflow_0005294004_parsing_python_string.txt
Q: Python: My server mail is sent to spam I'm trying to send email verification emails from an app I'm writing. I'm running on Linode using server = smtplib.SMTP() and server.sendmail(). For some reason, gmail is marking these messages as spam. My mail template is: {% if define('From', 'CQ <Invite@campusquery.com>') ...
Python: My server mail is sent to spam
I'm trying to send email verification emails from an app I'm writing. I'm running on Linode using server = smtplib.SMTP() and server.sendmail(). For some reason, gmail is marking these messages as spam. My mail template is: {% if define('From', 'CQ <Invite@campusquery.com>') or define('Reply-To', 'noreply@campusquery.c...
[ "What server are you sending from? There are tons of other factors involved like IP blacklists, rate of messages, whether users have marked you as spam, DNS/reverse DNS, SPF records.\nYou might consider signing up for an account with litmus.com to test your emails and see how you're performing on spam lists, and wh...
[ 1, 0 ]
[]
[]
[ "email", "python", "sendmail", "smtp", "smtplib" ]
stackoverflow_0005294154_email_python_sendmail_smtp_smtplib.txt
Q: Regular Expression and escape sequences I have a file which contains the list of regular expressions to look for in db. one such pattern is (/|\)cmd\.com$. But when i use it with re module, it throws up the below error. If i use the re pattern as (/|\\\\)cmd\.com$,it works. So, the question is when i read from a...
Regular Expression and escape sequences
I have a file which contains the list of regular expressions to look for in db. one such pattern is (/|\)cmd\.com$. But when i use it with re module, it throws up the below error. If i use the re pattern as (/|\\\\)cmd\.com$,it works. So, the question is when i read from a file in to variable for EX: a, how do i conv...
[ "First note that your original regex is invalid. It should be (/|\\\\)cmd\\.com$. If such a string is coming from a database (or any other source other than a string literal in your code), then no additional manipulation needs to be done before the regex engine sees it -- the slashes are correct.\nFull details and ...
[ 3, 1 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0005294720_python_regex.txt
Q: Python message cache for comet? I can best describe what I'm looking for with an example of a simplified version. One of the demos for Tornado is a simple chat server: https://github.com/facebook/tornado/blob/master/demos/chat/chatdemo.py I'm interested in the MessageMixin class here. It keeps a static-length back...
Python message cache for comet?
I can best describe what I'm looking for with an example of a simplified version. One of the demos for Tornado is a simple chat server: https://github.com/facebook/tornado/blob/master/demos/chat/chatdemo.py I'm interested in the MessageMixin class here. It keeps a static-length backlog of messages, and when new message...
[ "Redis has a publish/subscribe feature, along with additional data structure-oriented commands which you can use to persist and expire the message backlog, list users in a given room, or other attributes associated with them. The protocol is text-based and is a superset of the Memcached commands. \nHere is a descr...
[ 3 ]
[]
[]
[ "comet", "mq", "python", "tornado" ]
stackoverflow_0005253512_comet_mq_python_tornado.txt
Q: Dynamic Django form not only with inputs I haven't used Django for long and I have a dynamic Django form: class GoodsAddPropertyForm(forms.Form): def __init__(self, groups_and_properties, *args, **kwargs): super(GoodsAddPropertyForm, self).__init__(*args, **kwargs) for group_and_properties in g...
Dynamic Django form not only with inputs
I haven't used Django for long and I have a dynamic Django form: class GoodsAddPropertyForm(forms.Form): def __init__(self, groups_and_properties, *args, **kwargs): super(GoodsAddPropertyForm, self).__init__(*args, **kwargs) for group_and_properties in groups_and_properties: self.fields[group...
[ "Define a custom widget:\nfrom django.utils.safestring import mark_safe\n\n class HTMLWidget(forms.widgets.Widget):\n def render(self, name, value, attrs=None):\n output = []\n output.append('<p>Hello world: %s</p>' % value)\n return mark_safe(u''.join(output))\n\nThe spec...
[ 1 ]
[ "You should look at forms.MultiValueField and forms.MultiWidget. But it doesnt fine, so you have to subclass them.\n" ]
[ -1 ]
[ "django", "django_forms", "python" ]
stackoverflow_0004852695_django_django_forms_python.txt
Q: pylab in wx application when I try make a picture with pylab import pylab pylab.plot([0,1,2,3],[10,50,30,40]) pylab.savefig('graph.png') in a wx application, no returned the terminal control. A: I imagine that you are calling the wx main-loop in your main (only?) thread. However can you clarify the context of ...
pylab in wx application
when I try make a picture with pylab import pylab pylab.plot([0,1,2,3],[10,50,30,40]) pylab.savefig('graph.png') in a wx application, no returned the terminal control.
[ "I imagine that you are calling the wx main-loop in your main (only?) thread. However can you clarify the context of your code snippet? How do you make it into a \"wx application\" and why do you want terminal control? For example, do you want to see your figure on screen while also entering stuff at the termina...
[ 0 ]
[]
[]
[ "matplotlib", "python", "wxpython", "wxwidgets" ]
stackoverflow_0005245957_matplotlib_python_wxpython_wxwidgets.txt
Q: Partitioning a list based on values in tuples - Python What is the best way to go about partitioning a list of tuples in python? Currently I have a sorted list of tuples, by the second element (a value), and I want to find all values that are repeated at the beginning in an efficient manner. say: [ ("tearing", 3)...
Partitioning a list based on values in tuples - Python
What is the best way to go about partitioning a list of tuples in python? Currently I have a sorted list of tuples, by the second element (a value), and I want to find all values that are repeated at the beginning in an efficient manner. say: [ ("tearing", 3), ("me", 3), ("apart", 3), ("lisa", 3), ("denny", 0), ("m...
[ "import itertools\nimport operator\n\nL = [(\"tearing\", 3), (\"me\", 3), (\"apart\", 3), (\"lisa\", 3), (\"denny\", 0), (\"mark\",0)]\n\nprint list(itertools.groupby(L, operator.itemgetter(1)).next()[1])\n\n# [('tearing', 3), ('me', 3), ('apart', 3), ('lisa', 3)]\n\nBut really, there was no need to remind me about...
[ 4, 1, 0 ]
[]
[]
[ "list", "python", "tuples" ]
stackoverflow_0005295508_list_python_tuples.txt
Q: Can python output multiple random numbers? How can they be uniformly distributed and also be random? I have started to learn python. I am using the book "Python scripting for computational science." I am trying to write a program for "Write a script that prints a uniformly distributed random number between −1 and...
Can python output multiple random numbers? How can they be uniformly distributed and also be random?
I have started to learn python. I am using the book "Python scripting for computational science." I am trying to write a program for "Write a script that prints a uniformly distributed random number between −1 and 1. The number should be written with four decimals as implied by the %.4f format." I am using random.uni...
[ "Try that:\nfor x in range(4):\n print '%.4f' % random.uniform(1,-1)\n\nMaybe you'll enjoy the book:\nLearning Python - 4th Edition by Mark Lutz\n", "Could you be looking for something like this:\n[random.uniform(-1+x, 1+x) for x in range(10)]\n\n" ]
[ 3, 3 ]
[]
[]
[ "python", "random" ]
stackoverflow_0005295335_python_random.txt
Q: Pyramid Framework - Can you call two seperate view functions to the same template I was playing around with the pyramid framework, and I was wondering if it is possible to call two view functions to the same template: so for example: def view1(request) args1 = 'a string' return render_to_response('page.mak...
Pyramid Framework - Can you call two seperate view functions to the same template
I was playing around with the pyramid framework, and I was wondering if it is possible to call two view functions to the same template: so for example: def view1(request) args1 = 'a string' return render_to_response('page.mak',{'args1'=args1}, request=request) def view2(request) args2 = 'a string 2' re...
[ "\n{'args1'=args1}\n\nis not valid Python.\n\n{'args1':args1}\n\nis though.\n", "Yes it is. Why do you suspect this would be a problem? Have you tried it and hit some error?\n" ]
[ 6, 3 ]
[]
[]
[ "model_view_controller", "pylons", "pyramid", "python" ]
stackoverflow_0005289680_model_view_controller_pylons_pyramid_python.txt
Q: Python Virtualenv: creating python2.5 environment on ubuntu 10.04 when I try to create a virtualenv that uses python2.5 I get the following error: File "/usr/local/lib/python2.6/dist-packages/virtualenv.py", line 1489, in <module>main() File "/usr/local/lib/python2.6/dist-packages/virtualenv.py", line 526, in main...
Python Virtualenv: creating python2.5 environment on ubuntu 10.04
when I try to create a virtualenv that uses python2.5 I get the following error: File "/usr/local/lib/python2.6/dist-packages/virtualenv.py", line 1489, in <module>main() File "/usr/local/lib/python2.6/dist-packages/virtualenv.py", line 526, in main use_distribute=options.use_distribute) File "/usr/local/lib/python2.6/...
[ "I had some other Python 2.5 installed. I forgot the name but something like Python 2.5 minimal and it gave some problems with the deadsnakes install. When I uninstall it everything started working fine.\n", "You don't need two virtualenvs installed. You can tell virtualenv which python to use by using the --pyth...
[ 2, 1, 1, 0 ]
[]
[]
[ "python", "ubuntu", "virtualenv" ]
stackoverflow_0003632325_python_ubuntu_virtualenv.txt
Q: Having trouble parsing HTML I looked around and found a few examples of how to split text in python but having problems on my example. Here's what I want to parse: <img alt="" src="http://example.com/servlet/charting?base_color=grey&amp;chart_width=288&amp;chart_height=160&amp;chart_type=png&amp;chart_style=manufu...
Having trouble parsing HTML
I looked around and found a few examples of how to split text in python but having problems on my example. Here's what I want to parse: <img alt="" src="http://example.com/servlet/charting?base_color=grey&amp;chart_width=288&amp;chart_height=160&amp;chart_type=png&amp;chart_style=manufund_pie&amp;3DSet=true&amp;chart_s...
[ "Use the built-in urlparse module, do not do these splits yourself.\n>>> import urlparse\n>>> url_to_parse = \"http://example.com/servlet/charting?base_color=grey&amp;chart_width=288&amp;chart_height=160&amp;chart_type=png&amp;chart_style=manufund_pie&amp;3DSet=true&amp;chart_size=small&amp;leg_on=left&amp;static_x...
[ 7, 0, 0 ]
[]
[]
[ "html", "jython", "python" ]
stackoverflow_0005296336_html_jython_python.txt
Q: python/clojure equivalent to mathematica's NestWhileList Impetus: I was looking for something in python which would get me f([1,2,3]) == [[1,2,3], [2,3], [3]] In clojure, this would just be (nest rest #(not (empty? %)) lst), or it would if we had a nest function. Do we? I'm tired of staring at the clojure api li...
python/clojure equivalent to mathematica's NestWhileList
Impetus: I was looking for something in python which would get me f([1,2,3]) == [[1,2,3], [2,3], [3]] In clojure, this would just be (nest rest #(not (empty? %)) lst), or it would if we had a nest function. Do we? I'm tired of staring at the clojure api list.. Better approaches in python or clojure would also be appr...
[ "data = [1,2,3]\nresult = [ data[i:] for i in range(len(data)) ]\n\n", "Return seqs:\nuser> (take-while seq (iterate rest [1 2 3]))\n([1 2 3] (2 3) (3))\n\nReturn vectors:\nuser> (take-while seq (iterate #(subvec % 1) [1 2 3]))\n([1 2 3] [2 3] [3])\n\nI've seen this pattern packaged up into an iterate-while funct...
[ 3, 3, 1, 1, 1, 0 ]
[]
[]
[ "clojure", "python", "wolfram_mathematica" ]
stackoverflow_0005293176_clojure_python_wolfram_mathematica.txt
Q: WinCVS - Python - TCL I have got a list of files in txt files and I need to check them out in edit mode, and make some changes(there are word documents), and check them back in via WinCVS. I know I can write tcl scripts or macro, or python scripts in wincvs shell but I have some problems with them. I have installe...
WinCVS - Python - TCL
I have got a list of files in txt files and I need to check them out in edit mode, and make some changes(there are word documents), and check them back in via WinCVS. I know I can write tcl scripts or macro, or python scripts in wincvs shell but I have some problems with them. I have installed TCL 8.5 and selected tcl ...
[ "The problem is that Tcl's trying to build the standard file descriptors into available-by-default channels (i.e., stdin, stdout and stderr) but this goes wrong when they're not opened by default. That's the case on Windows when running disconnected (which is what happens inside GUI applications on that platform). ...
[ 1 ]
[]
[]
[ "python", "tcl", "wincvs" ]
stackoverflow_0005272116_python_tcl_wincvs.txt
Q: Python : convert unicode string to raw object/text I've got a set of key, value pairs dictionary in my Django application. The value in the dictionary is a string type. {u'question': u'forms.CharField(max_length=512)'} I need to convert this "value" string to an actual object, and get something like this. prope...
Python : convert unicode string to raw object/text
I've got a set of key, value pairs dictionary in my Django application. The value in the dictionary is a string type. {u'question': u'forms.CharField(max_length=512)'} I need to convert this "value" string to an actual object, and get something like this. properties = { 'question' : forms.CharField(max_lenth=512...
[ "If you modify your representation a bit:\nfields = {u'question': u'{\"field\": \"django.forms.CharField\", \"params\": {\"max_length\": 512}}'}\n\nthen you can use the following:\nfrom django.utils import importlib, simplejson\n\ndef get_field(fname):\n module, name = fname.rsplit('.', 1)\n return getattr(import...
[ 3, 1, 0 ]
[]
[]
[ "django", "forms", "python", "unicode" ]
stackoverflow_0005296449_django_forms_python_unicode.txt
Q: Python dbfpy and FoxPro Alright, I'm using an ancient database format here, dbf files. Don't ask why, just know a certain software decided to extend foxpro support because microsoft decided to extend foxpro support. Now, I'm getting the following error on a specific file. I have successfully loaded another file an...
Python dbfpy and FoxPro
Alright, I'm using an ancient database format here, dbf files. Don't ask why, just know a certain software decided to extend foxpro support because microsoft decided to extend foxpro support. Now, I'm getting the following error on a specific file. I have successfully loaded another file and I'm curious if there is som...
[ "Your traceback is dbfpy's way of telling you that your file has an unsupported-by-dbfpy field type code, 0. It's a Visual FoxPro (\"VFP\") thing.\nThis is nothing to do with memo files. Yes, if there are memo fields, they are stored in a .FPT file. foo.fpt needs to be present when you access foo.dbf.\nYou say \"\"...
[ 2, 0, 0 ]
[]
[]
[ "dbase", "dbf", "foxpro", "python" ]
stackoverflow_0005276641_dbase_dbf_foxpro_python.txt
Q: Gradient facecolor matplotlib bar plot How do I add a gradient facecolor to my bar plots? I want to know how to use simple one-color gradients to complex multicolor gradients. Here is some example code: import numpy as np import matplotlib.pyplot as plt plt.figure(figsize=(1,5)) plt.axis([0,1,-50,200]) plt.xticks...
Gradient facecolor matplotlib bar plot
How do I add a gradient facecolor to my bar plots? I want to know how to use simple one-color gradients to complex multicolor gradients. Here is some example code: import numpy as np import matplotlib.pyplot as plt plt.figure(figsize=(1,5)) plt.axis([0,1,-50,200]) plt.xticks([]) plt.yticks([-40,180]) plt.bar(left=0, w...
[ "import numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\n# http://matplotlib.sourceforge.net/examples/api/colorbar_only.html\n\nfig=plt.figure(figsize=(1,5))\nax=fig.add_subplot(111)\nax.axis([0,1,-50,200])\ncmap = mpl.cm.jet\nnorm = mpl.colors.Normalize(vmin=-40, vmax=180)\ncb1 = mpl.color...
[ 8 ]
[]
[]
[ "colors", "gradient", "matplotlib", "python" ]
stackoverflow_0005296335_colors_gradient_matplotlib_python.txt
Q: Django: tests.py adds project name to class In my views.py I have a piece of code that checks if a model inherits from an other model. def inherits_from_animal(some_animal): return Animal in inspect.getmro(some_animal) Now in my views.py this works but in my tests it's failing because the name of the projec...
Django: tests.py adds project name to class
In my views.py I have a piece of code that checks if a model inherits from an other model. def inherits_from_animal(some_animal): return Animal in inspect.getmro(some_animal) Now in my views.py this works but in my tests it's failing because the name of the project gets added to the class name. So if I have a pr...
[ "the inspect module is doing probably something hinky.\nPython has the builtin function issubclass() for just this occasion!\ndef inherits_from_animal(some_animal):\n return issubclass(some_animal, Animal)\n\nalthough i dont see why you couldnt just use issubclass wherever you are using inherits_from_animal now ...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0005290250_django_python.txt
Q: store the content in datastore is there a way that I can somehow get the html content from the django template . I know that I can get the content of the input type by calling self.request.get("name") in get(post) method <input type="text" name="name"> but how about the other types like <div>hello</div> what i...
store the content in datastore
is there a way that I can somehow get the html content from the django template . I know that I can get the content of the input type by calling self.request.get("name") in get(post) method <input type="text" name="name"> but how about the other types like <div>hello</div> what if I want to store the html(hello) of ...
[ "HTML content exists on the client and is not sent to the server.\nIf you want to, you can send the HTML content to the server using AJAX.\n", "In that way. You can use the jquery ajax form submit plugin. You can see some examples Here.\n", "you can work with jquery ajax ,fetch from server data and then send da...
[ 0, 0, 0 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0005290772_google_app_engine_python.txt