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:
Digital Image cropping in Python
Got this question from a professor, a physicist.
I am a beginner in Python programming. I am not a computer professional I am a physicist. I was trying to write a code in python for my own research which involves a little image processing.
All I need to do is to display an image an... | Digital Image cropping in Python | Got this question from a professor, a physicist.
I am a beginner in Python programming. I am not a computer professional I am a physicist. I was trying to write a code in python for my own research which involves a little image processing.
All I need to do is to display an image and then select a region of interest usi... | [
"While I agree with David that you should probably just use GIMP or some other image manipulation program, here is a script (as I took it to be an exercise to the reader) using pygame that does what you want. You will need to install pygame as well as the PIL, usage would be:\nscriptname.py <input_path> <output_pa... | [
6,
4,
2,
2,
0
] | [] | [] | [
"image_processing",
"python"
] | stackoverflow_0000601874_image_processing_python.txt |
Q:
Help Translate this query into Django ORM
I have a Friendship model with two related user objects associated with it. I would like to write a method that takes a user and returns a list of that user's friends. I was doing it via:
friends = Friendship.objects.filter(Q(user1=user) | Q(user2=user))
friends_list =... | Help Translate this query into Django ORM | I have a Friendship model with two related user objects associated with it. I would like to write a method that takes a user and returns a list of that user's friends. I was doing it via:
friends = Friendship.objects.filter(Q(user1=user) | Q(user2=user))
friends_list = [f.user1 if user == f.user2 else f.user2 for f... | [
"Assuming you set up your Friendship model similar to the example below and use friend_set as the related name of the from_friend field in your model, getting a list of a users friends can be as simple as a basic list comprehension:\nfriends = [friendship.to_friend for friendship in user.friend_set.all()]\n\nThis w... | [
0
] | [] | [] | [
"django",
"orm",
"python",
"sql"
] | stackoverflow_0006879991_django_orm_python_sql.txt |
Q:
How do you escape a binary file for sqlite3 in python?
The python sqlite3 documentation gives this example for inserting parameters into an SQL query.
for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
... | How do you escape a binary file for sqlite3 in python? | The python sqlite3 documentation gives this example for inserting parameters into an SQL query.
for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
('2006-04-06', 'SELL', 'IBM', 500, 53.00),
]:
c.execute('insert into stocks values (?,?,?,?,?... | [
"Insert binary data just as you would for any other type of field:\ncontents = open(image_path, \"rb\").read()\nc.execute('insert into images values (?, ?)', (image_path, contents))\n\n"
] | [
2
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0006880096_python_sqlite.txt |
Q:
Is a hmac-sha1 hash always 20 bytes long? Python code
Is the digest always 20 bytes long? len(hashed.digest()) seems to always be 20.
hashed = hmac.new(key, signature_base_string, sha)
print hashed.digest()
print len(hashed.digest())
i = 0
for c in hashed.digest():
i = i + 1
print ord(c)
print base64.b... | Is a hmac-sha1 hash always 20 bytes long? Python code | Is the digest always 20 bytes long? len(hashed.digest()) seems to always be 20.
hashed = hmac.new(key, signature_base_string, sha)
print hashed.digest()
print len(hashed.digest())
i = 0
for c in hashed.digest():
i = i + 1
print ord(c)
print base64.b64encode(hashed.digest())
| [
"All hashing functions have fixed length outputs. SHA1 is 160 bits, or 20 bytes.\n",
"Yes. SHA1 HMAC hash is always 160 bits (e.g. 20 bytes).\n",
"SHA-1 always returns 160 bits, or 20 bytes.\nhttp://www.itl.nist.gov/fipspubs/fip180-1.htm\n\"For a message of length < 2^64 bits, the SHA-1 produces a 160-bit conde... | [
11,
2,
2
] | [] | [] | [
"hmacsha1",
"python"
] | stackoverflow_0006880514_hmacsha1_python.txt |
Q:
is there any simple library for producing pdf from text file in python?
I am newbie here. How to generate whole text file into pdf using python. Is there any sample code? After search on Google, I only find pdf to text converter module. My python version is 2.5. Thanks.
A:
reportlab is the traditional Python pdf... | is there any simple library for producing pdf from text file in python? | I am newbie here. How to generate whole text file into pdf using python. Is there any sample code? After search on Google, I only find pdf to text converter module. My python version is 2.5. Thanks.
| [
"reportlab is the traditional Python pdf solution.\n"
] | [
4
] | [] | [] | [
"module",
"pdf",
"python",
"text"
] | stackoverflow_0006880691_module_pdf_python_text.txt |
Q:
numpy arbitrary precision linear algebra
I have a numpy 2d array [medium/large sized - say 500x500]. I want to find the eigenvalues of the element-wise exponent of it. The problem is that some of the values are quite negative (-800,-1000, etc), and their exponents underflow (meaning they are so close to zero, so t... | numpy arbitrary precision linear algebra | I have a numpy 2d array [medium/large sized - say 500x500]. I want to find the eigenvalues of the element-wise exponent of it. The problem is that some of the values are quite negative (-800,-1000, etc), and their exponents underflow (meaning they are so close to zero, so that numpy treats them as zero). Is there anywa... | [
"SymPy can calculate arbitrary precision:\nfrom sympy import exp, N, S\nfrom sympy.matrices import Matrix\n\ndata = [[S(\"-800.21\"),S(\"-600.00\")],[S(\"-600.00\"),S(\"-1000.48\")]]\nm = Matrix(data)\nex = m.applyfunc(exp).applyfunc(lambda x:N(x, 100))\nvecs = ex.eigenvects()\nprint vecs[0][0] # eigen value\nprint... | [
20,
14,
8
] | [
"So you need 350 digits of precision. You will not get that with IEEE floating point numbers (what numpy is using). You can get it with the bc program:\n$ bc -l\nbc 1.06\nCopyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.\nThis is free software with ABSOLUTELY NO WARRANTY.\nFor details type `warra... | [
-3,
-5
] | [
"arbitrary_precision",
"linear_algebra",
"math",
"numpy",
"python"
] | stackoverflow_0006876377_arbitrary_precision_linear_algebra_math_numpy_python.txt |
Q:
How can I use json module in google app engine?
Possible Duplicate:
How can I parse JSON in Google App Engine?
json module was added in python 2.6 but GAE supports 2.5 only.
How can I use it there?
A:
Well you wotn be able to use the standard python library, you will have to use some third party lib such as
... | How can I use json module in google app engine? |
Possible Duplicate:
How can I parse JSON in Google App Engine?
json module was added in python 2.6 but GAE supports 2.5 only.
How can I use it there?
| [
"Well you wotn be able to use the standard python library, you will have to use some third party lib such as\n\njyson or\nsimplejson\n\nAt least simplejson works on python 2.4\n",
"You can try using yaml module (which is included in GAE) as JSON parser. YAML in recent version is superset of JSON.\n>>> import yaml... | [
2,
0,
0
] | [] | [] | [
"google_app_engine",
"json",
"python",
"python_2.5"
] | stackoverflow_0002511653_google_app_engine_json_python_python_2.5.txt |
Q:
selectively enabling a test program if Python is available - automake
I've got a program that's written in C, built using automake/autoconf, and has two test suites. One is a unit test suite also written in C; the other is end-to-end and is (currently) written in Python. I want "make check" to run the unit tests... | selectively enabling a test program if Python is available - automake | I've got a program that's written in C, built using automake/autoconf, and has two test suites. One is a unit test suite also written in C; the other is end-to-end and is (currently) written in Python. I want "make check" to run the unit tests always, and the end-to-end tests only if Python is installed. This is wha... | [
"You must use _SOURCES for compiled things only, so that's why it'a adding $(EXEEXT). Try this:\nTESTS = unittests\nif HAVE_PYTHON\nTESTS += tester.py\n# Possibly use += here depending on the rest of your Makefile.am\ncheck_SCRIPTS = tester.py\n# I added $(srcdir) here so VPATH builds still work.\ntester.py: $(srcd... | [
5
] | [] | [] | [
"automake",
"portability",
"python"
] | stackoverflow_0006878756_automake_portability_python.txt |
Q:
How to search for string in Python by removing line breaks but return the exact line where the string was found?
I have a bunch of PDF files that I have to search for a set of keywords against. I have to extract the exact line where the keyword was found. I first used xpdf's pdf2text to convert the file to PDF. (T... | How to search for string in Python by removing line breaks but return the exact line where the string was found? | I have a bunch of PDF files that I have to search for a set of keywords against. I have to extract the exact line where the keyword was found. I first used xpdf's pdf2text to convert the file to PDF. (Tried solr but had a tough time tailoring the output/schema to suit my requirement).
import sys
file_name = sys.argv[... | [
"There may be a better way of doing it, but my suggestion would be to start by taking in two lines (let's call them line1 and line2), concatenating them into line3 or something similar, and then search that resultant line.\nThen you'd assign line2 to line1, get a new line2, and repeat the process.\n",
"Note: Some... | [
1,
1,
0
] | [] | [] | [
"file",
"keyword",
"python",
"string"
] | stackoverflow_0006874609_file_keyword_python_string.txt |
Q:
Re-ordering a Linked List in Python
I realize this sort of data structure is better done with built in list type, but I'm trying to understand this more for academic reasons. Given that I have a linked list like this:
a -> b -> c -> d -> e -> f
I would like to change the references to
b -> a -> d -> c -> f -> e
In... | Re-ordering a Linked List in Python | I realize this sort of data structure is better done with built in list type, but I'm trying to understand this more for academic reasons. Given that I have a linked list like this:
a -> b -> c -> d -> e -> f
I would like to change the references to
b -> a -> d -> c -> f -> e
In other words every pair gets switched. I ... | [
"Sometimes the best thing is to first think \"how fast would an optimal solution be?\" This seems pretty apparently O(length), so something that runs through the list, preferably once, is going to be about as good as you can do.\nGiven that, you're probably going to find the simplest choice is best. In pseudocode... | [
3,
2
] | [] | [] | [
"data_structures",
"linked_list",
"python"
] | stackoverflow_0006878550_data_structures_linked_list_python.txt |
Q:
httplib2 on twisted way
How can I convert the httplib2 part to a "twisted" way?
from twisted.python import log, usage
from twisted.internet import reactor
from twisted.internet.serialport import SerialPort
from twisted.web.client import Agent
from struct import unpack
import httplib2
import sys
class JamesOpti... | httplib2 on twisted way | How can I convert the httplib2 part to a "twisted" way?
from twisted.python import log, usage
from twisted.internet import reactor
from twisted.internet.serialport import SerialPort
from twisted.web.client import Agent
from struct import unpack
import httplib2
import sys
class JamesOptions(usage.Options):
optPa... | [
"Use twisted.web.client.Agent().request(). It will return a Deferred.\nSee the Agent howto for more details and examples.\n"
] | [
2
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0006880689_python_twisted.txt |
Q:
Is there a point to dependency injection container in Python?
Been messing about with python, as usual it throws my rigid static typed Object Oriented world in to a bit of a mess. Python supports duck typing, has no usable concept of interface based programming (as in C# interfaces) and allows Global variables. Wi... | Is there a point to dependency injection container in Python? | Been messing about with python, as usual it throws my rigid static typed Object Oriented world in to a bit of a mess. Python supports duck typing, has no usable concept of interface based programming (as in C# interfaces) and allows Global variables. With all these goodies is there really any point to a dependency inje... | [
"\nhas no usable concept of interface based programming (as in C# interfaces)\n\nJust because the compiler can't check that you're using the interface correctly doesn't mean there's \"no usable concept of interfaces\". You document an interface, and write unit tests.\nAs for globals, it's not like public static met... | [
13,
8
] | [] | [] | [
"dependency_injection",
"python"
] | stackoverflow_0006880884_dependency_injection_python.txt |
Q:
Mac to Windows Python
I have recently moved a set of near identical programs from my mac to my school's windows, and while the paths appear to be the same (or the tail end of them), they will not run properly.
import glob
import pylab
from pylab import *
def main():
outfnam = "igdata.csv"
fpout = open(out... | Mac to Windows Python | I have recently moved a set of near identical programs from my mac to my school's windows, and while the paths appear to be the same (or the tail end of them), they will not run properly.
import glob
import pylab
from pylab import *
def main():
outfnam = "igdata.csv"
fpout = open(outfnam, "w")
nrows = 0
... | [
"If the script doesn't raise any errors, this piece of code is most likely returning an empty list.\nglob.glob(\"c/Cmos6_*.IG\")\n\nSeeing as glob.glob works perfectly fine with forward slashes on Windows, the problem is most likely that it's not finding the files, which most likely means that the string you provid... | [
3,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0006879340_python.txt |
Q:
Why hash (without using a salt) random numbers?
The following snippet of code is in php but I've seen developers of other web programming languages hash random numbers.
if ($loginValid=='yes') {
$token = sha256(generateRandomNumber());
$_SESSION["token"] = $token;
$_SESSION["userid"] = $id;
setcook... | Why hash (without using a salt) random numbers? | The following snippet of code is in php but I've seen developers of other web programming languages hash random numbers.
if ($loginValid=='yes') {
$token = sha256(generateRandomNumber());
$_SESSION["token"] = $token;
$_SESSION["userid"] = $id;
setcookie("authenticationtoken", $token, ...)
}
sha256 is a... | [
"My guess is that it's just a simple way of getting a hash of a known size, independently of the size that generateRandomNumber() returns. Obviously if generateRandomNumber() has a small range, that will be reflected in the number of distinct hashes returned too.\n",
"Assuming that GenerateRandomNumber does not h... | [
4,
1
] | [] | [] | [
"asp.net",
"javascript",
"php",
"python",
"ruby_on_rails"
] | stackoverflow_0006881650_asp.net_javascript_php_python_ruby_on_rails.txt |
Q:
Indention Error in django python code
I am getting an Indention Error. This code is straight from the django first tutorial.
class ChoiceInline(admin.StackedInline):
model = Choice
extra = 3
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
... | Indention Error in django python code | I am getting an Indention Error. This code is straight from the django first tutorial.
class ChoiceInline(admin.StackedInline):
model = Choice
extra = 3
class PollAdmin(admin.ModelAdmin):
fieldsets = [
(None, {'fields': ['question']}),
('Date information', {'fields': ['pub_dat... | [
"Works fine for me on python2.7, make sure you didn't mix tabs and spaces in your actual code. There is also an extra comma at the end of the second line in fieldsets, but that should be fine in python.\n"
] | [
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0006881930_django_python.txt |
Q:
Not creating elements when using if / else in python dictionary
Hi,
I'm using if / else conditions to create elements in a dictionnary, such as
x = {
'id' : id,
'image' : res['image'] if 'image' in res.keys() else '',
}
Is there a way to not create a image key in the second case ? I cannot remove the else cla... | Not creating elements when using if / else in python dictionary |
Hi,
I'm using if / else conditions to create elements in a dictionnary, such as
x = {
'id' : id,
'image' : res['image'] if 'image' in res.keys() else '',
}
Is there a way to not create a image key in the second case ? I cannot remove the else clause, but would like to keep that way of creating the dictionary rath... | [
"Python doesn't provide the syntactic sugar to do what you want, but you can slightly change the if statement to fit on one line\nif 'image' in res.keys(): x['image'] = image\n\n",
"If you declare a key for a dictioanry, you have to set a value to that so,if you define 'image' you have to set a value for it...\n... | [
1,
0
] | [] | [] | [
"dictionary",
"if_statement",
"python"
] | stackoverflow_0006882075_dictionary_if_statement_python.txt |
Q:
calling locals() in a function nested in a class method
Here is a snippet:
class Foo(object):
def bar(self, x):
def baz(y):
print locals()['self']
..
return baz(..)
foo = Foo()
foo.bar(..)
I have 2 boxes. On Windows Vista with Python 2.5 calling foo.bar(..) works. On Ubunt... | calling locals() in a function nested in a class method | Here is a snippet:
class Foo(object):
def bar(self, x):
def baz(y):
print locals()['self']
..
return baz(..)
foo = Foo()
foo.bar(..)
I have 2 boxes. On Windows Vista with Python 2.5 calling foo.bar(..) works. On Ubuntu with Python 2.7 calling foo.bar(..) throws a KeyError, not ... | [
"Admitting that you can compute the variables dict before running bad, you can use this:\nclass Foo(object):\n def bar(self, x):\n outer_locals = locals()\n def baz(y):\n print outer_locals['self']\n ..\n return baz(..)\n\nIf, instead, you have to compute the dictionary at ... | [
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0006881282_python.txt |
Q:
HTML input array parsing in Python (GAE)
I'm two days in to Python and GAE, thanks in advance for the help.
I have an input array in HTML like this:
<input type="text" name="p_item[]">
<input type="text" name="p_item[]">
<input type="text" name="p_item[]">
I want to parse the input in Python, and I'm trying this,... | HTML input array parsing in Python (GAE) | I'm two days in to Python and GAE, thanks in advance for the help.
I have an input array in HTML like this:
<input type="text" name="p_item[]">
<input type="text" name="p_item[]">
<input type="text" name="p_item[]">
I want to parse the input in Python, and I'm trying this, which isn't working:
items = self.request.get... | [
"Change your html to this\n<input type=\"text\" name=\"p_item\">\n<input type=\"text\" name=\"p_item\">\n<input type=\"text\" name=\"p_item\">\n\nand use the self.request.get_all() method http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html#Request_get_all\np.s. For reference, there is no con... | [
5,
0
] | [] | [] | [
"arrays",
"google_app_engine",
"html",
"input",
"python"
] | stackoverflow_0006881221_arrays_google_app_engine_html_input_python.txt |
Q:
Why am I not allowed to have multiple assignments in for each loop with different lengths of lists in python
Just like I'm allowed to do this:
(EDIT - I'm NOT allowed to do this either, sorry messed up, but anyway I guess my question is more on the lines of how to go about doing parallel assignments in a loop)
fo... | Why am I not allowed to have multiple assignments in for each loop with different lengths of lists in python | Just like I'm allowed to do this:
(EDIT - I'm NOT allowed to do this either, sorry messed up, but anyway I guess my question is more on the lines of how to go about doing parallel assignments in a loop)
for (x,i) in ([0,1,2],[3,4,5]):
# do something
why am I not allowed to do this in a for each loop (different list... | [
"For this kind of stuff, itertools is your friend.\nIn your case, itertools.islice() will do the trick:\nimport itertools\nfor key in itertools.islice(sorted(dict.keys(), key=custom_sort), 10):\n # Only the first 10 keys are processed.\n\nAlternatively, if you need the index as well, use zip or itertools.izip:\n... | [
2,
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006882346_python.txt |
Q:
public string blaBla { get; set; } in python
Consider the following example to understand better my question:
public class ClassName
{
public ClassName { }
public string Val { get; set; }
...
}
ClassName cn = new ClassName();
cn.Val = "Hi StackOverflow!!";
What would be the equivalent of this cod... | public string blaBla { get; set; } in python | Consider the following example to understand better my question:
public class ClassName
{
public ClassName { }
public string Val { get; set; }
...
}
ClassName cn = new ClassName();
cn.Val = "Hi StackOverflow!!";
What would be the equivalent of this code in python?
| [
"You can easily add members to any Python object as show in other answers. For more complicated get/set methods like in C#, see the property builtin:\nclass Foo(object):\n def __init__(self):\n self._x = 0\n\n def _get_x(self):\n return self._x\n\n def _set_x(self, x):\n self._x = x\n\n def ... | [
6,
2,
0
] | [] | [] | [
"c#",
"class",
"equivalent",
"methods",
"python"
] | stackoverflow_0006882792_c#_class_equivalent_methods_python.txt |
Q:
why does this code do not work? (python)
class MyClass:
def __init__(self):
pass
val = ""
def getval(self):
# code to get val
# ... and at the end:
self.val = "bla bla"
self.getval()
print val
Now at this point it says that the name self is not fou... | why does this code do not work? (python) | class MyClass:
def __init__(self):
pass
val = ""
def getval(self):
# code to get val
# ... and at the end:
self.val = "bla bla"
self.getval()
print val
Now at this point it says that the name self is not found. If I try only getval() (without the self p... | [
"Here is a example that makes slightly more sense:\nclass MyClass:\n def __init__(self):\n pass\n\n # this is a class variable\n val = \"\"\n\n def getval(self):\n # code to get val \n # ... and at the end:\n self.val = \"bla bla\"\n return self.val\n\n# make ... | [
6,
1
] | [] | [] | [
"class",
"methods",
"python"
] | stackoverflow_0006882957_class_methods_python.txt |
Q:
accessing *args from within a function in Python
Hi everyone this is probably something extremely simple that i'm overlooking but can someone point me in the right direction for how to handle this problem.
def nodeFunction(self,*args):
return self[1] + self[2]
Basically what I am trying to do is grab the ... | accessing *args from within a function in Python | Hi everyone this is probably something extremely simple that i'm overlooking but can someone point me in the right direction for how to handle this problem.
def nodeFunction(self,*args):
return self[1] + self[2]
Basically what I am trying to do is grab the data passed in through the arguments. I am just stuck ... | [
"args is simply a tuple:\ndef nodeMethod(self, *args):\n return args[0], args[1]\n\nIs that what you mean?\nNote that there's nothing special about \"args\". You could use any variable name. It's the * operator that counts. \n>>> class Node(object):\n... def nodeMethod(self, *cornucopia):\n... return... | [
23,
5
] | [] | [] | [
"args",
"arguments",
"function",
"python"
] | stackoverflow_0006883033_args_arguments_function_python.txt |
Q:
Python lists comparing and merging
I have 2 lists:
correct_list = [1,2,3,4,5,6,7,8,9,10]
other_list = [4,5,6,7,8,10]
I would like to combine these two lists so:
combined_list = [{k:1, v:0},{k:2, v:0},{k:3, v:0}, {k:4, v:4}, {etc}]
so basically am saying that the key is the correct list, and where ever the other_... | Python lists comparing and merging | I have 2 lists:
correct_list = [1,2,3,4,5,6,7,8,9,10]
other_list = [4,5,6,7,8,10]
I would like to combine these two lists so:
combined_list = [{k:1, v:0},{k:2, v:0},{k:3, v:0}, {k:4, v:4}, {etc}]
so basically am saying that the key is the correct list, and where ever the other_list does not match the correct_list, fi... | [
"[{'k': c, 'v': c if c in other_list else 0} for c in correct_list]\n\nBy the way, if the only elements of the dictionaries are k and v, consider building a dictionary instead of a list of dictionaries:\n>>> dict((c, c if c in other_list else 0) for c in correct_list)\n{1: 0, 2: 0, 3: 0, 4: 4, 5: 5, 6: 6, 7: 7, 8: ... | [
4
] | [] | [] | [
"compare",
"list",
"python"
] | stackoverflow_0006883096_compare_list_python.txt |
Q:
python stop selenium standalone server
How would I stop the selenium-server-standalone. I know you can start it by java -jar selenium-server-standalone.jar But how would you stop it? Also, is there a simple way to script it in python to start and stop it as I am running tests.I feel like this is pretty simple. But... | python stop selenium standalone server | How would I stop the selenium-server-standalone. I know you can start it by java -jar selenium-server-standalone.jar But how would you stop it? Also, is there a simple way to script it in python to start and stop it as I am running tests.I feel like this is pretty simple. But am unable to find the answer to my question... | [
"You can start the server with subprocess.Popen, and shut it down with sel.shut_down_selenium_server():\nimport selenium\nimport socket\nimport subprocess\nimport shlex\nimport sys\nimport time\n\n# CHANGE path='/path/to/selenium-server.jar' AS NEEDED:\ndef start_server(path='/path/to/selenium-server.jar'):\n ... | [
3
] | [] | [] | [
"python",
"selenium"
] | stackoverflow_0006881500_python_selenium.txt |
Q:
Regex to extract URLs from href attribute in HTML with Python
Possible Duplicate:
What is the best regular expression to check if a string is a valid URL?
Considering a string as follows:
string = "<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://2.example">Even More Examples</a>"
... | Regex to extract URLs from href attribute in HTML with Python |
Possible Duplicate:
What is the best regular expression to check if a string is a valid URL?
Considering a string as follows:
string = "<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://2.example">Even More Examples</a>"
How could I, with Python, extract the URLs, inside the anchor tag'... | [
"import re\n\nurl = '<p>Hello World</p><a href=\"http://example.com\">More Examples</a><a href=\"http://2.example\">Even More Examples</a>'\n\nurls = re.findall('https?://(?:[-\\w.]|(?:%[\\da-fA-F]{2}))+', url)\n\n>>> print urls\n['http://example.com', 'http://2.example']\n\n",
"The best answer is...\nDon't use a... | [
182,
68
] | [] | [] | [
"python",
"regex",
"url"
] | stackoverflow_0006883049_python_regex_url.txt |
Q:
Configuring extension modules with distutils/setuptools
I have a Python project with mutiple extension modules written in C, which talk to a third-party library. However, depending on the user's environment and options some modules should not be built, and some compiler flags should be enabled/disabled. The prob... | Configuring extension modules with distutils/setuptools | I have a Python project with mutiple extension modules written in C, which talk to a third-party library. However, depending on the user's environment and options some modules should not be built, and some compiler flags should be enabled/disabled. The problem is that I have to build the list of extension modules bef... | [
"\nIs there a preferred way to do this?\n\nFrom my experience working with other people's modules, I can say there is certainly not consensus on the right way to do this.\nI have tried and rejected subclassing bits of distutils -- I found it fragile and difficult to get working across different Python versions and ... | [
1,
0,
0,
0
] | [] | [] | [
"distutils",
"python",
"setuptools"
] | stackoverflow_0001930900_distutils_python_setuptools.txt |
Q:
django-tagging install fails
i am getting this error while installing django-tagging,
krisdigitx-Satellite-Pro-L450D django-tagging # python setup.py install
Traceback (most recent call last):
File "setup.py", line 49, in <module>
version_tuple = __import__('tagging').VERSION
File "/home/site/krisdigitx/dj... | django-tagging install fails | i am getting this error while installing django-tagging,
krisdigitx-Satellite-Pro-L450D django-tagging # python setup.py install
Traceback (most recent call last):
File "setup.py", line 49, in <module>
version_tuple = __import__('tagging').VERSION
File "/home/site/krisdigitx/django-tagging/tagging/__init__.py",... | [
"export PYTHONPATH=/path/to/your/krisdigitx\n"
] | [
0
] | [] | [] | [
"python"
] | stackoverflow_0006883348_python.txt |
Q:
Accessing objects added to the Tkinter root
Let's say that I have the following code:
root = Tk()
open = Button(self.root, text='Open', command=self.open, state='disabled')
open.pack()
close = Button(self.root, text='Close', command=self.close, state='disabled')
close.pack()
I only want to enable the buttons when... | Accessing objects added to the Tkinter root | Let's say that I have the following code:
root = Tk()
open = Button(self.root, text='Open', command=self.open, state='disabled')
open.pack()
close = Button(self.root, text='Close', command=self.close, state='disabled')
close.pack()
I only want to enable the buttons when some action is performed, so I need to access th... | [
"Since you are using the pack method you can use the pack_slaves method to find items added. So to iterate over them you can do something like,\nfor item in root.pack_slaves():\n item.do_stuff()\n\n",
"There is no definitive way to ask the root window for a list of all widgets. You can use pack_slaves or grid... | [
1,
1,
0
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006879781_python_tkinter.txt |
Q:
Running subset of auto-discovered python unittests
Short Question
Is it possible to select, at run time, what unittests are going to be run when using an auto-discovery method in Python's unittest module.
Background
I am using the unittest module to run system tests on an external system. See below for an examp... | Running subset of auto-discovered python unittests | Short Question
Is it possible to select, at run time, what unittests are going to be run when using an auto-discovery method in Python's unittest module.
Background
I am using the unittest module to run system tests on an external system. See below for an example sudo-testcase. The unittest module allows me to crea... | [
"Store each subset of tests in its own module. Get a list of module names by having the user select them using, as you stated, checkboxes or text entry. Once you have the list of module names, you can build a corresponding test suite doing something similar to the following.\ntestsuite = unittest.TestSuite()\nfor m... | [
1
] | [] | [] | [
"python",
"unit_testing"
] | stackoverflow_0006880508_python_unit_testing.txt |
Q:
Calling a GWT RPC function from Python-mechanize
I am getting a 500 : Internal error, the payload of the POST is definately right, one thing I noticed is the Content-Type is not "sticking" using b.addheaders = [('Content-Type',"text-x-gwt-rpc")] -- and I'm not sure why.
Does anyone have quick/dirty code used to ac... | Calling a GWT RPC function from Python-mechanize | I am getting a 500 : Internal error, the payload of the POST is definately right, one thing I noticed is the Content-Type is not "sticking" using b.addheaders = [('Content-Type',"text-x-gwt-rpc")] -- and I'm not sure why.
Does anyone have quick/dirty code used to access a GWT RPC (i.e. emulate the GWT client) in Python... | [
"Do not use GWT-RPC from non-GWT solutions, the format is internal and subject to change without notice. Consider RESTifying the app (or use SOAP and reuse the existing code of the methods, but care needs to be given to the interface definitions).\n",
"The answer to the question is GWT requires the content-type t... | [
0,
0
] | [] | [] | [
"gwt",
"gwt_rpc",
"python"
] | stackoverflow_0006880142_gwt_gwt_rpc_python.txt |
Q:
Get friendly URLs with Python or .htaccess
using Python on a Linux server, I would like to use "smart URLs" also known as "semantic/friendly/SEO URLs" to get content from a python script. But I don't want to create all the files (one for each items depending on the URL subpath).
The data to use are stored in a p... | Get friendly URLs with Python or .htaccess | using Python on a Linux server, I would like to use "smart URLs" also known as "semantic/friendly/SEO URLs" to get content from a python script. But I don't want to create all the files (one for each items depending on the URL subpath).
The data to use are stored in a python dictionary and here is the file location:
... | [
"With htaccess you can use this rule\nRewriteEngine On\nRewriteRule ^blog/([0-9]+)$ /blog/data.py?article=$1 [L]\n\n",
"Use a web framework. Even a minimal one like Flask will give you proper URL routing with the ability to define your own URL patterns. Plus, it'll almost certainly work much faster than executing... | [
4,
4
] | [] | [] | [
".htaccess",
"friendly_url",
"python",
"redirect"
] | stackoverflow_0006883855_.htaccess_friendly_url_python_redirect.txt |
Q:
Use Thread in Pygtk
I'm in a project to develop a chat application like netmeeting. I want to separate thread one is for GUI (gtk.main) another is simultaneously accepting client chat request (socket.accept) . But there is a problem..
here is my simple line of code which is 2nd thread for accepting client request:... | Use Thread in Pygtk | I'm in a project to develop a chat application like netmeeting. I want to separate thread one is for GUI (gtk.main) another is simultaneously accepting client chat request (socket.accept) . But there is a problem..
here is my simple line of code which is 2nd thread for accepting client request:
while True:
self.new... | [
"Have a look at PyGTK FAQ. In particular, I suggest the gobject.idle_add() approach. When your second thread needs any GUI interaction, schedule some code running in the main thread with `gobject.idle_add(), sort of like this:\ndef ask_close ():\n self.CloseDialog.run ()\ngobject.idle_add (ask_close)\n\nThen y... | [
1
] | [] | [] | [
"multithreading",
"python",
"sockets"
] | stackoverflow_0006882467_multithreading_python_sockets.txt |
Q:
Python, beginner's question! Repository or Object persisting itself?
I am a seasoned .Net developer who's trying to write some Python code. On one of the projects I am contributing to, we have a services layer which is a set of classes which abstract away functionality and a django web app which consumes these in ... | Python, beginner's question! Repository or Object persisting itself? | I am a seasoned .Net developer who's trying to write some Python code. On one of the projects I am contributing to, we have a services layer which is a set of classes which abstract away functionality and a django web app which consumes these in process services (which are just classes).
I had created a repository laye... | [
"Maybe that is a Django pattern, but not a Python one by all means. \nThat said, if the target audience of your module are Django developers, I would advise you to follow as much as possible the Django philosophy and its associated patterns.\n",
"Django's ORM provides save() and delete() methods on the object. SQ... | [
3,
2,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0005462635_python.txt |
Q:
Reference Parameters in Python
I am using a custom SDK for a WWAN card. I want to be able to access the functions from the dll in python. I have read up on loading the dll and accessing the functions.
The part I am stuck on is using the functions that have reference parameters and arrays and using them in python. ... | Reference Parameters in Python | I am using a custom SDK for a WWAN card. I want to be able to access the functions from the dll in python. I have read up on loading the dll and accessing the functions.
The part I am stuck on is using the functions that have reference parameters and arrays and using them in python.
Here is the documentation page for ... | [
"Well, I think pDevicesSize should be integer, \nand pDevices should be a list of objects whose class have deviceId(str) and deviceKey(str) as properties.\n",
"Declaring a structure in the proper device format and passing that will make it easier to process the devices when they are returned. Here's an example:\... | [
0,
0
] | [] | [] | [
"ctypes",
"python",
"sdk"
] | stackoverflow_0006878255_ctypes_python_sdk.txt |
Q:
Error: Invalid Syntax on "def"
So I'm getting Invalid Syntax where it says def before the add_entry function. I have no idea why. I tried commenting out, and then there was the same error on a different function. I'm using Python 2.7.
date,number = 0,1
month,day,year = 1,2,0
from datetime import datetime
def home... | Error: Invalid Syntax on "def" | So I'm getting Invalid Syntax where it says def before the add_entry function. I have no idea why. I tried commenting out, and then there was the same error on a different function. I'm using Python 2.7.
date,number = 0,1
month,day,year = 1,2,0
from datetime import datetime
def home():
option = ''
option = raw... | [
"Your print statement in view_log has an extra [\nIt should be\n print line[date[month]],line[date[day]],line[date[year]],line[number]\n\n"
] | [
12
] | [] | [] | [
"python"
] | stackoverflow_0006884764_python.txt |
Q:
Problems getting Django up and running on OSX
First, I'm following the tutorial on the Django Poll application on their site and have hit a few road blocks.
I've installed Python 2.7 and Django 1.3
Created a new project with
django-admin.py startproject myproject
I got mysql up and running and entered the creden... | Problems getting Django up and running on OSX | First, I'm following the tutorial on the Django Poll application on their site and have hit a few road blocks.
I've installed Python 2.7 and Django 1.3
Created a new project with
django-admin.py startproject myproject
I got mysql up and running and entered the credentials in settings.py
Then when I try to run
python ... | [
"jondavidjohn's comment is spot on: you will have no end of confusion with multiple versions of Python on the Mac. There are some things you can do to deal with this.\n\nStick with 2.6 \nConvert to Lion, which has 2.7 \nAdd an alias to your shell environment to invoke version 2.7 with $ python. In my bash_profile, ... | [
2,
0
] | [] | [] | [
"django",
"easy_install",
"mysql_python",
"python"
] | stackoverflow_0006883967_django_easy_install_mysql_python_python.txt |
Q:
PostgreSQL connection closes unexpectedly when doing a large insert
I'm populating a PostgreSQL table with ~11.000.000 rows that have been selected before from another database. I'm using Python and psycopg2. The whole process takes an estimated 1.5 hours to complete. However, after ~30 minutes I get "connection c... | PostgreSQL connection closes unexpectedly when doing a large insert | I'm populating a PostgreSQL table with ~11.000.000 rows that have been selected before from another database. I'm using Python and psycopg2. The whole process takes an estimated 1.5 hours to complete. However, after ~30 minutes I get "connection closed unexpectedly" exception. The source code looks like this:
incursor ... | [
"I don't know of any such \"hidden\" timeout in postgresql itself. PostgreSQL does have statement_timeout, but if you hit that you should get a ERROR: canceling statement due to statement timeout in the server log (and it will log the cancelled statement too). I can't speak for psycopg2. Definitely check the serve... | [
5,
0,
0
] | [] | [] | [
"postgresql",
"psycopg",
"python"
] | stackoverflow_0005089825_postgresql_psycopg_python.txt |
Q:
Can mmap and gzip collaborate?
I'm trying to figure how to use mmap with a gzip compressed file. Is that even possible ?
import mmap
import os
import gzip
filename = r'C:\temp\data.gz'
file = gzip.open(filename, "rb+")
size = os.path.getsize(filename)
file = mmap.mmap(file.fileno(), size)
print file.read(8)
... | Can mmap and gzip collaborate? | I'm trying to figure how to use mmap with a gzip compressed file. Is that even possible ?
import mmap
import os
import gzip
filename = r'C:\temp\data.gz'
file = gzip.open(filename, "rb+")
size = os.path.getsize(filename)
file = mmap.mmap(file.fileno(), size)
print file.read(8)
The output data is compressed.
| [
"You can do easilly. Indeed the gzip module gets as optional argument a file-like object.\nimport mmap\nimport gzip\n\nfilename = \"a.gz\"\nhandle = open(filename, \"rb\")\nmapped = mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ)\ngzfile = gzip.GzipFile(mode=\"r\", fileobj=mapped)\n\nprint gzfile.read()\n\nT... | [
18,
17
] | [] | [] | [
"gzip",
"mmap",
"python"
] | stackoverflow_0005127921_gzip_mmap_python.txt |
Q:
Having some trouble with Learn Python The Hard Way Excercise 48
In the section we are given a series of unit tests and need to create a function that will make the tests pass. Here is the test:
from nose.tools import *
from testing import *
def test_numbers():
assert_equal(scan("1234"), [('number', 1234)])
... | Having some trouble with Learn Python The Hard Way Excercise 48 | In the section we are given a series of unit tests and need to create a function that will make the tests pass. Here is the test:
from nose.tools import *
from testing import *
def test_numbers():
assert_equal(scan("1234"), [('number', 1234)])
result = scan("3 91234")
assert_equal(result, [('number', 3),
... | [
"Just add @staticmethod above def scan(s): to make it work.\n",
"I suspect that you certainly want def scan(self, s): instead of def scan(s):.\n"
] | [
1,
0
] | [] | [] | [
"python",
"python_2.7"
] | stackoverflow_0006885147_python_python_2.7.txt |
Q:
Why is my django snippet not working?
I put together a function to link to news items with django as a filter. It works on dev_appserver but on production server it returns None Can you tell me why it's not working? Should I investigate the except clause of the code where it currently just passes?
def news(n):
... | Why is my django snippet not working? | I put together a function to link to news items with django as a filter. It works on dev_appserver but on production server it returns None Can you tell me why it's not working? Should I investigate the except clause of the code where it currently just passes?
def news(n):
url = os.environ.get('HTTP_HOST') if os.en... | [
"Python functions that don't explicitly return anything will return None. If this code is returning None on your production server, it's probably because it's hitting that last except: pass block, as you mentioned.\nWithout reading the actual code (which I haven't), I'd say replace that pass with return '' to safel... | [
2
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0006881897_django_google_app_engine_python.txt |
Q:
Track a file [C++ or Python]
How can I "track" a file using C++, or Python (I'm guessing C++ will be way more powerfull. Just putting Python in there in case there is a way with it, which would be simpler than C++).
When I mean track, I mean registering any moving of the file to a different path, changes in name, ... | Track a file [C++ or Python] | How can I "track" a file using C++, or Python (I'm guessing C++ will be way more powerfull. Just putting Python in there in case there is a way with it, which would be simpler than C++).
When I mean track, I mean registering any moving of the file to a different path, changes in name, etc. Changes in the actual content... | [
"(migrated from comment)\nYou can do that using launchd on OS X. Check out: Is there a command like \"watch\" or \"inotifywait\" on the Mac?\n"
] | [
0
] | [] | [] | [
"c++",
"file",
"path",
"python",
"tracking"
] | stackoverflow_0006882944_c++_file_path_python_tracking.txt |
Q:
Spelling suggestions module in pure Python (for GAE)?
Could you recommend me a spelling suggestion library that can be used in Google App Engine (pure python).
Before moving to GAE we were using aspell-python.
UPDATE
What about some spelling API (e.g. google, yahoo, bing)?
A:
I would have a look to whoosh for Ap... | Spelling suggestions module in pure Python (for GAE)? | Could you recommend me a spelling suggestion library that can be used in Google App Engine (pure python).
Before moving to GAE we were using aspell-python.
UPDATE
What about some spelling API (e.g. google, yahoo, bing)?
| [
"I would have a look to whoosh for App Engine.\nIt offers a pure-python spell checker.\n"
] | [
0
] | [] | [] | [
"aspell",
"google_app_engine",
"python",
"spell_checking"
] | stackoverflow_0006884353_aspell_google_app_engine_python_spell_checking.txt |
Q:
Python3 obtain keys from values?
It seems like this is a common problem, but I can't seem to find a solution.
I have a Python3 script containing two dictionaries sqldict and hitsdict. This code outputs dictionary values, if sqldict[value][0] == hitsdict[thing][1].
for value in sqldict:
for thing in hitsdi... | Python3 obtain keys from values? | It seems like this is a common problem, but I can't seem to find a solution.
I have a Python3 script containing two dictionaries sqldict and hitsdict. This code outputs dictionary values, if sqldict[value][0] == hitsdict[thing][1].
for value in sqldict:
for thing in hitsdict:
if sqldict[value][0] =... | [
"A dictionary lookup is \"by key\" not \"by value.\"\n>>> d = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}\n>>> for key in d:\n... print key\n... \nkey3\nkey2\nkey1\n\nI'm sorry, but I can't think of any other answer but \"You are doin it rong!\"\n",
"You are finding values by looping through the it... | [
1,
1,
0
] | [] | [] | [
"dictionary",
"python",
"python_3.x"
] | stackoverflow_0006884753_dictionary_python_python_3.x.txt |
Q:
Reading columns of a csv file with python
I am using python's CSV module to iterate over the rows of a column.
What I need to do is:
Get the first row for column "title"
Remove any spanish characters (accents, Ñ)
Remove single quotes
Finally, replace spaces with dashes and convert everything to lowercase.
I got ... | Reading columns of a csv file with python | I am using python's CSV module to iterate over the rows of a column.
What I need to do is:
Get the first row for column "title"
Remove any spanish characters (accents, Ñ)
Remove single quotes
Finally, replace spaces with dashes and convert everything to lowercase.
I got this to work with a simple test file,not a csv.... | [
"line is a dict. Probably you want to call replace on line['title']. \n",
"With the new information at hand, I think you might find this method to be simpler.\nUse the inbuilt function 'map'. I'll leave the explanation of what 'map' does to the python documentation.\nHere is what I think you should do\nCreate a ... | [
1,
1,
0
] | [] | [] | [
"csv",
"python"
] | stackoverflow_0006884737_csv_python.txt |
Q:
How to use pagination in class-based generic views?
I try to implement pagination to class-based generic view and in way I did it, it's not works.
urls
url(r'^cat/(?P<category>[\w+\s]*)/page(?P<page>[0-9]+)/$',
CategorizedPostsView.as_view(), {'paginate_by': 3}),
view
class CategorizedPostsView(ListView):
... | How to use pagination in class-based generic views? | I try to implement pagination to class-based generic view and in way I did it, it's not works.
urls
url(r'^cat/(?P<category>[\w+\s]*)/page(?P<page>[0-9]+)/$',
CategorizedPostsView.as_view(), {'paginate_by': 3}),
view
class CategorizedPostsView(ListView):
template_name = 'categorizedposts.djhtml'
context_ob... | [
"hey there is already a kwarg paginate_by for the ListView so just pass it in.\ntry something like this:\nurl(r'^cat/(?P<category>[\\w+\\s]*)/page(?P<page>[0-9]+)/$',\n CategorizedPostsView.as_view(paginate_by=3)),\n\nand for your template you could try something like:\n{% if is_paginated %}\n <div class=\"pa... | [
4
] | [] | [] | [
"django",
"django_generic_views",
"django_pagination",
"python"
] | stackoverflow_0006884752_django_django_generic_views_django_pagination_python.txt |
Q:
Pygame Error: Video System not Initialized
I have used Pygame with python 2.7 before but recently I 'upgraded' to python 3.2. I downloaded and installed the newest version of Pygame which is said to work with this version of python. I have, however, had this rather frustrating error on what should be a simple bloc... | Pygame Error: Video System not Initialized | I have used Pygame with python 2.7 before but recently I 'upgraded' to python 3.2. I downloaded and installed the newest version of Pygame which is said to work with this version of python. I have, however, had this rather frustrating error on what should be a simple block of code. The code is:
import pygame, random
t... | [
"if event.type == pygame.quit():\n\nIn the line above, you're calling pygame.quit() which is a function, while what you really want is the constant pygame.QUIT. By calling pygame.quit(), pygame is no longer initialized, which is why you get that error.\nThus, changing the line to:\nif event.type == pygame.QUIT: # N... | [
16
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0006881482_pygame_python.txt |
Q:
Class or Metaclass Design for Astrodynamics Engine
Gurus out there:
The differential equations for modeling spacecraft motion can be described in terms of a collection of acceleration terms:
d2r/dt2 = a0 + a1 + a2 + ... + an
Normally a0 is the point mass acceleration due to a body (a0 = -mu * r/r^3); the "higher... | Class or Metaclass Design for Astrodynamics Engine | Gurus out there:
The differential equations for modeling spacecraft motion can be described in terms of a collection of acceleration terms:
d2r/dt2 = a0 + a1 + a2 + ... + an
Normally a0 is the point mass acceleration due to a body (a0 = -mu * r/r^3); the "higher order" terms can be due to other planets, solar radiati... | [
"PyDSTool lets you build up \"components\" that have spatial or physical meaning, and have mathematical expressions associated with them, into bigger components that know how to sum things up etc. The result is a way to specify differential equations in a modular fashion using symbolic tools, and then PyDSTool will... | [
2,
1,
1,
0
] | [] | [] | [
"math",
"oop",
"physics",
"python",
"simulation"
] | stackoverflow_0002000979_math_oop_physics_python_simulation.txt |
Q:
Calling a Method in Python more Efficiently
I'm a newb working through Learn Python the Hard Way.
The point of this exercise is to write a word scanner for that passes the nosetests when run by a provided unit test.
While running nosetests on the following provided unit test I was getting this error:
`TypeError: u... | Calling a Method in Python more Efficiently | I'm a newb working through Learn Python the Hard Way.
The point of this exercise is to write a word scanner for that passes the nosetests when run by a provided unit test.
While running nosetests on the following provided unit test I was getting this error:
`TypeError: unbound method scan() must be called with lexicon ... | [
"In the online version of Learn Python The Hard Way they have:\ndef test_directions():\n assert_equal(lexicon.scan(\"north\"), [('direction', 'north')])\n result = lexicon.scan(\"north south east\")\n assert_equal(result, [('direction', 'north'),\n ('direction', 'south'),\n ... | [
4,
2
] | [] | [] | [
"methods",
"nosetests",
"python",
"unit_testing"
] | stackoverflow_0006886028_methods_nosetests_python_unit_testing.txt |
Q:
How can I search a file for all text lines prefaced with numbers in a certain format and move them to a new line
I'm searching a flat text file version of the KJV bible for a word or group of words to get a match that returns the line, the book, chapter, and the verse that the word was found. My problem is that I ... | How can I search a file for all text lines prefaced with numbers in a certain format and move them to a new line | I'm searching a flat text file version of the KJV bible for a word or group of words to get a match that returns the line, the book, chapter, and the verse that the word was found. My problem is that I had to manually find the line number that each book started with and put them in a dictionary, but I didn't consider, ... | [
"This is a fairly complex problem. Being so and not knowing Python, below is a Perl\nsolution that features one, of possibly many, regex solutions. Its what I came up\nwith in 5 minutes, I'm sure it can be refactored to be more efficient, but you should\nget the drift.\nuse strict;\nuse warnings;\n\nmy $str = '\n1:... | [
2,
1,
1,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0006885788_python_regex.txt |
Q:
Python - Pycrypto - Sending encrypted data over network
I am trying to get 2 programs to share encrypted data over a network using public keys, but I am stuck with a difficult problem : the information that is shared (the keys and/or the encrypted data) seems to get modified. I am hoping to keep the encrypted data... | Python - Pycrypto - Sending encrypted data over network | I am trying to get 2 programs to share encrypted data over a network using public keys, but I am stuck with a difficult problem : the information that is shared (the keys and/or the encrypted data) seems to get modified. I am hoping to keep the encrypted data format as well as the format of the keys as simple as possib... | [
"You're right about which line is the source of the problem.\nconnexion.send(str(enc_data))\n\nenc_data here is a tuple, the first (and in fact only) element of which is a string containing the actual ciphertext. When you are calling str on it, you're getting Python's attempt to convert the tuple to a string, which... | [
5
] | [] | [] | [
"file",
"networking",
"public_key_encryption",
"pycrypto",
"python"
] | stackoverflow_0006886240_file_networking_public_key_encryption_pycrypto_python.txt |
Q:
python - how does split method work?
Anyone knows how does the split function work in python? I mean, does it read the string char by char and then evaluates the code or it has another way of working? I've read the doc but it doesn't mention.
EDIT
For those who are curious like me, just check here. It should be on... | python - how does split method work? | Anyone knows how does the split function work in python? I mean, does it read the string char by char and then evaluates the code or it has another way of working? I've read the doc but it doesn't mention.
EDIT
For those who are curious like me, just check here. It should be on the 147th line as Chris stated.
| [
"If you check out the python source code (I used 2.7.1, but I doubt the location changed in the 3.x series), the full implementation can be found at $src_dir/Objects/stringlib/split.h. The function's name is stringlib_split and in 2.7.1 can be found on line 147.\n",
"Speaking as of 3.2, there are several split() ... | [
3,
3
] | [] | [] | [
"methods",
"python",
"split"
] | stackoverflow_0006886544_methods_python_split.txt |
Q:
Argument parsing with python decorators
I was wondering if it's possible to wrap some class methods with a decorator that parses the arguments before sending it to the function. for example:
class integer(int):
def __init__(self, value=0)
self.value = value
for m in ['__add__','... | Argument parsing with python decorators | I was wondering if it's possible to wrap some class methods with a decorator that parses the arguments before sending it to the function. for example:
class integer(int):
def __init__(self, value=0)
self.value = value
for m in ['__add__','__sub__','__mul__']:#and so on
... | [
"def magic_decorator(method):\n def fun(self, arg):\n if (type(arg) == str):\n arg = int(arg)\n return getattr(int, method)(self, arg)\n return fun\n\nclass integer(int):\n pass\n\nfor m in ['__add__','__sub__','__mul__']:\n setattr(integer, m, magic_decorator(m))\n\ni = integer... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0006886600_python.txt |
Q:
Rewriting A Custom PHP App on a framework. Torn between Python (Django) and PHP (CodeIgniter)
I was thinking of rewriting my custom PHP app on a framework... mainly for the solidity and more ease of growth going forward. Right now its a pseudo MVC setup with lots of hacks in between.
I already have the db built o... | Rewriting A Custom PHP App on a framework. Torn between Python (Django) and PHP (CodeIgniter) | I was thinking of rewriting my custom PHP app on a framework... mainly for the solidity and more ease of growth going forward. Right now its a pseudo MVC setup with lots of hacks in between.
I already have the db built out and the app uses a lot of AJAX too.
I am not concerned with the amount of work involved as the s... | [
"Which language do you prefer? That's all that really matters. Both have solid frameworks and similar performance. If you want to increase performance, writing more efficient code is going to make a way bigger difference.\nPersonally, I like python. Django is great, but you might also consider Flask or Pyramid/P... | [
0,
0
] | [] | [] | [
"django",
"php",
"python"
] | stackoverflow_0006886699_django_php_python.txt |
Q:
How to search values in a dictionary in python
I have a big csv files with the following format:
CSV FILE 1
id, person, city
1, John, NY
2, Lucy, Miami
3, Smith, Los Angeles
4, Mike, Chicago
5, David, Los Angeles
6, Daniel, NY
On another CSV file I have each city with a numerical co... | How to search values in a dictionary in python | I have a big csv files with the following format:
CSV FILE 1
id, person, city
1, John, NY
2, Lucy, Miami
3, Smith, Los Angeles
4, Mike, Chicago
5, David, Los Angeles
6, Daniel, NY
On another CSV file I have each city with a numerical code:
CSV FILE 2
city , code
NY , 100
Miami, 101
L... | [
"You have some extra whitespace there, and unlike some storage formats, CSV does care about it. If that is actually in your source data, you may have to strip it out before it will be processed as you expect (otherwise various fields will have leading and trailing whitespace).\nAssuming that the whitespace is gone,... | [
8,
2,
1
] | [] | [] | [
"csv",
"list",
"python"
] | stackoverflow_0006886757_csv_list_python.txt |
Q:
Issue with Python data-mining code from "Programming Collective Intelligence" to count crossed lines
I'm currently working through Toby Segaran's Programming Collective Intelligence and trying to do work through some of the code in the optimisation chapter, specifically the counting lines code. However I have come... | Issue with Python data-mining code from "Programming Collective Intelligence" to count crossed lines | I'm currently working through Toby Segaran's Programming Collective Intelligence and trying to do work through some of the code in the optimisation chapter, specifically the counting lines code. However I have come across two issues in the code which I don't quite understand.
The code
def crosscount(v):
loc = dict(... | [
"Well ipe, i read this book, I searched trought my test codes and I found how it worked for me, the graph score function follows:\ndef graphscore(v, proxlimit = 50):\nloc = dict([(people[i], (v[i*2], v[i*2+1])) for i in range(0, len(people))])\ntotal = 0.0\n\n#penalize crosscount\nfor i in range(len(links)):\n f... | [
2
] | [] | [] | [
"data_mining",
"python"
] | stackoverflow_0006885575_data_mining_python.txt |
Q:
compile cgal-python
I tried to build cgal-python and had the following errors (just a snippet):
In file included from /opt/local/include/boost/config.hpp:40,
from /opt/local/include/CGAL/config.h:37,
from /opt/local/include/CGAL/basic.h:28,
from Kernel_module.cpp:21,
... | compile cgal-python | I tried to build cgal-python and had the following errors (just a snippet):
In file included from /opt/local/include/boost/config.hpp:40,
from /opt/local/include/CGAL/config.h:37,
from /opt/local/include/CGAL/basic.h:28,
from Kernel_module.cpp:21,
from All_files_at_on... | [
"I upgraded XCode to 4.1 and now the above errors are gone.\n"
] | [
1
] | [] | [] | [
"c++",
"cgal",
"macos",
"python"
] | stackoverflow_0006882999_c++_cgal_macos_python.txt |
Q:
Problem with Button Command Tkinter Python
So I have this program that searches the SEC Edgar database for annual reports (10-K's), and returns a list of 40 different items in a listbox. Well I want to create a 'Next 40' button which displays the next 40 items in the listbox, which the following code accomplishes:... | Problem with Button Command Tkinter Python | So I have this program that searches the SEC Edgar database for annual reports (10-K's), and returns a list of 40 different items in a listbox. Well I want to create a 'Next 40' button which displays the next 40 items in the listbox, which the following code accomplishes:
def Next():
global entryWidget
page = 'http:/... | [
"Use an Application class instead of globals. Currently you're always downloading the first page. But your application class should cache the 'soup' of the current page, which next uses to get the onClick value from the \"Next 40\" form button:\nclass Application(Frame):\n def __init__(self, parent=None):\n ... | [
1
] | [] | [] | [
"button",
"python",
"tkinter"
] | stackoverflow_0006884928_button_python_tkinter.txt |
Q:
pygame for python on virtual (VMWare) Windows XP on Mac OS10.6.8
I'm running Python 2.7 on Windows XP as a virtual machine on my Macbook (OS 10.6.8) using VMWare.
I'm going through the python/pygame video tutorials at thenewboston.com and am running the following code:
bif="bg.jpg"
mif="ball.png"
import pygame, s... | pygame for python on virtual (VMWare) Windows XP on Mac OS10.6.8 | I'm running Python 2.7 on Windows XP as a virtual machine on my Macbook (OS 10.6.8) using VMWare.
I'm going through the python/pygame video tutorials at thenewboston.com and am running the following code:
bif="bg.jpg"
mif="ball.png"
import pygame, sys
from pygame.locals import *
pygame.init()
screen = pygame.display... | [
"I don't know much about the behaviour on virtual machines so I can't really help you there. But it might help you to say that I did try your code on my Linux machine and the program do work as expected with the image following the mouse.\nSo, given that, you are probably right that there's something strange happen... | [
0,
0
] | [] | [] | [
"pygame",
"python"
] | stackoverflow_0006885618_pygame_python.txt |
Q:
What would be better for Django comet?
Django + Orbited + Stomppy server +
Apache
OR
Django + Eventlet + Spawning web
server
Orbited and Stomppy seems out of date...is that correct?
Or if someone has a better solution (with a good tutorial, please) , please list it.
A:
If you don't require comet specificall... | What would be better for Django comet? |
Django + Orbited + Stomppy server +
Apache
OR
Django + Eventlet + Spawning web
server
Orbited and Stomppy seems out of date...is that correct?
Or if someone has a better solution (with a good tutorial, please) , please list it.
| [
"If you don't require comet specifically, I'd recommend checking out Cody Soyland's Django + gevent + Socket.io. I've got a little app running using this technique, and I also implemented a similar server using tornado (with the tornadio socket.io server tacked on) but in the end gevent was a better fit for my proj... | [
0
] | [] | [] | [
"ajax",
"django",
"javascript",
"python"
] | stackoverflow_0005787134_ajax_django_javascript_python.txt |
Q:
elegantly splitting a list (or dict) into two via some arbitrary function in python
Is there any elegant way of splitting a list/dict into two lists/dicts in python, taking in some arbitrary splitter function?
I could easily have two list comprehensions, or two selects, but it seems to me there should be some bet... | elegantly splitting a list (or dict) into two via some arbitrary function in python | Is there any elegant way of splitting a list/dict into two lists/dicts in python, taking in some arbitrary splitter function?
I could easily have two list comprehensions, or two selects, but it seems to me there should be some better way of doing it that avoids iterating over every element twice.
I could do it easily ... | [
"How about 3 lines?\nfatcows, thincows = {}, {}\nfor name, weight in cows.items():\n (fatcows if weight > 50 else thincows)[name] = weight\n\nTested:\n>>> cows = {'bessie':53, 'maud':22, 'annabel': 77, 'myrna':43 }\n>>> fatcows, thincows = {}, {}\n>>> for name, weight in cows.items():\n... (fatcows if weight... | [
6,
5,
3,
3,
2,
1
] | [] | [] | [
"dictionary",
"list_comprehension",
"python",
"select"
] | stackoverflow_0006887095_dictionary_list_comprehension_python_select.txt |
Q:
Nested dictionary with duplicate keys but different values
I'm having a hard time returning the values of each instance of $t in the nested dictionary below. What I need to do is pull each of the key-value pairs and add them individually to another dictionary.
Here's the JSON:
"breed": [
{
... | Nested dictionary with duplicate keys but different values | I'm having a hard time returning the values of each instance of $t in the nested dictionary below. What I need to do is pull each of the key-value pairs and add them individually to another dictionary.
Here's the JSON:
"breed": [
{
"$t": "Chihuahua"
},
{
... | [
"Something like this?\n>>> o = [ { \"$t\": \"Chihuahua\" }, { \"$t\": \"Jack Russell Terrier\" } ]\n>>> [ item[\"$t\"] for item in o ]\n['Chihuahua', 'Jack Russell Terrier']\n>>>\n\n",
"Is this what you are looking for? (It depends I think on how you want to handle the multiple values corresponding to the same $t... | [
1,
0,
0
] | [] | [] | [
"dictionary",
"json",
"python"
] | stackoverflow_0006885335_dictionary_json_python.txt |
Q:
Getting blank image when using imgur's API
I'm currently developing a small script to take screenshots and upload them to imgur using Python.
The code looks like this:
import time
import os
import ImageGrab
import urllib
import urllib2
time.sleep(1)
shot = ImageGrab.grab()
dir = os.path.join(r'C:\SAMPLE\PATH', 'S... | Getting blank image when using imgur's API | I'm currently developing a small script to take screenshots and upload them to imgur using Python.
The code looks like this:
import time
import os
import ImageGrab
import urllib
import urllib2
time.sleep(1)
shot = ImageGrab.grab()
dir = os.path.join(r'C:\SAMPLE\PATH', 'Screen ' + time.strftime(r'%Y-%m-%d %H-%M-%S') + ... | [
"You should use b64encode from the base64 module. I don't know why, but it gives different results:\nfrom base64 import b64encode\n\n(...)\n\ndata = urllib.urlencode({\"key\":'MY_API_KEY', \"image\":urllib.quote(b64encode(open(dir,'rb').read()))})\n\n"
] | [
0
] | [] | [] | [
"imgur",
"python",
"urllib2"
] | stackoverflow_0006887291_imgur_python_urllib2.txt |
Q:
Python Two-Dimensional Query..
I am seeing a very unusual behavior in python.. Kindly let me know what am i doing wrong!!
bc = [[0]*(n+1)]*(n+1)
for i in range(n+1):
bc[i][i] = 1
print (bc)
Output
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
I am trying to initialize the diagonal elemen... | Python Two-Dimensional Query.. | I am seeing a very unusual behavior in python.. Kindly let me know what am i doing wrong!!
bc = [[0]*(n+1)]*(n+1)
for i in range(n+1):
bc[i][i] = 1
print (bc)
Output
[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]
I am trying to initialize the diagonal elements of two dimensional array to 1, bu... | [
"Your array is initialized incorrectly. The correct way to initialize a 2d array is this:\nbc = [[0 for i in xrange(n + 1)] for i in xrange(n + 1)]\n\nIt's a common mistake, but the * operator copies the pointer to an list rather than copying the list, so while it looks like you have a 2d list, you actually have a ... | [
6,
3,
0
] | [] | [] | [
"multidimensional_array",
"python"
] | stackoverflow_0006888241_multidimensional_array_python.txt |
Q:
The complexity of member looking up: Python Vs. Javascript
I am curious about the complexity of Python and JS 's looking up:
Python supports multi-inheritance, which affects the member lookup. Specifically, when referencing a member from an instance of a class, the process will start from the instance's dict, the... | The complexity of member looking up: Python Vs. Javascript | I am curious about the complexity of Python and JS 's looking up:
Python supports multi-inheritance, which affects the member lookup. Specifically, when referencing a member from an instance of a class, the process will start from the instance's dict, then to the class of the instance, then up to the super classes of ... | [
"You're missing the fact that MI is very, very rarely used in Python, usually only for mixins where the inheritance chain tends to be very short anyways.\n"
] | [
3
] | [] | [] | [
"javascript",
"python"
] | stackoverflow_0006888332_javascript_python.txt |
Q:
python Django model indentation error
from django.db import models
class Category(models.Model):
title = models.CharField(max_length=250)
slug = models.SlugField(unique=True)
description = models.TextField()
class Meta:
verbose_name_plural = "Categories"
def __uni... | python Django model indentation error | from django.db import models
class Category(models.Model):
title = models.CharField(max_length=250)
slug = models.SlugField(unique=True)
description = models.TextField()
class Meta:
verbose_name_plural = "Categories"
def __unicode__(self):
return self.title
I ... | [
"class Meta:\n verbose_name_plural = \"Categories\"\n\nYou are not indenting correctly after class Meta:.\n",
"it should be \n from django.db import models\n\n class Category(models.Model):\n title = models.CharField(max_length=250)\n slug = models.SlugField(unique=True)\n descriptio... | [
5,
3
] | [] | [] | [
"django",
"indentation",
"python"
] | stackoverflow_0006888430_django_indentation_python.txt |
Q:
2D Game Programming for Linux, OSX, and Windows - C++/Python/OpenGL?
A friend of mine is making the jump from graphic designer to game developer, and I have decided to work with him in my free time. Neither of us have much development experience, but I am very interested in learning Python, and my friend wants to ... | 2D Game Programming for Linux, OSX, and Windows - C++/Python/OpenGL? | A friend of mine is making the jump from graphic designer to game developer, and I have decided to work with him in my free time. Neither of us have much development experience, but I am very interested in learning Python, and my friend wants to learn C++.
I have read that C++ is the common denominator in game programm... | [
"There's actually a handy set of libraries and modules for Python, pygame, that is extremely useful, well documented and has a ton of community support and a lot of fun games have been built with it. And the best part, to answer part of your question, is that OpenGL is not required.\nAnd, because it's based on Pyth... | [
5,
2,
1,
1,
0,
0
] | [] | [] | [
"c++",
"opengl",
"python"
] | stackoverflow_0006886553_c++_opengl_python.txt |
Q:
Dynamic text tagging with tkinter
What I couldn't figure out is how to dynamically tag ranges of text with the Tkinter text widget.
The idea is that when the user selects a range of text, it dynamically creates a tag to modify the style.
Here's my code:
#...code...
tag = text_field.tag_ranges(SEL)
text_field.tag_a... | Dynamic text tagging with tkinter | What I couldn't figure out is how to dynamically tag ranges of text with the Tkinter text widget.
The idea is that when the user selects a range of text, it dynamically creates a tag to modify the style.
Here's my code:
#...code...
tag = text_field.tag_ranges(SEL)
text_field.tag_add('sizesel',tag[0],tag[1])
text_field.... | [
"If you want a unique style for each range you'll need to use a unique tag, because style information belongs to the tag rather than the range of text. The easiest method is to keep a global (or instance attribute) counter that you increment each time you add a tag, and use that as part of the tag name. \n",
"Her... | [
2,
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0006885842_python_tkinter.txt |
Q:
Plotting lines with gnuplot python
I have a list:
x = [1,2,3,4]
Now using gnuplot, I have plotted the points as (0,1), (1,2), ...
Here is the syntax I used:
g = Gnuplot.Gnuplot()
g.plot(x)
Now I have my required set of points but I want to join these points by a line. How do I do that?
A:
Does the following wo... | Plotting lines with gnuplot python | I have a list:
x = [1,2,3,4]
Now using gnuplot, I have plotted the points as (0,1), (1,2), ...
Here is the syntax I used:
g = Gnuplot.Gnuplot()
g.plot(x)
Now I have my required set of points but I want to join these points by a line. How do I do that?
| [
"Does the following work for you?\n>>> import Gnuplot\n>>> x = [1,2,3,4]\n>>> gp = Gnuplot.Gnuplot()\n>>> gp.title('My title')\n>>> gp('set style data linespoints')\n>>> gp.plot(x)\n\nYou can pass whatever options you want in the 5th command.\n"
] | [
3
] | [] | [] | [
"gnuplot",
"python"
] | stackoverflow_0006888580_gnuplot_python.txt |
Q:
Python run Popen( ) subprocess with elevated UAC privleges
Possible Duplicate:
Request UAC elevation from within a Python script?
I'd like to execute a series of Java processes from a Python script, but I must run the Java with elevated UAC privleges (as Administrator) in order to get the results I'm expecting. ... | Python run Popen( ) subprocess with elevated UAC privleges |
Possible Duplicate:
Request UAC elevation from within a Python script?
I'd like to execute a series of Java processes from a Python script, but I must run the Java with elevated UAC privleges (as Administrator) in order to get the results I'm expecting. My call right now is basically:
from subprocess import Popen
ca... | [
"I'm afraid that you cannot use Popen for that.\nOne option would be using win32api.ShellExecute and setting runas argument to Administrator.\nAnother option would be using JPython itself...\n"
] | [
3
] | [] | [] | [
"python",
"subprocess",
"uac",
"windows"
] | stackoverflow_0006888551_python_subprocess_uac_windows.txt |
Q:
AJAX web applications with no hand-written JavaScript
I'm looking for solutions that make it possible to create AJAX-enabled web applications without need to write JavaScript code manually. The requirements are:
Performance doesn't matter. It can be slow, JavaScript may be unoptimized, amount of code it generates... | AJAX web applications with no hand-written JavaScript | I'm looking for solutions that make it possible to create AJAX-enabled web applications without need to write JavaScript code manually. The requirements are:
Performance doesn't matter. It can be slow, JavaScript may be unoptimized, amount of code it generates may be large.
Platform doesn't matter as long as I can wor... | [
"I think GWT is perfect for you.\nHere is why to choose GWT.\n",
"I went with JSF 2 in combination with PrimeFaces to program my first website with AJAX. PrimeFaces is phenomenal and easy to use, no hand-written JavaScript necessary. They have a Showcase on their site. \n",
"I'd recommend you GWT from Google. I... | [
3,
2,
2,
1
] | [] | [] | [
"c#",
"java",
"javascript",
"python"
] | stackoverflow_0006888856_c#_java_javascript_python.txt |
Q:
Python, calling mmap with too-large address causes overflow exception
I am converting some C code that accesses a device driver via mmap. I thought I could easily do very similar things in Python. However I've run into this issue. The address that needs to be mmap'ed is provided by the PCI configuration, so I h... | Python, calling mmap with too-large address causes overflow exception | I am converting some C code that accesses a device driver via mmap. I thought I could easily do very similar things in Python. However I've run into this issue. The address that needs to be mmap'ed is provided by the PCI configuration, so I have no control over this address. In this case, the address found is 34519... | [
"I had a similar problem once, I also wanted to mmap a bigger-then-4GB chunk of data on a 64bit machine into a 64bit-compiled Python.\nIf I remember correctly the main reason it it did not work out was, that most fundamental python-object struct contains an object size member, which is only 32bit. And to change thi... | [
1
] | [] | [] | [
"posix",
"python"
] | stackoverflow_0006741633_posix_python.txt |
Q:
Why does pprint module sorts dict keys differently from print?
pprint sorts dicts keys alphabetically, print sorts them in default order.
from pprint import pprint
d = {'foo': 1, 'bar': 2, 'baz': 3}
pprint(d)
# {'bar': 2, 'baz': 3, 'foo': 1}
print d
# {'baz': 3, 'foo': 1, 'bar': 2}
The documentation of pprint m... | Why does pprint module sorts dict keys differently from print? | pprint sorts dicts keys alphabetically, print sorts them in default order.
from pprint import pprint
d = {'foo': 1, 'bar': 2, 'baz': 3}
pprint(d)
# {'bar': 2, 'baz': 3, 'foo': 1}
print d
# {'baz': 3, 'foo': 1, 'bar': 2}
The documentation of pprint mentions this, but does not say why. Why the discrepancy?
| [
"pprint stands for \"pretty print\", also implying \"pleasing to the human eye, and easily read by humans\". Sorting the dict keys just follows that aim, pprint isn't supposed to be primarily fast (sorting the keys adds a penalty), but, errr, pretty. :)\nprint on the other hand \"just prints\", as fast as possible.... | [
6,
0
] | [] | [] | [
"python"
] | stackoverflow_0006888714_python.txt |
Q:
SOAPpy installation unable to find fpconst eventhough its installed
I am a complete novice to the python world and have recently been asked to migrate a legacy application that runs on Python 2.4.15, SOAPpy Module & fpconst.
While installing SOAPpy 0.12.4 on the machine, I get an error saying that its unable to lo... | SOAPpy installation unable to find fpconst eventhough its installed | I am a complete novice to the python world and have recently been asked to migrate a legacy application that runs on Python 2.4.15, SOAPpy Module & fpconst.
While installing SOAPpy 0.12.4 on the machine, I get an error saying that its unable to locate fpconst eventhough it has been installed on the server.
PFB the step... | [
"Error: No local packages or download links found .. \nGo here -> decompress the file -> open a cmd and cd dir to SOAPpy files -> type python setup.py install to run it.\nThen run IDE to check it, by import SOAPpy.\n"
] | [
1
] | [] | [] | [
"python",
"soappy"
] | stackoverflow_0006491828_python_soappy.txt |
Q:
Finding and replacing XML/SVG element text by id with Python's lxml?
I'm new to XML and lxml and would like to use SVG as graphics template and programatically replace some elements (labels in the image).
For this, I have created an SVG file with Inkscape, however, lxml seems not to be able to handle the svg:names... | Finding and replacing XML/SVG element text by id with Python's lxml? | I'm new to XML and lxml and would like to use SVG as graphics template and programatically replace some elements (labels in the image).
For this, I have created an SVG file with Inkscape, however, lxml seems not to be able to handle the svg:namespaces used by Inkscape. Saving as plain SVG works:
from lxml import etree
... | [
"You should be able to use\nprint tree.xpath(\"//n:text[@id='findme']/n:tspan/text()\",\n namespaces={'n': \"http://www.w3.org/2000/svg\"})\n\nIf it doesn't work, please show us the SVG markup. I'm not sure what you mean by \"saving as plain SVG works\".\n"
] | [
3
] | [] | [] | [
"graphics",
"lxml",
"python",
"svg"
] | stackoverflow_0006888906_graphics_lxml_python_svg.txt |
Q:
Specific doubts on kgp.py program in dive into python book
Dive into Python: XML Processing -
Here I am referring to a portion of kgp.py program -
def getDefaultSource(self):
xrefs = {}
for xref in self.grammar.getElementsByTagName("xref"):
xrefs[xref.attributes["id"].value] = 1
xrefs = xrefs.keys()
... | Specific doubts on kgp.py program in dive into python book | Dive into Python: XML Processing -
Here I am referring to a portion of kgp.py program -
def getDefaultSource(self):
xrefs = {}
for xref in self.grammar.getElementsByTagName("xref"):
xrefs[xref.attributes["id"].value] = 1
xrefs = xrefs.keys()
standaloneXrefs = [e for e in self.refs.keys() if e not in xrefs... | [
"Dive Into Python is seven years old now (published 2004), and doesn't always contain the most modern code. So you need to go easy on it: Dive Into Python 3 might be a better bet.\nYour suggestion for doubt 1 changes the meaning of the code: putting the ids into the keys of a dictionary and then getting them out ag... | [
7,
1,
1
] | [] | [] | [
"python",
"xml"
] | stackoverflow_0006889235_python_xml.txt |
Q:
Dynamic upload path - include originating field
I have a Django model with multiple ImageFields and use a callable to determine the upload path. I want to include the originating upload field's name in the upload path, in this case tiny, small, medium or press.
The only way I could think of was to create a pre_sav... | Dynamic upload path - include originating field | I have a Django model with multiple ImageFields and use a callable to determine the upload path. I want to include the originating upload field's name in the upload path, in this case tiny, small, medium or press.
The only way I could think of was to create a pre_save receiver which replaces file.name with a uuid. Then... | [
"You can change image_path() so that it returns a callable which already knows the size:\ndef image_path(size):\n def callback(self, filename)\n \"\"\" Example return: [some-django-model]/[medium]/[product1].[jpg] \"\"\"\n return u'{}/{}/{}.{}'.format(\n slugify(self._meta.verbose_name),... | [
6
] | [] | [] | [
"django",
"django_models",
"django_signals",
"python"
] | stackoverflow_0006889156_django_django_models_django_signals_python.txt |
Q:
Django design pattern for web analytics screens that take a really long time to calculate
I have an "analytics dashboard" screen that is visible to my django web applications users that takes a really long time to calculate. It's one of these screens that goes through every single transaction in the database for ... | Django design pattern for web analytics screens that take a really long time to calculate | I have an "analytics dashboard" screen that is visible to my django web applications users that takes a really long time to calculate. It's one of these screens that goes through every single transaction in the database for a user and gives them metrics on it.
I would love for this to be a realtime operation, but calc... | [
"What you're looking for is a combination of offline processing and caching. By offline, I mean that the computation logic happens outside the request-response cycle. By caching, I mean that the result of your expensive calculation is sufficiently valid for X time, during which you do not need to recalculate it for... | [
14,
3,
1,
0
] | [] | [] | [
"batch_file",
"django",
"python"
] | stackoverflow_0006887100_batch_file_django_python.txt |
Q:
How to find sqlalchemy remote side object's class or class name without db queries?
Let's have a classes X and Y and relations between them x2y and y2x.
From class_mapper(Class).iterate_properties iterator we can get all class's properties.
So x2y and y2x are RelationshipProperty and what I hope to get from is a... | How to find sqlalchemy remote side object's class or class name without db queries? | Let's have a classes X and Y and relations between them x2y and y2x.
From class_mapper(Class).iterate_properties iterator we can get all class's properties.
So x2y and y2x are RelationshipProperty and what I hope to get from is a class or a class name of objects on remote side of relation.
I've already tried to make ... | [
"X.x2y.property.mapper.class_\nrelatonshipproperty will eventually get class-level attribute documentation the same as mapper does now.\nedit. Here is a test which illustrates the above returning \"Y\" from \"X\", and no reflection doesn't create relationships so should have no effect:\nfrom sqlalchemy import Col... | [
29,
3
] | [] | [] | [
"class",
"python",
"relation",
"relationship",
"sqlalchemy"
] | stackoverflow_0006843144_class_python_relation_relationship_sqlalchemy.txt |
Q:
Streaming or custom Jar in Hadoop
I'm running a streaming job in Hadoop (on Amazon's EMR) with the mapper and reducer written in Python. I want to know about the speed gains I would experience if I implement the same mapper and reducer in Java (or use Pig).
In particular, I'm looking for people's experiences on mi... | Streaming or custom Jar in Hadoop | I'm running a streaming job in Hadoop (on Amazon's EMR) with the mapper and reducer written in Python. I want to know about the speed gains I would experience if I implement the same mapper and reducer in Java (or use Pig).
In particular, I'm looking for people's experiences on migrating from streaming to custom jar de... | [
"Why consider deploying custom jars ?\n\nAbility to use more powerful custom Input formats. For streaming jobs, even if you use pluggable input/output like it's mentioned here, you are limited to the key and value(s) to your mapper/reducer being a text/string. You would need to expend some amount of CPU cycles to c... | [
4
] | [] | [] | [
"hadoop",
"java",
"mapreduce",
"python",
"streaming"
] | stackoverflow_0006873077_hadoop_java_mapreduce_python_streaming.txt |
Q:
python how to search an item in a nested list
say I have this list:
li = [["0", "20", "ar"], ["20", "40", "asdasd"], ["50", "199", "bar"], ["24", "69", "sarkozy"]]
Now, forget about the numbers, they are something that let me recognize the position of string. So basically, given that I have the string "ar" in han... | python how to search an item in a nested list | say I have this list:
li = [["0", "20", "ar"], ["20", "40", "asdasd"], ["50", "199", "bar"], ["24", "69", "sarkozy"]]
Now, forget about the numbers, they are something that let me recognize the position of string. So basically, given that I have the string "ar" in hand, how can I extract all the lists that contain "ar... | [
">>> [x for x in li if 'ar' in x[2]]\n[['0', '20', 'ar'], ['50', '199', 'bar'], ['24', '69', 'sarkozy']]\n\n"
] | [
10
] | [] | [] | [
"list",
"nested",
"nested_lists",
"python"
] | stackoverflow_0006889785_list_nested_nested_lists_python.txt |
Q:
Why does this nested list comprehension generate an error?
conn_request, weights = zip(*[
((conn, request), request[2])
for conn in unchoked_conns
for request in conn.peer_requests
])
Generates:
for conn in unchoked_conns
ValueError: need more than 0 values to unpack
I cannot work out what I'm do... | Why does this nested list comprehension generate an error? | conn_request, weights = zip(*[
((conn, request), request[2])
for conn in unchoked_conns
for request in conn.peer_requests
])
Generates:
for conn in unchoked_conns
ValueError: need more than 0 values to unpack
I cannot work out what I'm doing wrong. I think it has some thing to do with the dependence o... | [
">>> a, b = zip(*[])\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nValueError: need more than 0 values to unpack\n\nYour LC produces an empty list. Try verifying that unchoked_conns has any elements.\n",
"zipping an empty list returns a single empty list, hence the assignment fails... | [
4,
0
] | [] | [] | [
"list_comprehension",
"python",
"python_3.x",
"zip"
] | stackoverflow_0006889769_list_comprehension_python_python_3.x_zip.txt |
Q:
Make sequence of string.replace statements more readable
When I'm processing HTML code in Python I have to use the following code because of special characters.
line = string.replace(line, """, "\"")
line = string.replace(line, "'", "'")
line = string.replace(line, "&", "&")
line = string.replace(lin... | Make sequence of string.replace statements more readable | When I'm processing HTML code in Python I have to use the following code because of special characters.
line = string.replace(line, """, "\"")
line = string.replace(line, "'", "'")
line = string.replace(line, "&", "&")
line = string.replace(line, "<", "<")
line = string.replace(line, ">", ">")
line ... | [
"REPLACEMENTS = [\n (\""\", \"\\\"\"),\n (\"'\", \"'\"),\n ...\n ]\nfor entity, replacement in REPLACEMENTS:\n line = line.replace(entity, replacement)\n\nNote that string.replace is simply available as a method on str/unicode objects.\nBetter yet, check out this question!\nThe title of you... | [
4,
2,
2
] | [] | [] | [
"html",
"python",
"string"
] | stackoverflow_0006889172_html_python_string.txt |
Q:
gdb python programming: how to write code that will set breakpoints to every method of a C++ class?
I would like to be able to set breakpoints to every method of a C++ class in gdb.
I think the easiest way to do this is probably python, since now python has complete access to gdb. I know very little python, and w... | gdb python programming: how to write code that will set breakpoints to every method of a C++ class? | I would like to be able to set breakpoints to every method of a C++ class in gdb.
I think the easiest way to do this is probably python, since now python has complete access to gdb. I know very little python, and with gdb on top of it, it's even harder. I am wondering if anyone knows how to write a class python code ... | [
"Assuming you compiled with debugging symbols, you dont even need python for this:\nrbreak source.cpp:.\n\n",
"Edit: I just noticed you're asking for how to do this with a C++ class, not a python one. Oops. I'll leave the answer up in the hope that it will be useful to anyone debugging a python extension...\n\nA ... | [
3,
1,
0
] | [] | [] | [
"c++",
"debugging",
"gdb",
"python"
] | stackoverflow_0006267308_c++_debugging_gdb_python.txt |
Q:
DNSSEC Sign RRSET using DNSPython
I'm trying to DNSSEC Sign a RRSET, however I am not able finding any references to how to do so using DNSPython. Yes it has dns.dnssec.validate_rrsig(), but I want to DNSSEC sign a rrset, how can this be done?
I've been pooring over the RFC's however I'm obviously lacking somethin... | DNSSEC Sign RRSET using DNSPython | I'm trying to DNSSEC Sign a RRSET, however I am not able finding any references to how to do so using DNSPython. Yes it has dns.dnssec.validate_rrsig(), but I want to DNSSEC sign a rrset, how can this be done?
I've been pooring over the RFC's however I'm obviously lacking something in order to make it work.
| [
"Do you really have to do it with DNSPython? Is this a custom name server?\nThe typical way you normally do it (with bind, for example) is by pre-signing the zone file. The DNSSEC RRSIG does not have any dependency on the connection parameters so we don't really have to do on-the-fly signing. Also, things like NSEC... | [
0
] | [] | [] | [
"dns",
"dnspython",
"python"
] | stackoverflow_0006877553_dns_dnspython_python.txt |
Q:
How to extend the comments framework (django) by removing unnecessary fields?
I've been reading on the django docs about the comments framework and how to customize it (http://docs.djangoproject.com/en/1.1/ref/contrib/comments/custom/)
In that page, it shows how to add new fields to a form. But what I want to do i... | How to extend the comments framework (django) by removing unnecessary fields? | I've been reading on the django docs about the comments framework and how to customize it (http://docs.djangoproject.com/en/1.1/ref/contrib/comments/custom/)
In that page, it shows how to add new fields to a form. But what I want to do is to remove unnecesary fields, like URL, email (amongst other minor mods.)
On that ... | [
"I recently implemented the solution that Ofri mentioned, since I only wanted to accept a solitary \"comment\" field for a comment (like SO does, no \"name\", no \"email\" and no \"url\"). \nTo customize the default comment form and list display, I created a \"comments\" directory in my root \"templates\" directory... | [
12,
4,
2
] | [] | [] | [
"django",
"django_comments",
"python"
] | stackoverflow_0002393237_django_django_comments_python.txt |
Q:
python reverse byteorder from network service
I get the following bytes from a network service: \x83\x08\x04\x04\x60\x02\x00\x81\x15\x01\x01 These are 8 bit number. I want to change the representation to my system's representation (32 bits) to be able to work on the bytes. How would I do this with python? Is there... | python reverse byteorder from network service | I get the following bytes from a network service: \x83\x08\x04\x04\x60\x02\x00\x81\x15\x01\x01 These are 8 bit number. I want to change the representation to my system's representation (32 bits) to be able to work on the bytes. How would I do this with python? Is there a special 'reverse' function for this?
best regard... | [
"Determine which byte order the bytes are in, and supply the correct byte order character to struct.unpack.\n",
"If you want to reverse all of the bytes in a string, you can do this:\n'example string'[::-1]\n\nI would recommend the struct module for unpacking network or otherwise binary data, as you otherwise don... | [
1,
1,
1,
0,
0
] | [] | [] | [
"networking",
"python"
] | stackoverflow_0006890175_networking_python.txt |
Q:
What does this obfuscated python code do?
And how does it work?
#########shift_jis:ascii:latin1:coding:rot13:euc_jp:utf_8:gb2312:unicode_escape
v=vag (#(#(#( (#(#(#( (#(#(#( (#(#(#(
''.wbva (#( (#( (#( (#( (#(
znc( ... | What does this obfuscated python code do? | And how does it work?
#########shift_jis:ascii:latin1:coding:rot13:euc_jp:utf_8:gb2312:unicode_escape
v=vag (#(#(#( (#(#(#( (#(#(#( (#(#(#(
''.wbva (#( (#( (#( (#( (#(
znc( ynzoqn h:`(#(#( (#( ... | [
"You can run code like this at codepad.org. Running it there leads to the output\nHello, World\n\nThe first line abuses python's coding mechanism to obfuscate the used characters. Then, it calculates a large number, and converts that number into a string, and prints that string.\n"
] | [
8
] | [] | [] | [
"obfuscation",
"python"
] | stackoverflow_0006890626_obfuscation_python.txt |
Q:
How do sets work in Python?
>>> {x for x in 'spam'}
{'a', 'p', 's', 'm'}
Why does it change the order? If you take a look at a loop, it works perfectly:
>>> for x in 'spam':
... print(x)
...
s
p
a
m
>>>
A:
Sets in python (and in set theory) are not ordered. So when you loop over them, there is no defined... | How do sets work in Python? | >>> {x for x in 'spam'}
{'a', 'p', 's', 'm'}
Why does it change the order? If you take a look at a loop, it works perfectly:
>>> for x in 'spam':
... print(x)
...
s
p
a
m
>>>
| [
"Sets in python (and in set theory) are not ordered. So when you loop over them, there is no defined ordering.\nYou looped over the string literal 'spam' to make a set containing each character in that string. Once you did that, the ordering was gone.\nWhen you perform the for loop over 'spam', you are performing... | [
7,
5,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0006890816_python.txt |
Q:
Python: Socket doesn't want to shutdown() and setsockopt() is ignored? (Problem debugging)
Edited
Original question was about trouble with reconnecting (close() and shutdown() confusion). The below code is the working code (fixed)
For Googler's, this script is an IRC bot. Feature list:
Keep reconnecting until con... | Python: Socket doesn't want to shutdown() and setsockopt() is ignored? (Problem debugging) | Edited
Original question was about trouble with reconnecting (close() and shutdown() confusion). The below code is the working code (fixed)
For Googler's, this script is an IRC bot. Feature list:
Keep reconnecting until connection available
If assigned nick is already taken, puts string behind name (repeats until succ... | [
"This is most probably because you're switching off wi-fi and the interface is removed from system so you get something like Can't assign requested address. You would get such an error while trying to bind to non-existing local address.\nThe other thing is you won't be able to reconnect on the same socket after cal... | [
1
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0006890916_python_sockets.txt |
Q:
Posting directly to Facebook Wall over Google App Engine
I want to post to my Facebook User walldirectly from my Google App Engine application.
I found a solving that:
http://komunitasweb.com/2011/07/how-to-programmatically-post-to-facebook-wall/
This solve works in normal python console application but when i usi... | Posting directly to Facebook Wall over Google App Engine | I want to post to my Facebook User walldirectly from my Google App Engine application.
I found a solving that:
http://komunitasweb.com/2011/07/how-to-programmatically-post-to-facebook-wall/
This solve works in normal python console application but when i using in Google App Engine Project it isn't work because Google A... | [
"All Google App Engine applications run in a restrictive environment. There you can't use certain native python libraries. The best option is to use the apis Google provides such as the urlfetch api. And you should test your applications locally using App Engine sdk for Python.\nYou may use the facebook-sdk libray ... | [
0
] | [] | [] | [
"facebook_graph_api",
"google_app_engine",
"python"
] | stackoverflow_0006889640_facebook_graph_api_google_app_engine_python.txt |
Q:
Converting UTC datetime to user's local date and time
I'm using python on Django and Google App Engine. I'm also using the DateTimeProperty in one of my models. Occasionally I would like to display that date and time to the user.
What is the best to convert the datetime stored in DateTimeProperty into the user's ... | Converting UTC datetime to user's local date and time | I'm using python on Django and Google App Engine. I'm also using the DateTimeProperty in one of my models. Occasionally I would like to display that date and time to the user.
What is the best to convert the datetime stored in DateTimeProperty into the user's datetime?
Or a more precise way of framing the question: Wh... | [
"This is more a Python question, than a GAE one, unless GAE has some infrastructure to facilitate this (I've made a quick scan but haven't found any reference).\nBasically, you want to store date/times in UTC timezone (e.g. use datetime.datetime.utcnow) along with user timezones, which you can either try to extract... | [
9,
3,
0
] | [] | [] | [
"django",
"google_app_engine",
"localization",
"python"
] | stackoverflow_0004115310_django_google_app_engine_localization_python.txt |
Q:
Django comments change success url
I would like to change the URL you are redirected to when django posts a comment successfully - I'd much rather be taken to the page where the comment has been posted to, rather than the current redirect to a 'thanks for your comment' URL. Is there a place I can override this in ... | Django comments change success url | I would like to change the URL you are redirected to when django posts a comment successfully - I'd much rather be taken to the page where the comment has been posted to, rather than the current redirect to a 'thanks for your comment' URL. Is there a place I can override this in django? Thanks
| [
"Just add a hidden field called next to your comment form with the value of the url you'd like to re-direct to after the form has been posted.\nExample from the docs:\n<input type=\"hidden\" name=\"next\" value=\"{% url my_comment_was_posted %}\" />\n\nhttps://docs.djangoproject.com/en/dev/ref/contrib/comments/#red... | [
5
] | [] | [] | [
"django",
"django_comments",
"python"
] | stackoverflow_0006890371_django_django_comments_python.txt |
Q:
string matching in python
I am getting trouble with the following matter.Let's say, I have some string in two list in a dictionary:
left right
british 7
cuneate nucleus Medulla oblongata
Motoneurons anterior
An... | string matching in python | I am getting trouble with the following matter.Let's say, I have some string in two list in a dictionary:
left right
british 7
cuneate nucleus Medulla oblongata
Motoneurons anterior
And I have some test lines in a f... | [
"It doesn't tag at the beginning and the end because you expect one or more spaces before and after your keywords.\nInstead of \\s+, use \\b (word break).\nADDENDUM\nActual code:\nimport re\n\ndict = [('british','7'),('cuneate nucleus','Medulla oblongata'),('Motoneurons','anterior')]\n\nfiletext = \"\"\"<s id=\"69-... | [
3,
2
] | [] | [] | [
"python",
"string_matching"
] | stackoverflow_0006891365_python_string_matching.txt |
Q:
Python Strange Error: "TypeError: 'NoneType' object is not callable"
I'm implementing a simple class to represent a 2D vector. Here's are the relevant bits:
class Vector:
def __init__( self, x, y ):
self.vec_repr = x, y
def __add__( self, other ):
new_x = self.x + other.x
new_y = self.y + other.y
... | Python Strange Error: "TypeError: 'NoneType' object is not callable" | I'm implementing a simple class to represent a 2D vector. Here's are the relevant bits:
class Vector:
def __init__( self, x, y ):
self.vec_repr = x, y
def __add__( self, other ):
new_x = self.x + other.x
new_y = self.y + other.y
return Vector( new_x, new_y )
def __getattr__( self, name ):
if... | [
"The problem is that your __getattr__ doesn't return anything for attributes other than x and y and doesn't raise an AttributeError. Hence when the __add__ method is looked up, __getattr__ returns None and hence your error.\nYou could fix this by making __getattr__ return values for other attributes. In fact you h... | [
11
] | [] | [] | [
"python"
] | stackoverflow_0006891477_python.txt |
Q:
SQLAlchemy self-referential parent_id dilemna
I have a Category object like this:
def parent_default(context):
''' default parent id if the name is not root '''
id_ = None
if context.current_parameters['name'] != u'root' :
id_ = 1
return id_
class Category(Base):
''' Class representing... | SQLAlchemy self-referential parent_id dilemna | I have a Category object like this:
def parent_default(context):
''' default parent id if the name is not root '''
id_ = None
if context.current_parameters['name'] != u'root' :
id_ = 1
return id_
class Category(Base):
''' Class representing a product category. '''
__tablename__ = "CATE... | [
"Whether the tuple NULL, 'root' is unique varies a bit from DBMS to DBMS; this was added to the sql standard somewhat recently. In most cases, it is not unique, after all, NULL = NULL is not true. \nYou're already requiring that the root tuple have an id of 1, so you can safely remove the nullable=True from the p... | [
3
] | [] | [] | [
"database",
"python",
"sqlalchemy"
] | stackoverflow_0006891712_database_python_sqlalchemy.txt |
Q:
Having Trouble Putting Strings into a List (error message)
I am trying to use the following code:
for x in story:
var1 = str(x)
var1 = var1.replace("<p>", "\n")
var1 = var1.replace("</p>", "")
story[x] = var1
To remove paragraph tags, and insert a line break, and then reinsert them into the variab... | Having Trouble Putting Strings into a List (error message) | I am trying to use the following code:
for x in story:
var1 = str(x)
var1 = var1.replace("<p>", "\n")
var1 = var1.replace("</p>", "")
story[x] = var1
To remove paragraph tags, and insert a line break, and then reinsert them into the variable. The strings are as follows:
Panera Bread (NASDAQ: <a class="... | [
"for cycle iteratively substitutes elements of list story into x variable, while [] list instruction requires element index. This results into error.\nl = ['a','b']\nprint l[0]\nprint l['a'] // type error\n\nEDIT: I missed that story does not consists of strings. This changes can do the job:\nstory = [str(x).replac... | [
2,
0
] | [] | [] | [
"html",
"parsing",
"python"
] | stackoverflow_0006891809_html_parsing_python.txt |
Q:
How to run all tests in a setup.py script?
I would like to write a setup.py script that runs all of my django app's tests and fails the installation if one of the tests don't pass.
How can it be done? What do I need to do?
A:
Assuming you're using setuptools, check out test build package and run a unittest suite... | How to run all tests in a setup.py script? | I would like to write a setup.py script that runs all of my django app's tests and fails the installation if one of the tests don't pass.
How can it be done? What do I need to do?
| [
"Assuming you're using setuptools, check out test build package and run a unittest suite from their docs. which I believe lets you run setup.py test and doesn't install your package, but runs the tests in an egg. From here you can run setup.py install. This does seem to be a new command (my version doesn't have it... | [
3
] | [] | [] | [
"django",
"django_testing",
"python",
"setuptools"
] | stackoverflow_0006891128_django_django_testing_python_setuptools.txt |
Q:
Python Handlers.py
I'm writing my own WSGI Simple Server. I want to be able to send a few requests to it and have some responses returned.
I have a request that comes in from fiddler, gets processed and returned to fiddler. I'm currently ONLY trying to return a success code... Fiddler gets back a 200 success/OK re... | Python Handlers.py | I'm writing my own WSGI Simple Server. I want to be able to send a few requests to it and have some responses returned.
I have a request that comes in from fiddler, gets processed and returned to fiddler. I'm currently ONLY trying to return a success code... Fiddler gets back a 200 success/OK response, which is great. ... | [
"\nSurely write should attempt to convert to bytes before throwing this exception?!?\n\nNo, the ones who use your server should convert to bytes before calling write(), using their favorite encoding (which they also should specify in a header).\n(That said, they probably shouldn't use write at all, see PEP3333.)\n\... | [
1
] | [] | [] | [
"google_app_engine",
"python",
"wsgi"
] | stackoverflow_0006891208_google_app_engine_python_wsgi.txt |
Q:
Dynamic session access in templates
I'm trying to access session keys within a loop that needs to be dynamic, I think you'll get what I'm going for by looking at my code that isn't working.
{% for q in questions %}
<div class="question_wrap">
<h2>{{ q }}</h2>
# this does not work
{% if not request.ses... | Dynamic session access in templates | I'm trying to access session keys within a loop that needs to be dynamic, I think you'll get what I'm going for by looking at my code that isn't working.
{% for q in questions %}
<div class="question_wrap">
<h2>{{ q }}</h2>
# this does not work
{% if not request.session.get(str(q.id), False) %}
<!-... | [
"The syntax of Django templates is very limiting in order to prevent people from putting too much logic inside templates and doesn't allow you to pass parameters to methods. \nYou can prepare a list of tuples already in the view or write a simple template tag for that. The first options is usually easier:\nIn the v... | [
2
] | [] | [] | [
"django",
"python",
"session",
"templates"
] | stackoverflow_0006892154_django_python_session_templates.txt |
Q:
Python 3 equivalent of Config module
Config module only works in python 2.x what is the alternative in 3.0?
A:
Ok, configparser is the way to go then.
| Python 3 equivalent of Config module | Config module only works in python 2.x what is the alternative in 3.0?
| [
"Ok, configparser is the way to go then.\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0006888640_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.