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:
print_r functionality in iPython
Is there a way to get PHP-like print_r(object) funcionality in iPython?
I know I can use '?' to get info about an object, but how do I view the values of the object?
A:
Is
print my_object.__dict__
perhaps what you are looking for?
Or have a look at the standard python pretty printer for more advanced, recursive printing.
A:
dir(object) will give you all its attribute names.
A:
I'd use the pprint module if you want it to be nicely formatted:
import pprint
obj = {'a':1, 'b':2}
pprint.pprint(obj)
A:
repr() calls the __repr__() method of the object, which usually gives some information about the contents of the object if written appropriately.
|
print_r functionality in iPython
|
Is there a way to get PHP-like print_r(object) funcionality in iPython?
I know I can use '?' to get info about an object, but how do I view the values of the object?
|
[
"Is \nprint my_object.__dict__\n\nperhaps what you are looking for?\nOr have a look at the standard python pretty printer for more advanced, recursive printing.\n",
"dir(object) will give you all its attribute names.\n",
"I'd use the pprint module if you want it to be nicely formatted:\nimport pprint\nobj = {'a':1, 'b':2}\npprint.pprint(obj)\n\n",
"repr() calls the __repr__() method of the object, which usually gives some information about the contents of the object if written appropriately.\n"
] |
[
3,
2,
1,
0
] |
[] |
[] |
[
"ipython",
"object",
"php",
"python"
] |
stackoverflow_0002317921_ipython_object_php_python.txt
|
Q:
How do I use a regular expression to match a name?
I am a newbie in Python. I want to write a regular expression for some name checking.
My input string can contain a-z, A-Z, 0-9, and ' _ ', but it should start with either a-z or A-Z (not 0-9 and ' _ '). I want to write a regular expression for this. I tried, but nothing was matching perfectly.
Once the input string follows the regular expression rules, I can proceed further, otherwise discard that string.
A:
Here's an answer to your question:
Interpreting that you want _ (not -), this should do the job:
>>> tests = ["a", "A", "a1", "a_1", "1a", "_a", "a\n", "", "z_"]
>>> for test in tests:
... print repr(test), bool(re.match(r"[A-Za-z]\w*\Z", test))
...
'a' True
'A' True
'a1' True
'a_1' True
'1a' False
'_a' False
'a\n' False
'' False
'z_' True
>>>
Stoutly resist the temptation to use $; here's why:
Hello, hello, using $ is WRONG, use \Z instead
>>> re.match(r"[a-zA-Z][\w-]*$","A")
<_sre.SRE_Match object at 0x00BAFE90>
>>> re.match(r"[a-zA-Z][\w-]*$","A\n")
<_sre.SRE_Match object at 0x00BAFF70> # WRONG; SHOULDN'T MATCH
>>>
>>> re.match(r"[a-zA-Z][\w-]*\Z","A")
<_sre.SRE_Match object at 0x00BAFE90>
>>> re.match(r"[a-zA-Z][\w-]*\Z","A\n")
>>> # CORRECT: NO MATCH
The Fine Manual says:
'$'
Matches the end of the string or just before the newline at the end of the string [my emphasis], and in MULTILINE mode also matches before a newline. foo matches both ‘foo’ and ‘foobar’, while the regular expression foo$ matches only ‘foo’. More interestingly, searching for foo.$ in 'foo1\nfoo2\n' matches ‘foo2’ normally, but ‘foo1’ in MULTILINE mode; searching for a single $ in 'foo\n' will find two (empty) matches: one just before the newline, and one at the end of the string.
and
\Z
Matches only at the end of the string.
=== And now for something completely different ===
>>> import string
>>> letters = set(string.ascii_letters)
>>> ok_chars = letters | set(string.digits + "_")
>>>
>>> def is_valid_name(strg):
... return strg and strg[0] in letters and all(c in ok_chars for c in strg)
...
>>> for test in tests:
... print repr(test), repr(is_valid_name(test))
...
'a' True
'A' True
'a1' True
'a_1' True
'1a' False
'_a' False
'a\n' False
'' ''
'z_' True
>>>
A:
>>> import re
>>> re.match("[a-zA-Z][\w-]*$","A")
<_sre.SRE_Match object at 0x00932E20>
>>> re.match("[a-zA-Z][\w-]*$","A_B")
<_sre.SRE_Match object at 0x008CA950>
>>> re.match("[a-zA-Z][\w-]*$","0A")
>>>
>>> re.match("[a-zA-Z][\w-]*$","!A_B")
>>>
Note: OP mentioned string cannot start from ( 0-9 and "_")., apparently _ can be in the text. Thats why I am using \w
Note2: If you don't want match string ends with \n, you could use \Z instead of $ as John Machin mentioned.
|
How do I use a regular expression to match a name?
|
I am a newbie in Python. I want to write a regular expression for some name checking.
My input string can contain a-z, A-Z, 0-9, and ' _ ', but it should start with either a-z or A-Z (not 0-9 and ' _ '). I want to write a regular expression for this. I tried, but nothing was matching perfectly.
Once the input string follows the regular expression rules, I can proceed further, otherwise discard that string.
|
[
"Here's an answer to your question:\nInterpreting that you want _ (not -), this should do the job:\n>>> tests = [\"a\", \"A\", \"a1\", \"a_1\", \"1a\", \"_a\", \"a\\n\", \"\", \"z_\"]\n>>> for test in tests:\n... print repr(test), bool(re.match(r\"[A-Za-z]\\w*\\Z\", test))\n...\n'a' True\n'A' True\n'a1' True\n'a_1' True\n'1a' False\n'_a' False\n'a\\n' False\n'' False\n'z_' True\n>>>\n\nStoutly resist the temptation to use $; here's why:\nHello, hello, using $ is WRONG, use \\Z instead\n>>> re.match(r\"[a-zA-Z][\\w-]*$\",\"A\")\n<_sre.SRE_Match object at 0x00BAFE90>\n>>> re.match(r\"[a-zA-Z][\\w-]*$\",\"A\\n\")\n<_sre.SRE_Match object at 0x00BAFF70> # WRONG; SHOULDN'T MATCH\n>>>\n\n>>> re.match(r\"[a-zA-Z][\\w-]*\\Z\",\"A\")\n<_sre.SRE_Match object at 0x00BAFE90>\n>>> re.match(r\"[a-zA-Z][\\w-]*\\Z\",\"A\\n\")\n>>> # CORRECT: NO MATCH\n\nThe Fine Manual says:\n'$'\n Matches the end of the string or just before the newline at the end of the string [my emphasis], and in MULTILINE mode also matches before a newline. foo matches both ‘foo’ and ‘foobar’, while the regular expression foo$ matches only ‘foo’. More interestingly, searching for foo.$ in 'foo1\\nfoo2\\n' matches ‘foo2’ normally, but ‘foo1’ in MULTILINE mode; searching for a single $ in 'foo\\n' will find two (empty) matches: one just before the newline, and one at the end of the string.\nand\n\\Z\n Matches only at the end of the string.\n=== And now for something completely different ===\n>>> import string\n>>> letters = set(string.ascii_letters)\n>>> ok_chars = letters | set(string.digits + \"_\")\n>>>\n>>> def is_valid_name(strg):\n... return strg and strg[0] in letters and all(c in ok_chars for c in strg)\n...\n>>> for test in tests:\n... print repr(test), repr(is_valid_name(test))\n...\n'a' True\n'A' True\n'a1' True\n'a_1' True\n'1a' False\n'_a' False\n'a\\n' False\n'' ''\n'z_' True\n>>>\n\n",
">>> import re\n\n>>> re.match(\"[a-zA-Z][\\w-]*$\",\"A\")\n<_sre.SRE_Match object at 0x00932E20>\n\n>>> re.match(\"[a-zA-Z][\\w-]*$\",\"A_B\")\n<_sre.SRE_Match object at 0x008CA950>\n\n>>> re.match(\"[a-zA-Z][\\w-]*$\",\"0A\")\n>>> \n>>> re.match(\"[a-zA-Z][\\w-]*$\",\"!A_B\")\n>>>\n\nNote: OP mentioned string cannot start from ( 0-9 and \"_\")., apparently _ can be in the text. Thats why I am using \\w\nNote2: If you don't want match string ends with \\n, you could use \\Z instead of $ as John Machin mentioned.\n"
] |
[
7,
4
] |
[
"here's a non re way\nimport string\nflag=0\nmystring=\"abcadsf123\"\nif not mystring[0] in string.digits+\"_\":\n for c in mystring:\n if not c in string.letters+string.digits+\"-\":\n flag=1\n if flag: print \"%s not ok\" % mystring\n else: print \"%s ok\" % mystring\nelse: print \"%s starts with digits or _\" % mystring\n\n"
] |
[
-1
] |
[
"python",
"regex"
] |
stackoverflow_0002317134_python_regex.txt
|
Q:
Python Environment Variables in Windows?
I'm developing a script that runs a program with other scripts over and over for testing purposes.
How it currently works is I have one Python script which I launch. That script calls the program and loads the other scripts. It kills the program after 60 seconds to launch the program again with the next script.
For some scripts, 60 seconds is too long, so I was wondering if I am able to set a FLAG variable (not in the main script), such that when the script finishes, it sets FLAG, so the main script and read FLAG and kill the process?
Thanks for the help, my writing may be confusing, so please let me know if you cannot fully understand.
A:
You could use atexit to write a small file (flag.txt) when script1.py exits. mainscript.py could regularly be checking for the existence of flag.txt and when it finds it, will kill program.exe and exit.
Edit:
I've set persistent environment variables using this, but I only use it for python-based installation scripts. Usually I'm pretty shy about messing with the registry. (this is for windows btw)
A:
This seems like a perfect use case for sockets, in particular asyncore.
A:
You cannot use environment variables in this way. As you have discovered it is not persistent after the setting application completes
|
Python Environment Variables in Windows?
|
I'm developing a script that runs a program with other scripts over and over for testing purposes.
How it currently works is I have one Python script which I launch. That script calls the program and loads the other scripts. It kills the program after 60 seconds to launch the program again with the next script.
For some scripts, 60 seconds is too long, so I was wondering if I am able to set a FLAG variable (not in the main script), such that when the script finishes, it sets FLAG, so the main script and read FLAG and kill the process?
Thanks for the help, my writing may be confusing, so please let me know if you cannot fully understand.
|
[
"You could use atexit to write a small file (flag.txt) when script1.py exits. mainscript.py could regularly be checking for the existence of flag.txt and when it finds it, will kill program.exe and exit.\nEdit:\nI've set persistent environment variables using this, but I only use it for python-based installation scripts. Usually I'm pretty shy about messing with the registry. (this is for windows btw) \n",
"This seems like a perfect use case for sockets, in particular asyncore.\n",
"You cannot use environment variables in this way. As you have discovered it is not persistent after the setting application completes\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"environment_variables",
"python",
"testing",
"windows"
] |
stackoverflow_0000923586_environment_variables_python_testing_windows.txt
|
Q:
is there a limit to command.getstatusoutput() buffer in python
I have created a script to run a test script on a batch of files,have been testing it overnight for two nights, however it just hangs at a certain point.
I was wondering if the the commands.getstatusoutput() is the issue here since the test script is has a heavy logging mechanism.
Update:
How is using subprocess module functions different from using os.system() which way of doing things is better?
A:
The method getstatusoutput() returns a string, which can be very long and therefore take up a lot of space and cause paging to disk and other nasty things.
Since the commands module is deprecated anyway, better use the subprocess module which provides a file-like access to the process output. If you need the output for later, just write it into a file on the hard disk
cmd = subprocess.Popen(['ls'], stdout=file('output', 'w'))
If you want process to process the output, read stdout like this
cmd = subprocess.Popen(['ls'], stdout=subprocess.PIPE)
for line in cmd.stdout:
do_stuff(line)
Which will be easier on your memory.
|
is there a limit to command.getstatusoutput() buffer in python
|
I have created a script to run a test script on a batch of files,have been testing it overnight for two nights, however it just hangs at a certain point.
I was wondering if the the commands.getstatusoutput() is the issue here since the test script is has a heavy logging mechanism.
Update:
How is using subprocess module functions different from using os.system() which way of doing things is better?
|
[
"The method getstatusoutput() returns a string, which can be very long and therefore take up a lot of space and cause paging to disk and other nasty things. \nSince the commands module is deprecated anyway, better use the subprocess module which provides a file-like access to the process output. If you need the output for later, just write it into a file on the hard disk\ncmd = subprocess.Popen(['ls'], stdout=file('output', 'w'))\n\nIf you want process to process the output, read stdout like this\ncmd = subprocess.Popen(['ls'], stdout=subprocess.PIPE)\nfor line in cmd.stdout:\n do_stuff(line)\n\nWhich will be easier on your memory.\n"
] |
[
6
] |
[] |
[] |
[
"linux",
"python"
] |
stackoverflow_0002318881_linux_python.txt
|
Q:
Simple question: In numpy how do you make a multidimensional array of arrays?
Right, perhaps I should be using the normal Python lists for this, but here goes:
I want a 9 by 4 multidimensional array/matrix (whatever really) that I want to store arrays in. These arrays will be 1-dimensional and of length 4096.
So, I want to be able to go something like
column = 0 #column to insert into
row = 7 #row to insert into
storageMatrix[column,row][0] = NEW_VALUE
storageMatrix[column,row][4092] = NEW_VALUE_2
etc..
I appreciate I could be doing something a bit silly/unnecessary here, but it will make it ALOT easier for me to have it structured like this in my code (as there's alot of these, and alot of analysis to be done later).
Thanks!
A:
Note that to leverage the full power of numpy, you'd be much better off with a 3-dimensional numpy array. Breaking apart the 3-d array into a 2-d array with 1-d values
may complicate your code and force you to use loops instead of built-in numpy functions.
It may be worth investing the time to refactor your code to use the superior 3-d numpy arrays.
However, if that's not an option, then:
import numpy as np
storageMatrix=np.empty((4,9),dtype='object')
By setting the dtype to 'object', we are telling numpy to allow each element of storageMatrix to be an arbitrary Python object.
Now you must initialize each element of the numpy array to be an 1-d numpy array:
storageMatrix[column,row]=np.arange(4096)
And then you can access the array elements like this:
storageMatrix[column,row][0] = 1
storageMatrix[column,row][4092] = 2
A:
The Tentative NumPy Tutorial says you can declare a 2D array using the comma operator:
x = ones( (3,4) )
and index into a 2D array like this:
>>> x[1,2] = 20
>>> x[1,:] # x's second row
array([ 1, 1, 20, 1])
>>> x[0] = a # change first row of x
>>> x
array([[10, 20, -7, -3],
[ 1, 1, 20, 1],
[ 1, 1, 1, 1]])
|
Simple question: In numpy how do you make a multidimensional array of arrays?
|
Right, perhaps I should be using the normal Python lists for this, but here goes:
I want a 9 by 4 multidimensional array/matrix (whatever really) that I want to store arrays in. These arrays will be 1-dimensional and of length 4096.
So, I want to be able to go something like
column = 0 #column to insert into
row = 7 #row to insert into
storageMatrix[column,row][0] = NEW_VALUE
storageMatrix[column,row][4092] = NEW_VALUE_2
etc..
I appreciate I could be doing something a bit silly/unnecessary here, but it will make it ALOT easier for me to have it structured like this in my code (as there's alot of these, and alot of analysis to be done later).
Thanks!
|
[
"Note that to leverage the full power of numpy, you'd be much better off with a 3-dimensional numpy array. Breaking apart the 3-d array into a 2-d array with 1-d values \nmay complicate your code and force you to use loops instead of built-in numpy functions.\nIt may be worth investing the time to refactor your code to use the superior 3-d numpy arrays.\nHowever, if that's not an option, then:\nimport numpy as np\nstorageMatrix=np.empty((4,9),dtype='object')\n\nBy setting the dtype to 'object', we are telling numpy to allow each element of storageMatrix to be an arbitrary Python object.\nNow you must initialize each element of the numpy array to be an 1-d numpy array:\nstorageMatrix[column,row]=np.arange(4096)\n\nAnd then you can access the array elements like this:\nstorageMatrix[column,row][0] = 1\nstorageMatrix[column,row][4092] = 2\n\n",
"The Tentative NumPy Tutorial says you can declare a 2D array using the comma operator:\nx = ones( (3,4) )\n\nand index into a 2D array like this:\n>>> x[1,2] = 20\n>>> x[1,:] # x's second row\narray([ 1, 1, 20, 1])\n>>> x[0] = a # change first row of x\n>>> x\narray([[10, 20, -7, -3],\n [ 1, 1, 20, 1],\n [ 1, 1, 1, 1]])\n\n"
] |
[
8,
0
] |
[] |
[] |
[
"arrays",
"multidimensional_array",
"numpy",
"python"
] |
stackoverflow_0002318667_arrays_multidimensional_array_numpy_python.txt
|
Q:
Dictionaries in Python
I am trying to get to speed on the use of dictionaries. I spent three hours last night searching the web for examples similar to some of the things I am trying to do. For example, suppose I have two dictionaries (actually I have two lists of dictionaries).
d1={key1:1, key2:2}
d2={key1:1, key2:'A', key4:4}
I want to update d1 so it looks like the following:
d1={key1:1, key2:[2,'A'], key3:3, key4:4}
Ii can't seem to find adequate examples to get me started. I have a fair number of books and I also reviewed them but they all seem to have the same type of examples that I am finding on the web.
Does anyone know of a place or a book that has explicit examples and descriptions of how to use dictionaries?
I think one of the problems I am having is that I am not understanding how references are maintained as I access the dictionary.
I can check to see if the two dictionaries have a common key:
for k in d1.keys():
for k2 in d2.keys():
if k==k2:
print 'true'
but if they do I can't seem to combine the values into a list.
More than a direct answer to this particular example I would appreciate any suggestions about places where there are good examples of using dictionaries.
A:
Try this:
import collections
merged = collections.defaultdict(list)
for k in d1:
merged[k].append( d1[k] )
for k in d2:
merged[k].append( d2[k] )
This may be what you're looking for.
Or possibly this.
import collections
merged = collections.defaultdict(set)
for k in d1:
merged[k].add( d1[k] )
for k in d2:
merged[k].add( d2[k] )
A:
One good place to start is by getting iPython (easy_install ipython) then poking around with tab completion, ? and dir:
In [2]: dir {}
------> dir({})
Out[2]:
['__class__',
...
'keys',
'pop',
'popitem',
'setdefault',
'update',
'values']
In [3]: {}.update?
Type: dict
Base Class: <type 'dict'>
String Form: {}
Namespace: Interactive
Length: 0
Docstring:
dict() -> new empty dictionary.
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs.
dict(seq) -> new dictionary initialized as if via:
d = {}
for k, v in seq:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
(just for example)
Anyway, your problem with checking keys common between the two dictionaries: there are a few things to consider (maybe look at the set class?), but here's how I'd do it:
common_keys = [k for k in dict1 if k in dict2]
(ie, "each key k in dict1 if that key is also in dict2")
(note, too, that testing for dictionary membership is an O(1) operation, so this will run in O(|dict1|))
edit: alright, so this doesn't solve the problem of merging the two dicts into one with lists... But Lott's answer is good for that, or you could use the setdefault method:
new = {}
for (k, v) in dict1.items():
new.setdefault(k, []).append(v)
for (k, v) in dict2.items():
new.setdefault(k, []).append(v)
A:
I believe here is what you want:
>>> d1={'key1':1, 'key2':2}
>>> d2={'key1':1, 'key2':'A', 'key4':4}
>>> d = {}
>>> d.update(d1)
>>> for i in d2:
if i in d and d2[i] != d[i]:
d[i] = [d[i], d2[i]]
else:
d[i] = d2[i]
>>> d
{'key2': [2, 'A'], 'key1': 1, 'key4': 4}
A:
Here are some good links:
http://www.diveintopython.org/getting_to_know_python/dictionaries.html
http://docs.python.org/tutorial/datastructures.html#dictionaries
A:
Python dictionaries also work much like associative arrays in PHP, if you have any experience in that language.
The Built-in Types page in the Python docs also has a good section on dictionaries, and the section also has a list of functions available for them:
http://docs.python.org/library/stdtypes.html#mapping-types-dict
A:
well, for your first case, you might want a helper that combines two objects into a list of two objects, and two lists into one list containing items from the two lists,
This is assuming of course, that you always merge keys into lists, but you don't want your keys to end up being "lists of lists"
def listify( obj ):
if type(obj) != type([]): return [obj]
else: return obj
def merge( v1, v2 ):
return listify(v1) + listify(v2)
#so now you can merge two dictionaries:
dict1 = dict(a = 2, b = 5, c = 7 )
dict2 = dict(b = 4, d = 9, f = 10 )
dikt = {}
for k in set( dict1.keys() + dict2.keys() ):
dikt[k] = merge( dict1.get(k, []), dict2.get(k, []) )
#resutls in:
# {'a': [2], 'c': [7], 'b': [5, 4], 'd': [9], 'f': [10]}
You may notice, dict.keys() returns a list of keys,
set returns a list without duplicate items, so set( d1.keys(), d2.keys() ) returns union of the keys of d1 and d2
A:
A variation on @SilentGhost's answer (all other answers produce wrong dictionaries):
>>> d1 = dict(key1=1, key2=2)
>>> d2 = dict(key1=1, key2='A', key4=4)
>>> d = dict(d1)
>>> for k, v2 in d2.iteritems():
... v = d.get(k, None)
... d[k] = [v, v2] if v is not None and v != v2 else v2
...
>>> d
{'key2': [2, 'A'], 'key1': 1, 'key4': 4}
A:
Maybe this is a bit awkward to do because the data structure you are trying to create is not as natural as it could be. For example instead of having some values be lone values, and some be lists, why not keep everything in lists? E.g.
{'key1': [1], 'key2': [2, 'A'], 'key4': [4]}
It is possible in Python to have a collection of mixed data types but your code will often be cleaner if you keep it coherent. If you use this sort of data structure, inserting is as easy as
# Inserting a (key, value) pair
if key in my_dict:
my_dict[key].append(value)
else:
my_dict[key] = [value]
A:
Here is another variation.
d1 = {'key1'=1, 'key2'=2}
d2 = {'key1'=1, 'key2'='A', 'key4'=4)
d = d2
for k, v in d.iteritems():
... if k in d1.keys() and v!=d1[k]:
... d[k] = [d1[k], v2]
d
{'key2': [2, 'A'], 'key1': 1, 'key4': 4}
|
Dictionaries in Python
|
I am trying to get to speed on the use of dictionaries. I spent three hours last night searching the web for examples similar to some of the things I am trying to do. For example, suppose I have two dictionaries (actually I have two lists of dictionaries).
d1={key1:1, key2:2}
d2={key1:1, key2:'A', key4:4}
I want to update d1 so it looks like the following:
d1={key1:1, key2:[2,'A'], key3:3, key4:4}
Ii can't seem to find adequate examples to get me started. I have a fair number of books and I also reviewed them but they all seem to have the same type of examples that I am finding on the web.
Does anyone know of a place or a book that has explicit examples and descriptions of how to use dictionaries?
I think one of the problems I am having is that I am not understanding how references are maintained as I access the dictionary.
I can check to see if the two dictionaries have a common key:
for k in d1.keys():
for k2 in d2.keys():
if k==k2:
print 'true'
but if they do I can't seem to combine the values into a list.
More than a direct answer to this particular example I would appreciate any suggestions about places where there are good examples of using dictionaries.
|
[
"Try this:\nimport collections\nmerged = collections.defaultdict(list)\nfor k in d1:\n merged[k].append( d1[k] )\nfor k in d2:\n merged[k].append( d2[k] )\n\nThis may be what you're looking for.\nOr possibly this.\nimport collections\nmerged = collections.defaultdict(set)\nfor k in d1:\n merged[k].add( d1[k] )\nfor k in d2:\n merged[k].add( d2[k] )\n\n",
"One good place to start is by getting iPython (easy_install ipython) then poking around with tab completion, ? and dir:\nIn [2]: dir {}\n------> dir({})\n\nOut[2]: \n['__class__',\n ...\n 'keys',\n 'pop',\n 'popitem',\n 'setdefault',\n 'update',\n 'values']\n\nIn [3]: {}.update?\nType: dict\nBase Class: <type 'dict'>\nString Form: {}\nNamespace: Interactive\nLength: 0\nDocstring:\n dict() -> new empty dictionary.\n dict(mapping) -> new dictionary initialized from a mapping object's\n (key, value) pairs.\n dict(seq) -> new dictionary initialized as if via:\n d = {}\n for k, v in seq:\n d[k] = v\n dict(**kwargs) -> new dictionary initialized with the name=value pairs\n in the keyword argument list. For example: dict(one=1, two=2)\n\n(just for example)\nAnyway, your problem with checking keys common between the two dictionaries: there are a few things to consider (maybe look at the set class?), but here's how I'd do it:\ncommon_keys = [k for k in dict1 if k in dict2]\n\n(ie, \"each key k in dict1 if that key is also in dict2\")\n(note, too, that testing for dictionary membership is an O(1) operation, so this will run in O(|dict1|))\nedit: alright, so this doesn't solve the problem of merging the two dicts into one with lists... But Lott's answer is good for that, or you could use the setdefault method:\nnew = {}\nfor (k, v) in dict1.items():\n new.setdefault(k, []).append(v)\nfor (k, v) in dict2.items():\n new.setdefault(k, []).append(v)\n\n",
"I believe here is what you want:\n>>> d1={'key1':1, 'key2':2}\n>>> d2={'key1':1, 'key2':'A', 'key4':4}\n>>> d = {}\n>>> d.update(d1)\n>>> for i in d2:\n if i in d and d2[i] != d[i]:\n d[i] = [d[i], d2[i]]\n else:\n d[i] = d2[i] \n>>> d\n{'key2': [2, 'A'], 'key1': 1, 'key4': 4}\n\n",
"Here are some good links:\nhttp://www.diveintopython.org/getting_to_know_python/dictionaries.html\nhttp://docs.python.org/tutorial/datastructures.html#dictionaries\n",
"Python dictionaries also work much like associative arrays in PHP, if you have any experience in that language.\nThe Built-in Types page in the Python docs also has a good section on dictionaries, and the section also has a list of functions available for them:\nhttp://docs.python.org/library/stdtypes.html#mapping-types-dict\n",
"well, for your first case, you might want a helper that combines two objects into a list of two objects, and two lists into one list containing items from the two lists, \nThis is assuming of course, that you always merge keys into lists, but you don't want your keys to end up being \"lists of lists\"\ndef listify( obj ): \n if type(obj) != type([]): return [obj]\n else: return obj\n\ndef merge( v1, v2 ):\n return listify(v1) + listify(v2)\n\n#so now you can merge two dictionaries:\ndict1 = dict(a = 2, b = 5, c = 7 )\ndict2 = dict(b = 4, d = 9, f = 10 )\ndikt = {}\n\nfor k in set( dict1.keys() + dict2.keys() ):\n dikt[k] = merge( dict1.get(k, []), dict2.get(k, []) )\n#resutls in:\n# {'a': [2], 'c': [7], 'b': [5, 4], 'd': [9], 'f': [10]}\n\nYou may notice, dict.keys() returns a list of keys, \nset returns a list without duplicate items, so set( d1.keys(), d2.keys() ) returns union of the keys of d1 and d2\n",
"A variation on @SilentGhost's answer (all other answers produce wrong dictionaries):\n>>> d1 = dict(key1=1, key2=2)\n>>> d2 = dict(key1=1, key2='A', key4=4)\n>>> d = dict(d1)\n>>> for k, v2 in d2.iteritems():\n... v = d.get(k, None)\n... d[k] = [v, v2] if v is not None and v != v2 else v2\n...\n>>> d\n{'key2': [2, 'A'], 'key1': 1, 'key4': 4}\n\n",
"Maybe this is a bit awkward to do because the data structure you are trying to create is not as natural as it could be. For example instead of having some values be lone values, and some be lists, why not keep everything in lists? E.g.\n{'key1': [1], 'key2': [2, 'A'], 'key4': [4]}\n\nIt is possible in Python to have a collection of mixed data types but your code will often be cleaner if you keep it coherent. If you use this sort of data structure, inserting is as easy as\n# Inserting a (key, value) pair\nif key in my_dict:\n my_dict[key].append(value)\nelse:\n my_dict[key] = [value]\n\n",
"Here is another variation. \nd1 = {'key1'=1, 'key2'=2}\nd2 = {'key1'=1, 'key2'='A', 'key4'=4)\nd = d2\nfor k, v in d.iteritems():\n... if k in d1.keys() and v!=d1[k]:\n... d[k] = [d1[k], v2]\nd\n{'key2': [2, 'A'], 'key1': 1, 'key4': 4}\n\n"
] |
[
13,
6,
4,
2,
1,
0,
0,
0,
0
] |
[] |
[] |
[
"dictionary",
"python"
] |
stackoverflow_0000631463_dictionary_python.txt
|
Q:
django and sqlalchemy
I'm fairly new to Django and have a basic question: I want to use an ORM that I can work with it for Django and other python projects, so the basic question is Django ORM agnostic and if so how can I use SQLAlchemy with it for example?
If it's not, then what do you suggest for the above problem (using ORM objects that works with both Django and outside it)?
A:
Option 1: Use the Django ORM for other projects. Using only the DB part of Django
This works well. I prefer it.
Option 2: Use SQLAlchemy with Django. SQLAlchemy and django, is it production ready? and Configuring Django to use SQLAlchemy
This works well, also. I don't prefer it because I don't like reconfiguring Django.
|
django and sqlalchemy
|
I'm fairly new to Django and have a basic question: I want to use an ORM that I can work with it for Django and other python projects, so the basic question is Django ORM agnostic and if so how can I use SQLAlchemy with it for example?
If it's not, then what do you suggest for the above problem (using ORM objects that works with both Django and outside it)?
|
[
"Option 1: Use the Django ORM for other projects. Using only the DB part of Django\nThis works well. I prefer it.\nOption 2: Use SQLAlchemy with Django. SQLAlchemy and django, is it production ready? and Configuring Django to use SQLAlchemy\nThis works well, also. I don't prefer it because I don't like reconfiguring Django.\n"
] |
[
14
] |
[] |
[] |
[
"django",
"orm",
"python",
"sqlalchemy"
] |
stackoverflow_0002319231_django_orm_python_sqlalchemy.txt
|
Q:
Python+parsing custom config file
I have a quite big custom made config file I need to extract data from once a week. This is an "in house" config file which doesn't comply to any know standard like INI or such.
My quick and dirty approach was to use re to search for the section header I want and then extract the one or 2 lines of information under this header that I want. This is proving quite a challenge and I'm thinking there must be a easier/more reliable way of doing this, but I keep thinking that I will need to implement a full parser to parse this file and then only to extract the 5 lines of data I need.
The "sections" looks something like this:
Registry com.name.version =
Registry "unique-name I search for using re" =
String name = "modulename";
String timestamp = "not specified";
String java = "not specified";
String user = "not specified";
String host = "not specified";
String system = "not specified";
String version = "This I want";
String "version-major" = "not specified";
String "version-minor" = "not specified";
String scm = "not specified";
String scmrevision = "not specified";
String mode = "release";
String teamCityBuildNumber = "not specified";
;
A:
A simple parser using pyparsing can give you something close to a deserializer, that would let you access fields by key name (like in a dict), or as attributes. Here is the parser:
from pyparsing import (Suppress,quotedString,removeQuotes,Word,alphas,
alphanums, printables,delimitedList,Group,Dict,ZeroOrMore,OneOrMore)
# define punctuation and constants - suppress from parsed output
EQ,SEMI = map(Suppress,"=;")
REGISTRY = Suppress("Registry")
STRING = Suppress("String")
# define some basic building blocks
quotedString.setParseAction(removeQuotes)
ident = quotedString | Word(printables)
value = quotedString
java_path = delimitedList(Word(alphas,alphanums+"_"), '.', combine=True)
# define the config file sections
string_defn = Group(STRING + ident + EQ + value + SEMI)
registry_section = Group(REGISTRY + ident + EQ + Dict(ZeroOrMore(string_defn)))
# special definition for leading java module
java_module = REGISTRY + java_path("path") + EQ
# define the overall config file format
config = java_module("java") + Dict(OneOrMore(registry_section))
Here is a test using your data (read from your data file into config_source):
data = config.parseString(config_source)
print data.dump()
print data["unique-name I search for using re"].version
print data["unique-name I search for using re"].mode
print data["unique-name I search for using re"]["version-major"]
Prints:
['com.name.version', ['unique-name I search for using re', ...
- java: ['com.name.version']
- path: com.name.version
- path: com.name.version
- unique-name I search for using re: [['name', 'modulename'], ...
- host: not specified
- java: not specified
- mode: release
- name: modulename
- scm: not specified
- scmrevision: not specified
- system: not specified
- teamCityBuildNumber: not specified
- timestamp: not specified
- user: not specified
- version: This I want
- version-major: not specified
- version-minor: not specified
This I want
release
not specified
A:
If you only look for special content, using regexp is fine; if you need to read everything, you should rather build yourself a parser.
>> s = ''' ... ''' # as above
>> t = re.search( 'Registry "unique-name" =(.*?)\n;', s, re.S ).group( 1 )
>> u = re.findall( '^\s*(\w+) "?(.*?)"? = "(.*?)";\s*$', t, re.M )
>> for x in u:
print( x )
('String', 'name', 'modulename')
('String', 'timestamp', 'not specified')
('String', 'java', 'not specified')
('String', 'user', 'not specified')
('String', 'host', 'not specified')
('String', 'system', 'not specified')
('String', 'version', 'This I want')
('String', 'version-major', 'not specified')
('String', 'version-minor', 'not specified')
('String', 'scm', 'not specified')
('String', 'scmrevision', 'not specified')
('String', 'mode', 'release')
edit: Although the above version should work for multiple Registry sections, here is a more stricter version:
t = re.search( 'Registry "unique-name"\s*=\s*((?:\s*\w+ "?[^"=]+"?\s*=\s*"[^"]*?";\s*)+)\s*;', s ).group( 1 )
u = re.findall( '^\s*(\w+) "?([^"=]+)"?\s*=\s*"([^"]*?)";\s*$', t, re.M )
A:
Regexp have no state, so you can't use them to parse a complex input. But you can load the file into a string, use a regexp to find a substring and then cut the string at that place.
In your case, search for r'unique-name I search for using re"\s*=\s*', then cut after the match. Then search for r'\n\s*;\s*\n' and cut before the match. This leaves you with the values which you can chop using another regexp.
A:
I think you should create simple parser which create dictionaries of sections with dictionaries of keys. Something like:
#!/usr/bin/python
import re
re_section = re.compile('Registry (.*)=', re.IGNORECASE)
re_value = re.compile('\s+String\s+(\S+)\s*=\s*(.*);')
txt = '''
Registry com.name.version =
Registry "unique-name I search for using re" =
String name = "modulename";
String timestamp = "not specified";
String java = "not specified";
String user = "not specified";
String host = "not specified";
String system = "not specified";
String version = "This I want";
String "version-major" = "not specified";
String "version-minor" = "not specified";
String scm = "not specified";
String scmrevision = "not specified";
String mode = "release";
String teamCityBuildNumber = "not specified";
'''
my_config = {}
section = ''
lines = txt.split('\n')
for l in lines:
rx = re_section.search(l)
if rx:
section = rx.group(1)
section = section.strip('" ')
continue
rx = re_value.search(l)
if rx:
(k, v) = (rx.group(1).strip('" '), rx.group(2).strip('" '))
try:
my_config[section][k] = v
except KeyError:
my_config[section] = {k: v}
Then if you:
print my_config["unique-name I search for using re"]['version']
it will output:
This I want
|
Python+parsing custom config file
|
I have a quite big custom made config file I need to extract data from once a week. This is an "in house" config file which doesn't comply to any know standard like INI or such.
My quick and dirty approach was to use re to search for the section header I want and then extract the one or 2 lines of information under this header that I want. This is proving quite a challenge and I'm thinking there must be a easier/more reliable way of doing this, but I keep thinking that I will need to implement a full parser to parse this file and then only to extract the 5 lines of data I need.
The "sections" looks something like this:
Registry com.name.version =
Registry "unique-name I search for using re" =
String name = "modulename";
String timestamp = "not specified";
String java = "not specified";
String user = "not specified";
String host = "not specified";
String system = "not specified";
String version = "This I want";
String "version-major" = "not specified";
String "version-minor" = "not specified";
String scm = "not specified";
String scmrevision = "not specified";
String mode = "release";
String teamCityBuildNumber = "not specified";
;
|
[
"A simple parser using pyparsing can give you something close to a deserializer, that would let you access fields by key name (like in a dict), or as attributes. Here is the parser:\nfrom pyparsing import (Suppress,quotedString,removeQuotes,Word,alphas,\n alphanums, printables,delimitedList,Group,Dict,ZeroOrMore,OneOrMore)\n\n# define punctuation and constants - suppress from parsed output\nEQ,SEMI = map(Suppress,\"=;\")\nREGISTRY = Suppress(\"Registry\")\nSTRING = Suppress(\"String\")\n\n# define some basic building blocks\nquotedString.setParseAction(removeQuotes)\nident = quotedString | Word(printables)\nvalue = quotedString\njava_path = delimitedList(Word(alphas,alphanums+\"_\"), '.', combine=True)\n\n# define the config file sections\nstring_defn = Group(STRING + ident + EQ + value + SEMI)\nregistry_section = Group(REGISTRY + ident + EQ + Dict(ZeroOrMore(string_defn)))\n\n# special definition for leading java module\njava_module = REGISTRY + java_path(\"path\") + EQ\n\n# define the overall config file format\nconfig = java_module(\"java\") + Dict(OneOrMore(registry_section))\n\nHere is a test using your data (read from your data file into config_source):\ndata = config.parseString(config_source)\nprint data.dump()\nprint data[\"unique-name I search for using re\"].version\nprint data[\"unique-name I search for using re\"].mode\nprint data[\"unique-name I search for using re\"][\"version-major\"]\n\nPrints:\n['com.name.version', ['unique-name I search for using re', ...\n- java: ['com.name.version']\n - path: com.name.version\n- path: com.name.version\n- unique-name I search for using re: [['name', 'modulename'], ...\n - host: not specified\n - java: not specified\n - mode: release\n - name: modulename\n - scm: not specified\n - scmrevision: not specified\n - system: not specified\n - teamCityBuildNumber: not specified\n - timestamp: not specified\n - user: not specified\n - version: This I want\n - version-major: not specified\n - version-minor: not specified\nThis I want\nrelease\nnot specified\n\n",
"If you only look for special content, using regexp is fine; if you need to read everything, you should rather build yourself a parser.\n>> s = ''' ... ''' # as above\n>> t = re.search( 'Registry \"unique-name\" =(.*?)\\n;', s, re.S ).group( 1 )\n>> u = re.findall( '^\\s*(\\w+) \"?(.*?)\"? = \"(.*?)\";\\s*$', t, re.M )\n>> for x in u:\n print( x )\n\n('String', 'name', 'modulename')\n('String', 'timestamp', 'not specified')\n('String', 'java', 'not specified')\n('String', 'user', 'not specified')\n('String', 'host', 'not specified')\n('String', 'system', 'not specified')\n('String', 'version', 'This I want')\n('String', 'version-major', 'not specified')\n('String', 'version-minor', 'not specified')\n('String', 'scm', 'not specified')\n('String', 'scmrevision', 'not specified')\n('String', 'mode', 'release')\n\nedit: Although the above version should work for multiple Registry sections, here is a more stricter version:\nt = re.search( 'Registry \"unique-name\"\\s*=\\s*((?:\\s*\\w+ \"?[^\"=]+\"?\\s*=\\s*\"[^\"]*?\";\\s*)+)\\s*;', s ).group( 1 )\nu = re.findall( '^\\s*(\\w+) \"?([^\"=]+)\"?\\s*=\\s*\"([^\"]*?)\";\\s*$', t, re.M )\n\n",
"Regexp have no state, so you can't use them to parse a complex input. But you can load the file into a string, use a regexp to find a substring and then cut the string at that place.\nIn your case, search for r'unique-name I search for using re\"\\s*=\\s*', then cut after the match. Then search for r'\\n\\s*;\\s*\\n' and cut before the match. This leaves you with the values which you can chop using another regexp.\n",
"I think you should create simple parser which create dictionaries of sections with dictionaries of keys. Something like:\n#!/usr/bin/python\n\nimport re\n\nre_section = re.compile('Registry (.*)=', re.IGNORECASE)\nre_value = re.compile('\\s+String\\s+(\\S+)\\s*=\\s*(.*);')\n\ntxt = '''\nRegistry com.name.version =\nRegistry \"unique-name I search for using re\" =\n String name = \"modulename\";\n String timestamp = \"not specified\";\n String java = \"not specified\";\n String user = \"not specified\";\n String host = \"not specified\";\n String system = \"not specified\";\n String version = \"This I want\";\n String \"version-major\" = \"not specified\";\n String \"version-minor\" = \"not specified\";\n String scm = \"not specified\";\n String scmrevision = \"not specified\";\n String mode = \"release\";\n String teamCityBuildNumber = \"not specified\";\n'''\n\nmy_config = {}\nsection = ''\nlines = txt.split('\\n')\nfor l in lines:\n rx = re_section.search(l)\n if rx:\n section = rx.group(1)\n section = section.strip('\" ')\n continue\n rx = re_value.search(l)\n if rx:\n (k, v) = (rx.group(1).strip('\" '), rx.group(2).strip('\" '))\n try:\n my_config[section][k] = v\n except KeyError:\n my_config[section] = {k: v}\n\nThen if you:\nprint my_config[\"unique-name I search for using re\"]['version']\n\nit will output:\nThis I want\n\n"
] |
[
2,
1,
0,
0
] |
[] |
[] |
[
"config",
"file",
"parsing",
"python"
] |
stackoverflow_0002317070_config_file_parsing_python.txt
|
Q:
PyQt beginremoverows
In the example below:
from PyQt4 import QtCore, QtGui
class Ui_Dialog(QtGui.QDialog):
def __init__(self,parent=None):
QtGui.QDialog.__init__(self,parent)
self.setObjectName("Dialog")
self.resize(600, 500)
self.model = QtGui.QDirModel()
self.tree = QtGui.QTreeView()
self.tree.setModel(self.model)
print(self.model.flags(self.model.index("c:\Program Files")))
self.model.setFilter(QtCore.QDir.Dirs|QtCore.QDir.NoDotAndDotDot)
self.tree.setSortingEnabled(True)
self.tree.setRootIndex(self.model.index("c:\Program Files"))
#self.tree.hideColumn(1)
#self.tree.hideColumn(2)
#self.tree.hideColumn(3)
self.tree.setWindowTitle("Dir View")
self.tree.resize(400, 480)
self.tree.setColumnWidth(0,200)
self.tree.show()
QtCore.QObject.connect(self.tree, QtCore.SIGNAL("clicked(QModelIndex)"), self.test)
QtCore.QMetaObject.connectSlotsByName(self)
self.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
def test(self,index):
print(self.model.filePath(index))
print(self.model.rowCount(index))
#self.model.beginRemoveRows(index.parent(),index.row(),self.model.rowCount(index))
#self.model.endRemoveRows()
print("Row of the index =",index.row())
print("Parent = ",self.model.data(index.parent()))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
ui = Ui_Dialog()
#ui.show()
sys.exit(app.exec_())
I want to remove the row and its children (if any) when i click on it.
(The folder under click and it's children have to be removed.)
I know I'm making mistake on this line:
self.model.beginRemoveRows(index.parent(),index.row(),self.model.rowCount(index))
Thanks for your time.
A:
I know I'm making mistake on this
line:
self.model.beginRemoveRows(index.parent(),index.row(),self.model.rowCount(index))
Yes, you're right. Let's look at what you're passing in:
index.parent() - the parent of index
index.row() - the row number of index, the row you want deleted
self.model.rowCount(index) - the number of total children had by index
Now, take a look at the picture in the documentation on beginRemoveRows:
Your telling it that you want to remove from index.row() to the row equal to the number of children had by index. Your mis-matching your parent-child indices.
What you really wanted was:
beginRemoveRows(index.parent(), index.row(), index.row())
If you remove the row at index.row(), all of its children will be removed automatically.
BUT, there's a bigger problem: beginRemoveRows() does NOT remove any rows. It simply alerts your model that you are going to be removing rows. When you call endRemoveRows(), the model will then let anybody listening know that it's been updated so they can redraw correctly.
In C++, you wouldn't be allowed to call beginRemoveRows() because they are protected methods that only the model is intended to call.
To filter as you'd like, you'll need to create a custom proxy model (i.e. QSortFilterProxyModel) that does the filtering you want. You'll then manipulate the QSortFilterProxy model in response in your signal handler.
A:
Jebagnanadas - I recommend changing your design slightly; instead of using the UI as your model and view, create separate obects to represent what is in your TreeView, and then update those objects and rebuild/refresh your TreeView.
Your test() method should just remove the selected objects from a member variable, and then call a refresh() method (that you need to write) that will clear the TreeView and rebuild it using the updated member variable.
This design is much nicer to work with because it separates the UI from your model, and you don't need to worry about dealing with more QT methods then you have to.
A:
Thanks jcoon and kaleb.. I've hidden the row using setRowHidden() function from the tree view..
|
PyQt beginremoverows
|
In the example below:
from PyQt4 import QtCore, QtGui
class Ui_Dialog(QtGui.QDialog):
def __init__(self,parent=None):
QtGui.QDialog.__init__(self,parent)
self.setObjectName("Dialog")
self.resize(600, 500)
self.model = QtGui.QDirModel()
self.tree = QtGui.QTreeView()
self.tree.setModel(self.model)
print(self.model.flags(self.model.index("c:\Program Files")))
self.model.setFilter(QtCore.QDir.Dirs|QtCore.QDir.NoDotAndDotDot)
self.tree.setSortingEnabled(True)
self.tree.setRootIndex(self.model.index("c:\Program Files"))
#self.tree.hideColumn(1)
#self.tree.hideColumn(2)
#self.tree.hideColumn(3)
self.tree.setWindowTitle("Dir View")
self.tree.resize(400, 480)
self.tree.setColumnWidth(0,200)
self.tree.show()
QtCore.QObject.connect(self.tree, QtCore.SIGNAL("clicked(QModelIndex)"), self.test)
QtCore.QMetaObject.connectSlotsByName(self)
self.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
def test(self,index):
print(self.model.filePath(index))
print(self.model.rowCount(index))
#self.model.beginRemoveRows(index.parent(),index.row(),self.model.rowCount(index))
#self.model.endRemoveRows()
print("Row of the index =",index.row())
print("Parent = ",self.model.data(index.parent()))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
ui = Ui_Dialog()
#ui.show()
sys.exit(app.exec_())
I want to remove the row and its children (if any) when i click on it.
(The folder under click and it's children have to be removed.)
I know I'm making mistake on this line:
self.model.beginRemoveRows(index.parent(),index.row(),self.model.rowCount(index))
Thanks for your time.
|
[
"\nI know I'm making mistake on this\n line:\nself.model.beginRemoveRows(index.parent(),index.row(),self.model.rowCount(index))\n\n\nYes, you're right. Let's look at what you're passing in:\nindex.parent() - the parent of index\nindex.row() - the row number of index, the row you want deleted\nself.model.rowCount(index) - the number of total children had by index\n\nNow, take a look at the picture in the documentation on beginRemoveRows:\nYour telling it that you want to remove from index.row() to the row equal to the number of children had by index. Your mis-matching your parent-child indices.\nWhat you really wanted was:\nbeginRemoveRows(index.parent(), index.row(), index.row())\n\nIf you remove the row at index.row(), all of its children will be removed automatically.\nBUT, there's a bigger problem: beginRemoveRows() does NOT remove any rows. It simply alerts your model that you are going to be removing rows. When you call endRemoveRows(), the model will then let anybody listening know that it's been updated so they can redraw correctly.\nIn C++, you wouldn't be allowed to call beginRemoveRows() because they are protected methods that only the model is intended to call.\nTo filter as you'd like, you'll need to create a custom proxy model (i.e. QSortFilterProxyModel) that does the filtering you want. You'll then manipulate the QSortFilterProxy model in response in your signal handler.\n",
"Jebagnanadas - I recommend changing your design slightly; instead of using the UI as your model and view, create separate obects to represent what is in your TreeView, and then update those objects and rebuild/refresh your TreeView.\nYour test() method should just remove the selected objects from a member variable, and then call a refresh() method (that you need to write) that will clear the TreeView and rebuild it using the updated member variable.\nThis design is much nicer to work with because it separates the UI from your model, and you don't need to worry about dealing with more QT methods then you have to.\n",
"Thanks jcoon and kaleb.. I've hidden the row using setRowHidden() function from the tree view..\n"
] |
[
4,
0,
0
] |
[] |
[] |
[
"pyqt",
"python"
] |
stackoverflow_0002240582_pyqt_python.txt
|
Q:
django, admin template error Caught an exception while rendering: 'NoneType' object has no attribute 'label'
good day guys!
in project, among others, have models:
class Category(models.Model):
name = models.CharField(max_length = 50, blank = False, null = False)
def __unicode__(self):
return "Category %s" % self.name
class Meta:
db_table = "categories"
managed = False
class Site(models.Model):
user = models.ForeignKey(User, blank = False, null = False, db_column = "user_id")
name = models.URLField(verify_exists = True, blank = False, null = False)
categories = models.ManyToManyField(Category, blank = True, through = "CategorySites", verbose_name = "Category")
def __unicode__(self):
return self.name
class Meta:
db_table = "sites"
managed = False
class CategorySites(models.Model):
site = models.ForeignKey(Site, blank = False, null = False, db_column = "site_id")
category = models.ForeignKey(Category, blank = False, null = False, db_column = "category_id")
def __unicode__(self):
return "Relation between site %s and category %s" % (self.site.name, self.category.name)
class Meta:
db_table = "categories_sites"
managed = False
so, as you see there is many-to-many relation. generally it work well - i can add and manage models through manage.py shell, or server-side functions.
I want to enable editing this type of relation on admin site, so, i've added admin model for Sites:
class SiteAdmin(admin.ModelAdmin):
list_display = ('id', 'name')
list_filter = ('name', 'categories')
fieldsets = (
(None, {"fields": ("categories",)}),
)
def queryset(self, request):
qs = super(SiteAdmin, self).queryset(request)
if request.user.is_superuser:
return qs
else:
return qs.filter(user = request.user)
def has_change_permission(self, request, obj=None):
if not obj:
return True # So they can see the change list page
if request.user.is_superuser or obj.user == request.user:
return True
else:
return False
has_delete_permission = has_change_permission
but when i'm going in admin->sites->Add site (or edit) django throws Caught an exception while rendering: 'NoneType' object has no attribute 'label' .
how can if fix it?
A:
For that you need to add undocumented formfield_for_manytomany method to your SiteAdmin class:
from django.contrib.admin import widgets
class SitebAdmin(admin.ModelAdmin):
list_display = ('id', 'name')
list_filter = ('name', 'categories')
def formfield_for_manytomany(self, db_field, request, **kwargs):
if db_field.name == 'categories':
kwargs['widget'] = widgets.FilteredSelectMultiple(
db_field.verbose_name, (db_field.name in self.filter_vertical))
return super(SitebAdmin, self).formfield_for_foreignkey(
db_field, request, **kwargs)
fieldsets = (
(None, {
"fields": ("name", "categories",)
}),
)
to override default of not displaying multiple select widget for models with through option specified docs.
Although this works I still think that this should not cause error in Django.
|
django, admin template error Caught an exception while rendering: 'NoneType' object has no attribute 'label'
|
good day guys!
in project, among others, have models:
class Category(models.Model):
name = models.CharField(max_length = 50, blank = False, null = False)
def __unicode__(self):
return "Category %s" % self.name
class Meta:
db_table = "categories"
managed = False
class Site(models.Model):
user = models.ForeignKey(User, blank = False, null = False, db_column = "user_id")
name = models.URLField(verify_exists = True, blank = False, null = False)
categories = models.ManyToManyField(Category, blank = True, through = "CategorySites", verbose_name = "Category")
def __unicode__(self):
return self.name
class Meta:
db_table = "sites"
managed = False
class CategorySites(models.Model):
site = models.ForeignKey(Site, blank = False, null = False, db_column = "site_id")
category = models.ForeignKey(Category, blank = False, null = False, db_column = "category_id")
def __unicode__(self):
return "Relation between site %s and category %s" % (self.site.name, self.category.name)
class Meta:
db_table = "categories_sites"
managed = False
so, as you see there is many-to-many relation. generally it work well - i can add and manage models through manage.py shell, or server-side functions.
I want to enable editing this type of relation on admin site, so, i've added admin model for Sites:
class SiteAdmin(admin.ModelAdmin):
list_display = ('id', 'name')
list_filter = ('name', 'categories')
fieldsets = (
(None, {"fields": ("categories",)}),
)
def queryset(self, request):
qs = super(SiteAdmin, self).queryset(request)
if request.user.is_superuser:
return qs
else:
return qs.filter(user = request.user)
def has_change_permission(self, request, obj=None):
if not obj:
return True # So they can see the change list page
if request.user.is_superuser or obj.user == request.user:
return True
else:
return False
has_delete_permission = has_change_permission
but when i'm going in admin->sites->Add site (or edit) django throws Caught an exception while rendering: 'NoneType' object has no attribute 'label' .
how can if fix it?
|
[
"For that you need to add undocumented formfield_for_manytomany method to your SiteAdmin class:\nfrom django.contrib.admin import widgets\n\nclass SitebAdmin(admin.ModelAdmin):\n\n list_display = ('id', 'name')\n list_filter = ('name', 'categories')\n\n def formfield_for_manytomany(self, db_field, request, **kwargs):\n if db_field.name == 'categories':\n kwargs['widget'] = widgets.FilteredSelectMultiple(\n db_field.verbose_name, (db_field.name in self.filter_vertical))\n return super(SitebAdmin, self).formfield_for_foreignkey(\n db_field, request, **kwargs)\n\n fieldsets = (\n (None, {\n \"fields\": (\"name\", \"categories\",)\n }),\n )\n\nto override default of not displaying multiple select widget for models with through option specified docs.\nAlthough this works I still think that this should not cause error in Django.\n"
] |
[
1
] |
[] |
[] |
[
"django_admin",
"django_models",
"django_templates",
"python"
] |
stackoverflow_0002319649_django_admin_django_models_django_templates_python.txt
|
Q:
python & sql server
When I do a select statement for varbinary field in microsoft enterprise manager i get the field on readabel hex format like ab2c2f2d... but when i do the same statment with pymssql i get a gibrish
the select statment is : select x from table --where x the varbinary field
could someone help with this issue ?
A:
Microsoft Enterprise Manager is converting the binary value to a hexadecimal string for you.
One option is to change your query to SELECT CAST( x AS varchar ) FROM table. This will have SQL Server convert the varbinary to a hexdecimal string for you, http://msdn.microsoft.com/en-us/library/aa226054(SQL.80).aspx
Another option is to use the python module, binascii to convert the binary data to a hexadecimal string yourself. You use the functions binascii.b2a_hex(data) or binascii.hexlify(data) to do this.
|
python & sql server
|
When I do a select statement for varbinary field in microsoft enterprise manager i get the field on readabel hex format like ab2c2f2d... but when i do the same statment with pymssql i get a gibrish
the select statment is : select x from table --where x the varbinary field
could someone help with this issue ?
|
[
"Microsoft Enterprise Manager is converting the binary value to a hexadecimal string for you. \nOne option is to change your query to SELECT CAST( x AS varchar ) FROM table. This will have SQL Server convert the varbinary to a hexdecimal string for you, http://msdn.microsoft.com/en-us/library/aa226054(SQL.80).aspx\nAnother option is to use the python module, binascii to convert the binary data to a hexadecimal string yourself. You use the functions binascii.b2a_hex(data) or binascii.hexlify(data) to do this.\n"
] |
[
2
] |
[] |
[] |
[
"python",
"sql_server"
] |
stackoverflow_0002320342_python_sql_server.txt
|
Q:
Python: Fastest way to iterate this through a large file
Right, I'm iterating through a large binary file
I need to minimise the time of this loop:
def NB2(self, ID_LEN):
r1=np.fromfile(ReadFile.fid,dTypes.NB_HDR,1)
num_receivers=r1[0][0]
num_channels=r1[0][1]
num_samples=r1[0][5]
blockReturn = np.zeros((num_samples,num_receivers,num_channels))
for rec in range(0,num_receivers):
for chl in range(0,num_channels):
for smpl in range(0,num_samples):
r2_iq=np.fromfile(ReadFile.fid,np.int16,2)
blockReturn[smpl,rec,chl] = np.sqrt(math.fabs(r2_iq[0])*math.fabs(r2_iq[0]) + math.fabs(r2_iq[1])*math.fabs(r2_iq[1]))
return blockReturn
So, what's going on is as follows:
r1 is the header of the file, dTypes.NB_HDR is a type I made:
NB_HDR= np.dtype([('f3',np.uint32),('f4',np.uint32),('f5',np.uint32),('f6',np.int32),('f7',np.int32),('f8',np.uint32)])
That gets all the information about the forthcoming data block, and nicely puts us in the right position within the file (the start of the data block!).
In this data block there is:
4096 samples per channel,
4 channels per receiver,
9 receivers.
So num_receivers, num_channels, num_samples will always be the same (at the moment anyway), but as you can see this is a fairly large amount of data. Each 'sample' is a pair of int16 values that I want to find the magnitude of (hence Pythagoras).
This NB2 code is executed for each 'Block' in the file, for a 12GB file (which is how big they are) there are about 20,900 Blocks, and I've got to iterate through 1000 of these files (so, 12TB overall). Any speed advantage even it's it's milliseconds would be massively appreciated.
EDIT: Actually it might be of help to know how I'm moving around inside the file. I have a function as follows:
def navigateTo(self, blockNum, indexNum):
ReadFile.fid.seek(ReadFile.fileIndex[blockNum][indexNum],0)
ReadFile.currentBlock = blockNum
ReadFile.index = indexNum
Before I run all this code I scan the file and make a list of index locations at ReadFile.fileIndex that I browse using this function and then 'seek' to the absolute location - is this efficient?
Cheers
A:
import numpy as np
def NB2(self, ID_LEN):
r1=np.fromfile(ReadFile.fid,dTypes.NB_HDR,1)
num_receivers=r1[0][0]
num_channels=r1[0][1]
num_samples=r1[0][5]
# first, match your array bounds to the way you are walking the file
blockReturn = np.zeros((num_receivers,num_channels,num_samples))
for rec in range(0,num_receivers):
for chl in range(0,num_channels):
# second, read in all the samples at once if you have enough memory
r2_iq=np.fromfile(ReadFile.fid,np.int16,2*num_samples)
r2_iq.shape = (-1,2) # tell numpy that it is an array of two values
# create dot product vector by squaring data elementwise, and then
# adding those elements together. Results is of length num_samples
r2_iq = r2_iq * r2_iq
r2_iq = r2_iq[:,0] + r2_iq[:,1]
# get the distance by performing the square root "into" blockReturn
np.sqrt(r2_iq, out=blockReturn[rec,chl,:])
return blockReturn
This should help your performance. Two main ideas in numpy work. First, your result arrays dimensions should match how your loop dimensions are crafted, for memory locality.
Second, Numpy is FAST. I've beaten hand coded C with numpy, simply because it uses LAPack and vector acceleration. However to get that power, you have to let it manipulate more data at a time. That is why your sample loop has been collapsed to read in the full sample for the receiver and channel in one large read. Then use the supreme vector powers of numpy to calculate your magnitude by dot product.
There is a little more optimization to be had in the magnitude calculation, but numpy recycles buffers for you, making it less important than you might think. I hope this helps!
A:
Because you know the length of a block after you read the header, read the whole block at once. Then reshape the array (very fast, only affects metadata) and take use the np.hypot ufunc:
blockData = np.fromfile(ReadFile.fid, np.int16, num_receivers*num_channels*num_samples*2)
blockData = blockData.reshape((num_receivers, num_channes, num_samples, 2))
return np.hypot(blockData[:,:,:,0], blockData[:,:,:,1])
On my machine it runs in 11ms per block.
A:
I'd try to use as few loops and as much constants as possible.
Everything that can be done in a linear fashion should be done so.
If values don't change, use constants to reduce lookups and such,
because that eats up cpu cycles.
This is from a theoretical point of view ;-)
If possible use highly optimised libraries. I don't exaclty know what you are trying to achieve but i'd rather use an existing FFT-Lib than writing it myself :>
One more thing: http://en.wikipedia.org/wiki/Big_O_notation (can be an eye-opener)
A:
Most importantly, you shouldn't do file access at the lowest level of a triple nested loop, whether you do this in C or Python. You've got to read in large chunks of data at a time.
So to speed this up, read in large chunks of data at a time, and process that data using numpy indexing (that is, vectorize your code). This is particularly easy in your case since all your data is int32. Just read in big chunks of data, and reshape the data into an array that reflects the (receiver, channel, sample) structure, and then use the appropriate indexing to multiply and add things for Pythagoras, and the 'sum' command to add up the terms in the resulting array.
A:
This is more of an observation than a solution, but porting that function to C++ and loading it in with the Python API would get you a lot of speed gain to begin with before loop optimization.
|
Python: Fastest way to iterate this through a large file
|
Right, I'm iterating through a large binary file
I need to minimise the time of this loop:
def NB2(self, ID_LEN):
r1=np.fromfile(ReadFile.fid,dTypes.NB_HDR,1)
num_receivers=r1[0][0]
num_channels=r1[0][1]
num_samples=r1[0][5]
blockReturn = np.zeros((num_samples,num_receivers,num_channels))
for rec in range(0,num_receivers):
for chl in range(0,num_channels):
for smpl in range(0,num_samples):
r2_iq=np.fromfile(ReadFile.fid,np.int16,2)
blockReturn[smpl,rec,chl] = np.sqrt(math.fabs(r2_iq[0])*math.fabs(r2_iq[0]) + math.fabs(r2_iq[1])*math.fabs(r2_iq[1]))
return blockReturn
So, what's going on is as follows:
r1 is the header of the file, dTypes.NB_HDR is a type I made:
NB_HDR= np.dtype([('f3',np.uint32),('f4',np.uint32),('f5',np.uint32),('f6',np.int32),('f7',np.int32),('f8',np.uint32)])
That gets all the information about the forthcoming data block, and nicely puts us in the right position within the file (the start of the data block!).
In this data block there is:
4096 samples per channel,
4 channels per receiver,
9 receivers.
So num_receivers, num_channels, num_samples will always be the same (at the moment anyway), but as you can see this is a fairly large amount of data. Each 'sample' is a pair of int16 values that I want to find the magnitude of (hence Pythagoras).
This NB2 code is executed for each 'Block' in the file, for a 12GB file (which is how big they are) there are about 20,900 Blocks, and I've got to iterate through 1000 of these files (so, 12TB overall). Any speed advantage even it's it's milliseconds would be massively appreciated.
EDIT: Actually it might be of help to know how I'm moving around inside the file. I have a function as follows:
def navigateTo(self, blockNum, indexNum):
ReadFile.fid.seek(ReadFile.fileIndex[blockNum][indexNum],0)
ReadFile.currentBlock = blockNum
ReadFile.index = indexNum
Before I run all this code I scan the file and make a list of index locations at ReadFile.fileIndex that I browse using this function and then 'seek' to the absolute location - is this efficient?
Cheers
|
[
"import numpy as np\ndef NB2(self, ID_LEN):\n r1=np.fromfile(ReadFile.fid,dTypes.NB_HDR,1)\n num_receivers=r1[0][0]\n num_channels=r1[0][1]\n num_samples=r1[0][5]\n\n # first, match your array bounds to the way you are walking the file\n blockReturn = np.zeros((num_receivers,num_channels,num_samples))\n\n for rec in range(0,num_receivers):\n for chl in range(0,num_channels):\n # second, read in all the samples at once if you have enough memory\n r2_iq=np.fromfile(ReadFile.fid,np.int16,2*num_samples)\n r2_iq.shape = (-1,2) # tell numpy that it is an array of two values\n\n # create dot product vector by squaring data elementwise, and then\n # adding those elements together. Results is of length num_samples\n r2_iq = r2_iq * r2_iq\n r2_iq = r2_iq[:,0] + r2_iq[:,1]\n # get the distance by performing the square root \"into\" blockReturn\n np.sqrt(r2_iq, out=blockReturn[rec,chl,:])\n\n return blockReturn\n\nThis should help your performance. Two main ideas in numpy work. First, your result arrays dimensions should match how your loop dimensions are crafted, for memory locality.\nSecond, Numpy is FAST. I've beaten hand coded C with numpy, simply because it uses LAPack and vector acceleration. However to get that power, you have to let it manipulate more data at a time. That is why your sample loop has been collapsed to read in the full sample for the receiver and channel in one large read. Then use the supreme vector powers of numpy to calculate your magnitude by dot product. \nThere is a little more optimization to be had in the magnitude calculation, but numpy recycles buffers for you, making it less important than you might think. I hope this helps!\n",
"Because you know the length of a block after you read the header, read the whole block at once. Then reshape the array (very fast, only affects metadata) and take use the np.hypot ufunc:\nblockData = np.fromfile(ReadFile.fid, np.int16, num_receivers*num_channels*num_samples*2)\nblockData = blockData.reshape((num_receivers, num_channes, num_samples, 2))\nreturn np.hypot(blockData[:,:,:,0], blockData[:,:,:,1])\n\nOn my machine it runs in 11ms per block.\n",
"I'd try to use as few loops and as much constants as possible.\nEverything that can be done in a linear fashion should be done so.\nIf values don't change, use constants to reduce lookups and such,\nbecause that eats up cpu cycles.\nThis is from a theoretical point of view ;-)\nIf possible use highly optimised libraries. I don't exaclty know what you are trying to achieve but i'd rather use an existing FFT-Lib than writing it myself :>\nOne more thing: http://en.wikipedia.org/wiki/Big_O_notation (can be an eye-opener)\n",
"Most importantly, you shouldn't do file access at the lowest level of a triple nested loop, whether you do this in C or Python. You've got to read in large chunks of data at a time.\nSo to speed this up, read in large chunks of data at a time, and process that data using numpy indexing (that is, vectorize your code). This is particularly easy in your case since all your data is int32. Just read in big chunks of data, and reshape the data into an array that reflects the (receiver, channel, sample) structure, and then use the appropriate indexing to multiply and add things for Pythagoras, and the 'sum' command to add up the terms in the resulting array. \n",
"This is more of an observation than a solution, but porting that function to C++ and loading it in with the Python API would get you a lot of speed gain to begin with before loop optimization.\n"
] |
[
3,
3,
1,
1,
0
] |
[] |
[] |
[
"binary",
"iteration",
"numpy",
"python"
] |
stackoverflow_0002319928_binary_iteration_numpy_python.txt
|
Q:
python egg development environment setup
I inherited a python project, which has been packaged as egg. Upon check out through SVN, I am seeing package content as:
__init__.py
scripts/
ptools/
setup.py
...
Here, ptools/ hold the source of various modules. scripts/ is bunch of end-user tools that make use of modules provided by the "ptools". The package has been installed on this shared host environment through "easy_install", but I want to modify both scripts/ and ptools/ and test them out without having to go through the cycle of "make an egg, and easy_install" that will affect everyone else.
However, I am lost on how to make environment changes to make scripts/ not to search default .egg when invoking through my development tree, instead of using the "local" modules in ptools/ ... any ideas?
Update: I should have added that I tried PYTHONPATH approach by putting the module path in dev tree there, but then I tried verify through "import sys; print sys.path", there is no change in module search path, which baffles me.
thanks
Oliver
A:
I think I have found the solution to my problem, and this has been answered in the following post. "setup.py develop" seems to be the perfect solution
PYTHONPATH vs. sys.path
A:
You can use the PYTHONPATH environment variable to customize the locations Python searches for modules.
|
python egg development environment setup
|
I inherited a python project, which has been packaged as egg. Upon check out through SVN, I am seeing package content as:
__init__.py
scripts/
ptools/
setup.py
...
Here, ptools/ hold the source of various modules. scripts/ is bunch of end-user tools that make use of modules provided by the "ptools". The package has been installed on this shared host environment through "easy_install", but I want to modify both scripts/ and ptools/ and test them out without having to go through the cycle of "make an egg, and easy_install" that will affect everyone else.
However, I am lost on how to make environment changes to make scripts/ not to search default .egg when invoking through my development tree, instead of using the "local" modules in ptools/ ... any ideas?
Update: I should have added that I tried PYTHONPATH approach by putting the module path in dev tree there, but then I tried verify through "import sys; print sys.path", there is no change in module search path, which baffles me.
thanks
Oliver
|
[
"I think I have found the solution to my problem, and this has been answered in the following post. \"setup.py develop\" seems to be the perfect solution\nPYTHONPATH vs. sys.path\n",
"You can use the PYTHONPATH environment variable to customize the locations Python searches for modules.\n"
] |
[
1,
0
] |
[] |
[] |
[
"egg",
"python",
"setuptools"
] |
stackoverflow_0002316052_egg_python_setuptools.txt
|
Q:
Python and curl question
I will be transmitting purchase info (like CC) to a bank gateway and retrieve the result by using Django thus via Python.
What would be the efficient and secure way of doing this?
I have read a documentation of this gateway for php, they seem to use this method:
$xml= Some xml holding data of a purchase.
$curl = `/usr/bin/curl -s -d 'DATA=$xml' "https://url of the virtual bank POS"`;
$data=explode("\n",$curl); //return value is also an xml, seems like they are splitting by each `\n`
and using the $data, they process if the payment is accepted, rejected etc..
I want to achieve this under python language, for this I have done some searching and seems like there is a python curl application named pycurl yet I have no experience using curl and do not know if this is library is suitable for this task. Please keep in mind that as this transfer requires security, I will be using SSL.
Any suggestion will be appreciated.
A:
Use of the standard library urllib2 module should be enough:
import urllib
import urllib2
request_data = urllib.urlencode({"DATA": xml})
response = urllib2.urlopen("https://url of the virtual bank POS", request_data)
response_data = response.read()
data = response_data.split('\n')
I assume that xml variable holds data to be sent.
A:
Citing pycurl.sourceforge.net:
To sum up, PycURL is very fast (esp. for multiple concurrent operations) and very feature complete, but has a somewhat complex interface. If you need something simpler or prefer a pure Python module you might want to check out urllib2 and urlgrabber. There is also a good comparison of the various libraries.
Both curl and urllib2 can work with https so it's up to you.
|
Python and curl question
|
I will be transmitting purchase info (like CC) to a bank gateway and retrieve the result by using Django thus via Python.
What would be the efficient and secure way of doing this?
I have read a documentation of this gateway for php, they seem to use this method:
$xml= Some xml holding data of a purchase.
$curl = `/usr/bin/curl -s -d 'DATA=$xml' "https://url of the virtual bank POS"`;
$data=explode("\n",$curl); //return value is also an xml, seems like they are splitting by each `\n`
and using the $data, they process if the payment is accepted, rejected etc..
I want to achieve this under python language, for this I have done some searching and seems like there is a python curl application named pycurl yet I have no experience using curl and do not know if this is library is suitable for this task. Please keep in mind that as this transfer requires security, I will be using SSL.
Any suggestion will be appreciated.
|
[
"Use of the standard library urllib2 module should be enough:\nimport urllib\nimport urllib2\n\nrequest_data = urllib.urlencode({\"DATA\": xml})\nresponse = urllib2.urlopen(\"https://url of the virtual bank POS\", request_data)\n\nresponse_data = response.read()\ndata = response_data.split('\\n')\n\nI assume that xml variable holds data to be sent.\n",
"Citing pycurl.sourceforge.net:\n\nTo sum up, PycURL is very fast (esp. for multiple concurrent operations) and very feature complete, but has a somewhat complex interface. If you need something simpler or prefer a pure Python module you might want to check out urllib2 and urlgrabber. There is also a good comparison of the various libraries. \n\nBoth curl and urllib2 can work with https so it's up to you.\n"
] |
[
10,
3
] |
[] |
[] |
[
"curl",
"django",
"python"
] |
stackoverflow_0002320107_curl_django_python.txt
|
Q:
Yet another Subversion "Commit failed" MERGE of 'blabla': 200 OK
I get the infamous "MERGE of 'whatever': 200 OK" whenever I try to commit using a post-commit hook on Windows (running the repository and Trac locally), and I'm going crazy. I've been looking all over for a day now, without finding any solutions.
So here's how it's set up and what I've tried so far:
Settings:
Windows 7 (64-bit)
VisualSVN Server
TortoiseSVN
Trac 0.11.6
I'm using the three standard scripts for post-commit on Windows.
Everything works when I run post-commit.cmd from the command prompt with repo and changesetnumber as parameters.
After extensive trouble-shooting, I found that if I remove the last line in trac-post-commit.cmd, Python "%~dp0\trac-post-commit-hook.py" -p "%TRAC_ENV%" -r "%REV%" -u "%AUTHOR%" -m "%LOG%", the Commit failed error goes away.
Adding 1/0 (generating a division by zero error) in the python script doesn't show anything different. From the command prompt I get an error, though.
Removing all code in the python script also makes the commit failed go away, so I guess the culprit is in trac-post-commit-hook.py.
Perhaps if I could send the actual error to a log file, I could dig a little deeper, but I'm not sure how.
post-commit.cmd:
call %~dp0\trac-post-commit-hook.cmd %1 %2
trac-post-commit-hook.cmd:
http://trac.edgewall.org/browser/trunk/contrib/trac-post-commit-hook?rev=920
Thank you so much, it would mean alot if someone could assist a little here!
/Martin
A:
To get the error message while doing the SVN commit, you should be able to change:
if __name__ == "__main__":
if len(sys.argv) < 5:
print "For usage: %s --help" % (sys.argv[0])
else:
CommitHook()
to:
if __name__ == "__main__":
if len(sys.argv) < 5:
print "For usage: %s --help" % (sys.argv[0])
else:
try:
CommitHook()
except Exception, e:
print >> sys.stderr, str(e)
sys.exit(1)
|
Yet another Subversion "Commit failed" MERGE of 'blabla': 200 OK
|
I get the infamous "MERGE of 'whatever': 200 OK" whenever I try to commit using a post-commit hook on Windows (running the repository and Trac locally), and I'm going crazy. I've been looking all over for a day now, without finding any solutions.
So here's how it's set up and what I've tried so far:
Settings:
Windows 7 (64-bit)
VisualSVN Server
TortoiseSVN
Trac 0.11.6
I'm using the three standard scripts for post-commit on Windows.
Everything works when I run post-commit.cmd from the command prompt with repo and changesetnumber as parameters.
After extensive trouble-shooting, I found that if I remove the last line in trac-post-commit.cmd, Python "%~dp0\trac-post-commit-hook.py" -p "%TRAC_ENV%" -r "%REV%" -u "%AUTHOR%" -m "%LOG%", the Commit failed error goes away.
Adding 1/0 (generating a division by zero error) in the python script doesn't show anything different. From the command prompt I get an error, though.
Removing all code in the python script also makes the commit failed go away, so I guess the culprit is in trac-post-commit-hook.py.
Perhaps if I could send the actual error to a log file, I could dig a little deeper, but I'm not sure how.
post-commit.cmd:
call %~dp0\trac-post-commit-hook.cmd %1 %2
trac-post-commit-hook.cmd:
http://trac.edgewall.org/browser/trunk/contrib/trac-post-commit-hook?rev=920
Thank you so much, it would mean alot if someone could assist a little here!
/Martin
|
[
"To get the error message while doing the SVN commit, you should be able to change:\nif __name__ == \"__main__\": \n if len(sys.argv) < 5: \n print \"For usage: %s --help\" % (sys.argv[0]) \n else: \n CommitHook() \n\nto:\nif __name__ == \"__main__\": \n if len(sys.argv) < 5: \n print \"For usage: %s --help\" % (sys.argv[0]) \n else: \n try:\n CommitHook()\n except Exception, e:\n print >> sys.stderr, str(e)\n sys.exit(1)\n\n"
] |
[
0
] |
[] |
[] |
[
"post_commit",
"python",
"svn",
"tortoisesvn",
"visualsvn_server"
] |
stackoverflow_0002320787_post_commit_python_svn_tortoisesvn_visualsvn_server.txt
|
Q:
Is it just me...or is "Facebook Mobile Web" only for PHP?
http://wiki.developers.facebook.com/index.php/Mobile
I use Django/Python as my mobile website.
Am I missing something?
A:
The library may be "officially' for PHP, But that doesnt stop you from making your own.
I would suggest looking at the API. You may be able to port the calls to python using python's httplib.
All the PHP library does is make curl POST and GET calls to Facebook's REST server.
If you are familiar with PHP or Javascript you may be able to look at the library and port the methods yourself.
I suggest a quick google search starting with: python facebook api
edit: In fact I just found: pyfacebook or pyfacebook (on github) These might be a good starting point for you also.
If I wasnt behind a restrictive work firewall I would pull up some API examples. sorry.
A:
"Facebook Connect for Mobile Web is a PHP library..."
|
Is it just me...or is "Facebook Mobile Web" only for PHP?
|
http://wiki.developers.facebook.com/index.php/Mobile
I use Django/Python as my mobile website.
Am I missing something?
|
[
"The library may be \"officially' for PHP, But that doesnt stop you from making your own.\nI would suggest looking at the API. You may be able to port the calls to python using python's httplib.\nAll the PHP library does is make curl POST and GET calls to Facebook's REST server. \nIf you are familiar with PHP or Javascript you may be able to look at the library and port the methods yourself.\nI suggest a quick google search starting with: python facebook api\nedit: In fact I just found: pyfacebook or pyfacebook (on github) These might be a good starting point for you also.\nIf I wasnt behind a restrictive work firewall I would pull up some API examples. sorry.\n",
"\"Facebook Connect for Mobile Web is a PHP library...\"\n"
] |
[
3,
1
] |
[] |
[] |
[
"django",
"facebook",
"mobile",
"php",
"python"
] |
stackoverflow_0002316802_django_facebook_mobile_php_python.txt
|
Q:
How to get the original TCP connection hostname in Python Twisted?
With Twisted's TCP mechanisms, when a protocol is created, the only information about the peer is its IP address and port. How can I retrieve the original hostname that I tried to connect with?
reactor.connectTCP('somehost.com', 80, MyFactory)
How can I ever get 'somehost.com' through a callback somehow? In other words, connectTCP returns an IConnector (whatever it does) - how do I correspond this to something tangible in a callback, since no deferreds are used?
A:
Jerub's answer makes sense semantically. After digging through Twisted code, there is a more expedient and direct way of doing specifically what I'm trying to achieve.
In protocol:
def connectionMade(self):
# This is the original connector that connectTCP returned
connector = self.transport.connector
# This is the original destination requested
connector.getDestination()
A:
The simple answer is, "Record it yourself".
Updating your example:
myfactory = MyFactory(connecthost='somehost.com')
reactor.connectTCP(myfactory.connecthost, 80, myfactory)
If it's an important piece of information, you should be explicitly passing it around explicitly, in much the same way as you would pass around details about why you connected to a host and what to do once a connection is established.
|
How to get the original TCP connection hostname in Python Twisted?
|
With Twisted's TCP mechanisms, when a protocol is created, the only information about the peer is its IP address and port. How can I retrieve the original hostname that I tried to connect with?
reactor.connectTCP('somehost.com', 80, MyFactory)
How can I ever get 'somehost.com' through a callback somehow? In other words, connectTCP returns an IConnector (whatever it does) - how do I correspond this to something tangible in a callback, since no deferreds are used?
|
[
"Jerub's answer makes sense semantically. After digging through Twisted code, there is a more expedient and direct way of doing specifically what I'm trying to achieve.\nIn protocol:\ndef connectionMade(self):\n # This is the original connector that connectTCP returned\n connector = self.transport.connector\n\n # This is the original destination requested\n connector.getDestination()\n\n",
"The simple answer is, \"Record it yourself\".\nUpdating your example:\nmyfactory = MyFactory(connecthost='somehost.com')\nreactor.connectTCP(myfactory.connecthost, 80, myfactory)\n\nIf it's an important piece of information, you should be explicitly passing it around explicitly, in much the same way as you would pass around details about why you connected to a host and what to do once a connection is established.\n"
] |
[
3,
2
] |
[] |
[] |
[
"python",
"tcp",
"twisted"
] |
stackoverflow_0002316365_python_tcp_twisted.txt
|
Q:
In Python, what's a good pattern for disabling certain code during unit tests?
In general I want to disable as little code as possible, and I want it to be explicit: I don't want the code being tested to decide whether it's a test or not, I want the test to tell that code "hey, BTW, I'm running a unit test, can you please not make your call to solr, instead can you please stick what you would send to solr in this spot so I can check it". I have my ideas but I don't like any of them, I am hoping that there's a good pythonic way to do this.
A:
You can use Mock objects to intercept the method calls that you do not want to execute.
E.g. You have some class A, where you don't want method no() to be called during a test.
class A:
def do(self):
print('do')
def no(self):
print('no')
A mock object could inherit from A and override no() to do nothing.
class MockA(A):
def no(self):
pass
You would then create MockA objects instead of As in your test code. Another way to do mocking would be to have A and MockA implement a common interface say InterfaceA.
There are tons of mocking frameworks available. See StackOverflow: Python mocking frameworks.
In particular see: Google's Python mocking framework.
A:
Use Michael Foord's Mock
in your unit test do this:
from mock import Mock
class Person(object):
def __init__(self, name):
super(Person, self).__init__()
self.name = name
def say(self, str):
print "%s says \"%s\"" % (self.name, str)
...
#In your unit test....
#create the class as normal
person = Person("Bob")
#now mock all of person's methods/attributes
person = Mock(spec=person)
#talkto is some function you are testing
talkTo(person)
#make sure the Person class's say method was called
self.assertTrue(person.say.called, "Person wasn't asked to talk")
#make sure the person said "Hello"
args = ("Hello")
keywargs = {}
self.assertEquals(person.say.call_args, (args, keywargs), "Person did not say hello")
A:
The big problem that I was having was with the mechanics of the dependency injection. I have now figured that part out.
I need to import the module in the exact same way in both places to successfully inject the new code. For example, if I have the following code that I want to disable:
from foo_service.foo import solr
solr.add(spam)
I can't seem to do this in the in my test runner:
from foo import solr
solr = mock_object
The python interpreter must be treating the modules foo_service.foo and foo as different entries. I changed from foo import solr to the more explicit from foo_service.foo import solr and my mock object was successfully injected.
A:
You have two ways to do this is no ,or minimal in the case of DI, modifications to your source code
Dependency injection
Monkey patching
The cleanest way is using dependency injection, but I don't really like extensive monkeypatching, and there are some things that are non-possible/difficult to do that dependency injection makes easy.
A:
Typically when something like this arises you use Monkey Patching (also called Duck Punching) to achieve the desired results. Check out this link to learn more about Monkey Patching.
In this case, for example, you would overwrite solr to just print the output you are looking for.
A:
I know it's the typical use case for mock objects, but that's also an old argument... are Mock objects necessary at all or are they evil ?
I'm on the side of those who believe mocks are evil and would try to avoid changing tested code at all. I even believe such need to modify tested code is a code smell...
If you wish to change or intercept an internal function call for testing purpose you could also make this function an explicit external dependency set at instanciation time that would be provided both by your production code and test code. If you do that the problem disappear and you end up with a cleaner interface.
Note that doing that there is not need to change the tested code at all neither internally nor by the test being performed.
|
In Python, what's a good pattern for disabling certain code during unit tests?
|
In general I want to disable as little code as possible, and I want it to be explicit: I don't want the code being tested to decide whether it's a test or not, I want the test to tell that code "hey, BTW, I'm running a unit test, can you please not make your call to solr, instead can you please stick what you would send to solr in this spot so I can check it". I have my ideas but I don't like any of them, I am hoping that there's a good pythonic way to do this.
|
[
"You can use Mock objects to intercept the method calls that you do not want to execute. \nE.g. You have some class A, where you don't want method no() to be called during a test.\nclass A:\n def do(self):\n print('do')\n def no(self):\n print('no')\n\nA mock object could inherit from A and override no() to do nothing.\nclass MockA(A):\n def no(self):\n pass\n\nYou would then create MockA objects instead of As in your test code. Another way to do mocking would be to have A and MockA implement a common interface say InterfaceA. \nThere are tons of mocking frameworks available. See StackOverflow: Python mocking frameworks.\nIn particular see: Google's Python mocking framework.\n",
"Use Michael Foord's Mock\nin your unit test do this:\nfrom mock import Mock\n\nclass Person(object):\n def __init__(self, name):\n super(Person, self).__init__()\n self.name = name\n\n def say(self, str):\n print \"%s says \\\"%s\\\"\" % (self.name, str)\n\n\n...\n\n#In your unit test....\n#create the class as normal\nperson = Person(\"Bob\")\n#now mock all of person's methods/attributes\nperson = Mock(spec=person)\n#talkto is some function you are testing\ntalkTo(person)\n#make sure the Person class's say method was called\nself.assertTrue(person.say.called, \"Person wasn't asked to talk\")\n\n#make sure the person said \"Hello\"\nargs = (\"Hello\")\nkeywargs = {}\nself.assertEquals(person.say.call_args, (args, keywargs), \"Person did not say hello\")\n\n",
"The big problem that I was having was with the mechanics of the dependency injection. I have now figured that part out.\nI need to import the module in the exact same way in both places to successfully inject the new code. For example, if I have the following code that I want to disable:\nfrom foo_service.foo import solr\nsolr.add(spam)\n\nI can't seem to do this in the in my test runner:\nfrom foo import solr\nsolr = mock_object\n\nThe python interpreter must be treating the modules foo_service.foo and foo as different entries. I changed from foo import solr to the more explicit from foo_service.foo import solr and my mock object was successfully injected.\n",
"You have two ways to do this is no ,or minimal in the case of DI, modifications to your source code\n\nDependency injection\nMonkey patching\n\nThe cleanest way is using dependency injection, but I don't really like extensive monkeypatching, and there are some things that are non-possible/difficult to do that dependency injection makes easy.\n",
"Typically when something like this arises you use Monkey Patching (also called Duck Punching) to achieve the desired results. Check out this link to learn more about Monkey Patching.\nIn this case, for example, you would overwrite solr to just print the output you are looking for.\n",
"I know it's the typical use case for mock objects, but that's also an old argument... are Mock objects necessary at all or are they evil ?\nI'm on the side of those who believe mocks are evil and would try to avoid changing tested code at all. I even believe such need to modify tested code is a code smell...\nIf you wish to change or intercept an internal function call for testing purpose you could also make this function an explicit external dependency set at instanciation time that would be provided both by your production code and test code. If you do that the problem disappear and you end up with a cleaner interface.\nNote that doing that there is not need to change the tested code at all neither internally nor by the test being performed.\n"
] |
[
7,
5,
1,
0,
0,
0
] |
[] |
[] |
[
"dependency_injection",
"python",
"testing",
"unit_testing"
] |
stackoverflow_0002320210_dependency_injection_python_testing_unit_testing.txt
|
Q:
Why am I getting the error "cannot import name Scanner" when I try to use the mwclient module for Python?
I'm using Python 2.5.2 (because mwclient still only works for 2.x). I've copied the mwclient folder into the /usr/lib/python2.5/site-packages/mwclient folder, and when I run a program that imports mwclient I get this:
Traceback (most recent call last):
File "get_wiki.py", line 2, in <module>
import mwclient
File "/usr/lib/python2.5/site-packages/PIL/__init__.py", line 32, in <module>
File "/usr/lib/python2.5/site-packages/mwclient/client.py", line 8, in <module>
import simplejson
File "/usr/lib/python2.5/site-packages/PIL/__init__.py", line 95, in <module>
File "/home/troy/eo_project/code/3rd_party/mwclient/simplejson/decoder.py", line 6, in <module>
ImportError: cannot import name Scanner
Scanner seens to exist in the file decoder.py, so I can't figure out what could be wrong.
I'm not set on using mwclient, but I want something that will parse out the mediawiki and HTMl tags whenever possible. I'm looking for plain text to train my language detection program.
A:
Remove the simplejson subdirectory in mwclient if you already have simplejson installed. Or download the latest version from SVN; it has been fixed.
|
Why am I getting the error "cannot import name Scanner" when I try to use the mwclient module for Python?
|
I'm using Python 2.5.2 (because mwclient still only works for 2.x). I've copied the mwclient folder into the /usr/lib/python2.5/site-packages/mwclient folder, and when I run a program that imports mwclient I get this:
Traceback (most recent call last):
File "get_wiki.py", line 2, in <module>
import mwclient
File "/usr/lib/python2.5/site-packages/PIL/__init__.py", line 32, in <module>
File "/usr/lib/python2.5/site-packages/mwclient/client.py", line 8, in <module>
import simplejson
File "/usr/lib/python2.5/site-packages/PIL/__init__.py", line 95, in <module>
File "/home/troy/eo_project/code/3rd_party/mwclient/simplejson/decoder.py", line 6, in <module>
ImportError: cannot import name Scanner
Scanner seens to exist in the file decoder.py, so I can't figure out what could be wrong.
I'm not set on using mwclient, but I want something that will parse out the mediawiki and HTMl tags whenever possible. I'm looking for plain text to train my language detection program.
|
[
"Remove the simplejson subdirectory in mwclient if you already have simplejson installed. Or download the latest version from SVN; it has been fixed.\n"
] |
[
2
] |
[] |
[] |
[
"import",
"mediawiki",
"module",
"python",
"wikipedia"
] |
stackoverflow_0002307805_import_mediawiki_module_python_wikipedia.txt
|
Q:
How to create nested lists in python?
I know you can create easily nested lists in python like this:
[[1,2],[3,4]]
But how to create a 3x3x3 matrix of zeroes?
[[[0] * 3 for i in range(0, 3)] for j in range (0,3)]
or
[[[0]*3]*3]*3
Doesn't seem right. There is no way to create it just passing a list of dimensions to a method? Ex:
CreateArray([3,3,3])
A:
In case a matrix is actually what you are looking for, consider the numpy package.
http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html#numpy.zeros
This will give you a 3x3x3 array of zeros:
numpy.zeros((3,3,3))
You also benefit from the convenience features of a module built for scientific computing.
A:
NumPy addresses this problem
http://www.scipy.org/Tentative_NumPy_Tutorial#head-d3f8e5fe9b903f3c3b2a5c0dfceb60d71602cf93
>>> a = array( [2,3,4] )
>>> a
array([2, 3, 4])
>>> type(a)
<type 'numpy.ndarray'>
But if you want to use the Python native lists as a matrix the following helper methods can become handy:
import copy
def Create(dimensions, item):
for dimension in dimensions:
item = map(copy.copy, [item] * dimension)
return item
def Get(matrix, position):
for index in position:
matrix = matrix[index]
return matrix
def Set(matrix, position, value):
for index in position[:-1]:
matrix = matrix[index]
matrix[position[-1]] = value
A:
List comprehensions are just syntactic sugar for adding expressiveness to list initialization; in your case, I would not use them at all, and go for a simple nested loop.
On a completely different level: do you think the n-dimensional array of NumPy could be a better approach?
Although you can use lists to implement multi-dimensional matrices, I think they are not the best tool for that goal.
A:
Or use the nest function defined here, combined with repeat(0) from the itertools module:
nest(itertools.repeat(0),[3,3,3])
|
How to create nested lists in python?
|
I know you can create easily nested lists in python like this:
[[1,2],[3,4]]
But how to create a 3x3x3 matrix of zeroes?
[[[0] * 3 for i in range(0, 3)] for j in range (0,3)]
or
[[[0]*3]*3]*3
Doesn't seem right. There is no way to create it just passing a list of dimensions to a method? Ex:
CreateArray([3,3,3])
|
[
"In case a matrix is actually what you are looking for, consider the numpy package.\nhttp://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html#numpy.zeros\nThis will give you a 3x3x3 array of zeros:\nnumpy.zeros((3,3,3)) \n\nYou also benefit from the convenience features of a module built for scientific computing.\n",
"NumPy addresses this problem\nhttp://www.scipy.org/Tentative_NumPy_Tutorial#head-d3f8e5fe9b903f3c3b2a5c0dfceb60d71602cf93\n>>> a = array( [2,3,4] )\n>>> a\narray([2, 3, 4])\n>>> type(a)\n<type 'numpy.ndarray'>\n\nBut if you want to use the Python native lists as a matrix the following helper methods can become handy:\nimport copy\n\ndef Create(dimensions, item):\n for dimension in dimensions:\n item = map(copy.copy, [item] * dimension)\n return item\ndef Get(matrix, position):\n for index in position:\n matrix = matrix[index]\n return matrix\ndef Set(matrix, position, value):\n for index in position[:-1]:\n matrix = matrix[index]\n matrix[position[-1]] = value\n\n",
"List comprehensions are just syntactic sugar for adding expressiveness to list initialization; in your case, I would not use them at all, and go for a simple nested loop.\nOn a completely different level: do you think the n-dimensional array of NumPy could be a better approach?\nAlthough you can use lists to implement multi-dimensional matrices, I think they are not the best tool for that goal.\n",
"Or use the nest function defined here, combined with repeat(0) from the itertools module:\nnest(itertools.repeat(0),[3,3,3])\n\n"
] |
[
9,
1,
1,
0
] |
[
"Just nest the multiplication syntax:\n[[[0] * 3] * 3] * 3\n\nIt's therefore simple to express this operation using folds\ndef zeros(dimensions):\n return reduce(lambda x, d: [x] * d, [0] + dimensions)\n\nOr if you want to avoid reference replication, so altering one item won't affect any other you should instead use copies:\nimport copy\ndef zeros(dimensions):\n item = 0\n for dimension in dimensions:\n item = map(copy.copy, [item] * dimension)\n return item\n\n"
] |
[
-3
] |
[
"arrays",
"list",
"matrix",
"nested_lists",
"python"
] |
stackoverflow_0002173087_arrays_list_matrix_nested_lists_python.txt
|
Q:
How to get the status of an Asterisk Server using a Socket - Python
I'm trying to get the status of an Asterisk Server using a python socket but nothing happens.
Here is my code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = '192.168.1.105'
PORT = 5038
s.connect((HOST, PORT))
params = """Action: login
Events: off
Username: admin
Secret: mypass
Action: status
Action: Logoff
"""
s.send(params)
data = s.recv(1024)
print data + '\n'
s.close()
I just get a message saying Asterisk Version and nothing more.
I hope somebody could help me with this.
Thanks in advance.
A:
You have malformed your code there. The Asterisk AMI requires \r\n termination between commands.
You need to send each command in a separate packet:
params = """Action: login
Events: off
Username: admin
Secret: mypass"""
s.send(params + '\r\n')
data = s.recv(1024)
print data + '\n'
params = 'Action: status'
s.send(params + '\r\n')
data = s.recv(1024)
print data + '\n'
params = 'Action: Logoff'
s.send(params + '\r\n')
data = s.recv(1024)
print data + '\n'
That should do the trick. Obviously you'll want to also make a function for it or whatever, but that will make it work.
Always separate AMI commands out!
A:
Handling of even such simple TCP based protocol may become tricky.
Problems in this case:
Each line should be terminated with '\r\n' (not just '\n' as you send)
You should receive all output or the connection may block. Please note, that output may came in multiple chunks (though, it will probably not happen in this case), which should be handled.
Try something like this:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = '192.168.1.105'
PORT = 5038
s.connect((HOST, PORT))
params = ["Action: login",
"Events: off",
"Username: admin",
"Secret: mypass"]
s.send("\r\n".join(params) + "\r\n")
# receive login response
data = ""
while "\r\n" not in data:
data += s.recv(1024)
s.send("Action: status\r\n\r\n")
# receive action response
data = ""
while "\r\n" not in data:
data += s.recv(1024)
print repr(data)
s.send("Action: Logoff\r\n\r\n")
s.close()
|
How to get the status of an Asterisk Server using a Socket - Python
|
I'm trying to get the status of an Asterisk Server using a python socket but nothing happens.
Here is my code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = '192.168.1.105'
PORT = 5038
s.connect((HOST, PORT))
params = """Action: login
Events: off
Username: admin
Secret: mypass
Action: status
Action: Logoff
"""
s.send(params)
data = s.recv(1024)
print data + '\n'
s.close()
I just get a message saying Asterisk Version and nothing more.
I hope somebody could help me with this.
Thanks in advance.
|
[
"You have malformed your code there. The Asterisk AMI requires \\r\\n termination between commands.\nYou need to send each command in a separate packet:\nparams = \"\"\"Action: login\nEvents: off\nUsername: admin\nSecret: mypass\"\"\"\n\ns.send(params + '\\r\\n')\ndata = s.recv(1024)\nprint data + '\\n'\n\nparams = 'Action: status'\ns.send(params + '\\r\\n')\ndata = s.recv(1024)\nprint data + '\\n'\n\nparams = 'Action: Logoff'\ns.send(params + '\\r\\n')\ndata = s.recv(1024)\nprint data + '\\n'\n\nThat should do the trick. Obviously you'll want to also make a function for it or whatever, but that will make it work.\nAlways separate AMI commands out!\n",
"Handling of even such simple TCP based protocol may become tricky.\nProblems in this case:\n\nEach line should be terminated with '\\r\\n' (not just '\\n' as you send)\nYou should receive all output or the connection may block. Please note, that output may came in multiple chunks (though, it will probably not happen in this case), which should be handled.\n\nTry something like this:\nimport socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nHOST = '192.168.1.105'\nPORT = 5038\n\ns.connect((HOST, PORT))\n\nparams = [\"Action: login\",\n \"Events: off\",\n \"Username: admin\",\n \"Secret: mypass\"]\n\ns.send(\"\\r\\n\".join(params) + \"\\r\\n\")\n\n# receive login response\ndata = \"\"\nwhile \"\\r\\n\" not in data:\n data += s.recv(1024)\n\ns.send(\"Action: status\\r\\n\\r\\n\")\n\n# receive action response\ndata = \"\"\nwhile \"\\r\\n\" not in data:\n data += s.recv(1024)\nprint repr(data)\n\ns.send(\"Action: Logoff\\r\\n\\r\\n\")\ns.close()\n\n"
] |
[
2,
1
] |
[] |
[] |
[
"asterisk",
"python",
"sockets"
] |
stackoverflow_0002306115_asterisk_python_sockets.txt
|
Q:
How to override NULL value from aggregate query using MySQLdb module in python?
I am selecting the maximum date value from a MySQL database table in python using the MySQLdb module. If the result comes back as null, I want to override it with a default value. I could do this in the MySQL using a sub-query, but would prefer to do it in python.
Any recommendations on a simple way to do this? I figure this is an easy one, but I'm new to python so I thought it was worth asking.
Here's my code so far:
db=MySQLdb.connect(...)
cur = db.cursor()
cur.execute("select max(date_val) from my_table;")
min_date = cur.fetchone()[0]
Thanks in advance!
Edit:
"print min_date" outputs "None" if the value is null. I want to override it with a default value, such as "2010-01-01".
A:
I could do this in the MySQL using a sub-query, but would prefer to do it in python.
Why do you say you need a subquery? You can just use COALESCE:
"select COALESCE(max(date_val), 'your_default_value_here') from my_table;"
A:
Try this:
min_date = cur.fetchone()[0]
min_date = min_date if min_date is not None else default_value
|
How to override NULL value from aggregate query using MySQLdb module in python?
|
I am selecting the maximum date value from a MySQL database table in python using the MySQLdb module. If the result comes back as null, I want to override it with a default value. I could do this in the MySQL using a sub-query, but would prefer to do it in python.
Any recommendations on a simple way to do this? I figure this is an easy one, but I'm new to python so I thought it was worth asking.
Here's my code so far:
db=MySQLdb.connect(...)
cur = db.cursor()
cur.execute("select max(date_val) from my_table;")
min_date = cur.fetchone()[0]
Thanks in advance!
Edit:
"print min_date" outputs "None" if the value is null. I want to override it with a default value, such as "2010-01-01".
|
[
"\nI could do this in the MySQL using a sub-query, but would prefer to do it in python.\n\nWhy do you say you need a subquery? You can just use COALESCE:\n\"select COALESCE(max(date_val), 'your_default_value_here') from my_table;\"\n\n",
"Try this:\nmin_date = cur.fetchone()[0]\nmin_date = min_date if min_date is not None else default_value\n\n"
] |
[
4,
1
] |
[] |
[] |
[
"mysql",
"python"
] |
stackoverflow_0002321518_mysql_python.txt
|
Q:
Render wikitext with Python
I need to render wikitext (pulled from the database of a mediawiki of it's relevant) and display in some other format (ultimately to be rendered as a PDF, but basically any other format will do).
I can definately hack together something that does the job but ultimately I'll be writing it as I go along, and I can see that the overhead of implementing new tags as people in my team use them will eat up a lot of my time.
Is there a project to do this?
I saw TiddlyWiki which is written in python, which I will look into borrowing their library, but in the meantime I figured there may be a project that's a bit more niche that someone knows?
Cheers
A:
redirect Python module for wiki markup
A:
http://www.mediawiki.org/wiki/Extension:Collection
|
Render wikitext with Python
|
I need to render wikitext (pulled from the database of a mediawiki of it's relevant) and display in some other format (ultimately to be rendered as a PDF, but basically any other format will do).
I can definately hack together something that does the job but ultimately I'll be writing it as I go along, and I can see that the overhead of implementing new tags as people in my team use them will eat up a lot of my time.
Is there a project to do this?
I saw TiddlyWiki which is written in python, which I will look into borrowing their library, but in the meantime I figured there may be a project that's a bit more niche that someone knows?
Cheers
|
[
"redirect Python module for wiki markup\n",
"http://www.mediawiki.org/wiki/Extension:Collection\n"
] |
[
5,
1
] |
[
"pywikipedia i have found to be best\n"
] |
[
-1
] |
[
"mediawiki",
"python",
"wikitext"
] |
stackoverflow_0001836884_mediawiki_python_wikitext.txt
|
Q:
Feedparser newbie questions
After a break from Python(and I knew very little then!) I'm coming back to it for a project(hopefully!). I want to do some parsing using Feedparser & need a few hints to start. Before anyone shouts, I have searched Google and read the docs, but I'm a bit too rusty unfortunately!(So please don't lmgtfy me!)
If I have a rss feed, then how would I parse it in order that I get each of the item titles seperately which can then be inserted into a web page?
Hope that makes sense. Many thanks for any responses.
A:
import feedparser
url = "http://..."
feed = feedparser.parse(url)
for post in feed.entries:
title = post.title
print(title)
If you'd like to extract just the third post, then you could use
post=feed.entries[2]
(since python uses 0-based indexing). Printing post might be helpful; it'll show you what information is available:
print post
And finally, to grab just the title of the third post:
print post['title']
or
print post.title
|
Feedparser newbie questions
|
After a break from Python(and I knew very little then!) I'm coming back to it for a project(hopefully!). I want to do some parsing using Feedparser & need a few hints to start. Before anyone shouts, I have searched Google and read the docs, but I'm a bit too rusty unfortunately!(So please don't lmgtfy me!)
If I have a rss feed, then how would I parse it in order that I get each of the item titles seperately which can then be inserted into a web page?
Hope that makes sense. Many thanks for any responses.
|
[
"import feedparser\nurl = \"http://...\"\nfeed = feedparser.parse(url)\nfor post in feed.entries:\n title = post.title\n print(title)\n\nIf you'd like to extract just the third post, then you could use\npost=feed.entries[2]\n\n(since python uses 0-based indexing). Printing post might be helpful; it'll show you what information is available:\nprint post\n\nAnd finally, to grab just the title of the third post:\nprint post['title']\n\nor\nprint post.title\n\n"
] |
[
1
] |
[] |
[] |
[
"feedparser",
"python",
"rss"
] |
stackoverflow_0002321523_feedparser_python_rss.txt
|
Q:
UTF-8 Encoding error, need help converting text
I've been working on a statistical translation system for haiti (code.google.com/p/ccmts) that uses a C++ backend (http://www.statmt.org/moses/?n=Development.GetStarted) and Python drives the C++ engine/backend.
I've passed a UTF-8 Python string into a C++ std::string, done some processing, gotten a result back into Python and here is the string (when printed from C++ into a Linux terminal):
mwen bezwen ã ¨ d medikal
What encoding is that? Is it a double encoded string?
How do I "fix it" so it's renderable?
Is that printed in that fashion because I'm missing a font or something?
The Python chardet library says:
{'confidence': 0.93812499999999999, 'encoding': 'utf-8'}
but, Python, when I run a string/unicode/codecs decode gives me the old:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 30: ordinal not in range(128)
Oh and Python prints that same exact string into standard output.
A repr() call prints the following: ' mwen bezwen \xc3\xa3 \xc2\xa8 d medikal '
A:
It looks like a case of garbage in, garbage out. Here are a few clues on how to see what you've got in your data. repr() and unicodedata.name() are your friends.
>>> s = ' mwen bezwen \xc3\xa3 \xc2\xa8 d medikal '
>>> print repr(s.decode('utf8'))
u' mwen bezwen \xe3 \xa8 d medikal '
>>> import unicodedata
>>> unicodedata.name(u'\xe3')
'LATIN SMALL LETTER A WITH TILDE'
>>> unicodedata.name(u'\xa8')
'DIAERESIS'
>>>
Update:
If (as A. N. Other implies) you are letting the package choose the output language at random, and you suspect its choice is e.g. Korean (a) tell us (b) try to decode the output using a codec that's relevant to that language .... here are not only Korean but also two each of Chinese, Japanese, and Russian:
>>> s = ' mwen bezwen \xc3\xa3 \xc2\xa8 d medikal '
>>> for enc in 'euc-kr big5 gb2312 shift-jis euc-jp cp1251 koi8-r'.split():
print enc, s.decode(enc)
euc-kr mwen bezwen 찾 짢 d medikal
big5 mwen bezwen 瓊 穡 d medikal
gb2312 mwen bezwen 茫 篓 d medikal
shift-jis mwen bezwen テ」 ツィ d medikal
euc-jp mwen bezwen 達 即 d medikal
cp1251 mwen bezwen ГЈ ВЁ d medikal
koi8-r mwen bezwen цё б╗ d medikal
>>>
None very plausible, really, especially the koi8-r. Further suggestions: Inspect the documentation of the package you interfacing with (URL please!) ... what does it say about encoding? Between which two languages are you trying it? Does "mwen bezwen" make any sense in the expected output language? Try a much larger sample of text -- does chardet still indicate UTF-8? Does any of the larger output make sense in the expected output language? Try it translating English to another language that uses only ASCII -- do you get meaningful ASCII output? Do you care to divulge your Python code and your swig interface code?
update 2 The information flow is interesting: "a string processing app" -> "a statistical language translation system" -> "a machine translation system (opensource/freesoftware) to help out in haiti (crisiscommons.org)"
Please try to replace "unknown" by the facts in the following:
Input language: English (guess)
Output language: Haitian Creole
Operating system: linux
Python version: unknown
C++ package name: unknown
C++ package URL: unknown
C++ package output encoding: unknown
Test 1 input: unknown
Test 1 expected output: unknown
Test 1 actual output (utf8): ' mwen bezwen \xc3\xa3 \xc2\xa8 d medikal '
[Are all of those internal spaces really in the string?]
Test 2 input: 'I need medical aid.'
Test 2 expected output (utf8): 'Mwen bezwen \xc3\xa8d medikal.'
Test 2 actual output (utf8): unknown
Test 2 obtained from both Google Translate (alpha) and
Microsoft Translate (beta):
Mwen bezwen èd medikal.
The third word is LATIN SMALL LETTER E with GRAVE (U+00E8) followed by 'd'.
Update 3
You said """input: utf8 (maybe, i think a couple of my files might have improperly coded text in them) """
Assuming (you've never stated this explicitly) that all your files should be encoded in UTF-8:
The zip file of aligned en-fr-ht corpus has several files that crash when one attempts to decode them as UTF-8.
Diagnosis of why this happens:
chardet is useless (in this case); it faffs about for a long time and comes back with a guess of ISO-8859-2 (Eastern Europe aka Latin2) with a confidence level of 80 to 90 pct.
Next step: chose the ht-en directory (ht uses fewer accented chars than fr therefore easier to see what is going on).
Expectation: e-grave is the most frequent non-ASCII character in presumed-good ht text (a web site, CMU files) ... about 3 times as many as the next one, o-grave. The 3rd most frequent one is lost in the noise.
Got counts of non-ascii bytes in file hten.txt. Top 5:
8a 99164
95 27682
c3 8210
a8 6004
b2 2159
The last three rows are explained by
e-grave is c3 a8 in UTF-8
o-grave is c3 b2 in UTF-8
2159 + 6004 approx == 8210
6004 approx == 3 * 2159
The first 2 rows are explained by
e-grave is 8a in old Western Europe DOS encodings like cp850!!
o-grave is 95 in old Western Europe DOS encodings like cp850!!
99164 approx == 3 * 27682
Explanations that include latin1 or cp1252 don't hold water (8a is a control character in latin1; 8a is S-caron in cp1252).
Inspection of the contents reveals that the file is a conglomeration of multiple original files, some UTF-8, at least one cp850 (or similar). The culprit appears to be the Bible!!!
The mixture of encodings explains why chardet was struggling.
Suggestions:
(1) Implement checking of encoding on all input files. Ensure that they are converted to UTF-8 right up front, like at border control.
(2) Implement a script to check UTF-8 decodability before release.
(3) The orthography of the Bible text appears (at a glance) to be different to that of websites (many more apostrophes). You may wish to discuss with your Creole experts whether your corpus is being distorted by a different orthography ... there is also the question of the words; do you expect to get much use of unleavened bread and sackcloth & ashes? Note the cp850 stuff appears to about 90% of the conglomeration; some Bible might be OK but 90% seems over the top.
(4) Why is Moses not complaining about non-UTF-8 input? Possibilities: (1) it is working on raw bytes i.e. it doesn't convert to Unicode (2) it attempts to convert to Unicode, but silently ignores failure :-(
A:
Looks like your default encoding is ASCII.
You can either explicitly convert your unicode strings:
print u"Hellö, Wörld".encode("utf-8")
Or, if you want to change this globally in your script, replace sys.stdout with a wrapper that encodes it as utf-8:
import sys, codecs
sys.stdout = codecs.EncodedFile(sys.stdout, "utf-8")
print u"Hellö, Wörld!"
Furthermore, you can change the default encoding once and for all (site-wide) via sys.setdefaultencoding, but this can only be done in sitecustomize.py. I would't do this, however -- convenient as it may seem, it affects all python scripts on your system, and might have unintended side-effects.
A:
Edit: Nevermind that junk I posted before; it was wrong.
As others have suggested, this will get you the correct unicode object in python, assuming that's meant to be utf-8:
>>> ' mwen bezwen \xc3\xa3 \xc2\xa8 d medikal '.decode('utf-8')
u' mwen bezwen \xe3 \xa8 d medikal '
>>> print _
mwen bezwen ã ¨ d medikal
It really does seem to be a case of your library giving you garbage, whether garbage when into it or not.
|
UTF-8 Encoding error, need help converting text
|
I've been working on a statistical translation system for haiti (code.google.com/p/ccmts) that uses a C++ backend (http://www.statmt.org/moses/?n=Development.GetStarted) and Python drives the C++ engine/backend.
I've passed a UTF-8 Python string into a C++ std::string, done some processing, gotten a result back into Python and here is the string (when printed from C++ into a Linux terminal):
mwen bezwen ã ¨ d medikal
What encoding is that? Is it a double encoded string?
How do I "fix it" so it's renderable?
Is that printed in that fashion because I'm missing a font or something?
The Python chardet library says:
{'confidence': 0.93812499999999999, 'encoding': 'utf-8'}
but, Python, when I run a string/unicode/codecs decode gives me the old:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 30: ordinal not in range(128)
Oh and Python prints that same exact string into standard output.
A repr() call prints the following: ' mwen bezwen \xc3\xa3 \xc2\xa8 d medikal '
|
[
"It looks like a case of garbage in, garbage out. Here are a few clues on how to see what you've got in your data. repr() and unicodedata.name() are your friends.\n>>> s = ' mwen bezwen \\xc3\\xa3 \\xc2\\xa8 d medikal '\n>>> print repr(s.decode('utf8'))\nu' mwen bezwen \\xe3 \\xa8 d medikal '\n>>> import unicodedata\n>>> unicodedata.name(u'\\xe3')\n'LATIN SMALL LETTER A WITH TILDE'\n>>> unicodedata.name(u'\\xa8')\n'DIAERESIS'\n>>>\n\nUpdate:\nIf (as A. N. Other implies) you are letting the package choose the output language at random, and you suspect its choice is e.g. Korean (a) tell us (b) try to decode the output using a codec that's relevant to that language .... here are not only Korean but also two each of Chinese, Japanese, and Russian:\n>>> s = ' mwen bezwen \\xc3\\xa3 \\xc2\\xa8 d medikal '\n>>> for enc in 'euc-kr big5 gb2312 shift-jis euc-jp cp1251 koi8-r'.split():\n print enc, s.decode(enc)\n\n\neuc-kr mwen bezwen 찾 짢 d medikal \nbig5 mwen bezwen 瓊 穡 d medikal \ngb2312 mwen bezwen 茫 篓 d medikal \nshift-jis mwen bezwen テ」 ツィ d medikal \neuc-jp mwen bezwen 達 即 d medikal \ncp1251 mwen bezwen ГЈ ВЁ d medikal \nkoi8-r mwen bezwen цё б╗ d medikal \n>>> \n\nNone very plausible, really, especially the koi8-r. Further suggestions: Inspect the documentation of the package you interfacing with (URL please!) ... what does it say about encoding? Between which two languages are you trying it? Does \"mwen bezwen\" make any sense in the expected output language? Try a much larger sample of text -- does chardet still indicate UTF-8? Does any of the larger output make sense in the expected output language? Try it translating English to another language that uses only ASCII -- do you get meaningful ASCII output? Do you care to divulge your Python code and your swig interface code?\nupdate 2 The information flow is interesting: \"a string processing app\" -> \"a statistical language translation system\" -> \"a machine translation system (opensource/freesoftware) to help out in haiti (crisiscommons.org)\"\nPlease try to replace \"unknown\" by the facts in the following:\nInput language: English (guess)\nOutput language: Haitian Creole\nOperating system: linux\nPython version: unknown\nC++ package name: unknown\nC++ package URL: unknown\nC++ package output encoding: unknown\n\nTest 1 input: unknown\nTest 1 expected output: unknown\nTest 1 actual output (utf8): ' mwen bezwen \\xc3\\xa3 \\xc2\\xa8 d medikal '\n[Are all of those internal spaces really in the string?]\n\nTest 2 input: 'I need medical aid.'\nTest 2 expected output (utf8): 'Mwen bezwen \\xc3\\xa8d medikal.'\nTest 2 actual output (utf8): unknown\n\nTest 2 obtained from both Google Translate (alpha) and\nMicrosoft Translate (beta):\nMwen bezwen èd medikal.\nThe third word is LATIN SMALL LETTER E with GRAVE (U+00E8) followed by 'd'.\nUpdate 3\nYou said \"\"\"input: utf8 (maybe, i think a couple of my files might have improperly coded text in them) \"\"\"\nAssuming (you've never stated this explicitly) that all your files should be encoded in UTF-8:\nThe zip file of aligned en-fr-ht corpus has several files that crash when one attempts to decode them as UTF-8.\nDiagnosis of why this happens:\nchardet is useless (in this case); it faffs about for a long time and comes back with a guess of ISO-8859-2 (Eastern Europe aka Latin2) with a confidence level of 80 to 90 pct.\nNext step: chose the ht-en directory (ht uses fewer accented chars than fr therefore easier to see what is going on).\nExpectation: e-grave is the most frequent non-ASCII character in presumed-good ht text (a web site, CMU files) ... about 3 times as many as the next one, o-grave. The 3rd most frequent one is lost in the noise.\nGot counts of non-ascii bytes in file hten.txt. Top 5:\n8a 99164\n95 27682\nc3 8210\na8 6004\nb2 2159\n\nThe last three rows are explained by\ne-grave is c3 a8 in UTF-8\no-grave is c3 b2 in UTF-8\n2159 + 6004 approx == 8210\n6004 approx == 3 * 2159\n\nThe first 2 rows are explained by\ne-grave is 8a in old Western Europe DOS encodings like cp850!!\no-grave is 95 in old Western Europe DOS encodings like cp850!!\n99164 approx == 3 * 27682\n\nExplanations that include latin1 or cp1252 don't hold water (8a is a control character in latin1; 8a is S-caron in cp1252).\nInspection of the contents reveals that the file is a conglomeration of multiple original files, some UTF-8, at least one cp850 (or similar). The culprit appears to be the Bible!!!\nThe mixture of encodings explains why chardet was struggling.\nSuggestions: \n(1) Implement checking of encoding on all input files. Ensure that they are converted to UTF-8 right up front, like at border control.\n(2) Implement a script to check UTF-8 decodability before release.\n(3) The orthography of the Bible text appears (at a glance) to be different to that of websites (many more apostrophes). You may wish to discuss with your Creole experts whether your corpus is being distorted by a different orthography ... there is also the question of the words; do you expect to get much use of unleavened bread and sackcloth & ashes? Note the cp850 stuff appears to about 90% of the conglomeration; some Bible might be OK but 90% seems over the top.\n(4) Why is Moses not complaining about non-UTF-8 input? Possibilities: (1) it is working on raw bytes i.e. it doesn't convert to Unicode (2) it attempts to convert to Unicode, but silently ignores failure :-(\n",
"Looks like your default encoding is ASCII.\nYou can either explicitly convert your unicode strings:\nprint u\"Hellö, Wörld\".encode(\"utf-8\")\n\nOr, if you want to change this globally in your script, replace sys.stdout with a wrapper that encodes it as utf-8:\nimport sys, codecs\nsys.stdout = codecs.EncodedFile(sys.stdout, \"utf-8\")\nprint u\"Hellö, Wörld!\"\n\nFurthermore, you can change the default encoding once and for all (site-wide) via sys.setdefaultencoding, but this can only be done in sitecustomize.py. I would't do this, however -- convenient as it may seem, it affects all python scripts on your system, and might have unintended side-effects.\n",
"Edit: Nevermind that junk I posted before; it was wrong.\nAs others have suggested, this will get you the correct unicode object in python, assuming that's meant to be utf-8:\n>>> ' mwen bezwen \\xc3\\xa3 \\xc2\\xa8 d medikal '.decode('utf-8')\nu' mwen bezwen \\xe3 \\xa8 d medikal '\n>>> print _\n mwen bezwen ã ¨ d medikal\n\nIt really does seem to be a case of your library giving you garbage, whether garbage when into it or not.\n"
] |
[
3,
1,
1
] |
[] |
[] |
[
"c++",
"python",
"swig",
"unicode"
] |
stackoverflow_0002320315_c++_python_swig_unicode.txt
|
Q:
Certain Python commands aren't caught in Stdout
I've written a simple program that captures and executes command line Python scripts, but there is a problem. The text passed to a Python input function isn't written to my program despite my program capturing stdout.
For example:
The Python script:
import sys
print("Hello, World!")
x = input("Please enter a number: ")
print(x)
print("This work?")
Would write "Hello, World!" then stop. When I pass it a number it would continue on writing "Please enter a number: 3". What is going on? Any solutions? My C# is as follows:
public partial class PyCon : Window
{
public string strPythonPath;
public string strFile;
public string strArguments;
private StreamWriter sw;
public PyCon(string pythonpath, string file, string args)
{
strPythonPath = pythonpath;
strFile = file;
strArguments = args;
InitializeComponent();
Process p = new Process();
p.StartInfo.FileName = strPythonPath;
p.StartInfo.Arguments = "\"" + strFile + "\" " + strArguments;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
p.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
sw = p.StandardInput;
}
private void p_OutputDataReceived(object sendingProcess, DataReceivedEventArgs received) {
if (!String.IsNullOrEmpty(received.Data)) {
AppendConsole(received.Data);
}
}
private void p_ErrorDataReceived(object sendingProcess, DataReceivedEventArgs received) {
if (!String.IsNullOrEmpty(received.Data)) {
AppendConsole(received.Data);
}
}
private void AppendConsole(string message) {
if (!txtConsole.Dispatcher.CheckAccess()) {
txtConsole.Dispatcher.Invoke(DispatcherPriority.Normal, (System.Windows.Forms.MethodInvoker)delegate() { txtConsole.AppendText(message + "\n"); });
} else {
//Format text
message = message.Replace("\n", Environment.NewLine);
txtConsole.AppendText(message + "\n");
}
}
private void txtInput_KeyUp(object sender, KeyEventArgs e) {
if (e.Key != Key.Enter) return;
sw.WriteLine(txtInput.Text);
txtInput.Text = "";
}
}
Edit: After a lot of research and help from this thread, I've come to the conclusion that the problem is with the Python input command not calling the C# DataReceivedEventHandler. There may not be a solution to this besides scripting changes. If that is the case, I'll make the answer containing those changes as accepted. Thanks for the help, guys!
A:
Smells like the Python i/o is line buffered, i.e. waits for a CRLF then sends a whole line at once. You could try turning that off (python -u myscript.py, or set the PYTHONUNBUFFERED environment variable) or work around it with something like this:
print("Hello, World!")
print("Please enter a number: ")
x = input()
print(x)
A:
It's difficult to tell because I'm using python 2.6 and you appear to be using 3.x, and I also have not programmed in c# for quite awhile but my guess is that this line:
sw.WriteLine(txtInput.Text);
Is sending "3" plus a windows new line character.
Try:
sw.Write(txtInput.Text + "\n")
sw.Flush()
This will just send a normal newline instead of a windows carriage return which may be the issue. Make sure you always Flush when dealing with complicated stream communication like this!
One more thing, make sure you can just redirect this at the command prompt. Too often programmers try to do everything at the same time and get stuck:
./stdintest.py < input.txt
If it doesn't work there, it's not going to work in C#. Good luck
|
Certain Python commands aren't caught in Stdout
|
I've written a simple program that captures and executes command line Python scripts, but there is a problem. The text passed to a Python input function isn't written to my program despite my program capturing stdout.
For example:
The Python script:
import sys
print("Hello, World!")
x = input("Please enter a number: ")
print(x)
print("This work?")
Would write "Hello, World!" then stop. When I pass it a number it would continue on writing "Please enter a number: 3". What is going on? Any solutions? My C# is as follows:
public partial class PyCon : Window
{
public string strPythonPath;
public string strFile;
public string strArguments;
private StreamWriter sw;
public PyCon(string pythonpath, string file, string args)
{
strPythonPath = pythonpath;
strFile = file;
strArguments = args;
InitializeComponent();
Process p = new Process();
p.StartInfo.FileName = strPythonPath;
p.StartInfo.Arguments = "\"" + strFile + "\" " + strArguments;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
p.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
sw = p.StandardInput;
}
private void p_OutputDataReceived(object sendingProcess, DataReceivedEventArgs received) {
if (!String.IsNullOrEmpty(received.Data)) {
AppendConsole(received.Data);
}
}
private void p_ErrorDataReceived(object sendingProcess, DataReceivedEventArgs received) {
if (!String.IsNullOrEmpty(received.Data)) {
AppendConsole(received.Data);
}
}
private void AppendConsole(string message) {
if (!txtConsole.Dispatcher.CheckAccess()) {
txtConsole.Dispatcher.Invoke(DispatcherPriority.Normal, (System.Windows.Forms.MethodInvoker)delegate() { txtConsole.AppendText(message + "\n"); });
} else {
//Format text
message = message.Replace("\n", Environment.NewLine);
txtConsole.AppendText(message + "\n");
}
}
private void txtInput_KeyUp(object sender, KeyEventArgs e) {
if (e.Key != Key.Enter) return;
sw.WriteLine(txtInput.Text);
txtInput.Text = "";
}
}
Edit: After a lot of research and help from this thread, I've come to the conclusion that the problem is with the Python input command not calling the C# DataReceivedEventHandler. There may not be a solution to this besides scripting changes. If that is the case, I'll make the answer containing those changes as accepted. Thanks for the help, guys!
|
[
"Smells like the Python i/o is line buffered, i.e. waits for a CRLF then sends a whole line at once. You could try turning that off (python -u myscript.py, or set the PYTHONUNBUFFERED environment variable) or work around it with something like this:\nprint(\"Hello, World!\")\nprint(\"Please enter a number: \")\nx = input()\nprint(x)\n\n",
"It's difficult to tell because I'm using python 2.6 and you appear to be using 3.x, and I also have not programmed in c# for quite awhile but my guess is that this line:\nsw.WriteLine(txtInput.Text);\n\nIs sending \"3\" plus a windows new line character.\nTry:\nsw.Write(txtInput.Text + \"\\n\")\nsw.Flush()\n\nThis will just send a normal newline instead of a windows carriage return which may be the issue. Make sure you always Flush when dealing with complicated stream communication like this!\nOne more thing, make sure you can just redirect this at the command prompt. Too often programmers try to do everything at the same time and get stuck:\n./stdintest.py < input.txt\n\nIf it doesn't work there, it's not going to work in C#. Good luck\n"
] |
[
1,
1
] |
[] |
[] |
[
"c#",
"input",
"python",
"stdout"
] |
stackoverflow_0002321868_c#_input_python_stdout.txt
|
Q:
Why does this code have the "ball" seem to slide along the edge
My son asked me if I could write a small program to have a ball bounce around the screen then have me explain it.
Spotting a neat father-son opportunity I said "Yes!, no problem". So I dug out my python skills and wrote this..
#!/usr/bin/python
#
# We have to tell python what stuff we're
# going to use. We do this by asking to import
# the code we'll be making use of
#
import curses
import random
import time
#
# We'll be using a screen handling
# package called "curses" so we need
# to initialise the screen
stdscr = curses.initscr()
# We need to make sure that
# keys we type will not show up
# on the screen spoiling the
# stuff we're drawing
curses.noecho()
# We need to tell curses that we don't
# want to wait when we ask for keys from
# the user, if there's non there then
# we want curses to carry on
stdscr.nodelay( True )
# This ones a bit tricky to explain.
# Basically it puts the keyboard into
# a mode which allows curses to do
# things with it...
curses.cbreak()
# Ok, now we can do the fun stuff
# First thing we need to do is to
# find out how big our screen is
max_y, max_x = stdscr.getmaxyx()
stdscr.box()
min_x = 1
min_y = 1
max_y = max_y - 2
max_x = max_x - 2
stdscr.addstr( min_y, min_x, "1" )
stdscr.addstr( min_y, max_x, "2" )
stdscr.addstr( max_y, min_x, "3" )
stdscr.addstr( max_y, max_x, "4" )
dir_x = 1
dir_y = 1
# Then we can pick a random point on the
# screen in both the y (up-down) and x
# (left-right) directions
y = random.randint( 0, max_y )
x = random.randint( 0, max_x )
# Ok, this basically says, while trying to
# get a key from the user keeps coming back
# with an error, meaning there aren't any keys
# to return, do the code inside the loop
while( stdscr.getch() == curses.ERR ):
# Ok, at the location we got, put a "0"
stdscr.addstr( y, x, "O" )
# stdscr.addstr( str( (y, x) ) )
# this just moves the cursor to a new location so we can see the "O" better
stdscr.move( 0, 0 )
# have the screen update
stdscr.refresh()
# now choose a new location
x = x + dir_x
y = y + dir_y
# have we gone too far
if x > max_x or x < min_x:
# change direction
dir_x = -dir_x
x = x + dir_x
if y > max_y or y < min_y:
# change direction
dir_y = -dir_y
y = y + dir_y
# wait a bit so we can see the screen we've drawn.
time.sleep( 0.05 )
# Ok, we're finished. Tidy up
curses.nocbreak()
stdscr.keypad( False )
curses.echo()
curses.endwin()
I ran the program and was quite pleased. However, when the ball hits the edge, it seems to "slide" and not bounce cleanly.
It's quite late in the evening so I couldn't get my head around it and I thought I'd throw it out there and see if anyone could explain why.
I'm not after fixing the code, I'm pretty sure that with <= or >= the tests would work. I just can't understand what it does what it does...
Thx
Mark.
A:
You need to add twice dir_* in the "change direction" code.
A:
You are figuring out a new x and y coordinate before you are testing. So, say the ball is at 20, 1 and is drawn, and assume the dir is North East with slope 1. The next position will be calculated at 21, 0. Here you see the y is out of range now. So you set it back to 1 when what you really want is 2, so you get a slide across the edge. Usually, what I do is test for the next conditions first, then add the new offsets. So...
if x + dir_x > max_x or x - dir_x < min_x:
A:
Getting this kind of simulation to work properly at the edges is tricky. I ran it here and it looks nice to me (OS X). When it hits the edge you'll get two O's in a row at the edge but then it comes back. At a guess, this has to do with how far your virtual x,y point has to penetrate before reversal happens, which depends on how fast it's moving.
A:
Took me a while to work out what you're meaning. You mean the double 'OO' on the wall when it changes direction? Seems to me the conditional allows the ball to go over (not up to) the line and then pulls it back again. I changed this bit:
# have we gone too far
if x >= max_x or x <= min_x:
# change direction
dir_x = -dir_x
#x = x + dir_x
if y >= max_y or y <= min_y:
# change direction
dir_y = -dir_y
#y = y + dir_y
(Note I changed > to >= and same with < and I also commented out the second increment - if you catch it on the line you don't need it.)
Nice little example by the way.
|
Why does this code have the "ball" seem to slide along the edge
|
My son asked me if I could write a small program to have a ball bounce around the screen then have me explain it.
Spotting a neat father-son opportunity I said "Yes!, no problem". So I dug out my python skills and wrote this..
#!/usr/bin/python
#
# We have to tell python what stuff we're
# going to use. We do this by asking to import
# the code we'll be making use of
#
import curses
import random
import time
#
# We'll be using a screen handling
# package called "curses" so we need
# to initialise the screen
stdscr = curses.initscr()
# We need to make sure that
# keys we type will not show up
# on the screen spoiling the
# stuff we're drawing
curses.noecho()
# We need to tell curses that we don't
# want to wait when we ask for keys from
# the user, if there's non there then
# we want curses to carry on
stdscr.nodelay( True )
# This ones a bit tricky to explain.
# Basically it puts the keyboard into
# a mode which allows curses to do
# things with it...
curses.cbreak()
# Ok, now we can do the fun stuff
# First thing we need to do is to
# find out how big our screen is
max_y, max_x = stdscr.getmaxyx()
stdscr.box()
min_x = 1
min_y = 1
max_y = max_y - 2
max_x = max_x - 2
stdscr.addstr( min_y, min_x, "1" )
stdscr.addstr( min_y, max_x, "2" )
stdscr.addstr( max_y, min_x, "3" )
stdscr.addstr( max_y, max_x, "4" )
dir_x = 1
dir_y = 1
# Then we can pick a random point on the
# screen in both the y (up-down) and x
# (left-right) directions
y = random.randint( 0, max_y )
x = random.randint( 0, max_x )
# Ok, this basically says, while trying to
# get a key from the user keeps coming back
# with an error, meaning there aren't any keys
# to return, do the code inside the loop
while( stdscr.getch() == curses.ERR ):
# Ok, at the location we got, put a "0"
stdscr.addstr( y, x, "O" )
# stdscr.addstr( str( (y, x) ) )
# this just moves the cursor to a new location so we can see the "O" better
stdscr.move( 0, 0 )
# have the screen update
stdscr.refresh()
# now choose a new location
x = x + dir_x
y = y + dir_y
# have we gone too far
if x > max_x or x < min_x:
# change direction
dir_x = -dir_x
x = x + dir_x
if y > max_y or y < min_y:
# change direction
dir_y = -dir_y
y = y + dir_y
# wait a bit so we can see the screen we've drawn.
time.sleep( 0.05 )
# Ok, we're finished. Tidy up
curses.nocbreak()
stdscr.keypad( False )
curses.echo()
curses.endwin()
I ran the program and was quite pleased. However, when the ball hits the edge, it seems to "slide" and not bounce cleanly.
It's quite late in the evening so I couldn't get my head around it and I thought I'd throw it out there and see if anyone could explain why.
I'm not after fixing the code, I'm pretty sure that with <= or >= the tests would work. I just can't understand what it does what it does...
Thx
Mark.
|
[
"You need to add twice dir_* in the \"change direction\" code. \n",
"You are figuring out a new x and y coordinate before you are testing. So, say the ball is at 20, 1 and is drawn, and assume the dir is North East with slope 1. The next position will be calculated at 21, 0. Here you see the y is out of range now. So you set it back to 1 when what you really want is 2, so you get a slide across the edge. Usually, what I do is test for the next conditions first, then add the new offsets. So...\nif x + dir_x > max_x or x - dir_x < min_x:\n\n",
"Getting this kind of simulation to work properly at the edges is tricky. I ran it here and it looks nice to me (OS X). When it hits the edge you'll get two O's in a row at the edge but then it comes back. At a guess, this has to do with how far your virtual x,y point has to penetrate before reversal happens, which depends on how fast it's moving.\n",
"Took me a while to work out what you're meaning. You mean the double 'OO' on the wall when it changes direction? Seems to me the conditional allows the ball to go over (not up to) the line and then pulls it back again. I changed this bit:\n# have we gone too far\nif x >= max_x or x <= min_x:\n # change direction\n dir_x = -dir_x\n #x = x + dir_x\n\nif y >= max_y or y <= min_y:\n # change direction\n dir_y = -dir_y\n #y = y + dir_y\n\n(Note I changed > to >= and same with < and I also commented out the second increment - if you catch it on the line you don't need it.)\nNice little example by the way.\n"
] |
[
10,
4,
0,
0
] |
[
"Not really too familiar with python, but is\ndir_x = -dir_x\n\nAcceptable? Maybe try\ndir_x *= -1\n\nor\ndir_x = dir_x * -1\n\n?\n"
] |
[
-2
] |
[
"python"
] |
stackoverflow_0002121287_python.txt
|
Q:
Should a Python generator raise an exception when there are no more elements to yield?
Should a Python generator raise an exception when there are no more elements to yield?
Which one?
A:
The only time I know that you have to manually raise StopIteration is when you are implementing a next() method on a class to signal that the iterator is terminated. For generators (functions with yield statements in them), the end of the function or a return statement will properly trigger the StopIteration for you.
A:
It doesn't have to, but it can raise a StopIteration.
The more normal way to end the iteration is to let the function end and return naturally, or to use a return statement. This will cause a StopIteration to be raised on your behalf.
|
Should a Python generator raise an exception when there are no more elements to yield?
|
Should a Python generator raise an exception when there are no more elements to yield?
Which one?
|
[
"The only time I know that you have to manually raise StopIteration is when you are implementing a next() method on a class to signal that the iterator is terminated. For generators (functions with yield statements in them), the end of the function or a return statement will properly trigger the StopIteration for you.\n",
"It doesn't have to, but it can raise a StopIteration.\nThe more normal way to end the iteration is to let the function end and return naturally, or to use a return statement. This will cause a StopIteration to be raised on your behalf.\n"
] |
[
11,
9
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002322342_python.txt
|
Q:
How can I interactively explore why a test is failing?
I have a test that is failing with:
======================================================================
FAIL: test_register_should_create_UserProfile (APP.forum.tests.test_views.UserTestCAse)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/Bryan/work/app/../app/forum/tests/test_views.py", line 25, in test_register_should_create_UserProfile
self.assertEqual(response.status_code, 200)
AssertionError: 404 != 200
Here is the test:
class UserTestCAse(TestCase):
def test_register_should_create_UserProfile(self):
from django.test.client import Client
c = Client()
# I'm skipping account/signin/ because that requires me to visit Google.
response = c.post('account/signin/complete/', {'username': 'john', "email":'john@beatles.com', u'bnewaccount': 'Signup'})
# request.POST from pdb() session with breakpoint in register()
# <QueryDict: {u'username': [u'john'], u'email': [u'john@beatles.com'], u'bnewaccount': [u'Signup']}>
#How do I inspect what is breaking in the test case?
#How do I run the test client in the shell?
self.assertEqual(response.status_code, 200)
user = User.objects.get(username ='john')
self.assertTrue(user.get_profile())
Is there anyway that I can see why this response is not returning 200?
I tried to use the TestClient() in the shell, but that didn't work:
In [1]: from django.test.client import Client
In [2]: c = Client()
In [3]: response = c.post('account/signin/complete/', {'username': 'john', "email":'john@beatles.com', u'bnewaccount': 'Signup'})
---------------------------------------------------------------------------
KeyError: 'tried'
A:
This doesn't look right.
user = User.objects.get('username'=='john')
If you want to query, you have to write queries in the style shown in the tutorial
http://docs.djangoproject.com/en/1.1/topics/db/queries/#topics-db-queries
user = User.objects.get( username = 'john' )
for example.
To debug, you can run things at the command line. That's what we do. The Django tutorial shows all examples as if they're typed interactively at the command line.
>>> from myapp.models import Client
>>> Client.objects.get( name = 'value' )
etc.
You don't generally try to run the unit tests from the command line. That's hard to do because of all the things the unit test framework does for you.
You generally just step through the application view function statements one at a time to be sure your view functions will actually work.
A:
If you're getting an unexpected 404, the Django error page would show you the error (assuming DEBUG is True). In which case, you could just print response.content to show that traceback, and cut and paste that into a browser.
Also, don't forget you can break into a running test with the interactive debugger, pdb, just like any other form of running code, so you could inspect the response dynamically. Or even, put the breakpoint before the post, so you can step through the view.
However, on a second look, I suspect your url is not matching because you are missing an initial \.
|
How can I interactively explore why a test is failing?
|
I have a test that is failing with:
======================================================================
FAIL: test_register_should_create_UserProfile (APP.forum.tests.test_views.UserTestCAse)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/Bryan/work/app/../app/forum/tests/test_views.py", line 25, in test_register_should_create_UserProfile
self.assertEqual(response.status_code, 200)
AssertionError: 404 != 200
Here is the test:
class UserTestCAse(TestCase):
def test_register_should_create_UserProfile(self):
from django.test.client import Client
c = Client()
# I'm skipping account/signin/ because that requires me to visit Google.
response = c.post('account/signin/complete/', {'username': 'john', "email":'john@beatles.com', u'bnewaccount': 'Signup'})
# request.POST from pdb() session with breakpoint in register()
# <QueryDict: {u'username': [u'john'], u'email': [u'john@beatles.com'], u'bnewaccount': [u'Signup']}>
#How do I inspect what is breaking in the test case?
#How do I run the test client in the shell?
self.assertEqual(response.status_code, 200)
user = User.objects.get(username ='john')
self.assertTrue(user.get_profile())
Is there anyway that I can see why this response is not returning 200?
I tried to use the TestClient() in the shell, but that didn't work:
In [1]: from django.test.client import Client
In [2]: c = Client()
In [3]: response = c.post('account/signin/complete/', {'username': 'john', "email":'john@beatles.com', u'bnewaccount': 'Signup'})
---------------------------------------------------------------------------
KeyError: 'tried'
|
[
"This doesn't look right.\nuser = User.objects.get('username'=='john') \n\nIf you want to query, you have to write queries in the style shown in the tutorial\nhttp://docs.djangoproject.com/en/1.1/topics/db/queries/#topics-db-queries\nuser = User.objects.get( username = 'john' ) \n\nfor example.\nTo debug, you can run things at the command line. That's what we do. The Django tutorial shows all examples as if they're typed interactively at the command line. \n>>> from myapp.models import Client\n>>> Client.objects.get( name = 'value' )\n\netc.\nYou don't generally try to run the unit tests from the command line. That's hard to do because of all the things the unit test framework does for you.\nYou generally just step through the application view function statements one at a time to be sure your view functions will actually work.\n",
"If you're getting an unexpected 404, the Django error page would show you the error (assuming DEBUG is True). In which case, you could just print response.content to show that traceback, and cut and paste that into a browser.\nAlso, don't forget you can break into a running test with the interactive debugger, pdb, just like any other form of running code, so you could inspect the response dynamically. Or even, put the breakpoint before the post, so you can step through the view.\nHowever, on a second look, I suspect your url is not matching because you are missing an initial \\.\n"
] |
[
3,
2
] |
[] |
[] |
[
"django",
"django_testing",
"python"
] |
stackoverflow_0002322093_django_django_testing_python.txt
|
Q:
Automatically prompt to update default site domain name when running Django’s ./manage.py syncdb?
Regarding Django Sites module and manage.py syncdb
The Auth module can prompt to ask for default superuser for the admin site, during .\manage.py syncdb. I would like to see similar things happen for the default site domain name. Currently it is example.com, hardcoded unless I use admin web site to change it. I want to change it during syncdb.
A:
I made a small django app that can be plugged in and play. To plug it in:
download it into project directory or into where your project can find.
add, in your settings.py INSTALLED_APPS, "site_default" (the app name) at the end or after "django.contrib.sites" that it depends on.
Run manage.py syncdb
or manage.py createdefaultsite
Screen shot:
(pinax-dev)>manage.py createdefaultsite
Site domain name: mydomain.com
Site display name: My Site!
(pinax-dev)
It comes with a unit test.
To run unit test:
(pinax-dev)>manage.py test site_default
"site_default" is the app name.
Source code:
http://github.com/peiwei/pinax/raw/master/pinax/apps/site_default.tgz
More Screenshot:
(pinax-dev)> manage.py syncdb
Creating table...
You just installed Django's auth system, which means you don't have any superuse
rs defined.
Would you like to create one now? (yes/no): yes
Username: administrator
E-mail address: who@who.com
Password:
Password (again):
Superuser created successfully.
Would you like to change the default site domain name? (yes/no)[default:no]: yes
Site domain name: mydomain.com
Site display name: My Site!
...
Installing index for signup_codes.SignupCode model
Installing index for signup_codes.SignupCodeResult model
A:
You can do this yourself:
Create a management command to prompt for your new site
connect it to the post_syncdb signal
The command will let you set the site conveniently from the command line. Connecting it to the signal will mean you get prompted whenever the sites app is installed. eg:
from django.contrib.sites import models as sites_app
signals.post_syncdb.connect(create_site, sender=sites_app)
When writing the create_site function (signal handler), you can copy the auth module's approach almost exactly:
def create_site(app, created_models, verbosity, **kwargs):
from django.contrib.sites.models import Site
from django.core.management import call_command
if Site in created_models and kwargs.get('interactive', True):
msg = "\nYou just installed Django's sites system, which means you don't have " \
"any sites defined.\nWould you like to create one now? (yes/no): "
confirm = raw_input(msg)
while 1:
if confirm not in ('yes', 'no'):
confirm = raw_input('Please enter either "yes" or "no": ')
continue
if confirm == 'yes':
call_command("createsite", interactive=True)
break
Now you just need to create your management command createsite and you're done. I do wonder why this isn't already in Django though, I hate example.com.
Put all this into a little app and reuse it for every project your do. Bonus points if you post the app somewhere like google code or django's bug tracker.
|
Automatically prompt to update default site domain name when running Django’s ./manage.py syncdb?
|
Regarding Django Sites module and manage.py syncdb
The Auth module can prompt to ask for default superuser for the admin site, during .\manage.py syncdb. I would like to see similar things happen for the default site domain name. Currently it is example.com, hardcoded unless I use admin web site to change it. I want to change it during syncdb.
|
[
"I made a small django app that can be plugged in and play. To plug it in:\n\ndownload it into project directory or into where your project can find.\nadd, in your settings.py INSTALLED_APPS, \"site_default\" (the app name) at the end or after \"django.contrib.sites\" that it depends on.\nRun manage.py syncdb \nor manage.py createdefaultsite\n\nScreen shot:\n(pinax-dev)>manage.py createdefaultsite\nSite domain name: mydomain.com\nSite display name: My Site!\n(pinax-dev)\n\nIt comes with a unit test.\nTo run unit test:\n(pinax-dev)>manage.py test site_default\n\n\"site_default\" is the app name.\nSource code:\nhttp://github.com/peiwei/pinax/raw/master/pinax/apps/site_default.tgz\nMore Screenshot:\n(pinax-dev)> manage.py syncdb\nCreating table...\nYou just installed Django's auth system, which means you don't have any superuse\nrs defined.\nWould you like to create one now? (yes/no): yes\nUsername: administrator\nE-mail address: who@who.com\nPassword:\nPassword (again):\nSuperuser created successfully.\n\nWould you like to change the default site domain name? (yes/no)[default:no]: yes\n\nSite domain name: mydomain.com\nSite display name: My Site!\n...\nInstalling index for signup_codes.SignupCode model\nInstalling index for signup_codes.SignupCodeResult model\n\n",
"You can do this yourself:\n\nCreate a management command to prompt for your new site\nconnect it to the post_syncdb signal\n\nThe command will let you set the site conveniently from the command line. Connecting it to the signal will mean you get prompted whenever the sites app is installed. eg:\nfrom django.contrib.sites import models as sites_app\nsignals.post_syncdb.connect(create_site, sender=sites_app)\n\nWhen writing the create_site function (signal handler), you can copy the auth module's approach almost exactly:\ndef create_site(app, created_models, verbosity, **kwargs):\nfrom django.contrib.sites.models import Site\nfrom django.core.management import call_command\nif Site in created_models and kwargs.get('interactive', True):\n msg = \"\\nYou just installed Django's sites system, which means you don't have \" \\\n \"any sites defined.\\nWould you like to create one now? (yes/no): \"\n confirm = raw_input(msg)\n while 1:\n if confirm not in ('yes', 'no'):\n confirm = raw_input('Please enter either \"yes\" or \"no\": ')\n continue\n if confirm == 'yes':\n call_command(\"createsite\", interactive=True)\n break\n\nNow you just need to create your management command createsite and you're done. I do wonder why this isn't already in Django though, I hate example.com.\nPut all this into a little app and reuse it for every project your do. Bonus points if you post the app somewhere like google code or django's bug tracker.\n"
] |
[
6,
4
] |
[] |
[] |
[
"django",
"django_sites",
"python"
] |
stackoverflow_0002321771_django_django_sites_python.txt
|
Q:
assign output of print to a variable in python
i want to know how to assign the output of print to a variable.
so if
mystring = "a=\'12\'"
then
print mystring
a=12
and i want to pass this like **kwargs,
test(mystring)
how can i do this?
for more of an explanation: i have a list of strings i got from a a comment line of a data file. it looks like this:
"a='0.015in' lPrime='0.292' offX='45um' offY='75um' sPrime='0.393' twistLength='0'",
"a='0.015in' lPrime='0.292' offX='60um' offY='75um' sPrime='0.393' twistLength='0'",
"a='0.015in' lPrime='0.292' offX='75um' offY='75um' sPrime='0.393' twistLength='0'",
'']
i want to put the values into some structure so i can plot the various things versus any variabls so the list is a legend basically, and i want to plot functions of the traces versus variables given in teh legend.
so if for each entry i have a trace, then i may want to plot max(trace) vs offX for a series of a values.
and my first idea was to pass the strings as **kwargs to a function which would produce a matrix of corresponding data.
A:
Redirect stdout and capture its output in an object?
import sys
# a simple class with a write method
class WritableObject:
def __init__(self):
self.content = []
def write(self, string):
self.content.append(string)
# example with redirection of sys.stdout
foo = WritableObject() # a writable object
sys.stdout = foo # redirection
print "one, two, three, four" # some writing
And then just take the "output" from foo.content and do what you want with it.
Please disregard if I have misunderstood your requirement.
A:
You can call __str__ and __repr__ on python objects to get their string representations (there's a tiny difference between them, so consult the docs). That's actually done by print internally.
A:
I believe one of these two things will accomplish what you're looking for:
The Python exec statement: http://docs.python.org/reference/simple_stmts.html#exec
or the Python eval function: http://docs.python.org/library/functions.html#eval
Both of them let you dynamically evaluate strings as Python code.
UPDATE:
What about:
def calltest(keywordstr):
return eval("test(" + keywordstr + ")")
I think that will do what you're looking for.
A:
for more of an explanation:
i have a list of strings i got from a a comment line of a data file.
it looks like this:
"a='0.015in' lPrime='0.292' offX='45um' offY='75um' sPrime='0.393' twistLength='0'",
"a='0.015in' lPrime='0.292' offX='60um' offY='75um' sPrime='0.393' twistLength='0'",
"a='0.015in' lPrime='0.292' offX='75um' offY='75um' sPrime='0.393' twistLength='0'",
'']
i want to put the values into some structure so i can plot the various things versus any variabls
so the list is a legend basically, and i want to plot functions of the traces versus variables given in teh legend.
so if for each entry i have a trace, then i may want to plot max(trace) vs offX for a series of a values.
A:
If you have a string 'my_string' like this:
a=123 b=456 c='hello'
Then you can pass it to a function 'my_fun' like this:
my_fun(**eval('{' + my_string.replace(' ', ',') + '}'))
Depending on the precise formatting of my_string, you may have to vary this a little, but this should get you 90% of the way there.
A:
I wouldn't do it that way, personally. A far less hackish solution is to build a dictionary from your data first, and then pass it whole to a function as **kwargs. For example (this isn't the most elegant way to do it, but it is illustrative):
import re
remove_non_digits = re.compile(r'[^\d.]+')
inputList = ["a='0.015in' lPrime='0.292' offX='45um' offY='75um' sPrime='0.393' twistLength='0'",
"a='0.015in' lPrime='0.292' offX='60um' offY='75um' sPrime='0.393' twistLength='0'",
"a='0.015in' lPrime='0.292' offX='75um' offY='75um' sPrime='0.393' twistLength='0'", '']
#remove empty strings
flag = True
while flag:
try:
inputList.remove('')
except ValueError:
flag=False
outputList = []
for varString in inputList:
varStringList = varString.split()
varDict = {}
for aVar in varStringList:
varList = aVar.split('=')
varDict[varList[0]] = varList[1]
outputList.append(varDict)
for aDict in outputList:
for aKey in aDict:
aDict[aKey] = float(remove_non_digits.sub('', aDict[aKey]))
print outputList
This prints:
[{'a': 0.014999999999999999, 'offY': 75.0, 'offX': 45.0, 'twistLength': 0.0, 'lPrime': 0.29199999999999998, 'sPrime': 0.39300000000000002}, {'a': 0.014999999999999999, 'offY': 75.0, 'offX': 60.0, 'twistLength': 0.0, 'lPrime': 0.29199999999999998, 'sPrime': 0.39300000000000002}, {'a': 0.014999999999999999, 'offY': 75.0, 'offX': 75.0, 'twistLength': 0.0, 'lPrime': 0.29199999999999998, 'sPrime': 0.39300000000000002}]
Which appears to be exactly what you want.
|
assign output of print to a variable in python
|
i want to know how to assign the output of print to a variable.
so if
mystring = "a=\'12\'"
then
print mystring
a=12
and i want to pass this like **kwargs,
test(mystring)
how can i do this?
for more of an explanation: i have a list of strings i got from a a comment line of a data file. it looks like this:
"a='0.015in' lPrime='0.292' offX='45um' offY='75um' sPrime='0.393' twistLength='0'",
"a='0.015in' lPrime='0.292' offX='60um' offY='75um' sPrime='0.393' twistLength='0'",
"a='0.015in' lPrime='0.292' offX='75um' offY='75um' sPrime='0.393' twistLength='0'",
'']
i want to put the values into some structure so i can plot the various things versus any variabls so the list is a legend basically, and i want to plot functions of the traces versus variables given in teh legend.
so if for each entry i have a trace, then i may want to plot max(trace) vs offX for a series of a values.
and my first idea was to pass the strings as **kwargs to a function which would produce a matrix of corresponding data.
|
[
"Redirect stdout and capture its output in an object?\nimport sys\n\n# a simple class with a write method\nclass WritableObject:\n def __init__(self):\n self.content = []\n def write(self, string):\n self.content.append(string)\n\n# example with redirection of sys.stdout\nfoo = WritableObject() # a writable object\nsys.stdout = foo # redirection\n\nprint \"one, two, three, four\" # some writing\n\nAnd then just take the \"output\" from foo.content and do what you want with it.\nPlease disregard if I have misunderstood your requirement.\n",
"You can call __str__ and __repr__ on python objects to get their string representations (there's a tiny difference between them, so consult the docs). That's actually done by print internally.\n",
"I believe one of these two things will accomplish what you're looking for:\nThe Python exec statement: http://docs.python.org/reference/simple_stmts.html#exec\nor the Python eval function: http://docs.python.org/library/functions.html#eval\nBoth of them let you dynamically evaluate strings as Python code.\nUPDATE:\nWhat about:\ndef calltest(keywordstr):\n return eval(\"test(\" + keywordstr + \")\")\n\nI think that will do what you're looking for.\n",
"for more of an explanation:\ni have a list of strings i got from a a comment line of a data file. \n it looks like this:\n\"a='0.015in' lPrime='0.292' offX='45um' offY='75um' sPrime='0.393' twistLength='0'\",\n \"a='0.015in' lPrime='0.292' offX='60um' offY='75um' sPrime='0.393' twistLength='0'\",\n \"a='0.015in' lPrime='0.292' offX='75um' offY='75um' sPrime='0.393' twistLength='0'\",\n '']\n\ni want to put the values into some structure so i can plot the various things versus any variabls \nso the list is a legend basically, and i want to plot functions of the traces versus variables given in teh legend. \nso if for each entry i have a trace, then i may want to plot max(trace) vs offX for a series of a values.\n",
"If you have a string 'my_string' like this:\na=123 b=456 c='hello'\n\nThen you can pass it to a function 'my_fun' like this:\nmy_fun(**eval('{' + my_string.replace(' ', ',') + '}'))\n\nDepending on the precise formatting of my_string, you may have to vary this a little, but this should get you 90% of the way there.\n",
"I wouldn't do it that way, personally. A far less hackish solution is to build a dictionary from your data first, and then pass it whole to a function as **kwargs. For example (this isn't the most elegant way to do it, but it is illustrative):\nimport re\n\nremove_non_digits = re.compile(r'[^\\d.]+')\n\ninputList = [\"a='0.015in' lPrime='0.292' offX='45um' offY='75um' sPrime='0.393' twistLength='0'\",\n \"a='0.015in' lPrime='0.292' offX='60um' offY='75um' sPrime='0.393' twistLength='0'\",\n \"a='0.015in' lPrime='0.292' offX='75um' offY='75um' sPrime='0.393' twistLength='0'\", '']\n\n#remove empty strings\nflag = True\nwhile flag:\n try:\n inputList.remove('')\n except ValueError:\n flag=False\n\noutputList = []\n\nfor varString in inputList:\n varStringList = varString.split()\n varDict = {}\n for aVar in varStringList:\n varList = aVar.split('=')\n varDict[varList[0]] = varList[1]\n outputList.append(varDict)\n\nfor aDict in outputList:\n for aKey in aDict:\n aDict[aKey] = float(remove_non_digits.sub('', aDict[aKey]))\n\nprint outputList\n\nThis prints:\n[{'a': 0.014999999999999999, 'offY': 75.0, 'offX': 45.0, 'twistLength': 0.0, 'lPrime': 0.29199999999999998, 'sPrime': 0.39300000000000002}, {'a': 0.014999999999999999, 'offY': 75.0, 'offX': 60.0, 'twistLength': 0.0, 'lPrime': 0.29199999999999998, 'sPrime': 0.39300000000000002}, {'a': 0.014999999999999999, 'offY': 75.0, 'offX': 75.0, 'twistLength': 0.0, 'lPrime': 0.29199999999999998, 'sPrime': 0.39300000000000002}]\n\nWhich appears to be exactly what you want. \n"
] |
[
6,
2,
0,
0,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002321939_python.txt
|
Q:
Django array or list output?
I'm pulling a set of image urls and their respective titles. I've tried creating a hash or associative array, but the data seems to overwrite so I only end up with the last item in the array.
For example;
thumbnail_list = []
for file in media:
thumbnail_list['url'] = file.url
thumbnail_list['title'] = file.title
I've even tried creating two lists and putting them in a larger one.
thumbnail_list.append('foo')
thumbnail_urls.append('bar')
all_thumbs = [thumbnail_list], [thumbnail_urls]
I'm trying to create a link out of this data:
<a href="image-url">image title</a>
I keep getting close, but I end up looping over too much data or all of the data at once in my django template.
Ideas?
Edit: Maybe zip() is what I need?
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print 'What is your {0}? It is {1}.'.format(q, a)
A:
You want a dict, which is Python's associative data structure, whereas you are creating a list.
But I'm not sure I understand your problem. Why not just pass your media collection into the template and iterate like this:
{% for file in media %}
<a href="{{ file.url }}">{{ file.title }}</a>
{% endfor %}
EDIT
Based on your comment, I now presume you are looking for something like this:
thumbnail_list = []
for file in media:
file_info = {}
file_info['url'] = file.url
file_info['title'] = file.title
thumbnail_list.append(file_info)
{% for file in thumbnail_list %}
<a href="{{ file.url }}">{{ file.title }}</a>
{% endfor %}
You can create a list, then for each file, append a dictionary into that list after you've processed the URL, title, or whatever.
Or, you could create your own class that encapsulates this a little better in case you have other logic to apply:
class FileInfo(object):
def __init__(self, file):
self.url = file.url # do whatever
self.title = file.title # do whatever
thumbnail_list = []
for file in media:
thumbnail_list.append(FileInfo(file))
|
Django array or list output?
|
I'm pulling a set of image urls and their respective titles. I've tried creating a hash or associative array, but the data seems to overwrite so I only end up with the last item in the array.
For example;
thumbnail_list = []
for file in media:
thumbnail_list['url'] = file.url
thumbnail_list['title'] = file.title
I've even tried creating two lists and putting them in a larger one.
thumbnail_list.append('foo')
thumbnail_urls.append('bar')
all_thumbs = [thumbnail_list], [thumbnail_urls]
I'm trying to create a link out of this data:
<a href="image-url">image title</a>
I keep getting close, but I end up looping over too much data or all of the data at once in my django template.
Ideas?
Edit: Maybe zip() is what I need?
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print 'What is your {0}? It is {1}.'.format(q, a)
|
[
"You want a dict, which is Python's associative data structure, whereas you are creating a list. \nBut I'm not sure I understand your problem. Why not just pass your media collection into the template and iterate like this:\n{% for file in media %}\n <a href=\"{{ file.url }}\">{{ file.title }}</a>\n{% endfor %}\n\nEDIT\nBased on your comment, I now presume you are looking for something like this:\nthumbnail_list = []\nfor file in media:\n file_info = {}\n file_info['url'] = file.url\n file_info['title'] = file.title\n thumbnail_list.append(file_info)\n\n{% for file in thumbnail_list %}\n <a href=\"{{ file.url }}\">{{ file.title }}</a>\n{% endfor %}\n\nYou can create a list, then for each file, append a dictionary into that list after you've processed the URL, title, or whatever.\nOr, you could create your own class that encapsulates this a little better in case you have other logic to apply:\nclass FileInfo(object):\n def __init__(self, file):\n self.url = file.url # do whatever\n self.title = file.title # do whatever\n\nthumbnail_list = []\nfor file in media:\n thumbnail_list.append(FileInfo(file))\n\n"
] |
[
5
] |
[] |
[] |
[
"associative_array",
"django",
"hash",
"python"
] |
stackoverflow_0002322739_associative_array_django_hash_python.txt
|
Q:
How do I change permissions to a socket?
I am trying to run a simple Python based web server given here.
And I get the following error message:
Traceback (most recent call last):
File "webserver.py", line 63, in <module>
main()
File "webserver.py", line 55, in main
server = HTTPServer(('', 80), MyHandler)
File "/usr/lib/python2.5/SocketServer.py", line 330, in __init__
self.server_bind()
File "/usr/lib/python2.5/BaseHTTPServer.py", line 101, in server_bind
SocketServer.TCPServer.server_bind(self)
File "/usr/lib/python2.5/SocketServer.py", line 341, in server_bind
self.socket.bind(self.server_address)
File "<string>", line 1, in bind
socket.error: (13, 'Permission denied')
As far as I understand my firewall blocks access to a socket? Am I right? If it is the case, how can I change the permissions? Is it dangerous to change these permissions?
A:
If you want to bind to port numbers < 1024, you need to be root. It's not a firewall
issue; it's enforced by the operating system. Here's a reference from w3.org,
and a FAQ entry specific to Unix.
A:
If you want to run on a port under 1024, you'll need to be root. You can open the socket and drop root's permission for the rest of your program by switching to another user.
Most times it's easier to run a real webserver (say nginx) on port 80 and proxy the requests through to your program which you can run on a high numbered port (8080 for example). This way you don't need to worry about screwing something up during the time your process is running as root, as it never runs as root.
If it's just for testing, run the server on port 8080 and connect at http://localhost:8080/
|
How do I change permissions to a socket?
|
I am trying to run a simple Python based web server given here.
And I get the following error message:
Traceback (most recent call last):
File "webserver.py", line 63, in <module>
main()
File "webserver.py", line 55, in main
server = HTTPServer(('', 80), MyHandler)
File "/usr/lib/python2.5/SocketServer.py", line 330, in __init__
self.server_bind()
File "/usr/lib/python2.5/BaseHTTPServer.py", line 101, in server_bind
SocketServer.TCPServer.server_bind(self)
File "/usr/lib/python2.5/SocketServer.py", line 341, in server_bind
self.socket.bind(self.server_address)
File "<string>", line 1, in bind
socket.error: (13, 'Permission denied')
As far as I understand my firewall blocks access to a socket? Am I right? If it is the case, how can I change the permissions? Is it dangerous to change these permissions?
|
[
"If you want to bind to port numbers < 1024, you need to be root. It's not a firewall\nissue; it's enforced by the operating system. Here's a reference from w3.org,\nand a FAQ entry specific to Unix.\n",
"If you want to run on a port under 1024, you'll need to be root. You can open the socket and drop root's permission for the rest of your program by switching to another user.\nMost times it's easier to run a real webserver (say nginx) on port 80 and proxy the requests through to your program which you can run on a high numbered port (8080 for example). This way you don't need to worry about screwing something up during the time your process is running as root, as it never runs as root.\nIf it's just for testing, run the server on port 8080 and connect at http://localhost:8080/\n"
] |
[
11,
2
] |
[] |
[] |
[
"firewall",
"python",
"sockets",
"ubuntu",
"webserver"
] |
stackoverflow_0002322349_firewall_python_sockets_ubuntu_webserver.txt
|
Q:
How do I prevent my Python application from automatically closing once reaching the end of code?
I'm new to programming, especially Python. I'm trying to make an application that converts Fahrenheit to Celsius, but I don't know how to make the program stay open. Whenever it reaches the end of the code, it automatically closes before the user can see his or her results. I'm using Python 2.6.
A:
Well, I guess you mean the terminal that Windows opens for you when you run a python file is closed too fast. You can add raw_input('Press Enter to exit') right before your program would exit. It tells Python to wait for input before exiting.
A:
As the other people say, just ask for input to get it to hold. However, I would recommend running your Python scripts in a different manner in Windows. Using the IDLE IDE (should have come with your distribution), just open the script you want to run and press F5. Then, not only can you see the output for as long as you like, but you can also examine any variables that were assigned interactively. This is very handy especially when you are just starting to program in Python.
You can also run scripts from the command line, but I would recommend use IDLE if you're just starting out.
A:
ask user to enter one more variable and print "Press enter to exit..."
|
How do I prevent my Python application from automatically closing once reaching the end of code?
|
I'm new to programming, especially Python. I'm trying to make an application that converts Fahrenheit to Celsius, but I don't know how to make the program stay open. Whenever it reaches the end of the code, it automatically closes before the user can see his or her results. I'm using Python 2.6.
|
[
"Well, I guess you mean the terminal that Windows opens for you when you run a python file is closed too fast. You can add raw_input('Press Enter to exit') right before your program would exit. It tells Python to wait for input before exiting. \n",
"As the other people say, just ask for input to get it to hold. However, I would recommend running your Python scripts in a different manner in Windows. Using the IDLE IDE (should have come with your distribution), just open the script you want to run and press F5. Then, not only can you see the output for as long as you like, but you can also examine any variables that were assigned interactively. This is very handy especially when you are just starting to program in Python.\nYou can also run scripts from the command line, but I would recommend use IDLE if you're just starting out.\n",
"ask user to enter one more variable and print \"Press enter to exit...\"\n"
] |
[
10,
3,
0
] |
[] |
[] |
[
"python",
"python_2.6",
"python_2.x"
] |
stackoverflow_0002322868_python_python_2.6_python_2.x.txt
|
Q:
Module "duck typing" pitfalls?
I just started experimenting with a new technique I name (for the moment at least) "module duck typing".
Example:
Main Module
import somepackage.req ## module required by all others
import abc
import Xyz
Module abc
__all__=[]
def getBus():
""" Locates the `req` for this application """
for mod_name in sys.modules:
if mod_name.find("req") > 0:
return sys.modules[mod_name].__dict__["Bus"]
raise RuntimeError("cannot find `req` module")
Bus=getBus()
In module abc I do not need to explicitly import req: it could be anywhere in the package hierarchy. Of course this requires some discipline...
With this technique, it is easy to relocate packages within the hierarchy.
Are there pitfalls awaiting me? e.g. moving to Python 3K
Updated: after some more testing, I decided to go back to inserting package dependencies directly in sys.path.
A:
There might be all kinds of modules imported that contain "req" and you don't know if it's the module you are actually looking for:
>>> import urllib.request
>>> import tst
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "tst.py", line 12, in <module>
Bus=getBus()
File "tst.py", line 9, in getBus
return sys.modules[mod_name].__dict__["Bus"]
KeyError: 'Bus'
The whole point of packages is that there are namespaces for module hierarchies. Looking up module names "from any package" just causes your code to break randomly if the user happens to import some library that happens to contain a module with a conflicting name.
A:
This technique is dangerous and error prone. It could work with your tests until the day that someone imports a new something.req and gets a confusing, far-off error. (This is in the best case scenario; the current implementation would jump on many other modules.) If you restructure packages, it's easy enough to at that time modify your code in an automated fashion without any use of magic. Python makes it possible to do all sorts of magical, dynamic things, but that doesn't mean we should.
A:
I think this is more like duck typing. I would also recommend using a more unique identifier than "Bus"
def getBus():
""" Locates the Bus for this application """
for mod in sys.modules.values():
if hasattr(mod, 'Bus') and type(mod.Bus) is...: # check other stuff about mod.Bus
return mod.Bus
raise RuntimeError("cannot find Bus")
|
Module "duck typing" pitfalls?
|
I just started experimenting with a new technique I name (for the moment at least) "module duck typing".
Example:
Main Module
import somepackage.req ## module required by all others
import abc
import Xyz
Module abc
__all__=[]
def getBus():
""" Locates the `req` for this application """
for mod_name in sys.modules:
if mod_name.find("req") > 0:
return sys.modules[mod_name].__dict__["Bus"]
raise RuntimeError("cannot find `req` module")
Bus=getBus()
In module abc I do not need to explicitly import req: it could be anywhere in the package hierarchy. Of course this requires some discipline...
With this technique, it is easy to relocate packages within the hierarchy.
Are there pitfalls awaiting me? e.g. moving to Python 3K
Updated: after some more testing, I decided to go back to inserting package dependencies directly in sys.path.
|
[
"There might be all kinds of modules imported that contain \"req\" and you don't know if it's the module you are actually looking for:\n>>> import urllib.request\n>>> import tst\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"tst.py\", line 12, in <module>\n Bus=getBus()\n File \"tst.py\", line 9, in getBus\n return sys.modules[mod_name].__dict__[\"Bus\"]\nKeyError: 'Bus'\n\nThe whole point of packages is that there are namespaces for module hierarchies. Looking up module names \"from any package\" just causes your code to break randomly if the user happens to import some library that happens to contain a module with a conflicting name.\n",
"This technique is dangerous and error prone. It could work with your tests until the day that someone imports a new something.req and gets a confusing, far-off error. (This is in the best case scenario; the current implementation would jump on many other modules.) If you restructure packages, it's easy enough to at that time modify your code in an automated fashion without any use of magic. Python makes it possible to do all sorts of magical, dynamic things, but that doesn't mean we should.\n",
"I think this is more like duck typing. I would also recommend using a more unique identifier than \"Bus\" \ndef getBus():\n \"\"\" Locates the Bus for this application \"\"\"\n for mod in sys.modules.values():\n if hasattr(mod, 'Bus') and type(mod.Bus) is...: # check other stuff about mod.Bus\n return mod.Bus\n raise RuntimeError(\"cannot find Bus\")\n\n"
] |
[
4,
1,
0
] |
[] |
[] |
[
"architecture",
"design_patterns",
"duck_typing",
"python"
] |
stackoverflow_0002322116_architecture_design_patterns_duck_typing_python.txt
|
Q:
Is there a Python equivalent of Ruby's 'any?' function?
In Ruby, you can call Enumerable#any? on a enumerable object to see if any of its elements satisfies the predicate you pass in the block. Like so:
lst.any?{|e| pred(e) }
In Python, there's an any function that does something similar, but on a list of booleans.
Of course, for a reasonably-sized list, I'd just do:
any(map(pred,lst))
However, if my list is very long, I don't want to have to do the entire map operation first.
So, the question: Is there a generic short-circuiting any function in Python?
Yes, I know it's really trivial to write one myself, but I'd like to use speedy builtin functions (and also not reinvent any wheels).
A:
any(pred(x) for x in lst)
alternatively
from itertools import imap
any(imap(pred, lst))
|
Is there a Python equivalent of Ruby's 'any?' function?
|
In Ruby, you can call Enumerable#any? on a enumerable object to see if any of its elements satisfies the predicate you pass in the block. Like so:
lst.any?{|e| pred(e) }
In Python, there's an any function that does something similar, but on a list of booleans.
Of course, for a reasonably-sized list, I'd just do:
any(map(pred,lst))
However, if my list is very long, I don't want to have to do the entire map operation first.
So, the question: Is there a generic short-circuiting any function in Python?
Yes, I know it's really trivial to write one myself, but I'd like to use speedy builtin functions (and also not reinvent any wheels).
|
[
"any(pred(x) for x in lst)\n\nalternatively\nfrom itertools import imap\nany(imap(pred, lst))\n\n"
] |
[
22
] |
[] |
[] |
[
"list",
"python",
"ruby"
] |
stackoverflow_0002323147_list_python_ruby.txt
|
Q:
SqlAlchemy optimizations for read-only object models
I have a complex network of objects being spawned from a sqlite database using sqlalchemy ORM mappings. I have quite a few deeply nested:
for parent in owner.collection:
for child in parent.collection:
for foo in child.collection:
do lots of calcs with foo.property
My profiling is showing me that the sqlalchemy instrumentation is taking a lot of time in this use case.
The thing is: I don't ever change the object model (mapped properties) at runtime, so once they are loaded I don't NEED the instrumentation, or indeed any sqlalchemy overhead at all. After much research, I'm thinking I might have to clone a 'pure python' set of objects from my already loaded 'instrumented objects', but that would be a pain.
Performance is really crucial here (it's a simulator), so maybe writing those layers as C extensions using sqlite api directly would be best. Any thoughts?
A:
If you reference a single attribute of a single instance lots of times, a simple trick is to store it in a local variable.
If you want a way to create cheap pure python clones, share the dict object with the original object:
class CheapClone(object):
def __init__(self, original):
self.__dict__ = original.__dict__
Creating a copy like this costs about half of the instrumented attribute access and attribute lookups are as fast as normal.
There might also be a way to have the mapper create instances of an uninstrumented class instead of the instrumented one. If I have some time, I might take a look how deeply ingrained is the assumption that populated instances are of the same type as the instrumented class.
Found a quick and dirty way that seems to at least somewhat work on 0.5.8 and 0.6. Didn't test it with inheritance or other features that might interact badly. Also, this touches some non-public API's, so beware of breakage when changing versions.
from sqlalchemy.orm.attributes import ClassManager, instrumentation_registry
class ReadonlyClassManager(ClassManager):
"""Enables configuring a mapper to return instances of uninstrumented
classes instead. To use add a readonly_type attribute referencing the
desired class to use instead of the instrumented one."""
def __init__(self, class_):
ClassManager.__init__(self, class_)
self.readonly_version = getattr(class_, 'readonly_type', None)
if self.readonly_version:
# default instantiation logic doesn't know to install finders
# for our alternate class
instrumentation_registry._dict_finders[self.readonly_version] = self.dict_getter()
instrumentation_registry._state_finders[self.readonly_version] = self.state_getter()
def new_instance(self, state=None):
if self.readonly_version:
instance = self.readonly_version.__new__(self.readonly_version)
self.setup_instance(instance, state)
return instance
return ClassManager.new_instance(self, state)
Base = declarative_base()
Base.__sa_instrumentation_manager__ = ReadonlyClassManager
Usage example:
class ReadonlyFoo(object):
pass
class Foo(Base, ReadonlyFoo):
__tablename__ = 'foo'
id = Column(Integer, primary_key=True)
name = Column(String(32))
readonly_type = ReadonlyFoo
assert type(session.query(Foo).first()) is ReadonlyFoo
A:
You should be able to disable lazy loading on the relationships in question and sqlalchemy will fetch them all in a single query.
|
SqlAlchemy optimizations for read-only object models
|
I have a complex network of objects being spawned from a sqlite database using sqlalchemy ORM mappings. I have quite a few deeply nested:
for parent in owner.collection:
for child in parent.collection:
for foo in child.collection:
do lots of calcs with foo.property
My profiling is showing me that the sqlalchemy instrumentation is taking a lot of time in this use case.
The thing is: I don't ever change the object model (mapped properties) at runtime, so once they are loaded I don't NEED the instrumentation, or indeed any sqlalchemy overhead at all. After much research, I'm thinking I might have to clone a 'pure python' set of objects from my already loaded 'instrumented objects', but that would be a pain.
Performance is really crucial here (it's a simulator), so maybe writing those layers as C extensions using sqlite api directly would be best. Any thoughts?
|
[
"If you reference a single attribute of a single instance lots of times, a simple trick is to store it in a local variable.\nIf you want a way to create cheap pure python clones, share the dict object with the original object:\nclass CheapClone(object):\n def __init__(self, original):\n self.__dict__ = original.__dict__\n\nCreating a copy like this costs about half of the instrumented attribute access and attribute lookups are as fast as normal.\nThere might also be a way to have the mapper create instances of an uninstrumented class instead of the instrumented one. If I have some time, I might take a look how deeply ingrained is the assumption that populated instances are of the same type as the instrumented class.\n\nFound a quick and dirty way that seems to at least somewhat work on 0.5.8 and 0.6. Didn't test it with inheritance or other features that might interact badly. Also, this touches some non-public API's, so beware of breakage when changing versions.\nfrom sqlalchemy.orm.attributes import ClassManager, instrumentation_registry\n\nclass ReadonlyClassManager(ClassManager):\n \"\"\"Enables configuring a mapper to return instances of uninstrumented \n classes instead. To use add a readonly_type attribute referencing the\n desired class to use instead of the instrumented one.\"\"\"\n def __init__(self, class_):\n ClassManager.__init__(self, class_)\n self.readonly_version = getattr(class_, 'readonly_type', None)\n if self.readonly_version:\n # default instantiation logic doesn't know to install finders\n # for our alternate class\n instrumentation_registry._dict_finders[self.readonly_version] = self.dict_getter()\n instrumentation_registry._state_finders[self.readonly_version] = self.state_getter()\n\n def new_instance(self, state=None):\n if self.readonly_version:\n instance = self.readonly_version.__new__(self.readonly_version)\n self.setup_instance(instance, state)\n return instance\n return ClassManager.new_instance(self, state)\n\nBase = declarative_base()\nBase.__sa_instrumentation_manager__ = ReadonlyClassManager\n\nUsage example:\nclass ReadonlyFoo(object):\n pass\n\nclass Foo(Base, ReadonlyFoo):\n __tablename__ = 'foo'\n id = Column(Integer, primary_key=True)\n name = Column(String(32))\n\n readonly_type = ReadonlyFoo\n\nassert type(session.query(Foo).first()) is ReadonlyFoo\n\n",
"You should be able to disable lazy loading on the relationships in question and sqlalchemy will fetch them all in a single query.\n"
] |
[
10,
0
] |
[
"Try using a single query with JOINs instead of the python loops.\n"
] |
[
-1
] |
[
"performance",
"python",
"readonly",
"sqlalchemy"
] |
stackoverflow_0002322437_performance_python_readonly_sqlalchemy.txt
|
Q:
What algorithm does buildbot use to assign builders to slaves?
I have a buildbot with some builders and two slave machines.
Some of the builders can run on one slave, and some of them can run on both machines.
What algorithm will buildbot use to schedule the builds? Will it notice that some builders can run on just one slave and that it should assign those that can run on both slaves to the less demanded one?
(I know buildbot can be used to run the same build on multiple architectures, say Windows, Linux, etc. We are using it to distribute builds for performance, because a single build is enough for us).
A:
First it gets a list of all the slaves attached to that builder. Then it picks one at random. If the slave is already running more than slave.max_builds builds, it picks another.
You can override the nextSlave method on the Builder to change the way slaves are chosen. The arguments passed to your function will be the Builder object, and a list of buildbot.buildslave.BuildSlave objects. You have to return one of the items of the latter list, or None.
|
What algorithm does buildbot use to assign builders to slaves?
|
I have a buildbot with some builders and two slave machines.
Some of the builders can run on one slave, and some of them can run on both machines.
What algorithm will buildbot use to schedule the builds? Will it notice that some builders can run on just one slave and that it should assign those that can run on both slaves to the less demanded one?
(I know buildbot can be used to run the same build on multiple architectures, say Windows, Linux, etc. We are using it to distribute builds for performance, because a single build is enough for us).
|
[
"First it gets a list of all the slaves attached to that builder. Then it picks one at random. If the slave is already running more than slave.max_builds builds, it picks another.\nYou can override the nextSlave method on the Builder to change the way slaves are chosen. The arguments passed to your function will be the Builder object, and a list of buildbot.buildslave.BuildSlave objects. You have to return one of the items of the latter list, or None.\n"
] |
[
11
] |
[] |
[] |
[
"build_automation",
"build_process",
"buildbot",
"project_management",
"python"
] |
stackoverflow_0002229481_build_automation_build_process_buildbot_project_management_python.txt
|
Q:
How to calculate a value to a certain number of decimal places?
Using numpy or python's standard library, either or. How can I take a value with several decimal places and truncate it to 4 decimal places? I only want to compare floating point numbers to their first 4 decimal points.
A:
round(a_float, 4)
>>> help(round)
Help on built-in function round in module __builtin__:
round(...)
round(number[, ndigits]) -> floating point number
Round a number to a given precision in decimal digits (default 0 digits).
This always returns a floating point number. Precision may be negative.
>>>
A:
If you want to compare two floats, you can compare on abs(a-b) < epsilon where epsilon is your precision requirement.
A:
>>> round(1.2345678,4) == round(1.2345999,4)
True
A:
you can use decimal module, especially the part on getcontext().prec
|
How to calculate a value to a certain number of decimal places?
|
Using numpy or python's standard library, either or. How can I take a value with several decimal places and truncate it to 4 decimal places? I only want to compare floating point numbers to their first 4 decimal points.
|
[
"round(a_float, 4)\n>>> help(round)\nHelp on built-in function round in module __builtin__:\n\nround(...)\n round(number[, ndigits]) -> floating point number\n\n Round a number to a given precision in decimal digits (default 0 digits).\n This always returns a floating point number. Precision may be negative.\n\n>>>\n\n",
"If you want to compare two floats, you can compare on abs(a-b) < epsilon where epsilon is your precision requirement.\n",
">>> round(1.2345678,4) == round(1.2345999,4)\nTrue\n\n",
"you can use decimal module, especially the part on getcontext().prec\n"
] |
[
6,
3,
2,
1
] |
[] |
[] |
[
"floating_accuracy",
"python"
] |
stackoverflow_0002323332_floating_accuracy_python.txt
|
Q:
django+flex: Debugging strategies
I love django, and I like flex. Django for it's cool debugging system (those yellow pages helps a lot to find bugs in my code), and flex for it possibilities.
Recently I come across a problem. If I create a form in flex and then communicate with the django server, I can't see any debugging info (when the exception happens in django).
Not sure, if there is a way to get the debugging info, because it is not accessible in command line (no error output), or in firebug....
Also I tried to create a quick html form, and post same data as I send from flex form, but it's a bit of pain to be honest.
Will be happy to listen how do you solve the problem
A:
I've used firebug to debug the flex side of things. But I've been using json or XML for communication between the two. Since flash uses the browser to do the network stuff, the request should be visible in the net tab of firebug.
To debug the django side of things, you have a few options.
If you're using the django dev server, you can add print statements to find out what's going on.
You can write a unit test to see if the django side of things is doing what you expect it to, given known data.
You can use the pyDev debugger to run the django dev server and step through your code.
I use a combination of these to debug my code.
|
django+flex: Debugging strategies
|
I love django, and I like flex. Django for it's cool debugging system (those yellow pages helps a lot to find bugs in my code), and flex for it possibilities.
Recently I come across a problem. If I create a form in flex and then communicate with the django server, I can't see any debugging info (when the exception happens in django).
Not sure, if there is a way to get the debugging info, because it is not accessible in command line (no error output), or in firebug....
Also I tried to create a quick html form, and post same data as I send from flex form, but it's a bit of pain to be honest.
Will be happy to listen how do you solve the problem
|
[
"I've used firebug to debug the flex side of things. But I've been using json or XML for communication between the two. Since flash uses the browser to do the network stuff, the request should be visible in the net tab of firebug.\nTo debug the django side of things, you have a few options.\n\nIf you're using the django dev server, you can add print statements to find out what's going on.\nYou can write a unit test to see if the django side of things is doing what you expect it to, given known data.\nYou can use the pyDev debugger to run the django dev server and step through your code.\n\nI use a combination of these to debug my code.\n"
] |
[
1
] |
[] |
[] |
[
"actionscript_3",
"django",
"python"
] |
stackoverflow_0002323371_actionscript_3_django_python.txt
|
Q:
zip() alternative for iterating through two iterables
I have two large (~100 GB) text files that must be iterated through simultaneously.
Zip works well for smaller files but I found out that it's actually making a list of lines from my two files. This means that every line gets stored in memory. I don't need to do anything with the lines more than once.
handle1 = open('filea', 'r'); handle2 = open('fileb', 'r')
for i, j in zip(handle1, handle2):
do something with i and j.
write to an output file.
no need to do anything with i and j after this.
Is there an alternative to zip() that acts as a generator that will allow me to iterate through these two files without using >200GB of ram?
A:
itertools has a function izip that does that
from itertools import izip
for i, j in izip(handle1, handle2):
...
If the files are of different sizes you may use izip_longest, as izip will stop at the smaller file.
A:
You can use izip_longest like this to pad the shorter file with empty lines
in python 2.6
from itertools import izip_longest
with handle1 as open('filea', 'r'):
with handle2 as open('fileb', 'r'):
for i, j in izip_longest(handle1, handle2, fillvalue=""):
...
or in Python 3+
from itertools import zip_longest
with handle1 as open('filea', 'r'), handle2 as open('fileb', 'r'):
for i, j in zip_longest(handle1, handle2, fillvalue=""):
...
A:
If you want to truncate to the shortest file:
handle1 = open('filea', 'r')
handle2 = open('fileb', 'r')
try:
while 1:
i = handle1.next()
j = handle2.next()
do something with i and j.
write to an output file.
except StopIteration:
pass
finally:
handle1.close()
handle2.close()
Else
handle1 = open('filea', 'r')
handle2 = open('fileb', 'r')
i_ended = False
j_ended = False
while 1:
try:
i = handle1.next()
except StopIteration:
i_ended = True
try:
j = handle2.next()
except StopIteration:
j_ended = True
do something with i and j.
write to an output file.
if i_ended and j_ended:
break
handle1.close()
handle2.close()
Or
handle1 = open('filea', 'r')
handle2 = open('fileb', 'r')
while 1:
i = handle1.readline()
j = handle2.readline()
do something with i and j.
write to an output file.
if not i and not j:
break
handle1.close()
handle2.close()
|
zip() alternative for iterating through two iterables
|
I have two large (~100 GB) text files that must be iterated through simultaneously.
Zip works well for smaller files but I found out that it's actually making a list of lines from my two files. This means that every line gets stored in memory. I don't need to do anything with the lines more than once.
handle1 = open('filea', 'r'); handle2 = open('fileb', 'r')
for i, j in zip(handle1, handle2):
do something with i and j.
write to an output file.
no need to do anything with i and j after this.
Is there an alternative to zip() that acts as a generator that will allow me to iterate through these two files without using >200GB of ram?
|
[
"itertools has a function izip that does that\nfrom itertools import izip\nfor i, j in izip(handle1, handle2):\n ...\n\nIf the files are of different sizes you may use izip_longest, as izip will stop at the smaller file.\n",
"You can use izip_longest like this to pad the shorter file with empty lines\nin python 2.6\nfrom itertools import izip_longest\nwith handle1 as open('filea', 'r'):\n with handle2 as open('fileb', 'r'): \n for i, j in izip_longest(handle1, handle2, fillvalue=\"\"):\n ...\n\nor in Python 3+\nfrom itertools import zip_longest\nwith handle1 as open('filea', 'r'), handle2 as open('fileb', 'r'): \n for i, j in zip_longest(handle1, handle2, fillvalue=\"\"):\n ...\n\n",
"If you want to truncate to the shortest file:\nhandle1 = open('filea', 'r')\nhandle2 = open('fileb', 'r')\n\ntry:\n while 1:\n i = handle1.next()\n j = handle2.next()\n\n do something with i and j.\n write to an output file.\n\nexcept StopIteration:\n pass\n\nfinally:\n handle1.close()\n handle2.close()\n\nElse\nhandle1 = open('filea', 'r')\nhandle2 = open('fileb', 'r')\n\ni_ended = False\nj_ended = False\nwhile 1:\n try:\n i = handle1.next()\n except StopIteration:\n i_ended = True\n try:\n j = handle2.next()\n except StopIteration:\n j_ended = True\n\n do something with i and j.\n write to an output file.\n if i_ended and j_ended:\n break\n\nhandle1.close()\nhandle2.close()\n\nOr\nhandle1 = open('filea', 'r')\nhandle2 = open('fileb', 'r')\n\nwhile 1:\n i = handle1.readline()\n j = handle2.readline()\n\n do something with i and j.\n write to an output file.\n\n if not i and not j:\n break\nhandle1.close()\nhandle2.close()\n\n"
] |
[
22,
16,
0
] |
[
"Something like this? Wordy, but it seems to be what you're asking for.\nIt can be adjusted to do things like a proper merge to match keys between the two files, which is often more what's needed than the simplistic zip function. Also, this doesn't truncate, which is what the SQL OUTER JOIN algorithm does, again, different from what zip does and more typical of files.\nwith open(\"file1\",\"r\") as file1:\n with open( \"file2\", \"r\" as file2:\n for line1, line2 in parallel( file1, file2 ):\n process lines\n\ndef parallel( file1, file2 ):\n if1_more, if2_more = True, True\n while if1_more or if2_more:\n line1, line2 = None, None # Assume simplistic zip-style matching\n # If you're going to compare keys, then you'd do that before\n # deciding what to read.\n if if1_more:\n try:\n line1= file1.next()\n except StopIteration:\n if1_more= False\n if if2_more:\n try:\n line2= file2.next()\n except StopIteration:\n if2_more= False\n yield line1, line2\n\n"
] |
[
-1
] |
[
"python"
] |
stackoverflow_0002323394_python.txt
|
Q:
Python drawing on screen
I'm coding an application that needs to select an area of the screen. I need to change the cursor to a cross and then draw a rectangle on the user selection. The first thing I searched for is how to manipulate the cursor and I came across wxPython. With wxPython I could easily do this on a Frame with a Panel, the thing is that I'd need the window to be transparent so the user can see his screen while is selecting the desired area, but if I make the Frame and the Panel objects transparent everything gets buggy.
So, I'm open to any solution, either using wxPython or not using it because I don't really know if I'm using it right.
I'm new to Python and I'm not a native english speaker, so I'm sorry if you can't understand something.
This is what I coded
import wx
class SelectableFrame(wx.Frame):
c1 = None
c2 = None
def __init__(self, parent=None, id=-1, title=""):
wx.Frame.__init__(self, parent, id, title, size=wx.DisplaySize(), style=wx.TRANSPARENT_WINDOW)
self.panel = wx.Panel(self, size=self.GetSize(), style=wx.TRANSPARENT_WINDOW)
self.panel.Bind(wx.EVT_MOTION, self.OnMouseMove)
self.panel.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
self.panel.Bind(wx.EVT_LEFT_UP, self.OnMouseUp)
self.panel.Bind(wx.EVT_PAINT, self.OnPaint)
self.SetCursor(wx.StockCursor(wx.CURSOR_CROSS))
def OnMouseMove(self, event):
if event.Dragging() and event.LeftIsDown():
self.c2 = event.GetPosition()
self.Refresh()
def OnMouseDown(self, event):
self.c1 = event.GetPosition()
def OnMouseUp(self, event):
self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
def OnPaint(self, event):
if self.c1 is None or self.c2 is None: return
dc = wx.PaintDC(self.panel)
dc.SetPen(wx.Pen('red', 1))
dc.SetBrush(wx.Brush(wx.Color(0, 0, 0), wx.TRANSPARENT))
dc.DrawRectangle(self.c1.x, self.c1.y, self.c2.x - self.c1.x, self.c2.y - self.c1.y)
def PrintPosition(self, pos):
return str(pos.x) + " " + str(pos.y)
class MyApp(wx.App):
def OnInit(self):
frame = SelectableFrame()
frame.Show(True)
self.SetTopWindow(frame)
return True
app = MyApp(0)
app.MainLoop()
A:
You shouldn't be using wx.TRANSPARENT in window creation, that is mostly used for wxDC paint commands. To make a window transparent just call win.SetTransparent(amount), where amount is from 0-255, 255 means opaque, 0 means totally transparent. see http://www.wxpython.org/docs/api/wx.Window-class.html#SetTransparent
I have modified your code, it will work only if your platform supports transparent windows, you can check that by CanSetTransparent. I tested it on windows XP.
import wx
class SelectableFrame(wx.Frame):
c1 = None
c2 = None
def __init__(self, parent=None, id=-1, title=""):
wx.Frame.__init__(self, parent, id, title, size=wx.DisplaySize())
self.panel = wx.Panel(self, size=self.GetSize())
self.panel.Bind(wx.EVT_MOTION, self.OnMouseMove)
self.panel.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
self.panel.Bind(wx.EVT_LEFT_UP, self.OnMouseUp)
self.panel.Bind(wx.EVT_PAINT, self.OnPaint)
self.SetCursor(wx.StockCursor(wx.CURSOR_CROSS))
self.SetTransparent(50)
def OnMouseMove(self, event):
if event.Dragging() and event.LeftIsDown():
self.c2 = event.GetPosition()
self.Refresh()
def OnMouseDown(self, event):
self.c1 = event.GetPosition()
def OnMouseUp(self, event):
self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
def OnPaint(self, event):
if self.c1 is None or self.c2 is None: return
dc = wx.PaintDC(self.panel)
dc.SetPen(wx.Pen('red', 1))
dc.SetBrush(wx.Brush(wx.Color(0, 0, 0), wx.TRANSPARENT))
dc.DrawRectangle(self.c1.x, self.c1.y, self.c2.x - self.c1.x, self.c2.y - self.c1.y)
def PrintPosition(self, pos):
return str(pos.x) + " " + str(pos.y)
class MyApp(wx.App):
def OnInit(self):
frame = SelectableFrame()
frame.Show(True)
self.SetTopWindow(frame)
return True
app = MyApp(0)
app.MainLoop()
|
Python drawing on screen
|
I'm coding an application that needs to select an area of the screen. I need to change the cursor to a cross and then draw a rectangle on the user selection. The first thing I searched for is how to manipulate the cursor and I came across wxPython. With wxPython I could easily do this on a Frame with a Panel, the thing is that I'd need the window to be transparent so the user can see his screen while is selecting the desired area, but if I make the Frame and the Panel objects transparent everything gets buggy.
So, I'm open to any solution, either using wxPython or not using it because I don't really know if I'm using it right.
I'm new to Python and I'm not a native english speaker, so I'm sorry if you can't understand something.
This is what I coded
import wx
class SelectableFrame(wx.Frame):
c1 = None
c2 = None
def __init__(self, parent=None, id=-1, title=""):
wx.Frame.__init__(self, parent, id, title, size=wx.DisplaySize(), style=wx.TRANSPARENT_WINDOW)
self.panel = wx.Panel(self, size=self.GetSize(), style=wx.TRANSPARENT_WINDOW)
self.panel.Bind(wx.EVT_MOTION, self.OnMouseMove)
self.panel.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)
self.panel.Bind(wx.EVT_LEFT_UP, self.OnMouseUp)
self.panel.Bind(wx.EVT_PAINT, self.OnPaint)
self.SetCursor(wx.StockCursor(wx.CURSOR_CROSS))
def OnMouseMove(self, event):
if event.Dragging() and event.LeftIsDown():
self.c2 = event.GetPosition()
self.Refresh()
def OnMouseDown(self, event):
self.c1 = event.GetPosition()
def OnMouseUp(self, event):
self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
def OnPaint(self, event):
if self.c1 is None or self.c2 is None: return
dc = wx.PaintDC(self.panel)
dc.SetPen(wx.Pen('red', 1))
dc.SetBrush(wx.Brush(wx.Color(0, 0, 0), wx.TRANSPARENT))
dc.DrawRectangle(self.c1.x, self.c1.y, self.c2.x - self.c1.x, self.c2.y - self.c1.y)
def PrintPosition(self, pos):
return str(pos.x) + " " + str(pos.y)
class MyApp(wx.App):
def OnInit(self):
frame = SelectableFrame()
frame.Show(True)
self.SetTopWindow(frame)
return True
app = MyApp(0)
app.MainLoop()
|
[
"You shouldn't be using wx.TRANSPARENT in window creation, that is mostly used for wxDC paint commands. To make a window transparent just call win.SetTransparent(amount), where amount is from 0-255, 255 means opaque, 0 means totally transparent. see http://www.wxpython.org/docs/api/wx.Window-class.html#SetTransparent\nI have modified your code, it will work only if your platform supports transparent windows, you can check that by CanSetTransparent. I tested it on windows XP.\nimport wx\n\nclass SelectableFrame(wx.Frame):\n\n c1 = None\n c2 = None\n\n def __init__(self, parent=None, id=-1, title=\"\"):\n wx.Frame.__init__(self, parent, id, title, size=wx.DisplaySize())\n\n self.panel = wx.Panel(self, size=self.GetSize())\n\n self.panel.Bind(wx.EVT_MOTION, self.OnMouseMove)\n self.panel.Bind(wx.EVT_LEFT_DOWN, self.OnMouseDown)\n self.panel.Bind(wx.EVT_LEFT_UP, self.OnMouseUp)\n self.panel.Bind(wx.EVT_PAINT, self.OnPaint)\n\n self.SetCursor(wx.StockCursor(wx.CURSOR_CROSS))\n\n self.SetTransparent(50)\n\n def OnMouseMove(self, event):\n if event.Dragging() and event.LeftIsDown():\n self.c2 = event.GetPosition()\n self.Refresh()\n\n def OnMouseDown(self, event):\n self.c1 = event.GetPosition()\n\n def OnMouseUp(self, event):\n self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\n\n def OnPaint(self, event):\n if self.c1 is None or self.c2 is None: return\n\n dc = wx.PaintDC(self.panel)\n dc.SetPen(wx.Pen('red', 1))\n dc.SetBrush(wx.Brush(wx.Color(0, 0, 0), wx.TRANSPARENT))\n\n dc.DrawRectangle(self.c1.x, self.c1.y, self.c2.x - self.c1.x, self.c2.y - self.c1.y)\n\n def PrintPosition(self, pos):\n return str(pos.x) + \" \" + str(pos.y)\n\n\nclass MyApp(wx.App):\n\n def OnInit(self):\n frame = SelectableFrame()\n frame.Show(True)\n self.SetTopWindow(frame)\n\n return True\n\n\napp = MyApp(0)\napp.MainLoop()\n\n"
] |
[
5
] |
[] |
[] |
[
"python",
"wxpython"
] |
stackoverflow_0002323640_python_wxpython.txt
|
Q:
Is there any difference between cpython and python
I want to know the difference between CPython and Python because I have heard Python is developed in C - then what is the use of CPython?
A:
Python is a language.
CPython is the default byte-code interpreter of Python, which is written in C.
There is also other implementation of Python such as IronPython (for .NET), Jython (for Java), etc.
A:
CPython is Guido van Rossum's
reference version of the Python
computing language. It's most often
called simply "Python"; speakers say
"CPython" generally to distinguish it
explicitly from other implementations.
|
Is there any difference between cpython and python
|
I want to know the difference between CPython and Python because I have heard Python is developed in C - then what is the use of CPython?
|
[
"Python is a language.\nCPython is the default byte-code interpreter of Python, which is written in C.\nThere is also other implementation of Python such as IronPython (for .NET), Jython (for Java), etc.\n",
"\nCPython is Guido van Rossum's\n reference version of the Python\n computing language. It's most often\n called simply \"Python\"; speakers say\n \"CPython\" generally to distinguish it\n explicitly from other implementations.\n\n"
] |
[
41,
20
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002324208_python.txt
|
Q:
Problem originating SSH tunnels from python
The object is to set up n number of ssh tunnels between satellite servers and a centralized registry database. I have already set up public key authentication between my servers so they just log right in without password prompts. Now what ? I've tried Paramiko. It seems decent but gets pretty complicated just to set up a basic tunnel, although code exmplaes would be aprreciated. I've tried Autossh and it dies 2 minutes after setting up a working tunnel, bizarre! Hopefully someone can help me with a simple code snippet that I can daemonize and monitor with supervisord or monit.
A:
Here is a cutdown version of the script that Alex pointed you to.
It simply connects to 192.168.0.8 and forwards port 3389 from 192.168.0.6 to localhost
import select
import SocketServer
import sys
import paramiko
class ForwardServer(SocketServer.ThreadingTCPServer):
daemon_threads = True
allow_reuse_address = True
class Handler (SocketServer.BaseRequestHandler):
def handle(self):
try:
chan = self.ssh_transport.open_channel('direct-tcpip', (self.chain_host, self.chain_port), self.request.getpeername())
except Exception, e:
print('Incoming request to %s:%d failed: %s' % (self.chain_host, self.chain_port, repr(e)))
return
if chan is None:
print('Incoming request to %s:%d was rejected by the SSH server.' % (self.chain_host, self.chain_port))
return
print('Connected! Tunnel open %r -> %r -> %r' % (self.request.getpeername(), chan.getpeername(), (self.chain_host, self.chain_port)))
while True:
r, w, x = select.select([self.request, chan], [], [])
if self.request in r:
data = self.request.recv(1024)
if len(data) == 0:
break
chan.send(data)
if chan in r:
data = chan.recv(1024)
if len(data) == 0:
break
self.request.send(data)
chan.close()
self.request.close()
print('Tunnel closed from %r' % (self.request.getpeername(),))
def main():
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
client.connect("192.168.0.8")
class SubHandler(Handler):
chain_host = "192.168.0.6"
chain_port = 3389
ssh_transport = client.get_transport()
try:
ForwardServer(('', 3389), SubHandler).serve_forever()
except KeyboardInterrupt:
sys.exit(0)
if __name__ == '__main__':
main()
A:
Is there a special reason not to just do it with ssh, the usual
(ssh -L <localport>:localhost:<remoteport> <remotehost>)
minuet? Anyway, this script is an example of local port forwarding (AKA tunneling).
|
Problem originating SSH tunnels from python
|
The object is to set up n number of ssh tunnels between satellite servers and a centralized registry database. I have already set up public key authentication between my servers so they just log right in without password prompts. Now what ? I've tried Paramiko. It seems decent but gets pretty complicated just to set up a basic tunnel, although code exmplaes would be aprreciated. I've tried Autossh and it dies 2 minutes after setting up a working tunnel, bizarre! Hopefully someone can help me with a simple code snippet that I can daemonize and monitor with supervisord or monit.
|
[
"Here is a cutdown version of the script that Alex pointed you to.\nIt simply connects to 192.168.0.8 and forwards port 3389 from 192.168.0.6 to localhost\nimport select\nimport SocketServer\nimport sys\nimport paramiko\n\nclass ForwardServer(SocketServer.ThreadingTCPServer):\n daemon_threads = True\n allow_reuse_address = True\n\nclass Handler (SocketServer.BaseRequestHandler):\n def handle(self):\n try:\n chan = self.ssh_transport.open_channel('direct-tcpip', (self.chain_host, self.chain_port), self.request.getpeername())\n except Exception, e:\n print('Incoming request to %s:%d failed: %s' % (self.chain_host, self.chain_port, repr(e)))\n return\n if chan is None:\n print('Incoming request to %s:%d was rejected by the SSH server.' % (self.chain_host, self.chain_port))\n return\n\n print('Connected! Tunnel open %r -> %r -> %r' % (self.request.getpeername(), chan.getpeername(), (self.chain_host, self.chain_port)))\n while True:\n r, w, x = select.select([self.request, chan], [], [])\n if self.request in r:\n data = self.request.recv(1024)\n if len(data) == 0:\n break\n chan.send(data)\n if chan in r:\n data = chan.recv(1024)\n if len(data) == 0:\n break\n self.request.send(data)\n chan.close()\n self.request.close()\n print('Tunnel closed from %r' % (self.request.getpeername(),))\n\ndef main():\n client = paramiko.SSHClient()\n client.load_system_host_keys()\n client.set_missing_host_key_policy(paramiko.WarningPolicy())\n client.connect(\"192.168.0.8\")\n\n class SubHandler(Handler):\n chain_host = \"192.168.0.6\"\n chain_port = 3389\n ssh_transport = client.get_transport()\n\n try:\n ForwardServer(('', 3389), SubHandler).serve_forever()\n except KeyboardInterrupt:\n sys.exit(0)\n\nif __name__ == '__main__':\n main()\n\n",
"Is there a special reason not to just do it with ssh, the usual\n(ssh -L <localport>:localhost:<remoteport> <remotehost>)\n\nminuet? Anyway, this script is an example of local port forwarding (AKA tunneling).\n"
] |
[
5,
2
] |
[] |
[] |
[
"paramiko",
"python",
"ssh",
"tunnel"
] |
stackoverflow_0002323471_paramiko_python_ssh_tunnel.txt
|
Q:
Is line wrap comment possible in Python?
I have a long string that I build with a bunch of calculated values. I then write this string to a file.
I have it formatted like:
string = str(a/b)+\
'\t'+str(c)\
'\t'+str(d)\
...
'\n'
I would like to add comment to what each value represents but commenting with # or ''' doesn't work. Here's an example:
string = str(a/b)+\ #this value is something
'\t'+str(c)\ #this value is another thing
'\t'+str(d)\ #and this one too
...
'\n'
I figured out it doesn't work :) so I'm wondering what code with a clean syntax would look like in a situation like this.
The only option that occurs to me would be to go for string += on each line but I'm scratching my head with "there must be a better way".
A:
A simple solution is to use parenthesis instead:
string = (str(a/b)+ #this value is something
'\t'+str(c)+ #this value is another thing
'\t'+str(d)+ #and this one too
...
'\n')
A:
How about
string = '\t'.join(map(str,((a/b), #this value is something
c, #this value is another thing
d, #and this one too
)))+'\n'
Or if you prefer
string = '\t'.join(map(str,(
(a/b), #this value is something
c, #this value is another thing
d, #and this one too
)))+'\n'
|
Is line wrap comment possible in Python?
|
I have a long string that I build with a bunch of calculated values. I then write this string to a file.
I have it formatted like:
string = str(a/b)+\
'\t'+str(c)\
'\t'+str(d)\
...
'\n'
I would like to add comment to what each value represents but commenting with # or ''' doesn't work. Here's an example:
string = str(a/b)+\ #this value is something
'\t'+str(c)\ #this value is another thing
'\t'+str(d)\ #and this one too
...
'\n'
I figured out it doesn't work :) so I'm wondering what code with a clean syntax would look like in a situation like this.
The only option that occurs to me would be to go for string += on each line but I'm scratching my head with "there must be a better way".
|
[
"A simple solution is to use parenthesis instead:\nstring = (str(a/b)+ #this value is something\n '\\t'+str(c)+ #this value is another thing\n '\\t'+str(d)+ #and this one too\n ...\n '\\n')\n\n",
"How about\nstring = '\\t'.join(map(str,((a/b), #this value is something\n c, #this value is another thing\n d, #and this one too\n )))+'\\n'\n\nOr if you prefer\nstring = '\\t'.join(map(str,(\n (a/b), #this value is something\n c, #this value is another thing\n d, #and this one too\n )))+'\\n'\n\n"
] |
[
7,
1
] |
[] |
[] |
[
"comments",
"python"
] |
stackoverflow_0002324483_comments_python.txt
|
Q:
What is the official name of this construct?
In python:
>>> a = b or {}
A:
I don't think it has an official name, it's just a clever/lazy way to be concise. It's roughly equivalent to:
a = b if b else {}
or:
if b:
a = b
else:
a = {}
I wrote this as a comment but I think it's worth mentioning here:
You have to be very careful when using this trick. If your intention is to set a default value when something is None, it would be better to write that is None test explicitly than use this trick. The reason is that None is not the only thing that evaluates to false in a boolean context. 0, [], {}, ... also evaluate to false. So this trick might not give you the expected results if you didn't think about these special cases.
Here's one way to do it that is safer:
a = b if b is not None else {}
A:
The expression b or {} is just a simple boolean OR expression. The special about this is just that this expression does not need return a boolean value per definition like in other languages:
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
(Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value. Because not has to invent a value anyway, it does not bother to return a value of the same type as its argument, so e.g., not 'foo' yields False, not ''.)
A:
That's not a special construct, at least to my somewhat tired eyes. It's saying to assign the result of
(b or {})
to a.
So, if b is a False value, a gets {} (the empty dictionary literal), otherwise it gets the value of b.
A:
May be The expression that return last evaluated argument.
A:
Default Assignment Idiom
|
What is the official name of this construct?
|
In python:
>>> a = b or {}
|
[
"I don't think it has an official name, it's just a clever/lazy way to be concise. It's roughly equivalent to:\na = b if b else {}\n\nor:\nif b:\n a = b\nelse:\n a = {}\n\nI wrote this as a comment but I think it's worth mentioning here:\nYou have to be very careful when using this trick. If your intention is to set a default value when something is None, it would be better to write that is None test explicitly than use this trick. The reason is that None is not the only thing that evaluates to false in a boolean context. 0, [], {}, ... also evaluate to false. So this trick might not give you the expected results if you didn't think about these special cases.\nHere's one way to do it that is safer:\na = b if b is not None else {}\n\n",
"The expression b or {} is just a simple boolean OR expression. The special about this is just that this expression does not need return a boolean value per definition like in other languages:\n\nThe expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.\n(Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value. Because not has to invent a value anyway, it does not bother to return a value of the same type as its argument, so e.g., not 'foo' yields False, not ''.)\n\n",
"That's not a special construct, at least to my somewhat tired eyes. It's saying to assign the result of \n (b or {}) \n\nto a.\nSo, if b is a False value, a gets {} (the empty dictionary literal), otherwise it gets the value of b.\n",
"May be The expression that return last evaluated argument.\n",
"Default Assignment Idiom\n"
] |
[
10,
2,
1,
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002324453_python.txt
|
Q:
How to run a piece of code in every view in django?
I need to check user authorization in every view of one of my Django apps (I don't use Django's built in auth system) and redirect user to a "login please" page, if authorization has failed.
Code looks like this:
try:
admin_from_session = request.session['admin'];
admin = Administrator.objects.get(login = admin_from_session.login, password = admin_from_session.password, enabled=True);
except KeyError, Administrator.DoesNotExist:
return HttpResponseRedirect('/controlpanel/login')
Question is: how can I run this code at the beginning of every view, without repeating it every time?
If I would write my program on PHP, i would put this code in separate file and write something like this at the beginning of every page that requires authorization:
include("redirect_if_not_logged_in.inc.php");
The solutions I found was:
inclusion tags - doesn't do,
because I can't redirect anywhere
from there
custom function -
also doesn't do, because of the same
reason.
The task seems trivial, but I can't find a solution. I would be very grateful for any help.
A:
Look at the source code for django.contrib.auth decorators. They do exactly what you want, but for the built-in Django authentication system (see the documentation). It shouldn't be hard to do something similar for your authentication system.
BTW, why don't you use the built-in auth? You can use it with custom authentication backends...
A:
I found the answer I was looking for. Function decorators allow to run a peace of code at the beginning of a function.
You must define a decorator function
def login_please_decorator(view_func):
"""
Redirect if admin was not logged in
"""
def _decorated(request, *args, **kwargs):
#Check authorization
try:
admin_from_session = request.session['admin'];
admin = Administrator.objects.get(login = admin_from_session.login, password = admin_from_session.password, enabled=True);
return view_func(request,*args, **kwargs);
except KeyError, Administrator.DoesNotExist:
return HttpResponseRedirect('/cp/login?ret=' + request.path);
return _decorated
And decorate a view using this function name:
@login_please_decorator
def some view(request):
# do something ...
# ...
Ludwik Trammer, bugspy.net, thank you for your help.
A:
Function decorators comes to mind
A:
Take a look at the User authentication page here http://docs.djangoproject.com/en/dev/topics/auth/
Read on to "The login_required decorator".
from django.contrib.auth.decorators import login_required
@login_required
def my_view(request):
...
You can setup where the user is to be redirected if not authenticated via the setting "settings.LOGIN_URL".
At the page there is also an example for a special authentication template you can style to anything you like!
|
How to run a piece of code in every view in django?
|
I need to check user authorization in every view of one of my Django apps (I don't use Django's built in auth system) and redirect user to a "login please" page, if authorization has failed.
Code looks like this:
try:
admin_from_session = request.session['admin'];
admin = Administrator.objects.get(login = admin_from_session.login, password = admin_from_session.password, enabled=True);
except KeyError, Administrator.DoesNotExist:
return HttpResponseRedirect('/controlpanel/login')
Question is: how can I run this code at the beginning of every view, without repeating it every time?
If I would write my program on PHP, i would put this code in separate file and write something like this at the beginning of every page that requires authorization:
include("redirect_if_not_logged_in.inc.php");
The solutions I found was:
inclusion tags - doesn't do,
because I can't redirect anywhere
from there
custom function -
also doesn't do, because of the same
reason.
The task seems trivial, but I can't find a solution. I would be very grateful for any help.
|
[
"Look at the source code for django.contrib.auth decorators. They do exactly what you want, but for the built-in Django authentication system (see the documentation). It shouldn't be hard to do something similar for your authentication system.\nBTW, why don't you use the built-in auth? You can use it with custom authentication backends...\n",
"I found the answer I was looking for. Function decorators allow to run a peace of code at the beginning of a function.\nYou must define a decorator function\ndef login_please_decorator(view_func):\n \"\"\"\n Redirect if admin was not logged in\n \"\"\"\n def _decorated(request, *args, **kwargs):\n #Check authorization\n try:\n admin_from_session = request.session['admin'];\n admin = Administrator.objects.get(login = admin_from_session.login, password = admin_from_session.password, enabled=True);\n return view_func(request,*args, **kwargs);\n except KeyError, Administrator.DoesNotExist:\n return HttpResponseRedirect('/cp/login?ret=' + request.path);\n\n return _decorated \n\nAnd decorate a view using this function name:\n@login_please_decorator\ndef some view(request): \n # do something ...\n # ...\n\nLudwik Trammer, bugspy.net, thank you for your help.\n",
"Function decorators comes to mind\n",
"Take a look at the User authentication page here http://docs.djangoproject.com/en/dev/topics/auth/\nRead on to \"The login_required decorator\".\nfrom django.contrib.auth.decorators import login_required\n\n@login_required\ndef my_view(request):\n ...\n\nYou can setup where the user is to be redirected if not authenticated via the setting \"settings.LOGIN_URL\".\nAt the page there is also an example for a special authentication template you can style to anything you like!\n"
] |
[
6,
2,
1,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002296117_django_python.txt
|
Q:
How do I activate (execute) methods of a class in Python?
I have a program (simple web server) which I try to understand. There is a class called MyHandler. In this class we define 2 methods do_GET and do_POST.
I do not understand several things:
Where do we use the two above defined methods? I would expect to see something like that objectname.do_GET() and objectname.do_POST() but I do not see such things.
At which point we instantiate the class? Do we use the whole class (not an instance of the class) as an argument to the HTTPServer?
Why do we specify argument in the definition of the class (BaseHTTPRequestHandler) and then do not use it?
A:
I'm quite new to Python, but I will have a go at an answer—it might help me learn too!
We don't ever call the do_GET() and do_POST() methods from our code, this is done automatically by the HTTPServer class instance when GET and POST requests are made (see point 2).
The HTTPServer will create an instance of the MyHandler class for each HTTP request that is made.
BaseHTTPRequestHandler is not an argument: it specifies that our MyHandler class subclasses BaseHTTPRequestHandler.
Hope this helps!
|
How do I activate (execute) methods of a class in Python?
|
I have a program (simple web server) which I try to understand. There is a class called MyHandler. In this class we define 2 methods do_GET and do_POST.
I do not understand several things:
Where do we use the two above defined methods? I would expect to see something like that objectname.do_GET() and objectname.do_POST() but I do not see such things.
At which point we instantiate the class? Do we use the whole class (not an instance of the class) as an argument to the HTTPServer?
Why do we specify argument in the definition of the class (BaseHTTPRequestHandler) and then do not use it?
|
[
"I'm quite new to Python, but I will have a go at an answer—it might help me learn too!\n\nWe don't ever call the do_GET() and do_POST() methods from our code, this is done automatically by the HTTPServer class instance when GET and POST requests are made (see point 2).\nThe HTTPServer will create an instance of the MyHandler class for each HTTP request that is made. \nBaseHTTPRequestHandler is not an argument: it specifies that our MyHandler class subclasses BaseHTTPRequestHandler.\n\nHope this helps!\n"
] |
[
4
] |
[] |
[] |
[
"class",
"methods",
"oop",
"python"
] |
stackoverflow_0002324804_class_methods_oop_python.txt
|
Q:
Creating Python RPM
I have been reading about creating an RPM for Python 2.6.4. In this page: http://docs.python.org/distutils/builtdist.html it says you can create an RPM of the current Python using python setup.py bdist_rpm. The question's I have are:
Do you have to type this command in your Python installation directory?
Does this command, package all the modules you have installed into the RPM?
Is this the correct command to do this?
Are there any other suggestion's that would make this easier?
Okay I sorted this out using checkinstall.
I downloaded checkinstall from http://www.asic-linux.com.mx/~izto/checkinstall/.
I then installed the package but had to enter /usr/local/sbin/checkinstall into my PATH to make it work. I then entered the next copmmand to get my RPM directory going.
yum install rpm-build
I then cd into the Python module and entered this command:
checkinstall -R --nodoc --delspec=no --exclude=/selinux python2.6 ./setup.py install
This command replaces the command checkinstall as your installing python libraries through setup.py instead of an ordinary make.
I then went through the checkinstall process. The finished RPM was placed into /usr/src/redhat/RPMS/i386/.
Note: THIS IS FOR LINUX RED HAT.
A:
This command has to be typed wherever your setup.py is located.
It packages everything that would show up in a bdist tarball.
Err... sort of. While it works, the package it creates is not of very high quality. It's better to use sdist_rpm, then unpack the resulting SRPM and then apply your distro's Python packaging guidelines to the generated spec file.
Get it to work via bdist first. That way any issues that crop up will be more manageable.
A:
These instructions explain how to create an RPM package for your module. As far as I know, there is no (easy) way to package all your Python installation into an RPM.
If you want to create an RPM package to install Python 2.6.4 on an older distro, you download the Python 2.6.4 source RPM and then rebuild it with rpmbuild. See Fedora RPM Guide.
|
Creating Python RPM
|
I have been reading about creating an RPM for Python 2.6.4. In this page: http://docs.python.org/distutils/builtdist.html it says you can create an RPM of the current Python using python setup.py bdist_rpm. The question's I have are:
Do you have to type this command in your Python installation directory?
Does this command, package all the modules you have installed into the RPM?
Is this the correct command to do this?
Are there any other suggestion's that would make this easier?
Okay I sorted this out using checkinstall.
I downloaded checkinstall from http://www.asic-linux.com.mx/~izto/checkinstall/.
I then installed the package but had to enter /usr/local/sbin/checkinstall into my PATH to make it work. I then entered the next copmmand to get my RPM directory going.
yum install rpm-build
I then cd into the Python module and entered this command:
checkinstall -R --nodoc --delspec=no --exclude=/selinux python2.6 ./setup.py install
This command replaces the command checkinstall as your installing python libraries through setup.py instead of an ordinary make.
I then went through the checkinstall process. The finished RPM was placed into /usr/src/redhat/RPMS/i386/.
Note: THIS IS FOR LINUX RED HAT.
|
[
"\nThis command has to be typed wherever your setup.py is located.\nIt packages everything that would show up in a bdist tarball.\nErr... sort of. While it works, the package it creates is not of very high quality. It's better to use sdist_rpm, then unpack the resulting SRPM and then apply your distro's Python packaging guidelines to the generated spec file.\nGet it to work via bdist first. That way any issues that crop up will be more manageable.\n\n",
"These instructions explain how to create an RPM package for your module. As far as I know, there is no (easy) way to package all your Python installation into an RPM.\nIf you want to create an RPM package to install Python 2.6.4 on an older distro, you download the Python 2.6.4 source RPM and then rebuild it with rpmbuild. See Fedora RPM Guide.\n"
] |
[
6,
1
] |
[] |
[] |
[
"checkinstall",
"linux",
"python",
"rpm",
"rpmbuild"
] |
stackoverflow_0002324933_checkinstall_linux_python_rpm_rpmbuild.txt
|
Q:
Django admin - Restrict user view by permission
I'm starting to learn Django and I have a question.
Is there any way to restric views in the administration interface? I see there are "change, "add" and "delete" permissions, but I wanted to restrict views also.
For example: Two users, "User 1" is superuser and "User 2" is in the editor group. User 1 has access to everything, but User 2 can't view a determined application in the administration.
Is that possible?
A:
If you make sure that User 2 has no permissions for any model related to the app you want to hide away (so no change, add or delete powers for any of the models in that app), then it won't appear in the admin for User 2.
|
Django admin - Restrict user view by permission
|
I'm starting to learn Django and I have a question.
Is there any way to restric views in the administration interface? I see there are "change, "add" and "delete" permissions, but I wanted to restrict views also.
For example: Two users, "User 1" is superuser and "User 2" is in the editor group. User 1 has access to everything, but User 2 can't view a determined application in the administration.
Is that possible?
|
[
"If you make sure that User 2 has no permissions for any model related to the app you want to hide away (so no change, add or delete powers for any of the models in that app), then it won't appear in the admin for User 2.\n"
] |
[
1
] |
[] |
[] |
[
"admin",
"django",
"django_admin",
"permissions",
"python"
] |
stackoverflow_0002325150_admin_django_django_admin_permissions_python.txt
|
Q:
Deploying Django with WSGI: App Import Error
I am new in apache, linux and python world. I am trying to deploy django application on apache using WSGI (the recommended way).
My django project directory structure is as follows...
/
/apache/django.wsgi
/apps/ #I put all my apps in this directory
/apps/providers/
/apps/shopping/
/apps/...
/middleware/
...
In apache I have following settings....
LoadModule wsgi_module modules/mod_wsgi.so
WSGIScriptAlias / D:/Projects/project-name/apache/django.wsgi
<Directory "D:/Projects/project-name/apache/">
Allow from all
Order deny,allow
</Directory>
django.wsgi file has got following code...
import os
import sys
import settings
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
os.environ['DJANGO_SETTINGS_MODULE'] = 'project_name.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
On running I found this error in the appache's error.log...
Error occured on this line. from apps.providers.models import Provider
Import Error: No module named providers.models
I don't know why it is giving me this error. It should have loaded Provider from apps.providers.models but it is trying to load it from providers.model.
Any solution will be appreciated.
Thanks
A:
Try this:
sys.path.insert(0, os.path.join(os.path.abspath(os.path.dirname(__file__)),'..'))
It puts your project folder at the first position and it uses os.path.join to go one directory up (which might be better on windows).
It might be the case that there is another "apps" module on your python path.
|
Deploying Django with WSGI: App Import Error
|
I am new in apache, linux and python world. I am trying to deploy django application on apache using WSGI (the recommended way).
My django project directory structure is as follows...
/
/apache/django.wsgi
/apps/ #I put all my apps in this directory
/apps/providers/
/apps/shopping/
/apps/...
/middleware/
...
In apache I have following settings....
LoadModule wsgi_module modules/mod_wsgi.so
WSGIScriptAlias / D:/Projects/project-name/apache/django.wsgi
<Directory "D:/Projects/project-name/apache/">
Allow from all
Order deny,allow
</Directory>
django.wsgi file has got following code...
import os
import sys
import settings
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
os.environ['DJANGO_SETTINGS_MODULE'] = 'project_name.settings'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
On running I found this error in the appache's error.log...
Error occured on this line. from apps.providers.models import Provider
Import Error: No module named providers.models
I don't know why it is giving me this error. It should have loaded Provider from apps.providers.models but it is trying to load it from providers.model.
Any solution will be appreciated.
Thanks
|
[
"Try this:\nsys.path.insert(0, os.path.join(os.path.abspath(os.path.dirname(__file__)),'..'))\n\nIt puts your project folder at the first position and it uses os.path.join to go one directory up (which might be better on windows).\nIt might be the case that there is another \"apps\" module on your python path.\n"
] |
[
1
] |
[] |
[] |
[
"apache",
"django",
"python",
"wsgi"
] |
stackoverflow_0002324219_apache_django_python_wsgi.txt
|
Q:
How to handle conditional-imports-dependent exceptions?
I'm wondering what is the most elegant way to handle exceptions that depend on a conditional import.
For example:
import ldap
try:
...
l = ldap.open(...)
l.simple_bind_s(...)
...
except ldap.INVALID_CREDENTIALS, e:
pass
except ldap.SERVER_DOWN, e:
pass
In the real-world scenario (the one that made me think of this), we have a cherrypy server with a 'login' page. And the login method does a lot of stuff - one of them is authentication.
However, I can use something else than LDAP to do authentication, in which case I do not want to import ldap at all.
But if I make the 'import ldap' statement conditional (e.g. it only gets imported when USE_LDAP value is True in a config file), I have to do something with the 'except's too. The question is: what?
Catch a generic Exception, use an if statement to check whether we use LDAP (i.e., ldap is imported) and then use isinstance to check, whether the Exception is the correct type (ldap.INVALID_CREDENTIALS)?
Try to concentrate the code that depends on ldap at one place and re-raise a user defined exception that finally gets caught in the login method?
What would you suggest as the most pythonic?
A:
Probably somewhere there should be a configuration option in your program that is used to decide which kind of authentication should be used. The imports should be done depending on this option.
If you put all the ldap related authentication functions into their own module, like auth_ldap and do the same for your other methods of authentication, you could do the login check like this:
if config.auth_method == 'ldap':
import ldap_auth as auth
elif config.auth_method == 'db':
import db_auth as auth
else:
raise Exception("No valid authentication module configured")
auth.check_login(user, password)
The check_login method in each module would here provide a uniform interface that internally does whatever is necessary to perform the specific login. This function could also translate specific Ldap exceptions into a generic LoginFailure or just return True or False depending on the success of the user check.
A:
This will be easier to handle if you write a set of abstraction modules for authn (Strategy Pattern). Each module will catch its specific authn exceptions, and in place raise generic exceptions defined by the application.
|
How to handle conditional-imports-dependent exceptions?
|
I'm wondering what is the most elegant way to handle exceptions that depend on a conditional import.
For example:
import ldap
try:
...
l = ldap.open(...)
l.simple_bind_s(...)
...
except ldap.INVALID_CREDENTIALS, e:
pass
except ldap.SERVER_DOWN, e:
pass
In the real-world scenario (the one that made me think of this), we have a cherrypy server with a 'login' page. And the login method does a lot of stuff - one of them is authentication.
However, I can use something else than LDAP to do authentication, in which case I do not want to import ldap at all.
But if I make the 'import ldap' statement conditional (e.g. it only gets imported when USE_LDAP value is True in a config file), I have to do something with the 'except's too. The question is: what?
Catch a generic Exception, use an if statement to check whether we use LDAP (i.e., ldap is imported) and then use isinstance to check, whether the Exception is the correct type (ldap.INVALID_CREDENTIALS)?
Try to concentrate the code that depends on ldap at one place and re-raise a user defined exception that finally gets caught in the login method?
What would you suggest as the most pythonic?
|
[
"Probably somewhere there should be a configuration option in your program that is used to decide which kind of authentication should be used. The imports should be done depending on this option.\nIf you put all the ldap related authentication functions into their own module, like auth_ldap and do the same for your other methods of authentication, you could do the login check like this:\nif config.auth_method == 'ldap':\n import ldap_auth as auth\nelif config.auth_method == 'db':\n import db_auth as auth\nelse:\n raise Exception(\"No valid authentication module configured\")\n\nauth.check_login(user, password)\n\nThe check_login method in each module would here provide a uniform interface that internally does whatever is necessary to perform the specific login. This function could also translate specific Ldap exceptions into a generic LoginFailure or just return True or False depending on the success of the user check.\n",
"This will be easier to handle if you write a set of abstraction modules for authn (Strategy Pattern). Each module will catch its specific authn exceptions, and in place raise generic exceptions defined by the application.\n"
] |
[
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002325345_python.txt
|
Q:
Python path: Reusing Python module
I have written a small DB access module that is extensively reused in many programs.
My code is stored in a single directory tree /projects for backup and versioning reasons, and so the module should be placed within this directory tree, say at /projects/my_py_lib/dbconn.py.
I want to easily configure Python to automatically search for modules at the /projects/my_py_lib directory structure (of course, __init__.py should be placed within any subdirectory).
What's the best way to do this under Ubuntu?
Thanks,
Adam
A:
You can add a PYTHONPATH environment variable to your .bashrc file. eg.
export PYTHONPATH=/projects/my_py_lib
A:
on linux, this directory will be added to your sys.path automatically for pythonN.M
~/.local/lib/pythonN.M/site-packages/
So you can put your packages in there for each version of python you are using.
You need a copy for each version of python, otherwise the .pyc file will be recompiled every time you import the module with a different python version
This also allows fine grained control if the module only works for some of the versions of python you have installed
If you create this file
~/.local/lib/pythonN.M/site-packages/usercustomize.py
it will be imported each time you start the python interpreter
A:
Another option is to create a soft link in /usr/lib*/python*/site-packages/:
ln -s /projects/my_py_lib /usr/lib*/python*/site-packages/
That will make the project visible to all Python programs plus any changes will be visible immediately, too.
The main drawback is that you will eventually have *.pyc files owned by root or another user unless you make sure you compile the files yourself before you start python as another user.
|
Python path: Reusing Python module
|
I have written a small DB access module that is extensively reused in many programs.
My code is stored in a single directory tree /projects for backup and versioning reasons, and so the module should be placed within this directory tree, say at /projects/my_py_lib/dbconn.py.
I want to easily configure Python to automatically search for modules at the /projects/my_py_lib directory structure (of course, __init__.py should be placed within any subdirectory).
What's the best way to do this under Ubuntu?
Thanks,
Adam
|
[
"You can add a PYTHONPATH environment variable to your .bashrc file. eg.\nexport PYTHONPATH=/projects/my_py_lib\n\n",
"on linux, this directory will be added to your sys.path automatically for pythonN.M\n~/.local/lib/pythonN.M/site-packages/\n\nSo you can put your packages in there for each version of python you are using.\nYou need a copy for each version of python, otherwise the .pyc file will be recompiled every time you import the module with a different python version\nThis also allows fine grained control if the module only works for some of the versions of python you have installed\nIf you create this file\n~/.local/lib/pythonN.M/site-packages/usercustomize.py\n\nit will be imported each time you start the python interpreter\n",
"Another option is to create a soft link in /usr/lib*/python*/site-packages/:\nln -s /projects/my_py_lib /usr/lib*/python*/site-packages/\n\nThat will make the project visible to all Python programs plus any changes will be visible immediately, too.\nThe main drawback is that you will eventually have *.pyc files owned by root or another user unless you make sure you compile the files yourself before you start python as another user.\n"
] |
[
8,
2,
0
] |
[] |
[] |
[
"path",
"python",
"ubuntu"
] |
stackoverflow_0002325418_path_python_ubuntu.txt
|
Q:
Is there an active Python-Chat?
Is there an active Python-Chat?
A:
If you are asking for an irc channel where people talk about Python, then try http://www.python.org/community/irc/
A:
Python Chat Server
Python Chat Client
A:
My guess is that you are looking for a IRC channel? well this is not related to programming so you should not be posting that question here?
any way quakenet has a python channel
|
Is there an active Python-Chat?
|
Is there an active Python-Chat?
|
[
"If you are asking for an irc channel where people talk about Python, then try http://www.python.org/community/irc/\n",
"Python Chat Server\nPython Chat Client\n",
"My guess is that you are looking for a IRC channel? well this is not related to programming so you should not be posting that question here?\nany way quakenet has a python channel\n"
] |
[
3,
0,
0
] |
[] |
[] |
[
"chat",
"irc",
"python"
] |
stackoverflow_0002325938_chat_irc_python.txt
|
Q:
Floating Point Modulo Problem
I've stumbled onto a very strange bug. Read the comments in the code to see what the bug is exactly, but essentially a variable modulo 1 is returning 1 (but it doesn't equal 1!). I'm assuming there is a display problem where the float is extremely close to one but not exactly. However, it should be moduloing to zero. I can't test for this case easily because (last % 1) != 1.0 ! When I try plugging the same numbers into another python terminal, everything behaves correctly. What's going on?
def r(k,i,p):
first = i*p
last = first + p
steps = int((i+1)*p) - int(i*p)
if steps < 1:
return p
elif steps >= 1:
if k == 0:
return 1 - (first % 1)
elif k == steps:
if i == 189:
print last, 1, type(last), last % 1, last - int(last)
# Prints: 73.0 1 <type 'float'> 1.0 1.0
print last % 1 == 1 # Returns False
if last % 1 == 1.0:
return 0
return (last % 1)
else:
return 1
A:
Welcome to IEEE754, enjoy your stay.
A:
Print doesn't show the full precision of the number as stored, you can use repr() to do that
>>> last=72.99999999999999
>>> print last, 1, type(last), last % 1, last - int(last)
73.0 1 <type 'float'> 1.0 1.0
>>> print last % 1 == 1
False
>>> print repr(last), 1, type(last), repr(last%1), repr(last - int(last))
72.999999999999986 1 <type 'float'> 0.99999999999998579 0.99999999999998579
>>>
A:
You should use math.fmod(x, y). Here's an excerpt from http://docs.python.org/library/math.html:
"Note that the Python expression x % y may not return the same result. The intent of the C standard is that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x - n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y). Python’s x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python’s -1e-100 % 1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising 1e100. For this reason, function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers."
A:
You could try the math.fmod function instead of last % 1, maybe it is better suited for you problem.
Or you could reformulate you problem in integer space.
Anyway, it is not good practice to compare float values using equality == operator, due to imprecise results even from seemigly trivial operations like 0.1 + 0.2 == 0.3
A:
If you need arbitrary precision, there are some projects out there that do just that. gmpy handles multi-precision integers, mpmath which looks quite good and bigfloat which wraps MPFR. What you have might be enough via gnibbler's answer, but, just in case.
|
Floating Point Modulo Problem
|
I've stumbled onto a very strange bug. Read the comments in the code to see what the bug is exactly, but essentially a variable modulo 1 is returning 1 (but it doesn't equal 1!). I'm assuming there is a display problem where the float is extremely close to one but not exactly. However, it should be moduloing to zero. I can't test for this case easily because (last % 1) != 1.0 ! When I try plugging the same numbers into another python terminal, everything behaves correctly. What's going on?
def r(k,i,p):
first = i*p
last = first + p
steps = int((i+1)*p) - int(i*p)
if steps < 1:
return p
elif steps >= 1:
if k == 0:
return 1 - (first % 1)
elif k == steps:
if i == 189:
print last, 1, type(last), last % 1, last - int(last)
# Prints: 73.0 1 <type 'float'> 1.0 1.0
print last % 1 == 1 # Returns False
if last % 1 == 1.0:
return 0
return (last % 1)
else:
return 1
|
[
"Welcome to IEEE754, enjoy your stay.\n",
"Print doesn't show the full precision of the number as stored, you can use repr() to do that\n>>> last=72.99999999999999\n>>> print last, 1, type(last), last % 1, last - int(last)\n73.0 1 <type 'float'> 1.0 1.0\n>>> print last % 1 == 1\nFalse\n>>> print repr(last), 1, type(last), repr(last%1), repr(last - int(last))\n72.999999999999986 1 <type 'float'> 0.99999999999998579 0.99999999999998579\n>>> \n\n",
"You should use math.fmod(x, y). Here's an excerpt from http://docs.python.org/library/math.html:\n\"Note that the Python expression x % y may not return the same result. The intent of the C standard is that fmod(x, y) be exactly (mathematically; to infinite precision) equal to x - n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y). Python’s x % y returns a result with the sign of y instead, and may not be exactly computable for float arguments. For example, fmod(-1e-100, 1e100) is -1e-100, but the result of Python’s -1e-100 % 1e100 is 1e100-1e-100, which cannot be represented exactly as a float, and rounds to the surprising 1e100. For this reason, function fmod() is generally preferred when working with floats, while Python’s x % y is preferred when working with integers.\"\n",
"You could try the math.fmod function instead of last % 1, maybe it is better suited for you problem.\nOr you could reformulate you problem in integer space.\nAnyway, it is not good practice to compare float values using equality == operator, due to imprecise results even from seemigly trivial operations like 0.1 + 0.2 == 0.3\n",
"If you need arbitrary precision, there are some projects out there that do just that. gmpy handles multi-precision integers, mpmath which looks quite good and bigfloat which wraps MPFR. What you have might be enough via gnibbler's answer, but, just in case.\n"
] |
[
6,
6,
3,
1,
0
] |
[] |
[] |
[
"floating_accuracy",
"floating_point",
"python"
] |
stackoverflow_0002323291_floating_accuracy_floating_point_python.txt
|
Q:
How to redefine a wx.GridSizer?
I have this code:
class SoundLog(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, size=(500, 350), *args, **kwargs)
self.SetBackgroundColour((110,110,110))
self.sizer = wx.BoxSizer(wx.VERTICAL)
pluginsNumber = len(plugins) - len(pluginsToHide)
self.gs = wx.GridSizer(pluginsNumber, 1, 0, 0)
pluginsList = self.getPluginsList()
self.gs.AddMany(pluginsList)
self.sizer.Add(self.gs, 1, wx.EXPAND)
self.SetSizer(self.sizer)
self.Centre()
self.Show(True)
How can I make a function that redefines the GridSizer defined here?
Is something like this:
def redefineSizer(self):
self.Show(False)
pluginsNumber = len(plugins) - len(pluginsToHide)
self.gs.Clear()
self.sizer.Remove(self.gs)
self.gs = wx.GridSizer(pluginsNumber, 1, 0, 0)
print self.gs
pluginsList = self.getPluginsList()
self.gs.AddMany(pluginsList)
self.sizer.Add(self.gs, 1, wx.EXPAND)
self.SetSizer(self.sizer)
self.Centre()
self.Show(True)
or something like this:
def redefineSizer(self):
pluginsNumber = len(plugins) - len(pluginsToHide)
self.gs.SetRows(pluginsNumber)
self.gs.Clear(deleteWindows=False)
pluginsList = self.getPluginsList()
self.gs.AddMany(pluginsList)
self.SetSizer(self.sizer)
But I know (cause it's not working) that I'm missing something.
What it is?
I put panels inside the GridSizer, but with an option to close them.
When I close one panel, I want to redefine the GridSizer to have one row less and to remove the closed panel.
So, when I click on close, I call redefineSizer to remove that panel and update itself.
That's what I want to do!
Thanks in advance :)
A:
If you're using something like the AUI framework, you can simply create a new grid sizer, and swap out the one you've already got.
|
How to redefine a wx.GridSizer?
|
I have this code:
class SoundLog(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, size=(500, 350), *args, **kwargs)
self.SetBackgroundColour((110,110,110))
self.sizer = wx.BoxSizer(wx.VERTICAL)
pluginsNumber = len(plugins) - len(pluginsToHide)
self.gs = wx.GridSizer(pluginsNumber, 1, 0, 0)
pluginsList = self.getPluginsList()
self.gs.AddMany(pluginsList)
self.sizer.Add(self.gs, 1, wx.EXPAND)
self.SetSizer(self.sizer)
self.Centre()
self.Show(True)
How can I make a function that redefines the GridSizer defined here?
Is something like this:
def redefineSizer(self):
self.Show(False)
pluginsNumber = len(plugins) - len(pluginsToHide)
self.gs.Clear()
self.sizer.Remove(self.gs)
self.gs = wx.GridSizer(pluginsNumber, 1, 0, 0)
print self.gs
pluginsList = self.getPluginsList()
self.gs.AddMany(pluginsList)
self.sizer.Add(self.gs, 1, wx.EXPAND)
self.SetSizer(self.sizer)
self.Centre()
self.Show(True)
or something like this:
def redefineSizer(self):
pluginsNumber = len(plugins) - len(pluginsToHide)
self.gs.SetRows(pluginsNumber)
self.gs.Clear(deleteWindows=False)
pluginsList = self.getPluginsList()
self.gs.AddMany(pluginsList)
self.SetSizer(self.sizer)
But I know (cause it's not working) that I'm missing something.
What it is?
I put panels inside the GridSizer, but with an option to close them.
When I close one panel, I want to redefine the GridSizer to have one row less and to remove the closed panel.
So, when I click on close, I call redefineSizer to remove that panel and update itself.
That's what I want to do!
Thanks in advance :)
|
[
"If you're using something like the AUI framework, you can simply create a new grid sizer, and swap out the one you've already got.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"wxpython"
] |
stackoverflow_0002325007_python_wxpython.txt
|
Q:
Creating a forward compatible OpenGL 3.x context in Python
I am using wxPython and I want to use an OpenGL based canvas, but I don't want the context to support deprecated functionality. I've navigated through pyopengl and pyglet in Eclipse, but it did not look like they support this. I'm saying this because I could not find WGL functions used in assigning attributes to a context, as in this white paper by AMD. There was also no mention in pylget's documentation of a compatibility status parameter when specifying a config for a context. Am I overlooking something? Is there a 'Python' solution or would I need to start looking at something like ctypes?
Edit: After reading some more documentation, it looks like there is a flag for the OpenGL pyopengl module, called FORWARD_COMPATIBLE_ONLY, that will filter deprecated entry points from OpenGL.GL, but only from this module. There is even mention of this on the pyopengl site under the OpenGL 3.x Deprecations section that I had not noticed before. If this implies GLSL deprecations will also be guarded against, then this looks like a solution.
A:
I can't categorically say that there's no way of doing this but I can point out that given the largely negative response to recent revisions of OpenGL that I doubt there will be a rush for developers to incorporate this sort of thing into their libraries.
For example, pyglet's core rendering functionality mainly relies on the old pre-shader system so there is really little reason for it to provide a way to deprecate all the older functions.
I expect that if you want this at this early stage, you'll have to do it yourself.
|
Creating a forward compatible OpenGL 3.x context in Python
|
I am using wxPython and I want to use an OpenGL based canvas, but I don't want the context to support deprecated functionality. I've navigated through pyopengl and pyglet in Eclipse, but it did not look like they support this. I'm saying this because I could not find WGL functions used in assigning attributes to a context, as in this white paper by AMD. There was also no mention in pylget's documentation of a compatibility status parameter when specifying a config for a context. Am I overlooking something? Is there a 'Python' solution or would I need to start looking at something like ctypes?
Edit: After reading some more documentation, it looks like there is a flag for the OpenGL pyopengl module, called FORWARD_COMPATIBLE_ONLY, that will filter deprecated entry points from OpenGL.GL, but only from this module. There is even mention of this on the pyopengl site under the OpenGL 3.x Deprecations section that I had not noticed before. If this implies GLSL deprecations will also be guarded against, then this looks like a solution.
|
[
"I can't categorically say that there's no way of doing this but I can point out that given the largely negative response to recent revisions of OpenGL that I doubt there will be a rush for developers to incorporate this sort of thing into their libraries. \nFor example, pyglet's core rendering functionality mainly relies on the old pre-shader system so there is really little reason for it to provide a way to deprecate all the older functions.\nI expect that if you want this at this early stage, you'll have to do it yourself.\n"
] |
[
1
] |
[] |
[] |
[
"opengl",
"openglcontext",
"python"
] |
stackoverflow_0002325996_opengl_openglcontext_python.txt
|
Q:
Why can't I break into a running test with the pdb interactive debugger?
How can I break into a running test with the pdb interactive debugger?
This is the test:
class UserTestCase(TestCase):
def test_register_should_create_UserProfile(self):
c = Client()
response = c.post('/account/register/', {u'username': [u'john'], u'email': [u'john@beatles.com'], u'bnewaccount': [u'Signup']})
self.assertEqual(response.status_code, 302)
import pdb; pdb.set_trace()
user = User.objects.get( username ='john')
self.assertTrue(user.get_profile())
When I attempt to run the tests:
$ python manage.py test
The test database is created. The progress dots '.' begin to progress across the screen as the tests pass.
Then the progess stops.
I am never shown a pdb> prompt in the terminal window.
How can I get pdb to work properly?
A:
Have you tried ipdb instead of vanilla pdb? I use ipdb and what you're trying to do works fine.
Alternatively, as a fallback, why not try the pdb call inside the method you're testing, just before the response is returned?
|
Why can't I break into a running test with the pdb interactive debugger?
|
How can I break into a running test with the pdb interactive debugger?
This is the test:
class UserTestCase(TestCase):
def test_register_should_create_UserProfile(self):
c = Client()
response = c.post('/account/register/', {u'username': [u'john'], u'email': [u'john@beatles.com'], u'bnewaccount': [u'Signup']})
self.assertEqual(response.status_code, 302)
import pdb; pdb.set_trace()
user = User.objects.get( username ='john')
self.assertTrue(user.get_profile())
When I attempt to run the tests:
$ python manage.py test
The test database is created. The progress dots '.' begin to progress across the screen as the tests pass.
Then the progess stops.
I am never shown a pdb> prompt in the terminal window.
How can I get pdb to work properly?
|
[
"Have you tried ipdb instead of vanilla pdb? I use ipdb and what you're trying to do works fine.\nAlternatively, as a fallback, why not try the pdb call inside the method you're testing, just before the response is returned? \n"
] |
[
1
] |
[] |
[] |
[
"django",
"pdb",
"python",
"testing"
] |
stackoverflow_0002326472_django_pdb_python_testing.txt
|
Q:
Opinion about Glashammer App engine Web framework
I am having to look into some code and consider working in a Python framework called Glashammer.
I know and love Django. I have some experience with Appengine native framework and Django on Appengine.
I'd like to know from you that have used one or more of those, how Glahammer compares and contrasts with others. What are there any Pros and Cons and what else do I need to be aware of.
A:
After a bit of googling (and finding your question:) and half an hour of reading docs and code I can say that
Glashammmer is great because it:
is well-documented;
is lightweight and very flexible;
provides almost everything to rapidly build a complex web app -- unlike Werkzeug itself;
does not suffer from NIH syndrome which is arguably the Django's greatest wart;
does not impose database-related libraries and thus supports whatever storage one could use from Python. Django only supports a number of relational databases and assumes you are happy with them. Of course you can drop Django ORM but this renders admin -- the Django's strongest point -- useless;
appliances are the best way to define views I've seen so far.
Galashammer is not so great because it:
has shorter development history and much smaller community than Django's, which leads to:
inevitably lower quality of core code, and
inevitably lower quantity of contributed code;
makes use of some components that may be unstable (e.g. flatland which is in alpha stage, though it's an arbitrary label and may be irrelevant to quality; moreover, it's only used in glashammer.utils.yconfig);
does not provide an API to define models (e.g. some declarative wrapper with backends), so the "pluginability" of applications can be significantly weaker that in Django (applications will make too many assumptions about the environment).
Anyway, I think this framework is worth diving into.
A:
I am highly biased, because I am the Glashammer author. But the pros for me are:
Werkzeug-based framework removes much of the boilerplate in creating Werkzeug based
applications
Easy pluggability and high flexibility: 2 levels of plugins, Appliances which are reusable components and Bundles which are behavioural
modifiers.
Well unit tested
Documentation is not bad (for an open source project)
Versus something like Django, I would just have to say "Werkzeug-based, with a nicer plugin framework."
Did I mention the code is beautiful like a glowing orb of ... (oh maybe this is subjective)
|
Opinion about Glashammer App engine Web framework
|
I am having to look into some code and consider working in a Python framework called Glashammer.
I know and love Django. I have some experience with Appengine native framework and Django on Appengine.
I'd like to know from you that have used one or more of those, how Glahammer compares and contrasts with others. What are there any Pros and Cons and what else do I need to be aware of.
|
[
"After a bit of googling (and finding your question:) and half an hour of reading docs and code I can say that\nGlashammmer is great because it:\n\nis well-documented;\nis lightweight and very flexible;\nprovides almost everything to rapidly build a complex web app -- unlike Werkzeug itself;\ndoes not suffer from NIH syndrome which is arguably the Django's greatest wart;\ndoes not impose database-related libraries and thus supports whatever storage one could use from Python. Django only supports a number of relational databases and assumes you are happy with them. Of course you can drop Django ORM but this renders admin -- the Django's strongest point -- useless;\nappliances are the best way to define views I've seen so far.\n\nGalashammer is not so great because it:\n\nhas shorter development history and much smaller community than Django's, which leads to:\n\n\ninevitably lower quality of core code, and\ninevitably lower quantity of contributed code;\n\nmakes use of some components that may be unstable (e.g. flatland which is in alpha stage, though it's an arbitrary label and may be irrelevant to quality; moreover, it's only used in glashammer.utils.yconfig);\ndoes not provide an API to define models (e.g. some declarative wrapper with backends), so the \"pluginability\" of applications can be significantly weaker that in Django (applications will make too many assumptions about the environment).\n\nAnyway, I think this framework is worth diving into.\n",
"I am highly biased, because I am the Glashammer author. But the pros for me are:\n\nWerkzeug-based framework removes much of the boilerplate in creating Werkzeug based\napplications\nEasy pluggability and high flexibility: 2 levels of plugins, Appliances which are reusable components and Bundles which are behavioural\nmodifiers.\nWell unit tested\nDocumentation is not bad (for an open source project)\n\nVersus something like Django, I would just have to say \"Werkzeug-based, with a nicer plugin framework.\"\nDid I mention the code is beautiful like a glowing orb of ... (oh maybe this is subjective)\n"
] |
[
3,
3
] |
[] |
[] |
[
"django",
"google_app_engine",
"python"
] |
stackoverflow_0002283616_django_google_app_engine_python.txt
|
Q:
Adding a constant tuple value to a list of tuples
I have a list of tuples (each tuple item is a pair of integers) and I would like to add a constant value to each tuple in the list.
For example
[(x0,y0),(x1,y1),...] -> [(x0+xk,y0+yk),(x1+xk,y1+yk)....]
xk,yk are constants
How do I do this
Thanks
A:
Use numpy, e.g.,
>>> import numpy as np
>>> a = np.array([[1,2],[2,3]])
>>> print a
[[1 2]
[2 3]]
>>> print a + 2
[[3 4]
[4 5]]
A:
>>>> l = [(1,2), (3,4)]
>>>> for i, e in enumerate(l):
.... l[i] = (e[0]+xk, e[1]+yk)
As always, untested. ;-)
If you don't need to do it in place, it's even simpler
>>>> l = [(e[0]+xk, e[1]+yk) for e in l]
A:
You can't add a constant to a tuple because tuples are immutable.
You can however create a new tuple from the old one by incrementing it's values. See jae's answer for the basics of how to do this.
You should note however that you will be creating a lot of new tuples in this loop and this may not be a very efficient way of handling this. You should investigate numpy (as suggested by nikow) or perhaps using lists or coordinate objects instead of tuples.
A:
an example to add things to tuple
>>> a=(1,2)
>>> a+=(1,)
>>> a
(1, 2, 1)
you can adapt it to your requirement
A:
Solution:
l = [(i[0]+k[0], i[1]+k[1]) for i in l]
Test code:
l = [(1,2), (3,4)]
k = (10, 100)
l = [(i[0]+k[0], i[1]+k[1]) for i in l]
assert l == [(11, 102), (13, 104)]
|
Adding a constant tuple value to a list of tuples
|
I have a list of tuples (each tuple item is a pair of integers) and I would like to add a constant value to each tuple in the list.
For example
[(x0,y0),(x1,y1),...] -> [(x0+xk,y0+yk),(x1+xk,y1+yk)....]
xk,yk are constants
How do I do this
Thanks
|
[
"Use numpy, e.g.,\n>>> import numpy as np\n>>> a = np.array([[1,2],[2,3]])\n>>> print a\n[[1 2]\n [2 3]]\n>>> print a + 2\n[[3 4]\n [4 5]]\n\n",
">>>> l = [(1,2), (3,4)]\n>>>> for i, e in enumerate(l):\n.... l[i] = (e[0]+xk, e[1]+yk)\n\nAs always, untested. ;-)\nIf you don't need to do it in place, it's even simpler\n>>>> l = [(e[0]+xk, e[1]+yk) for e in l]\n\n",
"You can't add a constant to a tuple because tuples are immutable. \nYou can however create a new tuple from the old one by incrementing it's values. See jae's answer for the basics of how to do this. \nYou should note however that you will be creating a lot of new tuples in this loop and this may not be a very efficient way of handling this. You should investigate numpy (as suggested by nikow) or perhaps using lists or coordinate objects instead of tuples.\n",
"an example to add things to tuple\n>>> a=(1,2)\n>>> a+=(1,)\n>>> a\n(1, 2, 1)\n\nyou can adapt it to your requirement\n",
"Solution:\nl = [(i[0]+k[0], i[1]+k[1]) for i in l]\n\nTest code:\nl = [(1,2), (3,4)]\nk = (10, 100)\nl = [(i[0]+k[0], i[1]+k[1]) for i in l]\nassert l == [(11, 102), (13, 104)]\n\n"
] |
[
4,
3,
3,
0,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002326359_python.txt
|
Q:
How to print contents of a tkinter.Canvas widget?
How would I print contents of a Python Tkinter.Canvas widget?
I've read that it's possible to print to a postscript printer from this control but examples are hard to come by.
So, any ideas what is needed to print the contents (including images)?
If you've got a cross-platform method all the better!
A:
AFAIK it can only be done using the postscript method from the Canvas. This generates a postscript file with the canvas contents.
Check the documentation for details about this method.
|
How to print contents of a tkinter.Canvas widget?
|
How would I print contents of a Python Tkinter.Canvas widget?
I've read that it's possible to print to a postscript printer from this control but examples are hard to come by.
So, any ideas what is needed to print the contents (including images)?
If you've got a cross-platform method all the better!
|
[
"AFAIK it can only be done using the postscript method from the Canvas. This generates a postscript file with the canvas contents.\nCheck the documentation for details about this method.\n"
] |
[
0
] |
[] |
[] |
[
"printing",
"python",
"tkinter_canvas"
] |
stackoverflow_0002326753_printing_python_tkinter_canvas.txt
|
Q:
Python template help
I'm using App Engine's web-app templating system (similar if not identical to django)
Normally I render templates from my static directory /templates/ as
follows in my main handler:
dirname = os.path.dirname(__file__)
template_file = os.path.join(dirname, os.path.join('templates', template_name))
output = template.render(template_file,template_values)
self.response.out.write(output)
For my current app, I want to render a template contained in a
string. I'm using the following code:
t = template.Template(template_string)
c = template.Context(template_values)
output = t.render(c)
self.response.out.write(output)
It renders the template, but not the "include" tags contained within
the string. For example, the string template
"hello world {% include 'helloworld.html' %}"
renders "hello world" but does not render the contents of
'helloworld.html'.
I'm guessing that this has something to do with the string not being
in the same directory as 'helloworld.html', but I'm not sure how to
specify that the include tags should look in '/templates/*'
Any help would be appreciated,
Arjun
A:
The webapp framework uses Django 0.9.6 templates. If you're loading templates from a string as you describe above, you need to configure the template loader so it can find dependencies loaded from files. Here's how webapp configures them.
A:
{% include 'dirname/helloworld.html' %}
should work!
|
Python template help
|
I'm using App Engine's web-app templating system (similar if not identical to django)
Normally I render templates from my static directory /templates/ as
follows in my main handler:
dirname = os.path.dirname(__file__)
template_file = os.path.join(dirname, os.path.join('templates', template_name))
output = template.render(template_file,template_values)
self.response.out.write(output)
For my current app, I want to render a template contained in a
string. I'm using the following code:
t = template.Template(template_string)
c = template.Context(template_values)
output = t.render(c)
self.response.out.write(output)
It renders the template, but not the "include" tags contained within
the string. For example, the string template
"hello world {% include 'helloworld.html' %}"
renders "hello world" but does not render the contents of
'helloworld.html'.
I'm guessing that this has something to do with the string not being
in the same directory as 'helloworld.html', but I'm not sure how to
specify that the include tags should look in '/templates/*'
Any help would be appreciated,
Arjun
|
[
"The webapp framework uses Django 0.9.6 templates. If you're loading templates from a string as you describe above, you need to configure the template loader so it can find dependencies loaded from files. Here's how webapp configures them.\n",
"{% include 'dirname/helloworld.html' %}\n\nshould work!\n"
] |
[
3,
0
] |
[] |
[] |
[
"django",
"django_templates",
"google_app_engine",
"python"
] |
stackoverflow_0002322069_django_django_templates_google_app_engine_python.txt
|
Q:
String templates in Python: what are legal characters?
I can't quite figure out what's going on with string templates:
t = Template('cannot teach an ${dog.old} ${tricks.new}. ${why} is this ${not} working')
print t.safe_substitute({'dog.old': 'old dog', 'tricks.new': 'new tricks', 'why': 'OH WHY', 'not': '@#%@#% NOT'})
This prints:
cannot teach an ${dog.old} ${tricks.new}. OH WHY is this @#%@#% NOT working
I thought that the braces handled arbitrary strings. What characters are allowed in braces and is there any way I can subclass Template to do what I want?
A:
From the documentation...
$identifier names a substitution placeholder matching a mapping key of "identifier". By default, "identifier" must spell a Python identifier. The first non-identifier character after the $ character terminates this placeholder specification.
The period is a non-identifier character, and braces are simply used to separate the identifier from adjacent non-identifier text.
A:
Aha, I tried this experiment:
from string import Template
import uuid
class MyTemplate(Template):
idpattern = r'[a-z][_a-z0-9]*(\.[a-z][_a-z0-9]*)*'
t1 = Template('cannot teach an ${dog.old} ${tricks.new}. ${why} is this ${not} working')
t2 = MyTemplate('cannot teach an ${dog.old} ${tricks.new}. ${why} is this ${not} working')
map1 = {'dog.old': 'old dog',
'tricks.new': 'new tricks', 'why': 'OH WHY', 'not': '@#%@#% NOT'}
map2 = {'dog': {'old': 'old dog'},
'tricks': {'new': 'new tricks'}, 'why': 'OH WHY', 'not': '@#%@#% NOT'}
print t1.safe_substitute(map1)
print t1.safe_substitute(map2)
print t2.safe_substitute(map1)
print t2.safe_substitute(map2)
which prints
cannot teach an ${dog.old} ${tricks.new}. OH WHY is this @#%@#% NOT working
cannot teach an ${dog.old} ${tricks.new}. OH WHY is this @#%@#% NOT working
cannot teach an old dog new tricks. OH WHY is this @#%@#% NOT working
cannot teach an ${dog.old} ${tricks.new}. OH WHY is this @#%@#% NOT working
so the third one (print t2.safe_substitute(map1)) works.
A:
Python interprets the . in your name as "access the field old of the instance dog". Try _ instead or make dog an object with a field old.
AFAIR, only valid identifiers and . are safe between the braces.
[EDIT] It's on the page where you link to:
${identifier} is equivalent to $identifier. It is required when valid identifier characters follow the placeholder but are not part of the placeholder, such as "${noun}ification".
and
"identifier" must spell a Python identifier.
which means: It must be a valid identifier.
[EDIT2] It seems that the identifier isn't analyzed as I thought. So you must specify a simple valid Python identifier in the braces (and you can't use the field accessor syntax) unless you create your own implementation of the Template class.
|
String templates in Python: what are legal characters?
|
I can't quite figure out what's going on with string templates:
t = Template('cannot teach an ${dog.old} ${tricks.new}. ${why} is this ${not} working')
print t.safe_substitute({'dog.old': 'old dog', 'tricks.new': 'new tricks', 'why': 'OH WHY', 'not': '@#%@#% NOT'})
This prints:
cannot teach an ${dog.old} ${tricks.new}. OH WHY is this @#%@#% NOT working
I thought that the braces handled arbitrary strings. What characters are allowed in braces and is there any way I can subclass Template to do what I want?
|
[
"From the documentation...\n\n$identifier names a substitution placeholder matching a mapping key of \"identifier\". By default, \"identifier\" must spell a Python identifier. The first non-identifier character after the $ character terminates this placeholder specification.\n\nThe period is a non-identifier character, and braces are simply used to separate the identifier from adjacent non-identifier text.\n",
"Aha, I tried this experiment:\nfrom string import Template\nimport uuid\n\nclass MyTemplate(Template):\n idpattern = r'[a-z][_a-z0-9]*(\\.[a-z][_a-z0-9]*)*'\n\nt1 = Template('cannot teach an ${dog.old} ${tricks.new}. ${why} is this ${not} working')\nt2 = MyTemplate('cannot teach an ${dog.old} ${tricks.new}. ${why} is this ${not} working')\nmap1 = {'dog.old': 'old dog', \n 'tricks.new': 'new tricks', 'why': 'OH WHY', 'not': '@#%@#% NOT'}\nmap2 = {'dog': {'old': 'old dog'}, \n 'tricks': {'new': 'new tricks'}, 'why': 'OH WHY', 'not': '@#%@#% NOT'} \nprint t1.safe_substitute(map1)\nprint t1.safe_substitute(map2)\nprint t2.safe_substitute(map1)\nprint t2.safe_substitute(map2)\n\nwhich prints \ncannot teach an ${dog.old} ${tricks.new}. OH WHY is this @#%@#% NOT working\ncannot teach an ${dog.old} ${tricks.new}. OH WHY is this @#%@#% NOT working\ncannot teach an old dog new tricks. OH WHY is this @#%@#% NOT working\ncannot teach an ${dog.old} ${tricks.new}. OH WHY is this @#%@#% NOT working\n\nso the third one (print t2.safe_substitute(map1)) works.\n",
"Python interprets the . in your name as \"access the field old of the instance dog\". Try _ instead or make dog an object with a field old.\nAFAIR, only valid identifiers and . are safe between the braces.\n[EDIT] It's on the page where you link to:\n\n${identifier} is equivalent to $identifier. It is required when valid identifier characters follow the placeholder but are not part of the placeholder, such as \"${noun}ification\".\n\nand\n\n\"identifier\" must spell a Python identifier.\n\nwhich means: It must be a valid identifier.\n[EDIT2] It seems that the identifier isn't analyzed as I thought. So you must specify a simple valid Python identifier in the braces (and you can't use the field accessor syntax) unless you create your own implementation of the Template class.\n"
] |
[
5,
5,
1
] |
[] |
[] |
[
"python",
"string",
"templates"
] |
stackoverflow_0002326757_python_string_templates.txt
|
Q:
Why is 'join' faster than normal concatenation?
I've seen several examples from different languages that unambiguously prove that joining elements of a list (array) is many times faster than just concatenating string. Why?
What is the inner algorithm that works under both operations and why is the one faster than another?
Here is a Python example of what I mean:
# This is slow
x = 'a'
x += 'b'
...
x += 'z'
# This is fast
x = ['a', 'b', ... 'z']
x = ''.join(x)
A:
The code in a join function knows upfront all the strings it’s being asked to concatenate and how large those strings are, and hence it can calculate the final string length before beginning the operation.
Hence it needs only allocate memory for the final string once and then it can place each source string (and delimiter) in the correct place in memory.
On the other hand, a single += operation on a string has no choice but to simply allocate enough memory for the final string which is the concatenation of just two strings. Subsequent +='s must do the same, each allocating memory which on the next += will be discarded. Each time the evergrowing string is copied from one place in memory to another.
A:
The reason is that strings in Python (and many other languages) are immutable objects - that is, once created, they can't be changed. Instead, concatenating a string actually makes a new string which consists of the contents of the two smaller strings being concatenated, and then replaces the old string with the new one.
Since creating a string takes a certain amount of time (need to allocate memory, copy the contents of the string to that memory, et cetera), making many strings takes longer than making a single string. Doing N concatenations requires creating N new strings in the process. join(), on the other hand, only has to create a single string (the final result) and thus works much faster.
A:
This is because a larger and larger chunk of memory has to be allocated for the string concatenation:
x = 'a' # String of size 1 allocated
x += 'b' # String of size 2 allocated, x copied, and 'b' added. Old x discarded
x += 'b' # String of size 3 allocated, x copied, and 'c' added. Old x discarded
x += 'b' # String of size 4 allocated, x copied, and 'd' added. Old x discarded
x += 'b' # String of size 5 allocated, x copied, and 'e' added. Old x discarded
So what happens is you perform large allocations and copies, but then turn around and throw them away. Very wasteful.
x = ['a', 'b', ..., 'z'] # 26 small allocations
x = ''.join(x) # A single, large allocation
A:
See Python string join performance and one specific answer that describes it very well:
The advice is about concatenating a lot of strings.
To compute s = s1 + s2 + ... + sn,
using +. A new string s1+s2 is created, then a new string s1+s2+s3 is created,..., etc, so a lot of memory allocation and copy operations is involved. In fact, s1 is copied n-1 times, s2 is copied n-2 time, ..., etc.
using "".join([s1,s2,...,sn]). The concatenation is done in one pass, and each char in the strings is copied only once.
A:
The other responses have basically covered it, but if you want even more detail, Joel Spolsky has an article where he describes "Schlemiel the painter's algorithm", which is extremely relevant and nicely makes the case for why understanding this sort of low level implementation detail is still very important even if you're working in a high level language like Python.
A:
Well, this is heavily language dependent, but in general the idea there is, that one big operation is faster than many small ones.
In your second example, the join knows all the elements that it has to join and thus can just allocate the necessary resources and put the characters in.
The concatenation in your first example has to reallocate resources at every single step (worst case).
A:
I don't know the internals of join, but in the first version you create a new string every time you call the += operator. Since strings are immutable, every time new memory is allocated and a copy is made.
Now, the join (which is a string method) could only do a single allocation, since it can calculate the size beforehand.
|
Why is 'join' faster than normal concatenation?
|
I've seen several examples from different languages that unambiguously prove that joining elements of a list (array) is many times faster than just concatenating string. Why?
What is the inner algorithm that works under both operations and why is the one faster than another?
Here is a Python example of what I mean:
# This is slow
x = 'a'
x += 'b'
...
x += 'z'
# This is fast
x = ['a', 'b', ... 'z']
x = ''.join(x)
|
[
"The code in a join function knows upfront all the strings it’s being asked to concatenate and how large those strings are, and hence it can calculate the final string length before beginning the operation.\nHence it needs only allocate memory for the final string once and then it can place each source string (and delimiter) in the correct place in memory.\nOn the other hand, a single += operation on a string has no choice but to simply allocate enough memory for the final string which is the concatenation of just two strings. Subsequent +='s must do the same, each allocating memory which on the next += will be discarded. Each time the evergrowing string is copied from one place in memory to another.\n",
"The reason is that strings in Python (and many other languages) are immutable objects - that is, once created, they can't be changed. Instead, concatenating a string actually makes a new string which consists of the contents of the two smaller strings being concatenated, and then replaces the old string with the new one.\nSince creating a string takes a certain amount of time (need to allocate memory, copy the contents of the string to that memory, et cetera), making many strings takes longer than making a single string. Doing N concatenations requires creating N new strings in the process. join(), on the other hand, only has to create a single string (the final result) and thus works much faster.\n",
"This is because a larger and larger chunk of memory has to be allocated for the string concatenation:\nx = 'a' # String of size 1 allocated\nx += 'b' # String of size 2 allocated, x copied, and 'b' added. Old x discarded\nx += 'b' # String of size 3 allocated, x copied, and 'c' added. Old x discarded\nx += 'b' # String of size 4 allocated, x copied, and 'd' added. Old x discarded\nx += 'b' # String of size 5 allocated, x copied, and 'e' added. Old x discarded\n\nSo what happens is you perform large allocations and copies, but then turn around and throw them away. Very wasteful.\nx = ['a', 'b', ..., 'z'] # 26 small allocations\nx = ''.join(x) # A single, large allocation\n\n",
"See Python string join performance and one specific answer that describes it very well:\n\nThe advice is about concatenating a lot of strings.\nTo compute s = s1 + s2 + ... + sn,\n\nusing +. A new string s1+s2 is created, then a new string s1+s2+s3 is created,..., etc, so a lot of memory allocation and copy operations is involved. In fact, s1 is copied n-1 times, s2 is copied n-2 time, ..., etc.\n\nusing \"\".join([s1,s2,...,sn]). The concatenation is done in one pass, and each char in the strings is copied only once.\n\n\n\n",
"The other responses have basically covered it, but if you want even more detail, Joel Spolsky has an article where he describes \"Schlemiel the painter's algorithm\", which is extremely relevant and nicely makes the case for why understanding this sort of low level implementation detail is still very important even if you're working in a high level language like Python.\n",
"Well, this is heavily language dependent, but in general the idea there is, that one big operation is faster than many small ones.\nIn your second example, the join knows all the elements that it has to join and thus can just allocate the necessary resources and put the characters in.\nThe concatenation in your first example has to reallocate resources at every single step (worst case).\n",
"I don't know the internals of join, but in the first version you create a new string every time you call the += operator. Since strings are immutable, every time new memory is allocated and a copy is made.\nNow, the join (which is a string method) could only do a single allocation, since it can calculate the size beforehand.\n"
] |
[
15,
14,
3,
3,
2,
0,
0
] |
[] |
[] |
[
"javascript",
"performance",
"python",
"string_concatenation"
] |
stackoverflow_0002324963_javascript_performance_python_string_concatenation.txt
|
Q:
Class level return/exit in Python
In my application I have a loop that in each turn creates an instance of a class which performs some operations. In this class I have a signal timer that when invoked is supposed to exit the current turn in the loop gracefully and allow the next operation to continue without any interruption.
In it's current state it raises an exception that is supposed to be caught by a try-except-block. However I have a "loadFinished" signal (that I don't know the id for) that is invoked after the exception is thrown and causes a runtime exception on the function definition that I can't catch.
Is there a way to do a class level return like one would do to end a function if something is wrong? Or maybe some kind of sys.exit() that only works on the class?
I hope I made myself clear. :) Thank you for your help.
A:
If you're talking about signals as in the signal module, then the handlers aren't called in a standard fashion.
You can't throw an exception out of them and expect it to appear in your normal code. Indeed you should try to do as little as possible in your handler - set a global flag, or send a message on a pipe perhaps.
A:
Christopher,
maybe using Timer and Event classes is more appropriate for you. You could check for the event to be set inside you loop an then exit the current iteration:
if my_event.isSet():
continue
I think what you are trying to do is not really a good design. I see no way to "throw" an exception into a different function. I assume by signal you mean asynchronous function call. This of course could also set the event mentioned above.
|
Class level return/exit in Python
|
In my application I have a loop that in each turn creates an instance of a class which performs some operations. In this class I have a signal timer that when invoked is supposed to exit the current turn in the loop gracefully and allow the next operation to continue without any interruption.
In it's current state it raises an exception that is supposed to be caught by a try-except-block. However I have a "loadFinished" signal (that I don't know the id for) that is invoked after the exception is thrown and causes a runtime exception on the function definition that I can't catch.
Is there a way to do a class level return like one would do to end a function if something is wrong? Or maybe some kind of sys.exit() that only works on the class?
I hope I made myself clear. :) Thank you for your help.
|
[
"If you're talking about signals as in the signal module, then the handlers aren't called in a standard fashion.\nYou can't throw an exception out of them and expect it to appear in your normal code. Indeed you should try to do as little as possible in your handler - set a global flag, or send a message on a pipe perhaps.\n",
"Christopher,\nmaybe using Timer and Event classes is more appropriate for you. You could check for the event to be set inside you loop an then exit the current iteration:\nif my_event.isSet():\n continue\n\nI think what you are trying to do is not really a good design. I see no way to \"throw\" an exception into a different function. I assume by signal you mean asynchronous function call. This of course could also set the event mentioned above.\n"
] |
[
1,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002327077_python.txt
|
Q:
It is said best way to deploy django is using wsgi, I am wondering why?
We are deploying django application, I found in the documentation that it is recommended to use WSGI appoach for doing that.
Before deploying I wanted to know, why it is recommended over other two approaches i.e. using mod_python and fastcgi...
Thanks a lot.
A:
wsgi is usually preferred because it decouples your choice of framework from your choice of web server: if tomorrow you want to move, say, from Apache to nginx, or whatever, the move is trivially easy with wsgi, not so easy otherwise.
Furthermore, using wsgi affords you the option to add some middleware that's framework-independent, rather than having to rely on every possible functionality you want having already been implemented and made available for your framework of choice.
A:
We tried mod_python. It's slower and harder to configure. It doesn't offer the daemon feature.
We couldn't get fast_cgi built for our combination of Apache, Red Hat and Python. I'm not sure specifically what was wrong, but we couldn't get it built properly. It wouldn't dispatch requests to Django properly, and we couldn't diagnose the problem.
We tried mod_wsgi third. It built nicely. It has the daemon option. It's very easy to configure. It allows trivial restart of the Django applications without restarting all of Apache.
A:
I use mod_wsgi for any production Django app. It's fast, stable, and very configurable.
You may also want to look in to the FastCGI method a bit more. Eric Florenzano just did a great write up of Django with FastCGI for the Django Advent: http://djangoadvent.com/1.2/deploying-django-site-using-fastcgi/
|
It is said best way to deploy django is using wsgi, I am wondering why?
|
We are deploying django application, I found in the documentation that it is recommended to use WSGI appoach for doing that.
Before deploying I wanted to know, why it is recommended over other two approaches i.e. using mod_python and fastcgi...
Thanks a lot.
|
[
"wsgi is usually preferred because it decouples your choice of framework from your choice of web server: if tomorrow you want to move, say, from Apache to nginx, or whatever, the move is trivially easy with wsgi, not so easy otherwise.\nFurthermore, using wsgi affords you the option to add some middleware that's framework-independent, rather than having to rely on every possible functionality you want having already been implemented and made available for your framework of choice.\n",
"We tried mod_python. It's slower and harder to configure. It doesn't offer the daemon feature.\nWe couldn't get fast_cgi built for our combination of Apache, Red Hat and Python. I'm not sure specifically what was wrong, but we couldn't get it built properly. It wouldn't dispatch requests to Django properly, and we couldn't diagnose the problem.\nWe tried mod_wsgi third. It built nicely. It has the daemon option. It's very easy to configure. It allows trivial restart of the Django applications without restarting all of Apache.\n",
"I use mod_wsgi for any production Django app. It's fast, stable, and very configurable.\nYou may also want to look in to the FastCGI method a bit more. Eric Florenzano just did a great write up of Django with FastCGI for the Django Advent: http://djangoadvent.com/1.2/deploying-django-site-using-fastcgi/\n"
] |
[
15,
5,
0
] |
[] |
[] |
[
"django",
"django_wsgi",
"mod_wsgi",
"python",
"wsgi"
] |
stackoverflow_0002327355_django_django_wsgi_mod_wsgi_python_wsgi.txt
|
Q:
Outlook contacts using Python client
I want to write a script which permits a user to modify his Contacts, can you help me ?
thanks,
A:
You can use Python-COM bindings to use Outlook's COM object and achieve what you want.
Here's a nice tutorial on how to use Python with COM.
|
Outlook contacts using Python client
|
I want to write a script which permits a user to modify his Contacts, can you help me ?
thanks,
|
[
"You can use Python-COM bindings to use Outlook's COM object and achieve what you want.\nHere's a nice tutorial on how to use Python with COM.\n"
] |
[
3
] |
[] |
[] |
[
"outlook",
"python"
] |
stackoverflow_0002327584_outlook_python.txt
|
Q:
Where should sys.path.append('...') statement go?
Just after standard pythonmodule imports?
If I postpone it to the main function and do my specific module imports before it, it gives error (which is quite obvious). Python Style guide no where mentions the correct location for it.
A:
It should go before the import or from statements that need it (which as you say is obvious). So for example a module could start with:
import sys
import os
import math
try:
import foo
except ImportError:
if 'foopath' in sys.path: raise
sys.path.append('foopath')
import foo
Note that I've made the append conditional (on the import failing and the specific module's path not being on sys.path yet) to avoid the risk of sys.path ending up with dozens of occurrences of string foopath, which would not be particularly helpful;-).
A:
One reason this isn't mentioned in PEP 8 or other good Python style guides is that modifying sys.path isn't something you want to do in a real program; it makes your program less robust and portable. A better solution might be to put your package somewhere that would already be in sys.path or to define PYTHONPATH systemwide to include your package.
A:
I often use a shell script to launch my python applications: I put my sys.path.insert (append) statement just after the "standard" python module imports in my "launch python script".
Using sys.path.insert(0, ...) gets your "imports" in priority in the path list.
A:
I generally do it before importing anything. If you're worried that your module names might conflict with the Python stdlib names, then change your module names!
A:
I think it's a matter of taste. But most people tend to put it behind the import sys :-)
I prefer wrapping it in an extra function:
def importmod_abs(name):
sys.path.append() ..
__import__ ...
sys.path.pop()
... this way sys.path remains clean. Of course that's only applicable to certain module structures. Anyways, I'd import everything that works without altering sys.path first.
|
Where should sys.path.append('...') statement go?
|
Just after standard pythonmodule imports?
If I postpone it to the main function and do my specific module imports before it, it gives error (which is quite obvious). Python Style guide no where mentions the correct location for it.
|
[
"It should go before the import or from statements that need it (which as you say is obvious). So for example a module could start with:\nimport sys\nimport os\nimport math\ntry:\n import foo\nexcept ImportError:\n if 'foopath' in sys.path: raise\n sys.path.append('foopath')\n import foo\n\nNote that I've made the append conditional (on the import failing and the specific module's path not being on sys.path yet) to avoid the risk of sys.path ending up with dozens of occurrences of string foopath, which would not be particularly helpful;-).\n",
"One reason this isn't mentioned in PEP 8 or other good Python style guides is that modifying sys.path isn't something you want to do in a real program; it makes your program less robust and portable. A better solution might be to put your package somewhere that would already be in sys.path or to define PYTHONPATH systemwide to include your package.\n",
"I often use a shell script to launch my python applications: I put my sys.path.insert (append) statement just after the \"standard\" python module imports in my \"launch python script\".\nUsing sys.path.insert(0, ...) gets your \"imports\" in priority in the path list.\n",
"I generally do it before importing anything. If you're worried that your module names might conflict with the Python stdlib names, then change your module names!\n",
"I think it's a matter of taste. But most people tend to put it behind the import sys :-)\nI prefer wrapping it in an extra function:\ndef importmod_abs(name):\n sys.path.append() ..\n\n __import__ ...\n\n sys.path.pop()\n\n... this way sys.path remains clean. Of course that's only applicable to certain module structures. Anyways, I'd import everything that works without altering sys.path first.\n"
] |
[
8,
4,
1,
0,
0
] |
[] |
[] |
[
"coding_style",
"python"
] |
stackoverflow_0002327322_coding_style_python.txt
|
Q:
How to best use GPS data?
I am currently developing an application that receives GPS data gathered using and android phone. I need to analyze that data in terms of speed, acceleration, etc...
My question is: Can I trust the speed values returned by the phone? Or should I use the difference in position and time between two points to get the values I want? Also, is there any "standard" method for filtering input data? Or any library (python welcomed) that does that kind of task?
Thank you in advance! :)
A:
Except using rather complicated data signal processing techniques, or by using an accelerometer and dead reckoning (which is highly inaccurate), a GPS device cannot measure its own velocity. Due to this, the velocity data provided by a GPS unit is interpolated using the exact same method you want to use. The two probably have similar precision excluding minor errors introduced from whatever algorithms both you and the GPS chip manufacturer use.
There are more advanced filtering / data processing techniques for interpolating velocity across multiple points, not just the most recent two. In all likelihood, your GPS chip is already implementing one of these and so will be more accurate than your more rudimentary implementation.
|
How to best use GPS data?
|
I am currently developing an application that receives GPS data gathered using and android phone. I need to analyze that data in terms of speed, acceleration, etc...
My question is: Can I trust the speed values returned by the phone? Or should I use the difference in position and time between two points to get the values I want? Also, is there any "standard" method for filtering input data? Or any library (python welcomed) that does that kind of task?
Thank you in advance! :)
|
[
"Except using rather complicated data signal processing techniques, or by using an accelerometer and dead reckoning (which is highly inaccurate), a GPS device cannot measure its own velocity. Due to this, the velocity data provided by a GPS unit is interpolated using the exact same method you want to use. The two probably have similar precision excluding minor errors introduced from whatever algorithms both you and the GPS chip manufacturer use.\nThere are more advanced filtering / data processing techniques for interpolating velocity across multiple points, not just the most recent two. In all likelihood, your GPS chip is already implementing one of these and so will be more accurate than your more rudimentary implementation.\n"
] |
[
9
] |
[] |
[] |
[
"android",
"filtering",
"gps",
"python"
] |
stackoverflow_0002327813_android_filtering_gps_python.txt
|
Q:
How to make PowerBuilder UI testing application?
I'm not familiar with PowerBuilder but I have a task to create Automatic UI Test Application for PB. We've decided to do it in Python with pywinauto and iaccesible libraries. The problem is that some UI elements like newly added lists record can not be accesed from it (even inspect32 can't get it).
Any ideas how to reach this elements and make them testable?
A:
I'm experimenting with code for a tool for automating PowerBuilder-based GUIs as well. From what I can see, your best bet would be to use the PowerBuilder Native Interface (PBNI), and call PowerScript code from within your NVO.
If you like, feel free to send me an email (see my profile for my email address), I'd be interested in exchanging ideas about how to do this.
A:
I didn't use PowerBuilder for a while but I guess that the problem that you are trying to solve is similar to the one I am trying to address for people making projects with SCADA systems like Wonderware Intouch.
The problem with such an application is that there is no API to get or set the value of a control. So a pywinauto approach can't work.
I've made a small tool to simulate the user events and to get the results from a screencapture. I am usig PIL and pytesser ORM for the analysis of the screen captures. It is not the easiest way but it works OK.
The tool is open-source and free of charge and can be downloaded from my website (Sorry in french). You just need an account but it's free as well. Just ask.
If you can read french, here is one article about testing Intouch-based applications
Sorry for the self promotion, but I was facing a similar problem with no solution so I've written my own. Anyway, that's free and open-source...
A:
If you are testing DataWindows (the class is pbdwxxx, e.g. pbdw110) you will have to use a combination of clicking at specific coordinates and sending Tab keys to get to the control you want. Of course you can also send up and down arrow keys to move among rows. The easiest thing to do is to start with a normal control like an SLE and tab into the DataWindow. The problem is that the DataWindow is essentially just an image. There is no control for a given field until you move the focus there by clicking or tabbing. I've also found that the DataWindow's iAccessible interface is a bit strange. If you ask the DataWindow for the object with focus, you don't get the right answer. If you enumerate through all of the children you can find the one that has focus. If you can modify the source I also advise that you set AccessibleName for your DataWindow controls, otherwise you probably won't be able to identify the controls except by position (by DataWindow controls I mean the ones inside the DataWindow, not the DataWindow itself). If it's an MDI application, you may also find it useful to locate the MicroHelp window (class fnhelpxxx, e.g. fnhelp110, find from the main application window) to help determine your current context.
Edited to add:
Sikuli looks very promising for testing PowerBuilder. It works by recognizing objects on the screen from a saved fragment of screenshot. That is, you take a screenshot of the part of the screen you want it to find.
A:
I've seen in AutomatedQa support that they a recipe recommending using msaa and setting some properties on the controls. I do not know if it works.
|
How to make PowerBuilder UI testing application?
|
I'm not familiar with PowerBuilder but I have a task to create Automatic UI Test Application for PB. We've decided to do it in Python with pywinauto and iaccesible libraries. The problem is that some UI elements like newly added lists record can not be accesed from it (even inspect32 can't get it).
Any ideas how to reach this elements and make them testable?
|
[
"I'm experimenting with code for a tool for automating PowerBuilder-based GUIs as well. From what I can see, your best bet would be to use the PowerBuilder Native Interface (PBNI), and call PowerScript code from within your NVO.\nIf you like, feel free to send me an email (see my profile for my email address), I'd be interested in exchanging ideas about how to do this.\n",
"I didn't use PowerBuilder for a while but I guess that the problem that you are trying to solve is similar to the one I am trying to address for people making projects with SCADA systems like Wonderware Intouch.\nThe problem with such an application is that there is no API to get or set the value of a control. So a pywinauto approach can't work.\nI've made a small tool to simulate the user events and to get the results from a screencapture. I am usig PIL and pytesser ORM for the analysis of the screen captures. It is not the easiest way but it works OK.\nThe tool is open-source and free of charge and can be downloaded from my website (Sorry in french). You just need an account but it's free as well. Just ask.\nIf you can read french, here is one article about testing Intouch-based applications\nSorry for the self promotion, but I was facing a similar problem with no solution so I've written my own. Anyway, that's free and open-source... \n",
"If you are testing DataWindows (the class is pbdwxxx, e.g. pbdw110) you will have to use a combination of clicking at specific coordinates and sending Tab keys to get to the control you want. Of course you can also send up and down arrow keys to move among rows. The easiest thing to do is to start with a normal control like an SLE and tab into the DataWindow. The problem is that the DataWindow is essentially just an image. There is no control for a given field until you move the focus there by clicking or tabbing. I've also found that the DataWindow's iAccessible interface is a bit strange. If you ask the DataWindow for the object with focus, you don't get the right answer. If you enumerate through all of the children you can find the one that has focus. If you can modify the source I also advise that you set AccessibleName for your DataWindow controls, otherwise you probably won't be able to identify the controls except by position (by DataWindow controls I mean the ones inside the DataWindow, not the DataWindow itself). If it's an MDI application, you may also find it useful to locate the MicroHelp window (class fnhelpxxx, e.g. fnhelp110, find from the main application window) to help determine your current context.\nEdited to add:\nSikuli looks very promising for testing PowerBuilder. It works by recognizing objects on the screen from a saved fragment of screenshot. That is, you take a screenshot of the part of the screen you want it to find. \n",
"I've seen in AutomatedQa support that they a recipe recommending using msaa and setting some properties on the controls. I do not know if it works.\n"
] |
[
2,
1,
1,
1
] |
[] |
[] |
[
"powerbuilder",
"python",
"testing"
] |
stackoverflow_0001741023_powerbuilder_python_testing.txt
|
Q:
How to run a clone of reddit.com website. Reddit.com source code gives error while implementing on Ubuntu 9.10 (karmic)
I am implementing the reddit.com source code on ubuntu karmic 9.10.
I have followed all the steps and in one step where i am using paster command it throws an error.
$paster shell example.ini
File "/usr/local/lib/python2.6/dist-packages/Pylons-0.9.6.2-
py2.6.egg/pylons/middleware.py", line 11, in
from webhelpers.rails.asset_tag import javascript_path
ImportError: No module named rails.asset_tag
I have checked for the version for webhelpers, its the latest installed.
Could anybody tell me that by installing another version of webhelpers will solve this problem?
Or Shall i modify the code?
Its a reddit.com source code written in python, using pylons framework.
I am unable to decide that whether by installing any previous version of webhelpers helps or shall i modify the code.
If there is anybody who have implemented the reddit.com website please help me or suggest me the best way.
thanks
SIA
A:
You need to ensure that all the libraries needed by your Reddit clone are on Python's module search path. There are a lot of different ways to accomplish this. The easiest is probably to just use setuptools' easy_install command to install them (though this is my own personal least favorite way to install Python libraries, and also opens new cans of worms in the form of "Why not use distribute or pip instead?").
The next easiest way is probably to download and unpack the source code for the libraries you need and either a) setup.py install them or b) add their directories to your $PYTHONPATH or sys.path variables.
The documentation linked above has more info on how to control the module search path.
|
How to run a clone of reddit.com website. Reddit.com source code gives error while implementing on Ubuntu 9.10 (karmic)
|
I am implementing the reddit.com source code on ubuntu karmic 9.10.
I have followed all the steps and in one step where i am using paster command it throws an error.
$paster shell example.ini
File "/usr/local/lib/python2.6/dist-packages/Pylons-0.9.6.2-
py2.6.egg/pylons/middleware.py", line 11, in
from webhelpers.rails.asset_tag import javascript_path
ImportError: No module named rails.asset_tag
I have checked for the version for webhelpers, its the latest installed.
Could anybody tell me that by installing another version of webhelpers will solve this problem?
Or Shall i modify the code?
Its a reddit.com source code written in python, using pylons framework.
I am unable to decide that whether by installing any previous version of webhelpers helps or shall i modify the code.
If there is anybody who have implemented the reddit.com website please help me or suggest me the best way.
thanks
SIA
|
[
"You need to ensure that all the libraries needed by your Reddit clone are on Python's module search path. There are a lot of different ways to accomplish this. The easiest is probably to just use setuptools' easy_install command to install them (though this is my own personal least favorite way to install Python libraries, and also opens new cans of worms in the form of \"Why not use distribute or pip instead?\").\nThe next easiest way is probably to download and unpack the source code for the libraries you need and either a) setup.py install them or b) add their directories to your $PYTHONPATH or sys.path variables.\nThe documentation linked above has more info on how to control the module search path.\n"
] |
[
1
] |
[] |
[] |
[
"paster",
"pylons",
"python",
"reddit"
] |
stackoverflow_0002326905_paster_pylons_python_reddit.txt
|
Q:
Interrupt all running signals in Python?
How can I interrupt all running signals in a Python script? I would like something like signal.interrupt_all().
Is there any way to do that?
Thanks
A:
What exactly do you mean? Do you want to temporairly ignore a signal, or to completely ignore some kinds of signals?
Generally speaking, you can't "vanish" a signal once it has been generated. You either set its action to "ignore" or you block the signal, preventing it from being delivered, but you need to do this beforehand.
On POSIX systems, your options are (see Signal Concepts):
Ignore the signal by setting its handler to SIG_IGN. This will also cause pending signals to be ignored (see Signal Concepts: SIG_IGN).
Block a signal from delivery. The signal will remain pending but your process/thread won't receive it (until it is unblocked). Unfortunately, you can't block signals in Python: see the signal module documentation.
Note that you can't interrupt a signal handler (signal-catching function); this shouldn't be a problem, as signal handlers are expected to return quickly.
See also this question: Trapping Signals in Python.
|
Interrupt all running signals in Python?
|
How can I interrupt all running signals in a Python script? I would like something like signal.interrupt_all().
Is there any way to do that?
Thanks
|
[
"What exactly do you mean? Do you want to temporairly ignore a signal, or to completely ignore some kinds of signals?\nGenerally speaking, you can't \"vanish\" a signal once it has been generated. You either set its action to \"ignore\" or you block the signal, preventing it from being delivered, but you need to do this beforehand.\nOn POSIX systems, your options are (see Signal Concepts):\n\nIgnore the signal by setting its handler to SIG_IGN. This will also cause pending signals to be ignored (see Signal Concepts: SIG_IGN).\nBlock a signal from delivery. The signal will remain pending but your process/thread won't receive it (until it is unblocked). Unfortunately, you can't block signals in Python: see the signal module documentation.\n\nNote that you can't interrupt a signal handler (signal-catching function); this shouldn't be a problem, as signal handlers are expected to return quickly.\nSee also this question: Trapping Signals in Python.\n"
] |
[
1
] |
[] |
[] |
[
"python",
"signals"
] |
stackoverflow_0002318831_python_signals.txt
|
Q:
Python and windows filesystem with none-ascii characters
I want to write a folder on a windows system, Vista and Win7 with NTFS file systems.
The folders may contain the characters å, ä and/or ö, "förjävligt" for example.
The python files and every string in it is currently in UTF-8, how do I convert it to suite the Windows file system?
A:
If you're working with normal Python 2 strings, you can simply convert them to Unicode
# -*- coding: utf-8 -*-
normalString = "äöü"
# Now convert to unicode. Specified encoding must match the file encoding
# in this example. In general, you must specify how the bytes-only string
# contained in "normalString" is encoded.
unicodeString = unicode(normalString, "utf-8")
with open(unicodeString, "w") as f:
...
and create the files using those Unicode strings. Python (and indirectly the Windows API) will take care of the rest.
A:
If you want to make the strings really nice for working with in windows you can use this safeFilenameCodec. It is a subset of allowable characters, but you won't have to worry about any craziness getting by. And it has generous licensing.
|
Python and windows filesystem with none-ascii characters
|
I want to write a folder on a windows system, Vista and Win7 with NTFS file systems.
The folders may contain the characters å, ä and/or ö, "förjävligt" for example.
The python files and every string in it is currently in UTF-8, how do I convert it to suite the Windows file system?
|
[
"If you're working with normal Python 2 strings, you can simply convert them to Unicode\n# -*- coding: utf-8 -*-\nnormalString = \"äöü\"\n\n# Now convert to unicode. Specified encoding must match the file encoding\n# in this example. In general, you must specify how the bytes-only string\n# contained in \"normalString\" is encoded.\nunicodeString = unicode(normalString, \"utf-8\")\n\nwith open(unicodeString, \"w\") as f:\n ...\n\nand create the files using those Unicode strings. Python (and indirectly the Windows API) will take care of the rest.\n",
"If you want to make the strings really nice for working with in windows you can use this safeFilenameCodec. It is a subset of allowable characters, but you won't have to worry about any craziness getting by. And it has generous licensing. \n"
] |
[
3,
1
] |
[] |
[] |
[
"ntfs",
"python",
"windows"
] |
stackoverflow_0002327226_ntfs_python_windows.txt
|
Q:
Python OOP - Class relationships
Assuming I have a system of three Classes.
The GameClass creates instances of both other classes upon initialization.
class FieldClass:
def __init__( self ):
return
def AnswerAQuestion( self ):
return 42
class PlayerClass:
def __init__( self ):
return
def DoMagicHere( self ):
# Access "AnswerAQuestion" located in the "FieldClass" instance in "GameClass"
pass
class GameClass:
def __init__( self ):
self.Field = FieldClass()
self.Player = PlayerClass()
What would be the best way of accessing AnswerAQuestion() located in FieldClass from within the instance of PlayerClass?
Do I have to pass a reference to the FieldClass instance to PlayerClass?
Is there another, better way of solving this? Doing the above would make me have to include an additional variable in PlayerClass to hold the FieldClass instance.
Is there a completely different way of managing class relationships in Python?
A:
I would go with Dependency Injection: instantiate a GameClass with the required FieldClass and PlayerClass in the constructor call etc. (i.e. instead of creating the dependent objects from within GameClass as you are doing at the moment).
class GameClass:
def __init__( self, fc, pc ):
self.Field = fc
self.Player = pc
class PlayerClass:
def __init__( self, fc ):
self.fc = fc
def DoMagicHere( self ):
# use self.fc
pass
fc=FieldClass()
pc=PlayerClass(fc)
gc=GameClass(fc, pc)
With DI, you can easily have access to the members you require once the setup phase is completed.
A:
To better understand your class relationships you have to tell us more about your project and what you are trying to accomplish.
One way to reference the instance of FieldClass from PlayerClass in your example is to pass the GameClass instance to the PlayerClass instance:
class PlayerClass:
def __init__(self, game):
self.game = game
def DoMagicHere(self):
self.game.Field.AnswerAQuestion()
# ...
class GameClass:
def __init__( self ):
self.Field = FieldClass()
self.Player = PlayerClass(self)
Another way is to pass the field variable
class PlayerClass:
def __init__(self, field):
self.field = field
def DoMagicHere(self):
self.field.AnswerAQuestion()
# ...
class GameClass:
def __init__( self ):
self.Field = FieldClass()
self.Player = PlayerClass(self.Field)
As a side note: you use a peculiar naming scheme. I suggest this:
class Game:
def __init__(self):
self.field = Field()
self.player = Player(...)
I suggest you read the Python Style Guide before acquiring bad habits.
A:
You could provide the context to the child objects, i.e.:
class FieldClass:
def __init__(self,game):
self.game = game
class PlayerClass:
def __init__(self,game):
self.game = game
def DoMagicHere(self):
self.game.Field.AnswerAQuestion()
class GameClass:
def __init__(self):
self.Field = FieldClass(self)
self.Player = PlayerClass(self)
Since the objects know their context they can reach into it and access other objects in the same context.
A:
I would do something like the following, where you pass Game in as a back-reference, allowing you access to the other associated classes. In this way, you could optionally give that player instance a direct relationship to the field.
class FieldClass(object):
def __init__(self, game):
self.Game = game
def AnswerAQuestion(self):
return 42
class PlayerClass(object):
def __init__(self, game):
self.Game = game
self.Field = game.Field # Optional
def DoMagicHere(self):
self.Game.Field.AnswerAQuestion()
self.Field.AnswerAQuestion() # Optional
class GameClass(object):
def __init__(self):
self.Field = FieldClass(self)
self.Player = PlayerClass(self)
One side note is that it's good practice now to have all your classes inherit from object rather than to have them standing alone.
|
Python OOP - Class relationships
|
Assuming I have a system of three Classes.
The GameClass creates instances of both other classes upon initialization.
class FieldClass:
def __init__( self ):
return
def AnswerAQuestion( self ):
return 42
class PlayerClass:
def __init__( self ):
return
def DoMagicHere( self ):
# Access "AnswerAQuestion" located in the "FieldClass" instance in "GameClass"
pass
class GameClass:
def __init__( self ):
self.Field = FieldClass()
self.Player = PlayerClass()
What would be the best way of accessing AnswerAQuestion() located in FieldClass from within the instance of PlayerClass?
Do I have to pass a reference to the FieldClass instance to PlayerClass?
Is there another, better way of solving this? Doing the above would make me have to include an additional variable in PlayerClass to hold the FieldClass instance.
Is there a completely different way of managing class relationships in Python?
|
[
"I would go with Dependency Injection: instantiate a GameClass with the required FieldClass and PlayerClass in the constructor call etc. (i.e. instead of creating the dependent objects from within GameClass as you are doing at the moment).\nclass GameClass:\n def __init__( self, fc, pc ):\n self.Field = fc\n self.Player = pc\n\nclass PlayerClass:\n def __init__( self, fc ):\n self.fc = fc\n\n def DoMagicHere( self ):\n # use self.fc\n pass\n\nfc=FieldClass()\npc=PlayerClass(fc)\ngc=GameClass(fc, pc)\n\nWith DI, you can easily have access to the members you require once the setup phase is completed.\n",
"To better understand your class relationships you have to tell us more about your project and what you are trying to accomplish. \nOne way to reference the instance of FieldClass from PlayerClass in your example is to pass the GameClass instance to the PlayerClass instance:\nclass PlayerClass:\n def __init__(self, game):\n self.game = game\n def DoMagicHere(self):\n self.game.Field.AnswerAQuestion()\n\n# ...\n\nclass GameClass:\n def __init__( self ):\n self.Field = FieldClass()\n self.Player = PlayerClass(self)\n\nAnother way is to pass the field variable\nclass PlayerClass:\n def __init__(self, field):\n self.field = field\n def DoMagicHere(self):\n self.field.AnswerAQuestion()\n# ...\n\nclass GameClass:\n def __init__( self ):\n self.Field = FieldClass()\n self.Player = PlayerClass(self.Field)\n\nAs a side note: you use a peculiar naming scheme. I suggest this:\n class Game:\n def __init__(self):\n self.field = Field()\n self.player = Player(...)\n\nI suggest you read the Python Style Guide before acquiring bad habits.\n",
"You could provide the context to the child objects, i.e.:\nclass FieldClass:\n def __init__(self,game):\n self.game = game\n\nclass PlayerClass:\n def __init__(self,game):\n self.game = game\n def DoMagicHere(self):\n self.game.Field.AnswerAQuestion()\n\nclass GameClass:\n def __init__(self):\n self.Field = FieldClass(self)\n self.Player = PlayerClass(self)\n\nSince the objects know their context they can reach into it and access other objects in the same context.\n",
"I would do something like the following, where you pass Game in as a back-reference, allowing you access to the other associated classes. In this way, you could optionally give that player instance a direct relationship to the field.\nclass FieldClass(object):\n def __init__(self, game):\n self.Game = game\n def AnswerAQuestion(self): \n return 42\n\nclass PlayerClass(object):\n def __init__(self, game):\n self.Game = game\n self.Field = game.Field # Optional\n def DoMagicHere(self):\n self.Game.Field.AnswerAQuestion()\n self.Field.AnswerAQuestion() # Optional\n\nclass GameClass(object):\n def __init__(self):\n self.Field = FieldClass(self)\n self.Player = PlayerClass(self)\n\nOne side note is that it's good practice now to have all your classes inherit from object rather than to have them standing alone.\n"
] |
[
6,
4,
1,
0
] |
[] |
[] |
[
"oop",
"python"
] |
stackoverflow_0002328094_oop_python.txt
|
Q:
IOError opening an existing file with Python
Running the following code:
import os
import datetime
import ftplib
currdate = datetime.datetime.now()
formatdate = currdate.strftime("%m-%d-%Y %H%M")
def log():
fqn = os.uname()[1]
ext_ip = urllib2.urlopen('http://whatismyip.org').read()
log = open ('/Users/admin/Documents/locatelog.txt','w')
log.write(str("Asset: %s " % fqn))
log.write(str("Checking in from IP#: %s" % ext_ip))
smush = str(fqn +' @ ' + formatdate)
os.rename('/Users/admin/Documents/locatelog.txt','/Users/admin/Documents/%s.txt' % smush )
s = ftplib.FTP('10.7.1.71','username','password')
f = open('/Users/admin/Documents/%s.txt' % smush,'r')
s.storbinary("STOR /Users/admin/Documents/%s.txt" % smush,f)
Generates the following error:
ftplib.error_perm: 550 /Users/admin/Documents/678538.local @ 02-24-2010 1301.txt: No such file or directory
I have a feeling something is amiss in this line :
s.storbinary("STOR /Users/admin/Documents/%s.txt" % smush,f)
678538 is the host I am testing on...using Mac OS X 10.5 and Python 2.5.1
A:
Shouldn't it bef = open('/Users/admin/Documents/%s.txt' % smush,'r') ? notice the / in front of Users
If you dont put the first /, the script will think the path to the file is relative to the current directory (where the script is run from)
Edit:
I m not too familiar with Python (I wish) but shouldnt it be:
s.storbinary('STOR /Users/admin/Documents/%s.txt' % smush,f) ?
In your example, Python will treat your string as literal and you want to interpolate the value of smush with %s
Edit 2:
Does the directory /Users/admin/Documents/ exist on your server? If not, I think you will have to create them before copying anything. (Since the error message is about some files/folders missing).
You can create them yourself first. Run your script. If the file is copied successfully, then you can add the creation of the directories from within your script.
A:
remove all spaces from file name .eg in smush = str(fqn +' @ ' + formatdate), you are putting a space in front of and after "@". you path looks like
/Users/admin/Documents/something @ something
and when you pass it to ftplib, it may have problem. another way is to try putting quotes, eg
s.storbinary("STOR '/Users/admin/Documents/%s.txt'" % smush,f)
A:
Edit:
This version works: Problem was that I was writing to buffer, and not to file.
import os
import urllib2
import datetime
import ftplib
currdate = datetime.datetime.now()
formatdate = currdate.strftime("%m-%d-%Y-%H%M")
def log():
fqn = os.uname()[1]
ext_ip = urllib2.urlopen('http://whatismyip.org').read()
smush = str(fqn + formatdate)
s = ftplib.FTP('10.7.1.71','username','password')
f = open('/Users/admin/Documents/%s.txt' % smush,'w')
f.write(str("Asset: %s " % fqn))
f.write('\n')
f.write(str("Checking in from IP#: %s" % ext_ip))
f.write('\n')
f.write(str("On: %s" % formatdate))
f.close
f = open('/Users/admin/Documents/%s.txt' % smush,'rb')
s.storbinary('STOR %s.txt' % smush , f)
s.close
f.close
|
IOError opening an existing file with Python
|
Running the following code:
import os
import datetime
import ftplib
currdate = datetime.datetime.now()
formatdate = currdate.strftime("%m-%d-%Y %H%M")
def log():
fqn = os.uname()[1]
ext_ip = urllib2.urlopen('http://whatismyip.org').read()
log = open ('/Users/admin/Documents/locatelog.txt','w')
log.write(str("Asset: %s " % fqn))
log.write(str("Checking in from IP#: %s" % ext_ip))
smush = str(fqn +' @ ' + formatdate)
os.rename('/Users/admin/Documents/locatelog.txt','/Users/admin/Documents/%s.txt' % smush )
s = ftplib.FTP('10.7.1.71','username','password')
f = open('/Users/admin/Documents/%s.txt' % smush,'r')
s.storbinary("STOR /Users/admin/Documents/%s.txt" % smush,f)
Generates the following error:
ftplib.error_perm: 550 /Users/admin/Documents/678538.local @ 02-24-2010 1301.txt: No such file or directory
I have a feeling something is amiss in this line :
s.storbinary("STOR /Users/admin/Documents/%s.txt" % smush,f)
678538 is the host I am testing on...using Mac OS X 10.5 and Python 2.5.1
|
[
"Shouldn't it bef = open('/Users/admin/Documents/%s.txt' % smush,'r') ? notice the / in front of Users\nIf you dont put the first /, the script will think the path to the file is relative to the current directory (where the script is run from)\nEdit:\nI m not too familiar with Python (I wish) but shouldnt it be:\ns.storbinary('STOR /Users/admin/Documents/%s.txt' % smush,f) ?\nIn your example, Python will treat your string as literal and you want to interpolate the value of smush with %s \nEdit 2:\nDoes the directory /Users/admin/Documents/ exist on your server? If not, I think you will have to create them before copying anything. (Since the error message is about some files/folders missing).\nYou can create them yourself first. Run your script. If the file is copied successfully, then you can add the creation of the directories from within your script.\n",
"remove all spaces from file name .eg in smush = str(fqn +' @ ' + formatdate), you are putting a space in front of and after \"@\". you path looks like \n/Users/admin/Documents/something @ something\n\nand when you pass it to ftplib, it may have problem. another way is to try putting quotes, eg\ns.storbinary(\"STOR '/Users/admin/Documents/%s.txt'\" % smush,f)\n\n",
"Edit: \nThis version works: Problem was that I was writing to buffer, and not to file.\nimport os\nimport urllib2\nimport datetime\nimport ftplib\n\ncurrdate = datetime.datetime.now()\nformatdate = currdate.strftime(\"%m-%d-%Y-%H%M\")\n\ndef log():\n\n fqn = os.uname()[1]\n ext_ip = urllib2.urlopen('http://whatismyip.org').read()\n smush = str(fqn + formatdate)\n s = ftplib.FTP('10.7.1.71','username','password')\n f = open('/Users/admin/Documents/%s.txt' % smush,'w')\n f.write(str(\"Asset: %s \" % fqn))\n f.write('\\n')\n f.write(str(\"Checking in from IP#: %s\" % ext_ip))\n f.write('\\n')\n f.write(str(\"On: %s\" % formatdate))\n f.close\n f = open('/Users/admin/Documents/%s.txt' % smush,'rb')\n s.storbinary('STOR %s.txt' % smush , f)\n s.close\n f.close\n\n"
] |
[
4,
1,
0
] |
[] |
[] |
[
"file_io",
"ftp",
"ftplib",
"macos",
"python"
] |
stackoverflow_0002327989_file_io_ftp_ftplib_macos_python.txt
|
Q:
Any potential gotchas or things to be aware of for a newcomer to Django?
In other words, what did you not know when you started with Django that you wish someone had told you?
I've dabbled some in Django but nothing really serious. However, I'm hoping to change that, and I'm wondering if there's any gotchas/shortcomings/whatever that I need to be aware of as I go.
A:
Be aware of specifying absolute paths in your settings.py file. Django doesn't come with an out-of-the-box solution for making everything relative, and you have to employ Python's utilities. The usual solution is something like:
import os
def abspath(file):
return os.path.join(os.path.dirname(__file__), file).replace('\\','/')
(The last replace part is for Windows runs).
And then use it as follows:
DATABASE_NAME = abspath('mydb.db')
MEDIA_ROOT = abspath('media/')
etc.
A:
You can't process data in templates. There are a fair number of questions in SO from people trying to do "real" processing in the templates. The Django template language is -- intentionally -- not JSP or ASP or PHP. It just does presentation and retrieval of values computed in view functions.
If you can't figure out how to do it in the template, you may be trying to do too much. Use the view functions as much as possible.
A:
Use forms for all data validation. Bulk loading, batch processing, web services, everything.
At first, it seems odd to read a CSV file, populate a Form, and then have the Form validate the data and build the database object. But that's the way it's supposed to work. Use the Forms for all validation no matter what the data source.
|
Any potential gotchas or things to be aware of for a newcomer to Django?
|
In other words, what did you not know when you started with Django that you wish someone had told you?
I've dabbled some in Django but nothing really serious. However, I'm hoping to change that, and I'm wondering if there's any gotchas/shortcomings/whatever that I need to be aware of as I go.
|
[
"Be aware of specifying absolute paths in your settings.py file. Django doesn't come with an out-of-the-box solution for making everything relative, and you have to employ Python's utilities. The usual solution is something like:\nimport os\ndef abspath(file):\n return os.path.join(os.path.dirname(__file__), file).replace('\\\\','/')\n\n(The last replace part is for Windows runs).\nAnd then use it as follows:\nDATABASE_NAME = abspath('mydb.db')\nMEDIA_ROOT = abspath('media/')\n\netc.\n",
"You can't process data in templates. There are a fair number of questions in SO from people trying to do \"real\" processing in the templates. The Django template language is -- intentionally -- not JSP or ASP or PHP. It just does presentation and retrieval of values computed in view functions.\nIf you can't figure out how to do it in the template, you may be trying to do too much. Use the view functions as much as possible.\n",
"Use forms for all data validation. Bulk loading, batch processing, web services, everything. \nAt first, it seems odd to read a CSV file, populate a Form, and then have the Form validate the data and build the database object. But that's the way it's supposed to work. Use the Forms for all validation no matter what the data source.\n"
] |
[
6,
4,
4
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002328767_django_python.txt
|
Q:
MATLAB to Python Code conversion (NumPy, SciPy, MatplotLib?)
I'm trying to convert the following code to Python from MATLAB for an EEG Project (partly because Python's slightly cheaper!)
Hopefully someone can point me in the right direction: I've started to alter it but got bogged down: Particularly trying to find equivalent functions.
Tried scipy.org (NumPy_for_Matlab_Users etc.) but I'm not sure if my arguments are of the right format/number)
I was originally using pyserial
ser.read()
To read the data in and then
ord()
To convert it into an integer, but this MATLAB code goes about it another way ('uchar')
My main issues were with
fopen
fread
find
repmat
And the whole plotting section as I have even less of an idea about that in Python (MatPlotLib?)
MATLAB also tends to start with '1' whereas Python uses 0: I've tried to alter these also but have missed a few I wasn't sure of.
Is Python happy with the whole range separated by colons
...repmat(0:2:10, .....
or not?
So, here is the MATLAB:
% EEG data grabber and plotter
N = 256; % Required number of sample frames
% Read in a block of data from the OpenEEG board
hCom = serial('COM1','BaudRate',57600,'timeout',5);
fopen(hCom);
numBlocks = (ceil(17*N/256) + 1);
rawdata = zeros(numBlocks*256,1);
for n = 1:numBlocks
rawdata((0:255) + n*256) = fread(hCom, 256, 'uchar'); % Read data
end
fclose(hCom);
% Convert raw data into a Matlab matrix
% First find the first frame start
startIndex = find(rawdata == 165);
while(rawdata(startIndex(1) + 1) ~= 90)
startIndex = startIndex(2:end);
end
% Now extract the samples
frameStarts = (0:(N-1))'*17 + startIndex(1);
indices = 4 + repmat(frameStarts, 1, 6) + repmat(0:2:10, length(frameStarts), 1);
eegData = (rawdata(indices)*256 + rawdata(indices + 1)) - 512;
% eegData is now a N by 6 matrix, each column is a channel of sampled data
% Plot time-series data
figure(1)
subplot(2,1,1)
plot((0:255)/256,eegData(:,1:2))
xlabel('Time [s]');
ylabel('EEG data');
% Calculate FFT and plot spectra
subplot(2,1,2)
window = 0.5 - 0.5 * cos(2*pi*(0:255)/255); % Von-Hann Window
f = abs(fft(repmat(window',1,2) .* eegData(:,1:2)));
plot((0:127),f(1:128,:))
xlabel('Frequency [Hz]');
ylabel('EEG FFT');
And here's my poor cousin version
import scipy
import serial #Serial Module to read serial port
from numpy import ceil,zeros #Ceil module & zeros for blank matrix
N = 256 #no of sample frames (256 = 1s)
#Reads a block of data from the serial port
ser = serial.Serial('COM18',57600,timeout=5)
scipy.fopen(ser) #MATLAB CODE: fopen(ser) is this correct????
numBlocks = (ceil(17*N/256) + 1)
rawdata = scipy.zeros(numBlocks*256,1)
for n = 1:numBlocks
rawdata((0:255) + n*256) = numpyio.fread(ser,256,'i') # read each byte as unsigned integer
end
ser.close()
#convert raw data to MATLAB matrix
#find start of frame (1st Byte always 165, 2nd always 90)
startIndex = find(rawdata == 165);
while (rawdata(startIndex(0) + 1) ~=90) #confirms 165,90 sequence
startIndex = startIndex(1:end) #uses rest of frame as data
end
#Extraction of sample values
#MATLAB CODE
frameStarts = (0: (N-1))'*17 + startIndex(1); #'#how to transpose matrix('): zip()??
indices = 4 + (numpy.tile(frameStarts, 1,6)) + (numpy.tile(0:2:10,length(frameStarts), 1);
eegData = (rawdata(indices)*256 + rawdata(indices +1)) - 512 #values are unsigned integers 0-1023 and must subtract 512 for actual value
#eeg data now N*6 Matrix each column is a channel of data
#MATLAB CODE: plot time series data (MatPlotLib?)
figure(1)
subplot (2,1,1)
plot((0:255)/256,eegData(:,1:2))
xlabel('Time [s]')
ylabel('EEG Voltage')
#fft
subplot(2,1,2)
window = 0.5 - 0.5*cos(2*pi*(0:255)/255);
f = abs(fft(repmat(window',1,2) .* eegData(:,1:2))) '#repmat=tile()? matrix transposition (')?
plot((0:127),f(1:128,:))
xlabel('Freq [Hz]')
ylabel('EEG FFT')
All suggestions gratefully received!
Dave!
A:
Um... lots of things.
Python has no end keyword, so you clearly need to read more about Python's syntax.
Python arrays and slices are indexed with [] not (). Ranges are expressed as range(0,10) for example, but slices in the Matlab sense only exist in extension packages like numpy and each one has its own interface.
Yes, you want to use matplotlib for plotting, it has pretty much the same capabilities as Matlab's plotting interface, at least at this level.
It looks like you're guessing that Python will have the same method names as Matlab in some random package. This is not a good plan. Instead, look up the Matlab method in its documentation, which is online, find out exactly what it does, and then read into the Python package documentation for a method that does what you want. This may not exist, but I'm betting that in a program this simple, most of the ones you need will.
The most important thing you need to understand in converting any Matlab code to other languages is the way Matlab arrays work, which is extremely unusual (but excellent for its target applications). Numpy has about the same capabilities, but a completely different notation for them.
The serial module has already given you an open file object on the port, so you don't need the fopen.
I think you need to spend a LOT of time with the documentation for both Python and Matlab, because it's quite clear you understand neither at the moment.
Don't let me discourage you, I'm just being honest about where you're at.
A:
One small point - indexing between the two is different. If you just copy everything from MATLAB to Python, as you seem to have done, you'll be very very confused. MATLAB x(1:5:end) translates to Python x[0::5]. Go back to NumPy for MATLAB Users and scan down to the section called "Linear Algebra Equivalents" (about halfway down the page). It gives a dictionary of how to go back and forth.
A:
This may or may not work, but you might want to try a Matlab to Python converter such as mat2py. I've never tried them, but it might save some time. Also, there's this page about Matlab to Numpy conversion that might help you get acquainted with the differences between the two.
|
MATLAB to Python Code conversion (NumPy, SciPy, MatplotLib?)
|
I'm trying to convert the following code to Python from MATLAB for an EEG Project (partly because Python's slightly cheaper!)
Hopefully someone can point me in the right direction: I've started to alter it but got bogged down: Particularly trying to find equivalent functions.
Tried scipy.org (NumPy_for_Matlab_Users etc.) but I'm not sure if my arguments are of the right format/number)
I was originally using pyserial
ser.read()
To read the data in and then
ord()
To convert it into an integer, but this MATLAB code goes about it another way ('uchar')
My main issues were with
fopen
fread
find
repmat
And the whole plotting section as I have even less of an idea about that in Python (MatPlotLib?)
MATLAB also tends to start with '1' whereas Python uses 0: I've tried to alter these also but have missed a few I wasn't sure of.
Is Python happy with the whole range separated by colons
...repmat(0:2:10, .....
or not?
So, here is the MATLAB:
% EEG data grabber and plotter
N = 256; % Required number of sample frames
% Read in a block of data from the OpenEEG board
hCom = serial('COM1','BaudRate',57600,'timeout',5);
fopen(hCom);
numBlocks = (ceil(17*N/256) + 1);
rawdata = zeros(numBlocks*256,1);
for n = 1:numBlocks
rawdata((0:255) + n*256) = fread(hCom, 256, 'uchar'); % Read data
end
fclose(hCom);
% Convert raw data into a Matlab matrix
% First find the first frame start
startIndex = find(rawdata == 165);
while(rawdata(startIndex(1) + 1) ~= 90)
startIndex = startIndex(2:end);
end
% Now extract the samples
frameStarts = (0:(N-1))'*17 + startIndex(1);
indices = 4 + repmat(frameStarts, 1, 6) + repmat(0:2:10, length(frameStarts), 1);
eegData = (rawdata(indices)*256 + rawdata(indices + 1)) - 512;
% eegData is now a N by 6 matrix, each column is a channel of sampled data
% Plot time-series data
figure(1)
subplot(2,1,1)
plot((0:255)/256,eegData(:,1:2))
xlabel('Time [s]');
ylabel('EEG data');
% Calculate FFT and plot spectra
subplot(2,1,2)
window = 0.5 - 0.5 * cos(2*pi*(0:255)/255); % Von-Hann Window
f = abs(fft(repmat(window',1,2) .* eegData(:,1:2)));
plot((0:127),f(1:128,:))
xlabel('Frequency [Hz]');
ylabel('EEG FFT');
And here's my poor cousin version
import scipy
import serial #Serial Module to read serial port
from numpy import ceil,zeros #Ceil module & zeros for blank matrix
N = 256 #no of sample frames (256 = 1s)
#Reads a block of data from the serial port
ser = serial.Serial('COM18',57600,timeout=5)
scipy.fopen(ser) #MATLAB CODE: fopen(ser) is this correct????
numBlocks = (ceil(17*N/256) + 1)
rawdata = scipy.zeros(numBlocks*256,1)
for n = 1:numBlocks
rawdata((0:255) + n*256) = numpyio.fread(ser,256,'i') # read each byte as unsigned integer
end
ser.close()
#convert raw data to MATLAB matrix
#find start of frame (1st Byte always 165, 2nd always 90)
startIndex = find(rawdata == 165);
while (rawdata(startIndex(0) + 1) ~=90) #confirms 165,90 sequence
startIndex = startIndex(1:end) #uses rest of frame as data
end
#Extraction of sample values
#MATLAB CODE
frameStarts = (0: (N-1))'*17 + startIndex(1); #'#how to transpose matrix('): zip()??
indices = 4 + (numpy.tile(frameStarts, 1,6)) + (numpy.tile(0:2:10,length(frameStarts), 1);
eegData = (rawdata(indices)*256 + rawdata(indices +1)) - 512 #values are unsigned integers 0-1023 and must subtract 512 for actual value
#eeg data now N*6 Matrix each column is a channel of data
#MATLAB CODE: plot time series data (MatPlotLib?)
figure(1)
subplot (2,1,1)
plot((0:255)/256,eegData(:,1:2))
xlabel('Time [s]')
ylabel('EEG Voltage')
#fft
subplot(2,1,2)
window = 0.5 - 0.5*cos(2*pi*(0:255)/255);
f = abs(fft(repmat(window',1,2) .* eegData(:,1:2))) '#repmat=tile()? matrix transposition (')?
plot((0:127),f(1:128,:))
xlabel('Freq [Hz]')
ylabel('EEG FFT')
All suggestions gratefully received!
Dave!
|
[
"Um... lots of things.\nPython has no end keyword, so you clearly need to read more about Python's syntax.\nPython arrays and slices are indexed with [] not (). Ranges are expressed as range(0,10) for example, but slices in the Matlab sense only exist in extension packages like numpy and each one has its own interface.\nYes, you want to use matplotlib for plotting, it has pretty much the same capabilities as Matlab's plotting interface, at least at this level.\nIt looks like you're guessing that Python will have the same method names as Matlab in some random package. This is not a good plan. Instead, look up the Matlab method in its documentation, which is online, find out exactly what it does, and then read into the Python package documentation for a method that does what you want. This may not exist, but I'm betting that in a program this simple, most of the ones you need will.\nThe most important thing you need to understand in converting any Matlab code to other languages is the way Matlab arrays work, which is extremely unusual (but excellent for its target applications). Numpy has about the same capabilities, but a completely different notation for them.\nThe serial module has already given you an open file object on the port, so you don't need the fopen.\nI think you need to spend a LOT of time with the documentation for both Python and Matlab, because it's quite clear you understand neither at the moment.\nDon't let me discourage you, I'm just being honest about where you're at.\n",
"One small point - indexing between the two is different. If you just copy everything from MATLAB to Python, as you seem to have done, you'll be very very confused. MATLAB x(1:5:end) translates to Python x[0::5]. Go back to NumPy for MATLAB Users and scan down to the section called \"Linear Algebra Equivalents\" (about halfway down the page). It gives a dictionary of how to go back and forth.\n",
"This may or may not work, but you might want to try a Matlab to Python converter such as mat2py. I've never tried them, but it might save some time. Also, there's this page about Matlab to Numpy conversion that might help you get acquainted with the differences between the two.\n"
] |
[
11,
5,
2
] |
[] |
[] |
[
"matlab",
"matplotlib",
"numpy",
"python",
"scipy"
] |
stackoverflow_0002326786_matlab_matplotlib_numpy_python_scipy.txt
|
Q:
Change the type of a global variable in a function initializing it
I have a __main__ function where I initialize a lot of variables that are to be used in my program, later on. I have a problem where a variable that I temporarely declare as None in the outer scope, is assigned an object of SomeClass, but due to scoping rules I cannot access it's content in the outer scope. Because the constructor of SomeClass demands an argument to be passed, I cannot simply declare myObject to be foo.bar.SomeClass to begin with. So what must I do in order to get access to the attributes in foo.bar.SomeClass?
Codewise it looks like this:
myObject = None
def setUp():
... lots of initialization ...
myObject = foo.bar.SomeClass(init_variable)
if __name__ == "__main__":
setUp()
myObject.member1 #throws AttributeError: 'NoneType' object has no attribute member1
A:
Assuming that setup() is meant to be initialize(), the problem is that the variable myObject in initialize() is a local variable that hides the global myObject, and when initialize() returns, the local name will go out of scope.
To update the global myObject variable, you need to change initialize() as follows:
def initialize():
global myObject
... lots of initialization ...
myObject = foo.bar.SomeClass(init_variable)
Adding the global statement means that the global myObject gets updated, rather than a local one.
A:
You don't have to do it that - using globals is considered bad practice for most uses. You can always return the data you want:
def initialize():
... lots of initialization ...
return foo.bar.SomeClass(init_variable)
if __name__ == "__main__":
myObject = initialize()
myObject.member1 # works
EDIT:
If you need to initialize multiple values, or if you see yourself using too much globals to share state between many toplevel functions, then it is time to use a class.
class MyProgram(object):
def __init__(self):
# ... lots of initialization ...
self.myObject = foo.bar.SomeClass(init_variable)
def usage(self):
self.myObject.member1
if __name__ == "__main__":
m = MyProgram()
m.usage()
A:
If your SomeClass requires an argument from the execution of the script, it would probably be easiest to just pass in whatever information you need to construct an instance of it as an argument. It might look something like:
def initialize(args):
... lots of initialization ...
myObject = foo.bar.SomeClass(args[0])
if __name__ == "__main__":
initialize(sys.argv)
Another way to do it would be to simply make the myObject instance global using the global keyword before calling initialize().
|
Change the type of a global variable in a function initializing it
|
I have a __main__ function where I initialize a lot of variables that are to be used in my program, later on. I have a problem where a variable that I temporarely declare as None in the outer scope, is assigned an object of SomeClass, but due to scoping rules I cannot access it's content in the outer scope. Because the constructor of SomeClass demands an argument to be passed, I cannot simply declare myObject to be foo.bar.SomeClass to begin with. So what must I do in order to get access to the attributes in foo.bar.SomeClass?
Codewise it looks like this:
myObject = None
def setUp():
... lots of initialization ...
myObject = foo.bar.SomeClass(init_variable)
if __name__ == "__main__":
setUp()
myObject.member1 #throws AttributeError: 'NoneType' object has no attribute member1
|
[
"Assuming that setup() is meant to be initialize(), the problem is that the variable myObject in initialize() is a local variable that hides the global myObject, and when initialize() returns, the local name will go out of scope.\nTo update the global myObject variable, you need to change initialize() as follows:\ndef initialize():\n global myObject\n ... lots of initialization ...\n myObject = foo.bar.SomeClass(init_variable)\n\nAdding the global statement means that the global myObject gets updated, rather than a local one.\n",
"You don't have to do it that - using globals is considered bad practice for most uses. You can always return the data you want:\ndef initialize():\n ... lots of initialization ...\n return foo.bar.SomeClass(init_variable)\n\nif __name__ == \"__main__\":\n myObject = initialize()\n myObject.member1 # works\n\n\nEDIT:\nIf you need to initialize multiple values, or if you see yourself using too much globals to share state between many toplevel functions, then it is time to use a class.\nclass MyProgram(object):\n def __init__(self):\n # ... lots of initialization ...\n self.myObject = foo.bar.SomeClass(init_variable)\n\n def usage(self):\n self.myObject.member1\n\nif __name__ == \"__main__\":\n m = MyProgram()\n m.usage()\n\n",
"If your SomeClass requires an argument from the execution of the script, it would probably be easiest to just pass in whatever information you need to construct an instance of it as an argument. It might look something like:\ndef initialize(args):\n ... lots of initialization ...\n myObject = foo.bar.SomeClass(args[0])\n\nif __name__ == \"__main__\":\n initialize(sys.argv)\n\nAnother way to do it would be to simply make the myObject instance global using the global keyword before calling initialize().\n"
] |
[
2,
2,
0
] |
[] |
[] |
[
"class",
"global_variables",
"python",
"scope"
] |
stackoverflow_0002328464_class_global_variables_python_scope.txt
|
Q:
Django - Template not complete rendered
I have a website on a django framework, and in a set of pages I use the Paginator. With paginator, my last page sometimes does not render completely.
You can see the problem here.
Code:
view rank - http://code.google.com/p/myps3t/source/browse/views.py
template - http://code.google.com/p/myps3t/source/browse/www/Rank.html
Just refresh a couple of times and look at the end of the table.
Sometimes it appears, sometimes not.
Can I see the template render output to understand how the page sometimes is full rendered, sometimes not?
A:
You asked if you can see the template render output. You can.
django.shortcuts.render_to_response is a very short function:
httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}
return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
You can make your own render_to_response function that shows the intermediate value. Use something like:
from django.template import loader
def my_render_to_response(*args, **kwargs):
httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}
x = loader.render_to_string(*args, **kwargs)
print "RENDERED AS",x
return HttpResponse(x , **httpresponse_kwargs)
If you use the django development web server, the print statement will come out on standard out. If you are using some other web server, you may need to write the value of x to a file.
In this way, you can see whether your entire template is rendered as you expect.
|
Django - Template not complete rendered
|
I have a website on a django framework, and in a set of pages I use the Paginator. With paginator, my last page sometimes does not render completely.
You can see the problem here.
Code:
view rank - http://code.google.com/p/myps3t/source/browse/views.py
template - http://code.google.com/p/myps3t/source/browse/www/Rank.html
Just refresh a couple of times and look at the end of the table.
Sometimes it appears, sometimes not.
Can I see the template render output to understand how the page sometimes is full rendered, sometimes not?
|
[
"You asked if you can see the template render output. You can.\ndjango.shortcuts.render_to_response is a very short function:\nhttpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}\nreturn HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)\n\nYou can make your own render_to_response function that shows the intermediate value. Use something like:\nfrom django.template import loader\ndef my_render_to_response(*args, **kwargs):\n httpresponse_kwargs = {'mimetype': kwargs.pop('mimetype', None)}\n x = loader.render_to_string(*args, **kwargs)\n print \"RENDERED AS\",x\n return HttpResponse(x , **httpresponse_kwargs)\nIf you use the django development web server, the print statement will come out on standard out. If you are using some other web server, you may need to write the value of x to a file.\nIn this way, you can see whether your entire template is rendered as you expect.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002318169_django_python.txt
|
Q:
Avoiding unnecessary slice copying in Python
Is there a common idiom for avoiding pointless slice copying for cases like this:
>>> a = bytearray(b'hello')
>>> b = bytearray(b'goodbye, cruel world.')
>>> a.extend(b[14:20])
>>> a
bytearray(b'hello world')
It seems to me that there is an unnecessary copy happening when the b[14:20] slice is created. Rather than create a new slice in memory to give to extend I want to say "use only this range of the current object".
Some methods will help you out with slice parameters, for example count:
>>> a = bytearray(1000000) # a million zero bytes
>>> a[0:900000].count(b'\x00') # expensive temporary slice
900000
>>> a.count(b'\x00', 0, 900000) # helpful start and end parameters
900000
but many, like extend in my first example, don't have this feature.
I realise that for many applications what I'm talking about would be a micro-optimisation, so before anyone asks - yes, I have profiled my application, and it is something worth worrying about for my case.
I have one 'solution' below, but any better ideas are most welcome.
A:
Creating a buffer object avoids copying the slice, but for short slices it's more efficient to just make the copy:
>>> a.extend(buffer(b, 14, 6))
>>> a
bytearray(b'hello world')
Here there's only one copy made of the memory, but the cost of creating the buffer object more than obliterates the saving. It should be better for larger slices though. I'm not sure how large the slice would have to be for this method to be more efficient overall.
Note that for Python 3 (and optionally in Python 2.7) you'd need a memoryview object instead:
>>> a.extend(memoryview(b)[14:20])
A:
itertools has islice. islice doesn't have a count method so it is useful in other cases where you wish to avoid copying the slice. As you pointed out - count has a mechanism for that anyway
>>> from itertools import islice
>>> a = bytearray(1000000)
>>> sum(1 for x in islice(a,0,900000) if x==0)
900000
>>> len(filter(b'\x00'.__eq__,islice(a,0,900000)))
900000
>>> a=bytearray(b"hello")
>>> b = bytearray(b'goodbye, cruel world.')
>>> a.extend(islice(b,14,20))
>>> a
bytearray(b'hello world')
|
Avoiding unnecessary slice copying in Python
|
Is there a common idiom for avoiding pointless slice copying for cases like this:
>>> a = bytearray(b'hello')
>>> b = bytearray(b'goodbye, cruel world.')
>>> a.extend(b[14:20])
>>> a
bytearray(b'hello world')
It seems to me that there is an unnecessary copy happening when the b[14:20] slice is created. Rather than create a new slice in memory to give to extend I want to say "use only this range of the current object".
Some methods will help you out with slice parameters, for example count:
>>> a = bytearray(1000000) # a million zero bytes
>>> a[0:900000].count(b'\x00') # expensive temporary slice
900000
>>> a.count(b'\x00', 0, 900000) # helpful start and end parameters
900000
but many, like extend in my first example, don't have this feature.
I realise that for many applications what I'm talking about would be a micro-optimisation, so before anyone asks - yes, I have profiled my application, and it is something worth worrying about for my case.
I have one 'solution' below, but any better ideas are most welcome.
|
[
"Creating a buffer object avoids copying the slice, but for short slices it's more efficient to just make the copy:\n>>> a.extend(buffer(b, 14, 6))\n>>> a\nbytearray(b'hello world')\n\nHere there's only one copy made of the memory, but the cost of creating the buffer object more than obliterates the saving. It should be better for larger slices though. I'm not sure how large the slice would have to be for this method to be more efficient overall.\nNote that for Python 3 (and optionally in Python 2.7) you'd need a memoryview object instead:\n>>> a.extend(memoryview(b)[14:20])\n\n",
"itertools has islice. islice doesn't have a count method so it is useful in other cases where you wish to avoid copying the slice. As you pointed out - count has a mechanism for that anyway\n>>> from itertools import islice\n>>> a = bytearray(1000000)\n>>> sum(1 for x in islice(a,0,900000) if x==0)\n900000\n>>> len(filter(b'\\x00'.__eq__,islice(a,0,900000)))\n900000\n\n>>> a=bytearray(b\"hello\")\n>>> b = bytearray(b'goodbye, cruel world.')\n>>> a.extend(islice(b,14,20))\n>>> a\nbytearray(b'hello world')\n\n"
] |
[
5,
2
] |
[] |
[] |
[
"idioms",
"optimization",
"python"
] |
stackoverflow_0002328171_idioms_optimization_python.txt
|
Q:
Referenced Model Loading in Google App Engine
In Python, say I've got a model of class A that has a ReferenceProperty b to model class B, which has a ReferenceProperty c to model class C.
Assuming an instance of A already exists in the datastore, I can get it by saying:
q = A.all()
a = q.get()
In this scenario, how does entity loading work? Is a.b retrieved when a is retrieved? Is a.b.c retrieved when a.b is retrieved? Are b and c retrieved only when they are first accessed? If I were to store a in memcache, would b and c also be stored? If not, when would they be retrieved when I get a back out of memcache?
The reason I'm asking these questions (besides curiosity) is because I have an entity which I'd like to store in memcache, but it links to another entity (which links to another entity, etc.), and the total size of the linked entities may be more than 1MB.
Thanks!
A:
The models will be dereferenced when you first access them. So calling a.b will get b, and calling a.b.c will get c.
Have a look at Nick Johnson's blog for some tips about memcahing models:
http://blog.notdot.net/2009/9/Efficient-model-memcaching
A:
ReferenceProperties are lazily-loaded. b will not be looked up from the datastore until you actually use it for something.
|
Referenced Model Loading in Google App Engine
|
In Python, say I've got a model of class A that has a ReferenceProperty b to model class B, which has a ReferenceProperty c to model class C.
Assuming an instance of A already exists in the datastore, I can get it by saying:
q = A.all()
a = q.get()
In this scenario, how does entity loading work? Is a.b retrieved when a is retrieved? Is a.b.c retrieved when a.b is retrieved? Are b and c retrieved only when they are first accessed? If I were to store a in memcache, would b and c also be stored? If not, when would they be retrieved when I get a back out of memcache?
The reason I'm asking these questions (besides curiosity) is because I have an entity which I'd like to store in memcache, but it links to another entity (which links to another entity, etc.), and the total size of the linked entities may be more than 1MB.
Thanks!
|
[
"The models will be dereferenced when you first access them. So calling a.b will get b, and calling a.b.c will get c.\nHave a look at Nick Johnson's blog for some tips about memcahing models:\nhttp://blog.notdot.net/2009/9/Efficient-model-memcaching\n",
"ReferenceProperties are lazily-loaded. b will not be looked up from the datastore until you actually use it for something.\n"
] |
[
2,
1
] |
[] |
[] |
[
"google_app_engine",
"loading",
"memcached",
"model",
"python"
] |
stackoverflow_0002329387_google_app_engine_loading_memcached_model_python.txt
|
Q:
how do you specify which python executable to use in Django 1.1.1?
I have a RH system running RHEL 5.3, which comes with python2.4 that can't be removed for numerous reasons.
I have been able to build 64-bit RPMS for python 2.6 as an altinstall. It's called with "python26".
How can I tell Django to use this command to get to the proper python version, instead of the default "python".
I can, of course, change the symlink in /usr/bin manually, but i'm looking to fully automate the buildout of these systems, and I'm almost certain this is possible.
Thanks.
A:
Look at virtualenv, you can setup your own environment for django (well, anything) with different lib versions, symlinks etc.
A:
That depends on the deploying method you use. E.g., if you use the django-recommended mod_wsgi deployment, then you must compile it with the correct python version.
|
how do you specify which python executable to use in Django 1.1.1?
|
I have a RH system running RHEL 5.3, which comes with python2.4 that can't be removed for numerous reasons.
I have been able to build 64-bit RPMS for python 2.6 as an altinstall. It's called with "python26".
How can I tell Django to use this command to get to the proper python version, instead of the default "python".
I can, of course, change the symlink in /usr/bin manually, but i'm looking to fully automate the buildout of these systems, and I'm almost certain this is possible.
Thanks.
|
[
"Look at virtualenv, you can setup your own environment for django (well, anything) with different lib versions, symlinks etc.\n",
"That depends on the deploying method you use. E.g., if you use the django-recommended mod_wsgi deployment, then you must compile it with the correct python version.\n"
] |
[
2,
2
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002329541_django_python.txt
|
Q:
Python:Extend the 'dict' class
I have to solve this exercise:
Python's dictionaries do not preserve the order of inserted data nor store the data sorted by the key. Write an extension for the dict class whose instances will keep the data sorted by their key value. Note that the order must be preserved also when new elements are added.
How do I extend dict? Do I need to have access to the source code for the dict type?
A:
You can either subclass dict or UserDict, since van already talked about UserDict, lets look at dict.
Type help(dict) into an interpreter and you see a big list of methods. You will need to override all the methods that modify the dict as well as the methods that iterate over the dict.
Methods that modify the dict include __delitem__,__setitem__,clear etc.
Methods that iterate the dict include __iter__,keys,values,items etc.
This should get you started
>>> class odict(dict):
... def __init__(self, *args, **kw):
... super(odict,self).__init__(*args, **kw)
... self.itemlist = super(odict,self).keys()
... def __setitem__(self, key, value):
... # TODO: what should happen to the order if
... # the key is already in the dict
... self.itemlist.append(key)
... super(odict,self).__setitem__(key, value)
... def __iter__(self):
... return iter(self.itemlist)
... def keys(self):
... return self.itemlist
... def values(self):
... return [self[key] for key in self]
... def itervalues(self):
... return (self[key] for key in self)
...
>>> od = odict(a=1,b=2)
>>> print od
{'a': 1, 'b': 2}
>>> od['d']=4
>>> od['c']=3
>>> print od # look at the `__str__` and `__repr__` methods
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>> print od.keys()
['a', 'b', 'd', 'c']
>>> print od.values()
[1, 2, 4, 3]
A:
The implementation of dict will not help you with the task. What you want is a class that has the same interface as dict, but a different implementation. That will require to implement methods like __getitem__, __setitem__, etc. If you Google for "ordereddict", you will find a lot of examples.
A:
If you use python 2.7+, then see collections.OrderedDict.
Otherwise, backport (copy the source) or see Recipe 576693: Ordered Dictionary for Py2.4 (Python) .
But if you really need to extend the dict, then start with UserDict, source for which you can find in /lib/UserDict.py of your python distribution (Lib/collections/__init__.py with Python 3).
A:
Good news: the problem is not difficult at all.
In order to poke around and see the entrails of a class you can use
>>> dir(dict)
['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
and help(dict), which has a very complete interactive documentation, but of course you also have access to the even more complete online documentation.
Once you have a grasp of what dict does behind the scenes, you should learn about inheritance in Python.
If you get stuck visit this site to get some ideas, but don't copy/paste, your teacher will not see it kindly.
|
Python:Extend the 'dict' class
|
I have to solve this exercise:
Python's dictionaries do not preserve the order of inserted data nor store the data sorted by the key. Write an extension for the dict class whose instances will keep the data sorted by their key value. Note that the order must be preserved also when new elements are added.
How do I extend dict? Do I need to have access to the source code for the dict type?
|
[
"You can either subclass dict or UserDict, since van already talked about UserDict, lets look at dict.\nType help(dict) into an interpreter and you see a big list of methods. You will need to override all the methods that modify the dict as well as the methods that iterate over the dict.\nMethods that modify the dict include __delitem__,__setitem__,clear etc.\nMethods that iterate the dict include __iter__,keys,values,items etc.\nThis should get you started\n>>> class odict(dict):\n... def __init__(self, *args, **kw):\n... super(odict,self).__init__(*args, **kw)\n... self.itemlist = super(odict,self).keys()\n... def __setitem__(self, key, value):\n... # TODO: what should happen to the order if\n... # the key is already in the dict \n... self.itemlist.append(key)\n... super(odict,self).__setitem__(key, value)\n... def __iter__(self):\n... return iter(self.itemlist)\n... def keys(self):\n... return self.itemlist\n... def values(self):\n... return [self[key] for key in self] \n... def itervalues(self):\n... return (self[key] for key in self)\n... \n>>> od = odict(a=1,b=2)\n>>> print od\n{'a': 1, 'b': 2}\n>>> od['d']=4\n>>> od['c']=3\n>>> print od # look at the `__str__` and `__repr__` methods \n{'a': 1, 'c': 3, 'b': 2, 'd': 4}\n>>> print od.keys()\n['a', 'b', 'd', 'c']\n>>> print od.values()\n[1, 2, 4, 3]\n\n",
"The implementation of dict will not help you with the task. What you want is a class that has the same interface as dict, but a different implementation. That will require to implement methods like __getitem__, __setitem__, etc. If you Google for \"ordereddict\", you will find a lot of examples.\n",
"If you use python 2.7+, then see collections.OrderedDict.\nOtherwise, backport (copy the source) or see Recipe 576693: Ordered Dictionary for Py2.4 (Python) . \nBut if you really need to extend the dict, then start with UserDict, source for which you can find in /lib/UserDict.py of your python distribution (Lib/collections/__init__.py with Python 3).\n",
"Good news: the problem is not difficult at all.\nIn order to poke around and see the entrails of a class you can use \n>>> dir(dict)\n['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']\n\nand help(dict), which has a very complete interactive documentation, but of course you also have access to the even more complete online documentation.\nOnce you have a grasp of what dict does behind the scenes, you should learn about inheritance in Python.\nIf you get stuck visit this site to get some ideas, but don't copy/paste, your teacher will not see it kindly.\n"
] |
[
40,
11,
6,
5
] |
[] |
[] |
[
"dictionary",
"extend",
"python"
] |
stackoverflow_0002328235_dictionary_extend_python.txt
|
Q:
Dealing with BACKSLASH character in non-string literals in Python
I have the following string read from an XML elememnt, and it is assigned to a variable called filename. I don't know how to make this any clearer as saying filename = the following string, without leading someone to think that I have a string literal then.
\\server\data\uploads\0224.1307.Varallo.mov
when I try and pass this to
os.path.basename(filename)
I get the following
\\server\\data\\uploads\x124.1307.Varallo.mov
I tried filename.replace('\\','\\\\') but that doesn't work either. os.path.basename(filename) then returns the following.
\\\\server\\data\\uploads\\0224.1307.Varallo.mov
Notice that the \0 is now not being converted to \x but now it doesn't process the string at all.
what can I do to my filename variable to get this String in a proper state so that os.path.basename() will actually give me back the basename. I am on OSX so the uncpath stuff is not available.
All attempts to replace the \ with \\ manually fail because of the \0 getting converted to \x in the beginning of the basename.
NOTE: this is NOT a string literal so r'' doesn't work.
A:
We need more information. What exactly is in the variable filename? To answer, use print repr(filename) and add the results to your question above.
Wild guess
DISCLAIMER: This is a guess - try:
import ntpath
print ntpath.basename(filename)
A:
All the downvoting in the world won't change the fact that you're doing it wrong. os.path is for native paths. \\foo\bar\baz is not a OS X path, it's a Windows UNC. posixpath is not equipped to handle UNCs; ntpath is.
|
Dealing with BACKSLASH character in non-string literals in Python
|
I have the following string read from an XML elememnt, and it is assigned to a variable called filename. I don't know how to make this any clearer as saying filename = the following string, without leading someone to think that I have a string literal then.
\\server\data\uploads\0224.1307.Varallo.mov
when I try and pass this to
os.path.basename(filename)
I get the following
\\server\\data\\uploads\x124.1307.Varallo.mov
I tried filename.replace('\\','\\\\') but that doesn't work either. os.path.basename(filename) then returns the following.
\\\\server\\data\\uploads\\0224.1307.Varallo.mov
Notice that the \0 is now not being converted to \x but now it doesn't process the string at all.
what can I do to my filename variable to get this String in a proper state so that os.path.basename() will actually give me back the basename. I am on OSX so the uncpath stuff is not available.
All attempts to replace the \ with \\ manually fail because of the \0 getting converted to \x in the beginning of the basename.
NOTE: this is NOT a string literal so r'' doesn't work.
|
[
"We need more information. What exactly is in the variable filename? To answer, use print repr(filename) and add the results to your question above.\n\nWild guess\nDISCLAIMER: This is a guess - try:\nimport ntpath\nprint ntpath.basename(filename)\n\n",
"All the downvoting in the world won't change the fact that you're doing it wrong. os.path is for native paths. \\\\foo\\bar\\baz is not a OS X path, it's a Windows UNC. posixpath is not equipped to handle UNCs; ntpath is.\n"
] |
[
2,
1
] |
[] |
[] |
[
"encoding",
"escaping",
"python",
"string"
] |
stackoverflow_0002329719_encoding_escaping_python_string.txt
|
Q:
First Order Logic Engine
I'd like to create an application that can do simple reasoning using first order logic. Can anyone recommend an "engine" that can accept an arbitrary number of FOL expressions, and allow querying of those expressions (preferably accessible via Python)?
A:
Don't query using first-order logic (FOL) unless you absolutely have to: first-order logic is not decidable, but only semi-decidable, and so queries will often, unavoidably not terminate.
Description logic is essentially a decidable fragment of first-order logic, reformulated in a manner that is good for talking about classes of entity and their interrelationships. There are many engines for description logic in Python, for example seth, based on OWL-DL.
If you are really sure that you need the vastness of FOL, then FLiP is worth a look. I've not used it (not really keen on Python, to be honest), but this is a good approach to making logic checking available to a programming language.
A:
PyLog:
PyLog is a first order logic library
including a PROLOG engine in Python.
A:
Recipe 303057: Pythologic -- Prolog syntax in Python / http://code.activestate.com/recipes/303057/
|
First Order Logic Engine
|
I'd like to create an application that can do simple reasoning using first order logic. Can anyone recommend an "engine" that can accept an arbitrary number of FOL expressions, and allow querying of those expressions (preferably accessible via Python)?
|
[
"Don't query using first-order logic (FOL) unless you absolutely have to: first-order logic is not decidable, but only semi-decidable, and so queries will often, unavoidably not terminate.\nDescription logic is essentially a decidable fragment of first-order logic, reformulated in a manner that is good for talking about classes of entity and their interrelationships. There are many engines for description logic in Python, for example seth, based on OWL-DL.\nIf you are really sure that you need the vastness of FOL, then FLiP is worth a look. I've not used it (not really keen on Python, to be honest), but this is a good approach to making logic checking available to a programming language.\n",
"PyLog:\n\nPyLog is a first order logic library\n including a PROLOG engine in Python.\n\n",
"Recipe 303057: Pythologic -- Prolog syntax in Python / http://code.activestate.com/recipes/303057/\n"
] |
[
12,
9,
1
] |
[] |
[] |
[
"logic",
"machine_learning",
"python",
"reasoning"
] |
stackoverflow_0002304726_logic_machine_learning_python_reasoning.txt
|
Q:
How to set the program title in python
I have been building a large python program for a while, and would like to know how I would go about setting the title of the program? On a mac the title of program, which has focus, is shown in the top left corner of the screen, next the apple menu. Currently this only shows the word "Python", but I would of course like to my program's title there instead.
A:
It depends on what type of application you have. If it's a graphical application, most graphical toolkits allow you to change the title of a window (tk, which comes with python, allows you to do this by calling the title() method of your window object, as does gtk, for which you can use the set_title() method on a Gtk.Window object)
If you're talking about changing the title of the terminal window (for mac or Linux), the you have this option (from here):
import sys
sys.stdout.write("\x1b]2;Another Title\x07")
For Windows, there's a different method:
import os
os.system("title Yet Another Title")
A:
Since your program is interpreted by Python, then what actually is run is Python itself - the interpreter program. You would have to have your Python script merged with Python into a single executable and that would be able to have a separate name. For windows there is py2exe, that does that, but I have no idea if there is a similar tool for Mac OS (and if there is any need for that, there is some BSD under the hood right?).
|
How to set the program title in python
|
I have been building a large python program for a while, and would like to know how I would go about setting the title of the program? On a mac the title of program, which has focus, is shown in the top left corner of the screen, next the apple menu. Currently this only shows the word "Python", but I would of course like to my program's title there instead.
|
[
"It depends on what type of application you have. If it's a graphical application, most graphical toolkits allow you to change the title of a window (tk, which comes with python, allows you to do this by calling the title() method of your window object, as does gtk, for which you can use the set_title() method on a Gtk.Window object)\nIf you're talking about changing the title of the terminal window (for mac or Linux), the you have this option (from here):\nimport sys\nsys.stdout.write(\"\\x1b]2;Another Title\\x07\")\n\nFor Windows, there's a different method:\nimport os\nos.system(\"title Yet Another Title\")\n\n",
"Since your program is interpreted by Python, then what actually is run is Python itself - the interpreter program. You would have to have your Python script merged with Python into a single executable and that would be able to have a separate name. For windows there is py2exe, that does that, but I have no idea if there is a similar tool for Mac OS (and if there is any need for that, there is some BSD under the hood right?).\n"
] |
[
15,
3
] |
[] |
[] |
[
"macos",
"menubar",
"python",
"title"
] |
stackoverflow_0002330393_macos_menubar_python_title.txt
|
Q:
How to convert ctypes' c_long to Python's int?
int(c_long(1)) doesn't work.
A:
>>> ctypes.c_long(1).value
1
A:
Use the 'value' attribute of c_long object.
c_long(1).value
or
i = c_long(1)
print i.value
A:
>>> type(ctypes.c_long(1).value)
<type 'int'>
|
How to convert ctypes' c_long to Python's int?
|
int(c_long(1)) doesn't work.
|
[
">>> ctypes.c_long(1).value\n1\n\n",
"Use the 'value' attribute of c_long object.\n\n\n c_long(1).value\n\n\nor\n\n\n i = c_long(1)\n print i.value\n\n\n",
">>> type(ctypes.c_long(1).value)\n<type 'int'>\n\n"
] |
[
52,
11,
9
] |
[] |
[] |
[
"ctypes",
"python"
] |
stackoverflow_0002330587_ctypes_python.txt
|
Q:
"HTTP Error 409: Conflict" when using urllib.request.urlopen()
Under Python 3.1, when trying to run this code:
from urllib import request
def test():
request.urlopen("http://www.google.com")
test()
I get an HTTP 409 error. The stack trace is:
Traceback (most recent call last):
File "C:\Users\Beau\Python\pokescrape.py", line 6, in <module>
test()
File "C:\Users\Beau\Python\pokescrape.py", line 4, in test
request.urlopen("http://www.google.com")
File "C:\Program Files\Python\lib\urllib\request.py", line 119, in urlopen
return _opener.open(url, data, timeout)
File "C:\Program Files\Python\lib\urllib\request.py", line 353, in open
response = meth(req, response)
File "C:\Program Files\Python\lib\urllib\request.py", line 465, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Program Files\Python\lib\urllib\request.py", line 385, in error
result = self._call_chain(*args)
File "C:\Program Files\Python\lib\urllib\request.py", line 325, in _call_chain
result = func(*args)
File "C:\Program Files\Python\lib\urllib\request.py", line 560, in http_error_302
return self.parent.open(new, timeout=req.timeout)
File "C:\Program Files\Python\lib\urllib\request.py", line 353, in open
response = meth(req, response)
File "C:\Program Files\Python\lib\urllib\request.py", line 465, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Program Files\Python\lib\urllib\request.py", line 391, in error
return self._call_chain(*args)
File "C:\Program Files\Python\lib\urllib\request.py", line 325, in _call_chain
result = func(*args)
File "C:\Program Files\Python\lib\urllib\request.py", line 473, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
And the actual error, as printed, is:
urllib.error.HTTPError: HTTP Error 409: Conflict
I'm behind a proxy set via a configuration script; I've had no issues regarding internet connection.
Why on earth am I getting an HTTP 409 error?
A:
I was running into this problem too (also from Lancaster, as it happens) and found that if I set the environment variable http_proxy, Python would use it. In this case (on Windows) it would be:
set http_proxy=http://wwwcache.lancs.ac.uk:8080
and on *nix:
export http_proxy=http://wwwcache.lancs.ac.uk:8080/
Edit: Thanks Beau Martínez for the *nix fix.
A:
The HTTP error you're seeing is one the remote end (or the proxy) is giving you. HTTP Error 409 is indeed 'Conflict', which usually means there were conflicting requests being made. If you are indeed using a proxy I would suspect that being the source of the 409, but more debugging would be in order. Either use a tool like wireshark to analyze the actual traffic, or use http.client.HTTPConnection directly and turn on its debugging.
A:
It turns out I had to manually set the proxy in-code. I'm assuming this was because I was using an automated proxy script.
For anybody with a similar issue, here's the code I used:
from urllib import request
import random
PROXY_URL = "http://wwwcache-{}.lancs.ac.uk:8080/"
def setLancsProxy():
httpProxy = PROXY_URL.format(random.randrange(4))
proxy = request.ProxyHandler({"http" : httpProxy})
opener = request.build_opener(proxy)
request.install_opener(opener)
I found http://groups.google.com/group/comp.lang.python/browse_thread/thread/a9db4a2f398ee3a4 and http://www.wkoorts.com/wkblog/2008/10/27/python-proxy-client-connections-requiring-authentication-using-urllib2-proxyhandler/ most helpful in dealing with the obscure issue.
|
"HTTP Error 409: Conflict" when using urllib.request.urlopen()
|
Under Python 3.1, when trying to run this code:
from urllib import request
def test():
request.urlopen("http://www.google.com")
test()
I get an HTTP 409 error. The stack trace is:
Traceback (most recent call last):
File "C:\Users\Beau\Python\pokescrape.py", line 6, in <module>
test()
File "C:\Users\Beau\Python\pokescrape.py", line 4, in test
request.urlopen("http://www.google.com")
File "C:\Program Files\Python\lib\urllib\request.py", line 119, in urlopen
return _opener.open(url, data, timeout)
File "C:\Program Files\Python\lib\urllib\request.py", line 353, in open
response = meth(req, response)
File "C:\Program Files\Python\lib\urllib\request.py", line 465, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Program Files\Python\lib\urllib\request.py", line 385, in error
result = self._call_chain(*args)
File "C:\Program Files\Python\lib\urllib\request.py", line 325, in _call_chain
result = func(*args)
File "C:\Program Files\Python\lib\urllib\request.py", line 560, in http_error_302
return self.parent.open(new, timeout=req.timeout)
File "C:\Program Files\Python\lib\urllib\request.py", line 353, in open
response = meth(req, response)
File "C:\Program Files\Python\lib\urllib\request.py", line 465, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Program Files\Python\lib\urllib\request.py", line 391, in error
return self._call_chain(*args)
File "C:\Program Files\Python\lib\urllib\request.py", line 325, in _call_chain
result = func(*args)
File "C:\Program Files\Python\lib\urllib\request.py", line 473, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
And the actual error, as printed, is:
urllib.error.HTTPError: HTTP Error 409: Conflict
I'm behind a proxy set via a configuration script; I've had no issues regarding internet connection.
Why on earth am I getting an HTTP 409 error?
|
[
"I was running into this problem too (also from Lancaster, as it happens) and found that if I set the environment variable http_proxy, Python would use it. In this case (on Windows) it would be:\nset http_proxy=http://wwwcache.lancs.ac.uk:8080\n\nand on *nix:\nexport http_proxy=http://wwwcache.lancs.ac.uk:8080/\n\nEdit: Thanks Beau Martínez for the *nix fix.\n",
"The HTTP error you're seeing is one the remote end (or the proxy) is giving you. HTTP Error 409 is indeed 'Conflict', which usually means there were conflicting requests being made. If you are indeed using a proxy I would suspect that being the source of the 409, but more debugging would be in order. Either use a tool like wireshark to analyze the actual traffic, or use http.client.HTTPConnection directly and turn on its debugging.\n",
"It turns out I had to manually set the proxy in-code. I'm assuming this was because I was using an automated proxy script.\nFor anybody with a similar issue, here's the code I used:\nfrom urllib import request\nimport random\n\nPROXY_URL = \"http://wwwcache-{}.lancs.ac.uk:8080/\"\n\ndef setLancsProxy():\n httpProxy = PROXY_URL.format(random.randrange(4))\n proxy = request.ProxyHandler({\"http\" : httpProxy})\n opener = request.build_opener(proxy)\n request.install_opener(opener)\n\nI found http://groups.google.com/group/comp.lang.python/browse_thread/thread/a9db4a2f398ee3a4 and http://www.wkoorts.com/wkblog/2008/10/27/python-proxy-client-connections-requiring-authentication-using-urllib2-proxyhandler/ most helpful in dealing with the obscure issue.\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"http",
"proxy",
"python",
"python_3.x"
] |
stackoverflow_0002247418_http_proxy_python_python_3.x.txt
|
Q:
Problem compiling mod_wsgi on Solaris 10 with Cool Stack 1.3.1
I try to compile mod_wsgi with Cool Stack 1.3.1 on the Solaris platform:
export PATH=/usr/sbin:/usr/bin:/usr/local/bin:/usr/sfw/bin:/usr/ccs/bin
FLAGS="-I/opt/coolstack/include" LIBS="-lintl -lgettextlib" \
LD_LIBRARY_PATH=/opt/coolstack/lib LDFLAGS="-L/opt/coolstack/lib -R/opt/coolstack/lib" \
./configure --prefix=/usr/local/mod_wsgi \
--with-apxs=/opt/coolstack/apache2/bin/apxs \
--with-python=/opt/csw/bin/python
I get this error message:
# make
/opt/coolstack/apache2/bin/apxs -c -I/usr/local/include/python2.6 -DNDEBUG mod_wsgi.c -L/opt/coolstack/lib -R/opt/coolstack/lib -L/usr/local/lib -L/usr/local/lib/python2.6/config -lpython2.6 -lsocket -lnsl -lrt -ldl -lm
/opt/coolstack/apache2/build/libtool --silent --mode=compile cc -prefer-pic -DSSL_EXPERIMENTAL -DSSL_ENGINE -xO4 -xtarget=generic -DSOLARIS2=10 -D_POSIX_PTHREAD_SEMANTICS -D_REENTRANT -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -I/opt/coolstack/apache2/include -I/opt/coolstack/apache2/include -I/opt/coolstack/apache2/include -I/opt/coolstack/include -I/usr/local/include/python2.6 -DNDEBUG -c -o mod_wsgi.lo mod_wsgi.c && touch mod_wsgi.slo
/opt/coolstack/apache2/build/libtool: line 1320: cc: command not found
apxs:Error: Command failed with rc=65536
What's wrong?
A:
You don't have SUN C/C++ compiler installed. The Cool Stack packages appear to have been built with that compiler and not gcc and in the case of Apache apxs/libtool, that is probably hardwired into the tools. Thus, when those tools are used, they will fail as can't find that compiler.
Note that it is not enough just to change 'cc' to 'gcc' as the tools are specifically configured for the compiler in question and use different options depending on which compiler it was configured for. In other words, it is not dynamic, with such information only filled out when the tools are configure/installed.
|
Problem compiling mod_wsgi on Solaris 10 with Cool Stack 1.3.1
|
I try to compile mod_wsgi with Cool Stack 1.3.1 on the Solaris platform:
export PATH=/usr/sbin:/usr/bin:/usr/local/bin:/usr/sfw/bin:/usr/ccs/bin
FLAGS="-I/opt/coolstack/include" LIBS="-lintl -lgettextlib" \
LD_LIBRARY_PATH=/opt/coolstack/lib LDFLAGS="-L/opt/coolstack/lib -R/opt/coolstack/lib" \
./configure --prefix=/usr/local/mod_wsgi \
--with-apxs=/opt/coolstack/apache2/bin/apxs \
--with-python=/opt/csw/bin/python
I get this error message:
# make
/opt/coolstack/apache2/bin/apxs -c -I/usr/local/include/python2.6 -DNDEBUG mod_wsgi.c -L/opt/coolstack/lib -R/opt/coolstack/lib -L/usr/local/lib -L/usr/local/lib/python2.6/config -lpython2.6 -lsocket -lnsl -lrt -ldl -lm
/opt/coolstack/apache2/build/libtool --silent --mode=compile cc -prefer-pic -DSSL_EXPERIMENTAL -DSSL_ENGINE -xO4 -xtarget=generic -DSOLARIS2=10 -D_POSIX_PTHREAD_SEMANTICS -D_REENTRANT -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -I/opt/coolstack/apache2/include -I/opt/coolstack/apache2/include -I/opt/coolstack/apache2/include -I/opt/coolstack/include -I/usr/local/include/python2.6 -DNDEBUG -c -o mod_wsgi.lo mod_wsgi.c && touch mod_wsgi.slo
/opt/coolstack/apache2/build/libtool: line 1320: cc: command not found
apxs:Error: Command failed with rc=65536
What's wrong?
|
[
"You don't have SUN C/C++ compiler installed. The Cool Stack packages appear to have been built with that compiler and not gcc and in the case of Apache apxs/libtool, that is probably hardwired into the tools. Thus, when those tools are used, they will fail as can't find that compiler.\nNote that it is not enough just to change 'cc' to 'gcc' as the tools are specifically configured for the compiler in question and use different options depending on which compiler it was configured for. In other words, it is not dynamic, with such information only filled out when the tools are configure/installed.\n"
] |
[
2
] |
[] |
[] |
[
"apache",
"python"
] |
stackoverflow_0002324661_apache_python.txt
|
Q:
which is the best way to get the value of 'session_key','uid','expires'
i have a string
'''
{"session_key":"3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986","uid":164
23386,"expires":12673200,"secret":"sm7WM_rRtjzXeOT_jDoQ__","sig":"6a6aeb66
64a1679bbeed4282154b35"}
'''
how to get the value .
thanks
A:
>>> import json
>>> s=''' {"session_key":"3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986","uid":16423386,"expires":12673200,"secret":"sm7WM_rRtjzXeOT_jDoQ__","sig":"6a6aeb66 64a1679bbeed4282154b35"} '''
>>> d=json.loads(s)
>>> d['session_key']
u'3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986'
>>> d['uid']
16423386
>>> d['expires']
12673200
>>> d['secret']
u'sm7WM_rRtjzXeOT_jDoQ__'
>>> d['sig']
u'6a6aeb66 64a1679bbeed4282154b35'
>>>
A:
The string appears to be JSON.
import json
obj= json.loads( aString )
obj['session_key']
Or it could be a Python dict. Try
obj= eval(myString)
obj['session_key']
A:
For a simple-to-code method, I suggest using ast.parse() or eval() to create a dictionary from your string, and then accessing the fields as usual. The difference between the two functions above is that ast.parse can only evaluate base types, and is therefore more secure if someone can give you a string that could contain "bad" code.
|
which is the best way to get the value of 'session_key','uid','expires'
|
i have a string
'''
{"session_key":"3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986","uid":164
23386,"expires":12673200,"secret":"sm7WM_rRtjzXeOT_jDoQ__","sig":"6a6aeb66
64a1679bbeed4282154b35"}
'''
how to get the value .
thanks
|
[
">>> import json\n>>> s=''' {\"session_key\":\"3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986\",\"uid\":16423386,\"expires\":12673200,\"secret\":\"sm7WM_rRtjzXeOT_jDoQ__\",\"sig\":\"6a6aeb66 64a1679bbeed4282154b35\"} '''\n>>> d=json.loads(s)\n\n>>> d['session_key']\nu'3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986'\n>>> d['uid']\n16423386\n>>> d['expires']\n12673200\n>>> d['secret']\nu'sm7WM_rRtjzXeOT_jDoQ__'\n>>> d['sig']\nu'6a6aeb66 64a1679bbeed4282154b35'\n>>> \n\n",
"The string appears to be JSON. \nimport json\nobj= json.loads( aString )\nobj['session_key']\n\nOr it could be a Python dict. Try \nobj= eval(myString)\nobj['session_key']\n\n",
"For a simple-to-code method, I suggest using ast.parse() or eval() to create a dictionary from your string, and then accessing the fields as usual. The difference between the two functions above is that ast.parse can only evaluate base types, and is therefore more secure if someone can give you a string that could contain \"bad\" code.\n"
] |
[
3,
2,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002330857_python.txt
|
Q:
Getting fast translation of string data transmitted via a socket into objects in Python
I currently have a Python application where newline-terminated ASCII strings are being transmitted to me via a TCP/IP socket. I have a high data rate of these strings and I need to parse them as quickly as possible. Currently, the strings are being transmitted as CSV and if the data rate is high enough, my Python application starts to lag behind the input data rate (probably not all that surprising).
The strings look something like this:
chan,2007-07-13T23:24:40.143,0,0188878425-079,0,0,True,S-4001,UNSIGNED_INT,name1,module1,...
I have a corresponding object that will parse these strings and store all of the data into an object. Currently the object looks something like this:
class ChanVal(object):
def __init__(self, csvString=None,**kwargs):
if csvString is not None:
self.parseFromCsv(csvString)
for key in kwargs:
setattr(self,key,kwargs[key])
def parseFromCsv(self, csvString):
lst = csvString.split(',')
self.eventTime=lst[1]
self.eventTimeExact=long(lst[2])
self.other_clock=lst[3]
...
To read the data in from the socket, I'm using a basic "socket.socket(socket.AF_INET,socket.SOCK_STREAM)" (my app is the server socket) and then I'm using the "select.poll()" object from the "select" module to constantly poll the socket for new input using its "poll(...)" method.
I have some control over the process sending the data (meaning I can get the sender to change the format), but it would be really convenient if we could speed up the ASCII processing enough to not have to use fixed-width or binary formats for the data.
So up until now, here are the things I've tried and haven't really made much of a difference:
Using the string "split" method and then indexing the list of results directly (see above), but "split" seems to be really slow.
Using the "reader" object in the "csv" module to parse the strings
Changing the strings being sent to a string format that I can use to directly instantiate an object via "eval" (e.g. sending something like "ChanVal(eventTime='2007-07-13T23:24:40.143',eventTimeExact=0,...)")
I'm trying to avoid going to a fixed-width or binary format, though I realize those would probably ultimately be much faster.
Ultimately, I'm open to suggestions on better ways to poll the socket, better ways to format/parse the data (though hopefully we can stick with ASCII) or anything else you can think of.
Thanks!
A:
You can't make Python faster. But you can make your Python application faster.
Principle 1: Do Less.
You can't do less input parsing over all but you can do less input parsing in the process that's also reading the socket and doing everything else with the data.
Generally, do this.
Break your application into a pipeline of discrete steps.
Read the socket, break into fields, create a named tuple, write the tuple to a pipe with something like pickle.
Read a pipe (with pickle) to construct the named tuple, do some processing, write to another pipe.
Read a pipe, do some processing, write to a file or something.
Each of these three processes, connected with OS pipes, runs concurrently. That means that the first process is reading the socket and make tuples while the second process is consuming tuples and doing calculations while the third process is doing calculations and writing a file.
This kind of pipeline maximizes what your CPU can do. Without too many painful tricks.
Reading and writing to pipes is trivial, since linux assures you that sys.stdin and sys.stdout will be pipes when the shell creates the pipeline.
Before doing anything else, break your program into pipeline stages.
proc1.py
import cPickle
from collections import namedtuple
ChanVal= namedtuple( 'ChanVal', ['eventTime','eventTimeExact', 'other_clock', ... ] )
for line socket:
c= ChanVal( **line.split(',') )
cPickle.dump( sys.stdout )
proc2.py
import cPickle
from collections import namedtuple
ChanVal= namedtuple( 'ChanVal', ['eventTime','eventTimeExact', 'other_clock', ... ] )
while True:
item = cPickle.load( sys.stdin )
# processing
cPickle.dump( sys.stdout )
This idea of processing namedtuples through a pipeline is very scalable.
python proc1.py | python proc2.py
A:
You need to profile your code to find out where the time is being spent.
That doesn't necessarily mean using python's profiler
For example you can just try parsing the same csv string 1000000 times with different methods. Choose the fastest method - divide by 1000000 now you know how much CPU time it takes to parse a string
Try to break the program into parts and work out how what resources are really required by each part.
The parts that need the most CPU per input line are your bottle necks
On my computer, the program below outputs this
ChanVal0 took 0.210402965546 seconds
ChanVal1 took 0.350302934647 seconds
ChanVal2 took 0.558166980743 seconds
ChanVal3 took 0.691503047943 seconds
So you see that about half the time there is taken up by parseFromCsv. But also that quite a lot of time is taken extracting the values and storing them in the class.
If the class isn't used right away it might be faster to store the raw data and use properties to parse the csvString on demand.
from time import time
import re
class ChanVal0(object):
def __init__(self, csvString=None,**kwargs):
self.csvString=csvString
for key in kwargs:
setattr(self,key,kwargs[key])
class ChanVal1(object):
def __init__(self, csvString=None,**kwargs):
if csvString is not None:
self.parseFromCsv(csvString)
for key in kwargs:
setattr(self,key,kwargs[key])
def parseFromCsv(self, csvString):
self.lst = csvString.split(',')
class ChanVal2(object):
def __init__(self, csvString=None,**kwargs):
if csvString is not None:
self.parseFromCsv(csvString)
for key in kwargs:
setattr(self,key,kwargs[key])
def parseFromCsv(self, csvString):
lst = csvString.split(',')
self.eventTime=lst[1]
self.eventTimeExact=long(lst[2])
self.other_clock=lst[3]
class ChanVal3(object):
splitter=re.compile("[^,]*,(?P<eventTime>[^,]*),(?P<eventTimeExact>[^,]*),(?P<other_clock>[^,]*)")
def __init__(self, csvString=None,**kwargs):
if csvString is not None:
self.parseFromCsv(csvString)
self.__dict__.update(kwargs)
def parseFromCsv(self, csvString):
self.__dict__.update(self.splitter.match(csvString).groupdict())
s="chan,2007-07-13T23:24:40.143,0,0188878425-079,0,0,True,S-4001,UNSIGNED_INT,name1,module1"
RUNS=100000
for cls in ChanVal0, ChanVal1, ChanVal2, ChanVal3:
start_time = time()
for i in xrange(RUNS):
cls(s)
print "%s took %s seconds"%(cls.__name__, time()-start_time)
|
Getting fast translation of string data transmitted via a socket into objects in Python
|
I currently have a Python application where newline-terminated ASCII strings are being transmitted to me via a TCP/IP socket. I have a high data rate of these strings and I need to parse them as quickly as possible. Currently, the strings are being transmitted as CSV and if the data rate is high enough, my Python application starts to lag behind the input data rate (probably not all that surprising).
The strings look something like this:
chan,2007-07-13T23:24:40.143,0,0188878425-079,0,0,True,S-4001,UNSIGNED_INT,name1,module1,...
I have a corresponding object that will parse these strings and store all of the data into an object. Currently the object looks something like this:
class ChanVal(object):
def __init__(self, csvString=None,**kwargs):
if csvString is not None:
self.parseFromCsv(csvString)
for key in kwargs:
setattr(self,key,kwargs[key])
def parseFromCsv(self, csvString):
lst = csvString.split(',')
self.eventTime=lst[1]
self.eventTimeExact=long(lst[2])
self.other_clock=lst[3]
...
To read the data in from the socket, I'm using a basic "socket.socket(socket.AF_INET,socket.SOCK_STREAM)" (my app is the server socket) and then I'm using the "select.poll()" object from the "select" module to constantly poll the socket for new input using its "poll(...)" method.
I have some control over the process sending the data (meaning I can get the sender to change the format), but it would be really convenient if we could speed up the ASCII processing enough to not have to use fixed-width or binary formats for the data.
So up until now, here are the things I've tried and haven't really made much of a difference:
Using the string "split" method and then indexing the list of results directly (see above), but "split" seems to be really slow.
Using the "reader" object in the "csv" module to parse the strings
Changing the strings being sent to a string format that I can use to directly instantiate an object via "eval" (e.g. sending something like "ChanVal(eventTime='2007-07-13T23:24:40.143',eventTimeExact=0,...)")
I'm trying to avoid going to a fixed-width or binary format, though I realize those would probably ultimately be much faster.
Ultimately, I'm open to suggestions on better ways to poll the socket, better ways to format/parse the data (though hopefully we can stick with ASCII) or anything else you can think of.
Thanks!
|
[
"You can't make Python faster. But you can make your Python application faster.\nPrinciple 1: Do Less.\nYou can't do less input parsing over all but you can do less input parsing in the process that's also reading the socket and doing everything else with the data.\nGenerally, do this.\nBreak your application into a pipeline of discrete steps.\n\nRead the socket, break into fields, create a named tuple, write the tuple to a pipe with something like pickle.\nRead a pipe (with pickle) to construct the named tuple, do some processing, write to another pipe.\nRead a pipe, do some processing, write to a file or something.\n\nEach of these three processes, connected with OS pipes, runs concurrently. That means that the first process is reading the socket and make tuples while the second process is consuming tuples and doing calculations while the third process is doing calculations and writing a file.\nThis kind of pipeline maximizes what your CPU can do. Without too many painful tricks.\nReading and writing to pipes is trivial, since linux assures you that sys.stdin and sys.stdout will be pipes when the shell creates the pipeline.\nBefore doing anything else, break your program into pipeline stages.\nproc1.py\nimport cPickle\nfrom collections import namedtuple\n\nChanVal= namedtuple( 'ChanVal', ['eventTime','eventTimeExact', 'other_clock', ... ] )\nfor line socket:\n c= ChanVal( **line.split(',') )\n cPickle.dump( sys.stdout )\n\nproc2.py\nimport cPickle\nfrom collections import namedtuple\nChanVal= namedtuple( 'ChanVal', ['eventTime','eventTimeExact', 'other_clock', ... ] )\nwhile True:\n item = cPickle.load( sys.stdin )\n # processing\n cPickle.dump( sys.stdout )\n\nThis idea of processing namedtuples through a pipeline is very scalable.\npython proc1.py | python proc2.py\n\n",
"You need to profile your code to find out where the time is being spent.\nThat doesn't necessarily mean using python's profiler\nFor example you can just try parsing the same csv string 1000000 times with different methods. Choose the fastest method - divide by 1000000 now you know how much CPU time it takes to parse a string\nTry to break the program into parts and work out how what resources are really required by each part.\nThe parts that need the most CPU per input line are your bottle necks\nOn my computer, the program below outputs this\nChanVal0 took 0.210402965546 seconds\nChanVal1 took 0.350302934647 seconds\nChanVal2 took 0.558166980743 seconds\nChanVal3 took 0.691503047943 seconds\n\nSo you see that about half the time there is taken up by parseFromCsv. But also that quite a lot of time is taken extracting the values and storing them in the class.\nIf the class isn't used right away it might be faster to store the raw data and use properties to parse the csvString on demand.\nfrom time import time\nimport re\n\nclass ChanVal0(object):\n def __init__(self, csvString=None,**kwargs):\n self.csvString=csvString\n for key in kwargs:\n setattr(self,key,kwargs[key])\n\nclass ChanVal1(object):\n def __init__(self, csvString=None,**kwargs):\n if csvString is not None:\n self.parseFromCsv(csvString)\n for key in kwargs:\n setattr(self,key,kwargs[key])\n\n def parseFromCsv(self, csvString):\n self.lst = csvString.split(',')\n\nclass ChanVal2(object):\n def __init__(self, csvString=None,**kwargs):\n if csvString is not None:\n self.parseFromCsv(csvString)\n for key in kwargs:\n setattr(self,key,kwargs[key])\n\n def parseFromCsv(self, csvString):\n lst = csvString.split(',')\n self.eventTime=lst[1]\n self.eventTimeExact=long(lst[2])\n self.other_clock=lst[3]\n\n\nclass ChanVal3(object):\n splitter=re.compile(\"[^,]*,(?P<eventTime>[^,]*),(?P<eventTimeExact>[^,]*),(?P<other_clock>[^,]*)\")\n def __init__(self, csvString=None,**kwargs):\n if csvString is not None:\n self.parseFromCsv(csvString)\n self.__dict__.update(kwargs)\n\n def parseFromCsv(self, csvString):\n self.__dict__.update(self.splitter.match(csvString).groupdict())\n\n\ns=\"chan,2007-07-13T23:24:40.143,0,0188878425-079,0,0,True,S-4001,UNSIGNED_INT,name1,module1\"\nRUNS=100000\n\nfor cls in ChanVal0, ChanVal1, ChanVal2, ChanVal3:\n start_time = time()\n for i in xrange(RUNS):\n cls(s)\n print \"%s took %s seconds\"%(cls.__name__, time()-start_time) \n\n"
] |
[
3,
0
] |
[] |
[] |
[
"parsing",
"performance",
"python",
"sockets",
"string"
] |
stackoverflow_0002330834_parsing_performance_python_sockets_string.txt
|
Q:
A user management system for a new app?
im using python. is there a widely accepted way of doing it? it deals with some data management things, so i dont want to implement it like in stackoverflow, with anonymous accounts. i also don't want to roll my own system from scratch. any recommendations?
A:
Are you talking about a web application? If so, OpenId is probably the way to go, and this library probably the most popular way to implement it in Python. If you're talking about user management for a NON-web app, please clarify your requirements and constraints!
|
A user management system for a new app?
|
im using python. is there a widely accepted way of doing it? it deals with some data management things, so i dont want to implement it like in stackoverflow, with anonymous accounts. i also don't want to roll my own system from scratch. any recommendations?
|
[
"Are you talking about a web application? If so, OpenId is probably the way to go, and this library probably the most popular way to implement it in Python. If you're talking about user management for a NON-web app, please clarify your requirements and constraints!\n"
] |
[
1
] |
[] |
[] |
[
"language_agnostic",
"python"
] |
stackoverflow_0002331699_language_agnostic_python.txt
|
Q:
How to set a icon file while creating file
I am creating a tar file ( from several files), now while saving this tar file i save this file as my particular extension like (.xyz), so i want whenever i save this type file (.xyz extension) from my tool this file should save with a particular ico file format. This is similar like when we save a bmp or jpeg file from mspaint they save with their icon file format.
Thanks
A:
To associate a icon with your extension you will have to create a registry entry for that and a icon associated with a extension doesn't mean anything unless you associate some program to open it with you, that too you can do in registry e.g
Create an entry for your program's icon name, e.g.
HKCU\Software\Classes\myprog.file.xyz
under HKCU\Software\Classes\myprog.file.xyz create enteries for default icon
HKCU\Software\Classes\myprog.file.xyz\DefaultIcon
here you can give path to an icon or to your app and icon will be taken from resource
Create a entry for Open and other commands if you want your extension to open correctly
e.g. HKCU\Software\Classes\myprog.file.xyz\Shell\Open\Command
and enter path to your program or any other program
similarly you can add command for view/print etc
Now you have to tell registry that extension .xyz should use info from HKCU\Software\Classes\myprog.file.xyz
so create an entry
HKCU\Software\Classes.xyz = myprog.file.xyz
Actually if you wish you can directly put 1-3 in HKCU\Software\Classes.xyz, but this redirection is a better way of doing things.
because now you can simply assign myprog.file.xyz to many extrnsions e.g. .xxx, .yyy or .zzz etc
Now using python module _winreg (http://docs.python.org/library/_winreg.html) you can create all these enteries programtically.
e.g. this script will set xyz to python icon
from _winreg import *
xyzKey = CreateKey(HKEY_CLASSES_ROOT, ".xyz")
SetValue(xyzKey, None, REG_SZ, "MyTest.xyz")
CloseKey(xyzKey)
myTestKey = CreateKey(HKEY_CLASSES_ROOT, "MyTest.xyz")
iconKey= CreateKey(myTestKey, "DefaultIcon")
CloseKey(myTestKey)
SetValue(iconKey, None, REG_SZ, "D:\\Python25\\python.exe")
CloseKey(iconKey)
|
How to set a icon file while creating file
|
I am creating a tar file ( from several files), now while saving this tar file i save this file as my particular extension like (.xyz), so i want whenever i save this type file (.xyz extension) from my tool this file should save with a particular ico file format. This is similar like when we save a bmp or jpeg file from mspaint they save with their icon file format.
Thanks
|
[
"To associate a icon with your extension you will have to create a registry entry for that and a icon associated with a extension doesn't mean anything unless you associate some program to open it with you, that too you can do in registry e.g\n\nCreate an entry for your program's icon name, e.g.\nHKCU\\Software\\Classes\\myprog.file.xyz\nunder HKCU\\Software\\Classes\\myprog.file.xyz create enteries for default icon\nHKCU\\Software\\Classes\\myprog.file.xyz\\DefaultIcon\nhere you can give path to an icon or to your app and icon will be taken from resource\nCreate a entry for Open and other commands if you want your extension to open correctly\ne.g. HKCU\\Software\\Classes\\myprog.file.xyz\\Shell\\Open\\Command\nand enter path to your program or any other program\nsimilarly you can add command for view/print etc\nNow you have to tell registry that extension .xyz should use info from HKCU\\Software\\Classes\\myprog.file.xyz\nso create an entry\nHKCU\\Software\\Classes.xyz = myprog.file.xyz\n\nActually if you wish you can directly put 1-3 in HKCU\\Software\\Classes.xyz, but this redirection is a better way of doing things.\nbecause now you can simply assign myprog.file.xyz to many extrnsions e.g. .xxx, .yyy or .zzz etc\nNow using python module _winreg (http://docs.python.org/library/_winreg.html) you can create all these enteries programtically.\ne.g. this script will set xyz to python icon\nfrom _winreg import *\n\nxyzKey = CreateKey(HKEY_CLASSES_ROOT, \".xyz\")\nSetValue(xyzKey, None, REG_SZ, \"MyTest.xyz\")\nCloseKey(xyzKey)\n\nmyTestKey = CreateKey(HKEY_CLASSES_ROOT, \"MyTest.xyz\")\niconKey= CreateKey(myTestKey, \"DefaultIcon\")\nCloseKey(myTestKey)\n\nSetValue(iconKey, None, REG_SZ, \"D:\\\\Python25\\\\python.exe\")\nCloseKey(iconKey)\n\n"
] |
[
2
] |
[] |
[] |
[
"python",
"wxpython"
] |
stackoverflow_0002331690_python_wxpython.txt
|
Q:
How to make a user friendly start of a Python program?
I have a Python program (GUI application). I can run this program from the command prompt on Windows (command line on Linux). But it can be too complicated for users. Is there an easy way to initiate a start of the program with a click (double click) on a pictogram (a small image on the desktop)?
A:
I'm not sure if I understood the question well, but if you just need a way to simulate a command line input with a simply clickable icon, just create a simple .bat file (assuming windows) on the desktop, as a new text file containing something like
C:\[Pythonpath]\python C:\[MyPythonAppPath]\myapp.py
See http://en.wikipedia.org/wiki/Batch_file for more info.
A:
Linux:
I am not sure, which linux distro and desktop you use but for gnome I create such files on desktop e.. create a myapp.desktop and put in on desktop
[Desktop Entry]
Version=1.0
Encoding=UTF-8
Name=MyApp
Type=Application
Exec=python /home/anushri/display.anurag/xxx.py
TryExec=
Icon=/usr/share/pixmaps/gnome-qeye.png
X-GNOME-DocPath=
Terminal=false
Name[en_IN]=MyApp
GenericName[en_IN]=MyApp
Comment[en_IN]=MyApp
GenericName=MyApp
Comment=MyApp
Windows:
Right-click an open area on the desktop, point to New, and then click Shortcut, type the command line to start you program, Type a name for the shortcut
A:
Use py2exe to make an exe and just to make it more 'user friendly' use Inno set up (www.jrsoftware.org/isinfo.php ) along with IStools to build up an installer which would integrate the GUI with sound, widgets, other elements etc and users who do not have python etc installed in their systems can also play your GUI perfectly fine !
By the way what GUI are you using ? pygame, tk, wx, PyQt ...etc ?
A:
What I've done in the past is use py2exe to create an executable from my python script. That embeds the interpreter and the source inside an EXE, that way it works just like a native executable and you don't have to have the users install python or anything complicated.
|
How to make a user friendly start of a Python program?
|
I have a Python program (GUI application). I can run this program from the command prompt on Windows (command line on Linux). But it can be too complicated for users. Is there an easy way to initiate a start of the program with a click (double click) on a pictogram (a small image on the desktop)?
|
[
"I'm not sure if I understood the question well, but if you just need a way to simulate a command line input with a simply clickable icon, just create a simple .bat file (assuming windows) on the desktop, as a new text file containing something like \n\nC:\\[Pythonpath]\\python C:\\[MyPythonAppPath]\\myapp.py\n\nSee http://en.wikipedia.org/wiki/Batch_file for more info.\n",
"Linux:\nI am not sure, which linux distro and desktop you use but for gnome I create such files on desktop e.. create a myapp.desktop and put in on desktop\n[Desktop Entry]\nVersion=1.0\nEncoding=UTF-8\nName=MyApp\nType=Application\nExec=python /home/anushri/display.anurag/xxx.py\nTryExec=\nIcon=/usr/share/pixmaps/gnome-qeye.png\nX-GNOME-DocPath=\nTerminal=false\nName[en_IN]=MyApp\nGenericName[en_IN]=MyApp\nComment[en_IN]=MyApp\nGenericName=MyApp\nComment=MyApp\n\nWindows:\nRight-click an open area on the desktop, point to New, and then click Shortcut, type the command line to start you program, Type a name for the shortcut\n",
"Use py2exe to make an exe and just to make it more 'user friendly' use Inno set up (www.jrsoftware.org/isinfo.php ) along with IStools to build up an installer which would integrate the GUI with sound, widgets, other elements etc and users who do not have python etc installed in their systems can also play your GUI perfectly fine ! \nBy the way what GUI are you using ? pygame, tk, wx, PyQt ...etc ? \n",
"What I've done in the past is use py2exe to create an executable from my python script. That embeds the interpreter and the source inside an EXE, that way it works just like a native executable and you don't have to have the users install python or anything complicated.\n"
] |
[
1,
1,
1,
0
] |
[] |
[] |
[
"command_line",
"command_prompt",
"desktop",
"python"
] |
stackoverflow_0002311455_command_line_command_prompt_desktop_python.txt
|
Q:
PyFacebook: Facebook() instance has no stream methods
I need to update my Facebook Fan Page in a django app so I have this code:
import facebook
from django.conf import settings
def login_facebook():
fb = facebook.Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY)
fb.session_key = settings.FACEBOOK_SESSION
fb.secret = settings.FACEBOOK_SECRET_KEY
fb.uid = settings.FACEBOOK_UID
return fb
def update_status(fb, message):
return fb.stream.publish(message=status_message)
And I use this to run it with ipython:
import src.tests.scripts.facebook_publish_fanpage as f
fb = f.login_facebook()
f.update_status(fb, 'This is a test')
But I get this exception:
AttributeError: 'Facebook' object has no attribute 'stream'
I already gave permissions to the app following this 2 steps:
Publish post on Facebook page(1) and Authorizing a Facebook Fan Page for Status Updates(2)
But no matter what I try (being doing it a few hours now...) I can't publish to the page...
I'm lost now, any help?
(1) tech.karolzielinski.com/publish-post-of-facebook-page-wall-as-a-page-not-a-user-python-facebook-rest-api
(2) stackoverflow.com/questions/2097665/authorizing-a-facebook-fan-page-for-status-updates
PD: Sorry don't have permission to add the links yet, I'm mostly a reader in SO
A:
After searching for hours I finally found the solution... not to use stream methods but this:
fb(method='stream_publish', args={'session_key': settings.FACEBOOK_SESSION, 'uid':PAGE_ID, 'target_id': 'NULL', 'message':'MESSAGE_HERE'})
Found the solution at this blog post: http://danielquinn.org/blog/1578.html
That works!!
|
PyFacebook: Facebook() instance has no stream methods
|
I need to update my Facebook Fan Page in a django app so I have this code:
import facebook
from django.conf import settings
def login_facebook():
fb = facebook.Facebook(settings.FACEBOOK_API_KEY, settings.FACEBOOK_SECRET_KEY)
fb.session_key = settings.FACEBOOK_SESSION
fb.secret = settings.FACEBOOK_SECRET_KEY
fb.uid = settings.FACEBOOK_UID
return fb
def update_status(fb, message):
return fb.stream.publish(message=status_message)
And I use this to run it with ipython:
import src.tests.scripts.facebook_publish_fanpage as f
fb = f.login_facebook()
f.update_status(fb, 'This is a test')
But I get this exception:
AttributeError: 'Facebook' object has no attribute 'stream'
I already gave permissions to the app following this 2 steps:
Publish post on Facebook page(1) and Authorizing a Facebook Fan Page for Status Updates(2)
But no matter what I try (being doing it a few hours now...) I can't publish to the page...
I'm lost now, any help?
(1) tech.karolzielinski.com/publish-post-of-facebook-page-wall-as-a-page-not-a-user-python-facebook-rest-api
(2) stackoverflow.com/questions/2097665/authorizing-a-facebook-fan-page-for-status-updates
PD: Sorry don't have permission to add the links yet, I'm mostly a reader in SO
|
[
"After searching for hours I finally found the solution... not to use stream methods but this:\nfb(method='stream_publish', args={'session_key': settings.FACEBOOK_SESSION, 'uid':PAGE_ID, 'target_id': 'NULL', 'message':'MESSAGE_HERE'})\n\nFound the solution at this blog post: http://danielquinn.org/blog/1578.html\nThat works!!\n"
] |
[
1
] |
[] |
[] |
[
"facebook",
"pyfacebook",
"python"
] |
stackoverflow_0002332315_facebook_pyfacebook_python.txt
|
Q:
Why am I getting this error in Django (I'm trying to do a 304 not modified)
def list_ajax(reqest):
#q = request.GET.get('q',None)
#get all where var = q.
return ...
list_ajax = condition(etag_func=list_ajax)(list_ajax)
As you can see, I'm trying to return a 304 to the client if the result is the same. But, I am getting this Django error, why?:
Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/views/decorators/http.py" in inner
130. response['ETag'] = quote_etag(res_etag)
File "/usr/local/lib/python2.6/dist-packages/django/utils/http.py" in quote_etag
118. return '"%s"' % etag.replace('\\', '\\\\').replace('"', '\\"')
Exception Type: AttributeError at /list/ajax/
Exception Value: 'HttpResponse' object has no attribute 'replace'
Edit: I did this:
def etag_generate(p):
thestring = cPickle.dumps(p)
return thestring
@etag(etag_generate)
def list_ajax(request):
...
etag_generate(mydictresults)
return render_to_response("list.html",mydictresults)
I'm turning all the results into a String, hoping that a hash could be generated from this dictionary. But, it seems like the @etag won't let me generate the cPickle. Error is:
Exception Type: TypeError at /list/ajax/
Exception Value: can't pickle file objects
A:
The correct etag_func would return some serializable data. In your case, the best choice is something like this:
@etag(_get_list)
def list_ajax(request):
objects = _get_list(request)
return render_to_response("list.html", {"objects": objects})
def _get_list(request):
q = request.GET["q"]
# find and return records here
# ...
A:
Fixed.
Passed the request in.
def list_ajax_etag(request):
return str(request.GET.get('l',''))+str(request.GET.get('a',''))
|
Why am I getting this error in Django (I'm trying to do a 304 not modified)
|
def list_ajax(reqest):
#q = request.GET.get('q',None)
#get all where var = q.
return ...
list_ajax = condition(etag_func=list_ajax)(list_ajax)
As you can see, I'm trying to return a 304 to the client if the result is the same. But, I am getting this Django error, why?:
Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
92. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/views/decorators/http.py" in inner
130. response['ETag'] = quote_etag(res_etag)
File "/usr/local/lib/python2.6/dist-packages/django/utils/http.py" in quote_etag
118. return '"%s"' % etag.replace('\\', '\\\\').replace('"', '\\"')
Exception Type: AttributeError at /list/ajax/
Exception Value: 'HttpResponse' object has no attribute 'replace'
Edit: I did this:
def etag_generate(p):
thestring = cPickle.dumps(p)
return thestring
@etag(etag_generate)
def list_ajax(request):
...
etag_generate(mydictresults)
return render_to_response("list.html",mydictresults)
I'm turning all the results into a String, hoping that a hash could be generated from this dictionary. But, it seems like the @etag won't let me generate the cPickle. Error is:
Exception Type: TypeError at /list/ajax/
Exception Value: can't pickle file objects
|
[
"The correct etag_func would return some serializable data. In your case, the best choice is something like this:\n@etag(_get_list)\ndef list_ajax(request):\n objects = _get_list(request)\n return render_to_response(\"list.html\", {\"objects\": objects})\n\ndef _get_list(request):\n q = request.GET[\"q\"]\n # find and return records here\n # ...\n\n",
"Fixed.\nPassed the request in.\ndef list_ajax_etag(request):\n return str(request.GET.get('l',''))+str(request.GET.get('a',''))\n\n"
] |
[
0,
0
] |
[] |
[] |
[
"django",
"header",
"http",
"http_status_code_304",
"python"
] |
stackoverflow_0002330435_django_header_http_http_status_code_304_python.txt
|
Q:
Migrate a SQLite3 database table to MySQL with Python without dump files
I need to migrate information that I created in SQLite3 to a MySQL database on my website. The website is on a hosted server. I have remote access to the MySQL database. I initially thought it would be easy, but I am not finding any good info on it, and everything I read seems to imply that you need to dump the SQLite3 file, convert it to a MySQL dump file using messy scripts, and then import it into the MySQL.
(example: Quick easy way to migrate SQLite3 to MySQL?)
My question: Is it not better to read it and import it straight from the script into MySQL. I haven't used MySQL at all with Python, but it would seem intuitive that it would be better to have less steps for things to be miss-read. I am also trying to save a little time by not having to understand the way that a MySQL dump file works.
If you have a script (Python if possible), tool or link that will help me out that would be great, but my main concern first of all is how to go about doing it. I can't realistically check everything (otherwise I would just do copy and paste), so I want to be sure that I am going about it the right way.
I am using Django, perhaps there is a Django specific method for it, but I haven't been able to find one.
A:
The reason the "messy" scripts are required is that it's generally a difficult problem to solve.
If you are lucky there won't be too many schema incompatibilities between the databases.
These may help
db_dump.py
dbpickle.py
What is your favorite solution for managing database migrations in django?
A:
Have you tried using django-admin's dumpdata and loaddata?
e.g. dump sqllite3 db
manage.py dumpdata
change db to mysql, recreate tables and load
manage.py loaddata mydata.json
dumpdata by default dumps json but you can set format to xml too.
Alternatively, you can just read whole sqlite3 db using python db api or sqlalchemy or django ORM and dump it to MySQL db.
|
Migrate a SQLite3 database table to MySQL with Python without dump files
|
I need to migrate information that I created in SQLite3 to a MySQL database on my website. The website is on a hosted server. I have remote access to the MySQL database. I initially thought it would be easy, but I am not finding any good info on it, and everything I read seems to imply that you need to dump the SQLite3 file, convert it to a MySQL dump file using messy scripts, and then import it into the MySQL.
(example: Quick easy way to migrate SQLite3 to MySQL?)
My question: Is it not better to read it and import it straight from the script into MySQL. I haven't used MySQL at all with Python, but it would seem intuitive that it would be better to have less steps for things to be miss-read. I am also trying to save a little time by not having to understand the way that a MySQL dump file works.
If you have a script (Python if possible), tool or link that will help me out that would be great, but my main concern first of all is how to go about doing it. I can't realistically check everything (otherwise I would just do copy and paste), so I want to be sure that I am going about it the right way.
I am using Django, perhaps there is a Django specific method for it, but I haven't been able to find one.
|
[
"The reason the \"messy\" scripts are required is that it's generally a difficult problem to solve.\nIf you are lucky there won't be too many schema incompatibilities between the databases.\nThese may help\ndb_dump.py\ndbpickle.py\nWhat is your favorite solution for managing database migrations in django? \n",
"Have you tried using django-admin's dumpdata and loaddata?\ne.g. dump sqllite3 db \nmanage.py dumpdata\n\nchange db to mysql, recreate tables and load\nmanage.py loaddata mydata.json\n\ndumpdata by default dumps json but you can set format to xml too.\nAlternatively, you can just read whole sqlite3 db using python db api or sqlalchemy or django ORM and dump it to MySQL db.\n"
] |
[
2,
2
] |
[] |
[] |
[
"django",
"mysql",
"python",
"sqlite"
] |
stackoverflow_0002332609_django_mysql_python_sqlite.txt
|
Q:
Perform a SQL JOIN on Django models that are not related?
I have 2 Models, User (django.contrib.auth.models.User) and a model named Log. Both contain an "email" field. Log does not have a ForeignKey pointing to the User model. I'm trying to figure out how I can perform a JOIN on these two tables using the email field as the commonality.
There are basically 2 queries I want to be able to perform. A basic join for filtering
#Get all the User objects that have related Log objects with the level parameter set to 3.
User.objects.filter(log__level=3)
I'd also like to do some aggregates.
User.objects.all().anotate(Count('log'))
Of course, it would be nice to be able to do the reverse as well.
log = Log.objects.get(pk=3)
log.user...
Is there a way to do this with the ORM? Maybe something I can add to the model's Meta class to "activate" the relation?
Thanks!
A:
You can add an extra method onto the User class, using MonkeyPatching/DuckPunching:
def logs(user):
return Log.objects.filter(email=user.email)
from django.contrib.auth.models import User
User.logs = property(logs)
Now, you can query a User, and ask for the logs attached (for instance, in a view):
user = request.user
logs = user.logs
This type of process is common in the Ruby world, but seems to be frowned upon in Python.
(I came across the DuckPunching term the other day. It is based on Duck Typing, where we don't care what class something is: if it quacks like a duck, it is a duck as far as we are concerned. If it doesn't quack when you punch it, keep punching until it quacks).
A:
why not use extra()?
example (untested):
User.objects.extra(
select={
'log_count': 'SELECT COUNT(*) FROM myapp_log WHERE myapp_log.email = auth_user.email'
},
)
for the User.objects.filter(log__level=3) portion here is the equivalent with extra (untested):
User.objects.extra(
select={
'log_level_3_count': 'SELECT COUNT(*) FROM myapp_log WHERE (myapp_log.email = auth_user.email) AND (myapp_log.level=3)'
},
).filter(log_level_3_count__gt=0)
A:
Do the Log.email values always correspond to a User? If so, how about just adding a ForeignKey(User) to the Log object?
class Log(models.Model):
# ...
user = models.ForeignKey(User)
With the FK to User, it becomes fairly straight forward to find what you want:
User.objects.filter(log__level=3)
User.objects.all().anotate(Count('log'))
user.log_set.all()
user.log_set.count()
log.user
If the Log.email value does not have to belong to a user you can try adding a method to a model manager.
class LogManager(models.Manager):
def for_user(self, user):
return super(LobManager, self).get_query_set().filter(email=user.email)
class Log(models.Model):
# ...
objects = LogManager()
And then use it like this:
user = User.objects.get(pk=1)
logs_for_user = Log.objects.for_user(user)
|
Perform a SQL JOIN on Django models that are not related?
|
I have 2 Models, User (django.contrib.auth.models.User) and a model named Log. Both contain an "email" field. Log does not have a ForeignKey pointing to the User model. I'm trying to figure out how I can perform a JOIN on these two tables using the email field as the commonality.
There are basically 2 queries I want to be able to perform. A basic join for filtering
#Get all the User objects that have related Log objects with the level parameter set to 3.
User.objects.filter(log__level=3)
I'd also like to do some aggregates.
User.objects.all().anotate(Count('log'))
Of course, it would be nice to be able to do the reverse as well.
log = Log.objects.get(pk=3)
log.user...
Is there a way to do this with the ORM? Maybe something I can add to the model's Meta class to "activate" the relation?
Thanks!
|
[
"You can add an extra method onto the User class, using MonkeyPatching/DuckPunching:\ndef logs(user):\n return Log.objects.filter(email=user.email)\n\nfrom django.contrib.auth.models import User\nUser.logs = property(logs)\n\nNow, you can query a User, and ask for the logs attached (for instance, in a view):\nuser = request.user\nlogs = user.logs\n\nThis type of process is common in the Ruby world, but seems to be frowned upon in Python.\n(I came across the DuckPunching term the other day. It is based on Duck Typing, where we don't care what class something is: if it quacks like a duck, it is a duck as far as we are concerned. If it doesn't quack when you punch it, keep punching until it quacks).\n",
"why not use extra()?\nexample (untested):\nUser.objects.extra(\n select={\n 'log_count': 'SELECT COUNT(*) FROM myapp_log WHERE myapp_log.email = auth_user.email'\n },\n)\n\nfor the User.objects.filter(log__level=3) portion here is the equivalent with extra (untested):\nUser.objects.extra(\n select={\n 'log_level_3_count': 'SELECT COUNT(*) FROM myapp_log WHERE (myapp_log.email = auth_user.email) AND (myapp_log.level=3)'\n },\n).filter(log_level_3_count__gt=0)\n\n",
"Do the Log.email values always correspond to a User? If so, how about just adding a ForeignKey(User) to the Log object?\nclass Log(models.Model):\n # ...\n user = models.ForeignKey(User)\n\nWith the FK to User, it becomes fairly straight forward to find what you want:\nUser.objects.filter(log__level=3)\nUser.objects.all().anotate(Count('log'))\n\nuser.log_set.all()\nuser.log_set.count()\n\nlog.user\n\nIf the Log.email value does not have to belong to a user you can try adding a method to a model manager.\nclass LogManager(models.Manager):\n def for_user(self, user):\n return super(LobManager, self).get_query_set().filter(email=user.email)\n\nclass Log(models.Model):\n # ...\n objects = LogManager()\n\nAnd then use it like this:\nuser = User.objects.get(pk=1)\nlogs_for_user = Log.objects.for_user(user)\n\n"
] |
[
3,
2,
0
] |
[] |
[] |
[
"django",
"orm",
"python"
] |
stackoverflow_0002328493_django_orm_python.txt
|
Q:
Colorize PyLint Output?
Anyone have any tricks/techniques for colorizing PyLint output?
A:
$ pylint --output-format=colorized
Try $ pylint --help | less for more useful tricks.
A:
If you feel up to writing a Pygments lexer then you could use pygmentize.
|
Colorize PyLint Output?
|
Anyone have any tricks/techniques for colorizing PyLint output?
|
[
"$ pylint --output-format=colorized\n\nTry $ pylint --help | less for more useful tricks. \n",
"If you feel up to writing a Pygments lexer then you could use pygmentize.\n"
] |
[
21,
3
] |
[] |
[] |
[
"colorize",
"pylint",
"python"
] |
stackoverflow_0002330608_colorize_pylint_python.txt
|
Q:
How to serialize db.Model objects to json?
When using
from django.utils import simplejson
on objects of types that derive from db.Model it throws exceptions. How to circumvent this?
A:
Ok - my python not great so any help would be appreciated - You dont need to write a parser - this is the solution:
add this utlity class http://code.google.com/p/google-app-engine-samples/source/browse/trunk/geochat/json.py?r=55
import datetime
import time
from google.appengine.api import users
from google.appengine.ext import db
#this is a mod on the orinal file for some reason it includes its own simplejson files i have ref django!
from django.utils import simplejson
class GqlEncoder(simplejson.JSONEncoder):
"""Extends JSONEncoder to add support for GQL results and properties.
Adds support to simplejson JSONEncoders for GQL results and properties by
overriding JSONEncoder's default method.
"""
# TODO Improve coverage for all of App Engine's Property types.
def default(self, obj):
"""Tests the input object, obj, to encode as JSON."""
if hasattr(obj, '__json__'):
return getattr(obj, '__json__')()
if isinstance(obj, db.GqlQuery):
return list(obj)
elif isinstance(obj, db.Model):
properties = obj.properties().items()
output = {}
for field, value in properties:
output[field] = getattr(obj, field)
return output
elif isinstance(obj, datetime.datetime):
output = {}
fields = ['day', 'hour', 'microsecond', 'minute', 'month', 'second',
'year']
methods = ['ctime', 'isocalendar', 'isoformat', 'isoweekday',
'timetuple']
for field in fields:
output[field] = getattr(obj, field)
for method in methods:
output[method] = getattr(obj, method)()
output['epoch'] = time.mktime(obj.timetuple())
return output
elif isinstance(obj, time.struct_time):
return list(obj)
elif isinstance(obj, users.User):
output = {}
methods = ['nickname', 'email', 'auth_domain']
for method in methods:
output[method] = getattr(obj, method)()
return output
return simplejson.JSONEncoder.default(self, obj)
def encode(input):
"""Encode an input GQL object as JSON
Args:
input: A GQL object or DB property.
Returns:
A JSON string based on the input object.
Raises:
TypeError: Typically occurs when an input object contains an unsupported
type.
"""
return GqlEncoder().encode(input)
save as json.py
TO USE
import cgi
import os
import json
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
class Greeting(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
date = db.DateTimeProperty(auto_now_add=True)
class MainPage(webapp.RequestHandler):
def get(self):
greetings_query = Greeting.all().order('-date')
greetings = greetings_query.fetch(5)
if users.get_current_user():
url = users.create_logout_url(self.request.uri)
url_linktext = 'Logout'
else:
url = users.create_login_url(self.request.uri)
url_linktext = 'Login'
template_values = {
'greetings': greetings,
'url': url,
'url_linktext': url_linktext,
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
class Guestbook(webapp.RequestHandler):
def post(self):
greeting = Greeting()
if users.get_current_user():
greeting.author = users.get_current_user()
greeting.content = self.request.get('content')
greeting.put()
self.redirect('/')
#here i return my json feed - simple implementaion for example
class FeedHandler(webapp.RequestHandler):
def get(self):
"""Retrieve a feed"""
user = None
greetings_query = Greeting.all().order('-date')
rs= greetings_query.fetch(5)
#this is the part that calls the encoder - dosnt cause an exception
data = json.encode(rs)
#roll out to browser -might need to check my headers etc
self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
self.response.out.write(data)
application = webapp.WSGIApplication(
[
('/', MainPage),
('/sign',Guestbook),
('/feed',FeedHandler),
], debug=True
)
def main():
run_wsgi_app(application)
if __name__ == "__main__":
main()
This is the browser response:
[{"content": "", "date": {"ctime": "Sat Jan 23 02:40:22 2010", "hour": 2, "isoweekday": 6, "month": 1, "second": 22, "microsecond": 434000, "isocalendar": [2010, 3, 6], "timetuple": [2010, 1, 23, 2, 40, 22, 5, 23, -1], "year": 2010, "epoch": 1264214422.0, "isoformat": "2010-01-23T02:40:22.434000", "day": 23, "minute": 40}, "author": {"nickname": "test@example.com", "email": "test@example.com", "auth_domain": "gmail.com"}}, {"content": "", "date": {"ctime": "Sat Jan 23 01:12:43 2010", "hour": 1, "isoweekday": 6, "month": 1, "second": 43, "microsecond": 972000, "isocalendar": [2010, 3, 6], "timetuple": [2010, 1, 23, 1, 12, 43, 5, 23, -1], "year": 2010, "epoch": 1264209163.0, "isoformat": "2010-01-23T01:12:43.972000", "day": 23, "minute": 12}, "author": {"nickname": "test@example.com", "email": "test@example.com", "auth_domain": "gmail.com"}}, {"content": "test", "date": {"ctime": "Fri Jan 22 22:32:13 2010", "hour": 22, "isoweekday": 5, "month": 1, "second": 13, "microsecond": 659000, "isocalendar": [2010, 3, 5], "timetuple": [2010, 1, 22, 22, 32, 13, 4, 22, -1], "year": 2010, "epoch": 1264199533.0, "isoformat": "2010-01-22T22:32:13.659000", "day": 22, "minute": 32}, "author": {"nickname": "test@example.com", "email": "test@example.com", "auth_domain": "gmail.com"}}, {"content": "", "date": {"ctime": "Fri Jan 22 22:29:49 2010", "hour": 22, "isoweekday": 5, "month": 1, "second": 49, "microsecond": 358000, "isocalendar": [2010, 3, 5], "timetuple": [2010, 1, 22, 22, 29, 49, 4, 22, -1], "year": 2010, "epoch": 1264199389.0, "isoformat": "2010-01-22T22:29:49.358000", "day": 22, "minute": 29}, "author": {"nickname": "test@example.com", "email": "test@example.com", "auth_domain": "gmail.com"}}, {"content": "ah it works!\r\n", "date": {"ctime": "Fri Jan 22 22:29:22 2010", "hour": 22, "isoweekday": 5, "month": 1, "second": 22, "microsecond": 995000, "isocalendar": [2010, 3, 5], "timetuple": [2010, 1, 22, 22, 29, 22, 4, 22, -1], "year": 2010, "epoch": 1264199362.0, "isoformat": "2010-01-22T22:29:22.995000", "day": 22, "minute": 29}, "author": {"nickname": "test@example.com", "email": "test@example.com", "auth_domain": "gmail.com"}}]
A:
The example provided by Jader Dias works fine for my concern after some tweaking. Remove the encode method as it contains a circular reference. The adjusted class should look like:
import datetime
import time
from google.appengine.api import users
from google.appengine.ext import db
from django.utils import simplejson
class GqlEncoder(simplejson.JSONEncoder):
"""Extends JSONEncoder to add support for GQL results and properties.
Adds support to simplejson JSONEncoders for GQL results and properties by
overriding JSONEncoder's default method.
"""
# TODO Improve coverage for all of App Engine's Property types.
def default(self, obj):
"""Tests the input object, obj, to encode as JSON."""
if hasattr(obj, '__json__'):
return getattr(obj, '__json__')()
if isinstance(obj, db.GqlQuery):
return list(obj)
elif isinstance(obj, db.Model):
properties = obj.properties().items()
output = {}
for field, value in properties:
output[field] = getattr(obj, field)
return output
elif isinstance(obj, datetime.datetime):
output = {}
fields = ['day', 'hour', 'microsecond', 'minute', 'month', 'second', 'year']
methods = ['ctime', 'isocalendar', 'isoformat', 'isoweekday', 'timetuple']
for field in fields:
output[field] = getattr(obj, field)
for method in methods:
output[method] = getattr(obj, method)()
output['epoch'] = time.mktime(obj.timetuple())
return output
elif isinstance(obj, datetime.date):
output = {}
fields = ['year', 'month', 'day']
methods = ['ctime', 'isocalendar', 'isoformat', 'isoweekday', 'timetuple']
for field in fields:
output[field] = getattr(obj, field)
for method in methods:
output[method] = getattr(obj, method)()
output['epoch'] = time.mktime(obj.timetuple())
return output
elif isinstance(obj, time.struct_time):
return list(obj)
elif isinstance(obj, users.User):
output = {}
methods = ['nickname', 'email', 'auth_domain']
for method in methods:
output[method] = getattr(obj, method)()
return output
return simplejson.JSONEncoder.default(self, obj)
As I've saved this class in a file called utils.py and when appropriate I import it using
import utils
Then I just call utils.GqlEncoder().encode(results), for example:
query = User.all()
results = query.fetch(10)
self.response.headers['Content-Type'] = "text/plain" # Alt. application/json
self.response.out.write( utils.GqlEncoder().encode(results) )
The result should look something like this (I've added some line feeds in order to make it a bit easier to read):
[
{"date": {"ctime": "Tue Feb 23 10:41:21 2010", "hour": 10, "isoweekday": 2, "month": 2,
"second": 21, "microsecond": 495535, "isocalendar": [2010, 8, 2], "timetuple": [2010, 2, 23, 10, 41, 21, 1, 54, -1],
"year": 2010, "epoch": 1266921681.0, "isoformat": "2010-02-23T10:41:21.495535", "day": 23, "minute": 41},
"claimed_id": "https:\/\/www.google.com\/accounts\/o8\/id?id=abcdefghijklmnopqrstuvxyz",
"display_name": "Alfred E Neumann",
"email": null,
"full_name": "Alfred E Neumann"
},
{"date": {"ctime": "Tue Feb 23 11:00:54 2010", "hour": 11, "isoweekday": 2, "month": 2,
"second": 54, "microsecond": 805261, "isocalendar": [2010, 8, 2], "timetuple": [2010, 2, 23, 11, 0, 54, 1, 54, -1],
"year": 2010, "epoch": 1266922854.0, "isoformat": "2010-02-23T11:00:54.805261", "day": 23, "minute": 0},
"claimed_id": "http:\/\/openid.domain.net\/john",
"display_name": "",
"email": "jd@domain.net",
"full_name": "John Doe"
}
]
A:
json cannot be used to serialize anything more than basic types such as dicts, lists, ints/longs, and strings (this is not comprehensive). For example, even these simple commands do not work:
import json
json.dumps(object())
If you want to serialize django objects, you should refer to the django documentation on serialization, which will use their own libraries, but they do do support json.
A:
Since I could not find an appropriate solution I wrote my own, which is not exactly a JSON serializer, but a Javascript serializer
from google.appengine.ext import db
from google.appengine.api.datastore_types import *
def dumpStr(obj):
return "'" + obj + "'"
def dumps(obj):
if isinstance(obj, str):
return dumpStr(obj)
elif obj == None:
return None
elif isinstance(obj, list):
items = [];
for item in obj:
items.append(dumps(item))
return '[' + ','.join(items) + ']'
elif isinstance(obj, datetime.datetime):
return "new Date('%s')" % obj.ctime()
properties = [];
for property in dir(obj):
if property[0] != '_':
value = obj.__getattribute__(property)
valueClass = str(value.__class__)
if not(('function' in valueClass) or ('built' in valueClass) or ('method' in valueClass)):
value = dumps(value)
if value != None:
properties.append("'" + property + "':" + value)
if len(properties) == 0:
return str(obj)
else:
return '{' + ','.join(properties) + '}'
|
How to serialize db.Model objects to json?
|
When using
from django.utils import simplejson
on objects of types that derive from db.Model it throws exceptions. How to circumvent this?
|
[
"Ok - my python not great so any help would be appreciated - You dont need to write a parser - this is the solution:\nadd this utlity class http://code.google.com/p/google-app-engine-samples/source/browse/trunk/geochat/json.py?r=55 \n import datetime \n import time \n\n from google.appengine.api import users \n from google.appengine.ext import db \n\n#this is a mod on the orinal file for some reason it includes its own simplejson files i have ref django!\n from django.utils import simplejson \n\n class GqlEncoder(simplejson.JSONEncoder): \n\n \"\"\"Extends JSONEncoder to add support for GQL results and properties. \n\n Adds support to simplejson JSONEncoders for GQL results and properties by \n overriding JSONEncoder's default method. \n \"\"\" \n\n # TODO Improve coverage for all of App Engine's Property types. \n\n def default(self, obj): \n\n \"\"\"Tests the input object, obj, to encode as JSON.\"\"\" \n\n if hasattr(obj, '__json__'): \n return getattr(obj, '__json__')() \n\n if isinstance(obj, db.GqlQuery): \n return list(obj) \n\n elif isinstance(obj, db.Model): \n properties = obj.properties().items() \n output = {} \n for field, value in properties: \n output[field] = getattr(obj, field) \n return output \n\n elif isinstance(obj, datetime.datetime): \n output = {} \n fields = ['day', 'hour', 'microsecond', 'minute', 'month', 'second', \n 'year'] \n methods = ['ctime', 'isocalendar', 'isoformat', 'isoweekday', \n 'timetuple'] \n for field in fields: \n output[field] = getattr(obj, field) \n for method in methods: \n output[method] = getattr(obj, method)() \n output['epoch'] = time.mktime(obj.timetuple()) \n return output \n\n elif isinstance(obj, time.struct_time): \n return list(obj) \n\n elif isinstance(obj, users.User): \n output = {} \n methods = ['nickname', 'email', 'auth_domain'] \n for method in methods: \n output[method] = getattr(obj, method)() \n return output \n\n return simplejson.JSONEncoder.default(self, obj) \n\n\n def encode(input): \n \"\"\"Encode an input GQL object as JSON \n\n Args: \n input: A GQL object or DB property. \n\n Returns: \n A JSON string based on the input object. \n\n Raises: \n TypeError: Typically occurs when an input object contains an unsupported \n type. \n \"\"\" \n return GqlEncoder().encode(input) \n\nsave as json.py\nTO USE\nimport cgi\nimport os\nimport json \n\nfrom google.appengine.ext.webapp import template\nfrom google.appengine.api import users\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom google.appengine.ext import db\n\n\nclass Greeting(db.Model):\n author = db.UserProperty()\n content = db.StringProperty(multiline=True)\n date = db.DateTimeProperty(auto_now_add=True)\n\nclass MainPage(webapp.RequestHandler):\n def get(self):\n greetings_query = Greeting.all().order('-date')\n greetings = greetings_query.fetch(5)\n\n if users.get_current_user():\n url = users.create_logout_url(self.request.uri)\n url_linktext = 'Logout'\n else:\n url = users.create_login_url(self.request.uri)\n url_linktext = 'Login'\n\n template_values = {\n 'greetings': greetings,\n 'url': url,\n 'url_linktext': url_linktext,\n }\n\n path = os.path.join(os.path.dirname(__file__), 'index.html')\n self.response.out.write(template.render(path, template_values))\n\n\nclass Guestbook(webapp.RequestHandler):\n def post(self):\n greeting = Greeting()\n\n if users.get_current_user():\n greeting.author = users.get_current_user()\n\n greeting.content = self.request.get('content')\n greeting.put()\n self.redirect('/')\n\n\n\n#here i return my json feed - simple implementaion for example\nclass FeedHandler(webapp.RequestHandler):\n\n def get(self):\n \"\"\"Retrieve a feed\"\"\"\n user = None\n\n greetings_query = Greeting.all().order('-date')\n rs= greetings_query.fetch(5)\n#this is the part that calls the encoder - dosnt cause an exception\n data = json.encode(rs)\n\n\n\n#roll out to browser -might need to check my headers etc\n self.response.headers['Content-Type'] = 'application/json; charset=utf-8' \n self.response.out.write(data)\n\n\n\n\napplication = webapp.WSGIApplication(\n [\n ('/', MainPage),\n ('/sign',Guestbook),\n ('/feed',FeedHandler),\n ], debug=True\n )\n\ndef main():\n run_wsgi_app(application)\n\nif __name__ == \"__main__\":\n main()\n\nThis is the browser response:\n\n[{\"content\": \"\", \"date\": {\"ctime\": \"Sat Jan 23 02:40:22 2010\", \"hour\": 2, \"isoweekday\": 6, \"month\": 1, \"second\": 22, \"microsecond\": 434000, \"isocalendar\": [2010, 3, 6], \"timetuple\": [2010, 1, 23, 2, 40, 22, 5, 23, -1], \"year\": 2010, \"epoch\": 1264214422.0, \"isoformat\": \"2010-01-23T02:40:22.434000\", \"day\": 23, \"minute\": 40}, \"author\": {\"nickname\": \"test@example.com\", \"email\": \"test@example.com\", \"auth_domain\": \"gmail.com\"}}, {\"content\": \"\", \"date\": {\"ctime\": \"Sat Jan 23 01:12:43 2010\", \"hour\": 1, \"isoweekday\": 6, \"month\": 1, \"second\": 43, \"microsecond\": 972000, \"isocalendar\": [2010, 3, 6], \"timetuple\": [2010, 1, 23, 1, 12, 43, 5, 23, -1], \"year\": 2010, \"epoch\": 1264209163.0, \"isoformat\": \"2010-01-23T01:12:43.972000\", \"day\": 23, \"minute\": 12}, \"author\": {\"nickname\": \"test@example.com\", \"email\": \"test@example.com\", \"auth_domain\": \"gmail.com\"}}, {\"content\": \"test\", \"date\": {\"ctime\": \"Fri Jan 22 22:32:13 2010\", \"hour\": 22, \"isoweekday\": 5, \"month\": 1, \"second\": 13, \"microsecond\": 659000, \"isocalendar\": [2010, 3, 5], \"timetuple\": [2010, 1, 22, 22, 32, 13, 4, 22, -1], \"year\": 2010, \"epoch\": 1264199533.0, \"isoformat\": \"2010-01-22T22:32:13.659000\", \"day\": 22, \"minute\": 32}, \"author\": {\"nickname\": \"test@example.com\", \"email\": \"test@example.com\", \"auth_domain\": \"gmail.com\"}}, {\"content\": \"\", \"date\": {\"ctime\": \"Fri Jan 22 22:29:49 2010\", \"hour\": 22, \"isoweekday\": 5, \"month\": 1, \"second\": 49, \"microsecond\": 358000, \"isocalendar\": [2010, 3, 5], \"timetuple\": [2010, 1, 22, 22, 29, 49, 4, 22, -1], \"year\": 2010, \"epoch\": 1264199389.0, \"isoformat\": \"2010-01-22T22:29:49.358000\", \"day\": 22, \"minute\": 29}, \"author\": {\"nickname\": \"test@example.com\", \"email\": \"test@example.com\", \"auth_domain\": \"gmail.com\"}}, {\"content\": \"ah it works!\\r\\n\", \"date\": {\"ctime\": \"Fri Jan 22 22:29:22 2010\", \"hour\": 22, \"isoweekday\": 5, \"month\": 1, \"second\": 22, \"microsecond\": 995000, \"isocalendar\": [2010, 3, 5], \"timetuple\": [2010, 1, 22, 22, 29, 22, 4, 22, -1], \"year\": 2010, \"epoch\": 1264199362.0, \"isoformat\": \"2010-01-22T22:29:22.995000\", \"day\": 22, \"minute\": 29}, \"author\": {\"nickname\": \"test@example.com\", \"email\": \"test@example.com\", \"auth_domain\": \"gmail.com\"}}]\n\n",
"The example provided by Jader Dias works fine for my concern after some tweaking. Remove the encode method as it contains a circular reference. The adjusted class should look like:\nimport datetime \nimport time \n\nfrom google.appengine.api import users \nfrom google.appengine.ext import db \nfrom django.utils import simplejson \n\n\nclass GqlEncoder(simplejson.JSONEncoder): \n\n \"\"\"Extends JSONEncoder to add support for GQL results and properties. \n\n Adds support to simplejson JSONEncoders for GQL results and properties by \n overriding JSONEncoder's default method. \n \"\"\" \n\n # TODO Improve coverage for all of App Engine's Property types. \n\n def default(self, obj): \n\n \"\"\"Tests the input object, obj, to encode as JSON.\"\"\" \n\n if hasattr(obj, '__json__'): \n return getattr(obj, '__json__')() \n\n if isinstance(obj, db.GqlQuery): \n return list(obj) \n \n elif isinstance(obj, db.Model): \n properties = obj.properties().items() \n output = {} \n for field, value in properties: \n output[field] = getattr(obj, field) \n return output \n \n elif isinstance(obj, datetime.datetime): \n output = {} \n fields = ['day', 'hour', 'microsecond', 'minute', 'month', 'second', 'year'] \n methods = ['ctime', 'isocalendar', 'isoformat', 'isoweekday', 'timetuple'] \n for field in fields: \n output[field] = getattr(obj, field) \n for method in methods: \n output[method] = getattr(obj, method)() \n output['epoch'] = time.mktime(obj.timetuple()) \n return output\n\n elif isinstance(obj, datetime.date): \n output = {} \n fields = ['year', 'month', 'day'] \n methods = ['ctime', 'isocalendar', 'isoformat', 'isoweekday', 'timetuple'] \n for field in fields: \n output[field] = getattr(obj, field) \n for method in methods: \n output[method] = getattr(obj, method)() \n output['epoch'] = time.mktime(obj.timetuple()) \n return output \n \n elif isinstance(obj, time.struct_time): \n return list(obj) \n \n elif isinstance(obj, users.User): \n output = {} \n methods = ['nickname', 'email', 'auth_domain'] \n for method in methods: \n output[method] = getattr(obj, method)() \n return output \n \n return simplejson.JSONEncoder.default(self, obj) \n\nAs I've saved this class in a file called utils.py and when appropriate I import it using\nimport utils\n\nThen I just call utils.GqlEncoder().encode(results), for example:\nquery = User.all()\nresults = query.fetch(10)\n \nself.response.headers['Content-Type'] = \"text/plain\" # Alt. application/json\nself.response.out.write( utils.GqlEncoder().encode(results) )\n\nThe result should look something like this (I've added some line feeds in order to make it a bit easier to read):\n[\n{\"date\": {\"ctime\": \"Tue Feb 23 10:41:21 2010\", \"hour\": 10, \"isoweekday\": 2, \"month\": 2, \n \"second\": 21, \"microsecond\": 495535, \"isocalendar\": [2010, 8, 2], \"timetuple\": [2010, 2, 23, 10, 41, 21, 1, 54, -1], \n \"year\": 2010, \"epoch\": 1266921681.0, \"isoformat\": \"2010-02-23T10:41:21.495535\", \"day\": 23, \"minute\": 41}, \n\"claimed_id\": \"https:\\/\\/www.google.com\\/accounts\\/o8\\/id?id=abcdefghijklmnopqrstuvxyz\", \n\"display_name\": \"Alfred E Neumann\", \n\"email\": null, \n\"full_name\": \"Alfred E Neumann\"\n}, \n{\"date\": {\"ctime\": \"Tue Feb 23 11:00:54 2010\", \"hour\": 11, \"isoweekday\": 2, \"month\": 2, \n \"second\": 54, \"microsecond\": 805261, \"isocalendar\": [2010, 8, 2], \"timetuple\": [2010, 2, 23, 11, 0, 54, 1, 54, -1], \n \"year\": 2010, \"epoch\": 1266922854.0, \"isoformat\": \"2010-02-23T11:00:54.805261\", \"day\": 23, \"minute\": 0}, \n\"claimed_id\": \"http:\\/\\/openid.domain.net\\/john\", \n\"display_name\": \"\", \n\"email\": \"jd@domain.net\", \n\"full_name\": \"John Doe\"\n}\n]\n\n",
"json cannot be used to serialize anything more than basic types such as dicts, lists, ints/longs, and strings (this is not comprehensive). For example, even these simple commands do not work:\nimport json\njson.dumps(object())\n\nIf you want to serialize django objects, you should refer to the django documentation on serialization, which will use their own libraries, but they do do support json.\n",
"Since I could not find an appropriate solution I wrote my own, which is not exactly a JSON serializer, but a Javascript serializer\nfrom google.appengine.ext import db\nfrom google.appengine.api.datastore_types import *\n\ndef dumpStr(obj):\n return \"'\" + obj + \"'\"\n\ndef dumps(obj):\n if isinstance(obj, str):\n return dumpStr(obj)\n elif obj == None:\n return None\n elif isinstance(obj, list):\n items = [];\n for item in obj:\n items.append(dumps(item))\n return '[' + ','.join(items) + ']'\n elif isinstance(obj, datetime.datetime):\n return \"new Date('%s')\" % obj.ctime()\n properties = [];\n for property in dir(obj):\n if property[0] != '_':\n value = obj.__getattribute__(property)\n valueClass = str(value.__class__)\n if not(('function' in valueClass) or ('built' in valueClass) or ('method' in valueClass)):\n value = dumps(value)\n if value != None:\n properties.append(\"'\" + property + \"':\" + value)\n if len(properties) == 0:\n return str(obj)\n else:\n return '{' + ','.join(properties) + '}'\n\n"
] |
[
14,
10,
3,
0
] |
[
"From what i can understand - and i am new to python - with google app engine the work around is to serialize the model object to a dictioanry python object and then use simple json to dump it as a json string - this makes no sense to me - maybe someone has the know to serialise to a ditionary (pickel?)\nAny help on this would be HELP! not to impressed that google app engine has no inbuilt solution for this.\n"
] |
[
-1
] |
[
"google_app_engine",
"python",
"simplejson"
] |
stackoverflow_0002114659_google_app_engine_python_simplejson.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.