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:
Google Static Maps API: representing a route as an encoded polyline
I'm trying to represent a route between a number of points on a static map using an encoded polyline. The code for this is in a function called getStaticMapAddress, defined like so:
def getStaticMapAddress(self, route):
destUser = DestUser(sel... | Google Static Maps API: representing a route as an encoded polyline | I'm trying to represent a route between a number of points on a static map using an encoded polyline. The code for this is in a function called getStaticMapAddress, defined like so:
def getStaticMapAddress(self, route):
destUser = DestUser(self.destination)
route += [destUser]
attempts = 0
while attempt... | [
"Random guess: you've accidentally swapped the longitude and latitude arguments.\n"
] | [
4
] | [] | [] | [
"geocoding",
"google_static_maps",
"polyline",
"python"
] | stackoverflow_0005215026_geocoding_google_static_maps_polyline_python.txt |
Q:
Redirecting django manage.py output (in windows) to a text file
I'm trying to redirect the output from manage.py to a text file, but only some output is getting redirected to the text file. How do I redirect all output to the text file?
My command prompt:
C:\Development\web-py\p1st2\pianos1st-system>python manage... | Redirecting django manage.py output (in windows) to a text file | I'm trying to redirect the output from manage.py to a text file, but only some output is getting redirected to the text file. How do I redirect all output to the text file?
My command prompt:
C:\Development\web-py\p1st2\pianos1st-system>python manage.py test > test_results.txt
............................................ | [
"Certain types of console messages will bypass the output redirection (or whatever using \">\" is called). I noticed that sys.stderr.write() for instance did this.\nAdding a \"2>&1\" at the end helps with this: \npython manage.py test purchaseplans > test_results.txt 2>&1\n\nEdit: Explanation of what is going on:... | [
26
] | [] | [] | [
"command_line",
"django",
"python",
"stdout",
"windows"
] | stackoverflow_0005215106_command_line_django_python_stdout_windows.txt |
Q:
django many-to-many compare
Is any way to compare two ManyToMany relationship from a different models?
I have a model Days in common and with this other two models:
Ticket (The Ticket has a m2m relation with Days)
Check (The check has a m2m relation with Days)
I can do it with two for what don't look really pret... | django many-to-many compare | Is any way to compare two ManyToMany relationship from a different models?
I have a model Days in common and with this other two models:
Ticket (The Ticket has a m2m relation with Days)
Check (The check has a m2m relation with Days)
I can do it with two for what don't look really pretty or readable.
| [
"If i'm reading your question correctly, you can achieve what you are asking for by defining related names in the m2m declarations in the Ticket and Check models and then comparing querysets\nexample:\nclass Day(models.Model):\n day = models.DateField()\n\nclass Ticket(models.Model):\n ticket_name = models.Ch... | [
1,
0
] | [] | [] | [
"compare",
"django",
"many_to_many",
"python"
] | stackoverflow_0005206254_compare_django_many_to_many_python.txt |
Q:
how to do regular expression replacer function in java?
In python , I can use a replacer function in sub(), that is very powerful for some situation, like this:
def replacer(match):
s = match.group(0)
if s.startswith('/'):
return ""
else:
return s
return re.sub(pattern, replacer, text)
... | how to do regular expression replacer function in java? | In python , I can use a replacer function in sub(), that is very powerful for some situation, like this:
def replacer(match):
s = match.group(0)
if s.startswith('/'):
return ""
else:
return s
return re.sub(pattern, replacer, text)
how to do this in Java?
| [
"In Java, there is an idiom:\nPattern pattern = Pattern.compile(yourPattern);\nMatcher matcher = patern.matcher(yourString);\nwhile (matcher.find()) {\n String group = matcher.group(0);\n // do your if statement\n}\n\nOne tip that's not readily apparent from the documentation - if yourString has special (reg exp)... | [
4,
1
] | [] | [] | [
"java",
"python",
"regex"
] | stackoverflow_0005215227_java_python_regex.txt |
Q:
Get the address of a ctypes object
I have a buffer like:
bufstr = ctypes.create_string_buffer("Test", 32)
How I obtain the address of that buffer? i.e. the one displayed if I do:
print bufstr
like:
<ctypes.c_char_Array_32 object at 0x042ACAD0>
I know I can pass it with byref(), for example; but what if I just w... | Get the address of a ctypes object | I have a buffer like:
bufstr = ctypes.create_string_buffer("Test", 32)
How I obtain the address of that buffer? i.e. the one displayed if I do:
print bufstr
like:
<ctypes.c_char_Array_32 object at 0x042ACAD0>
I know I can pass it with byref(), for example; but what if I just want to get that address (aside from slic... | [
"Use ctypes.addressof.\nctypes.addressof(bufstr)\n\n",
"I believe:\nctypes.addressof(bufstr)\n\nshould do it. Note that the address mentioned in toString is for the Python object, not the C memory.\n"
] | [
11,
5
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0005215391_ctypes_python.txt |
Q:
Python dependencies?
Is it possible to programmatically detect dependencies given a python project residing in SVN?
A:
Here is a twist which adds some precision, and which might be useful if you find you're frequently checking dependencies of miscellaneous code:
Catches only import statements executed by the co... | Python dependencies? | Is it possible to programmatically detect dependencies given a python project residing in SVN?
| [
"Here is a twist which adds some precision, and which might be useful if you find you're frequently checking dependencies of miscellaneous code:\n\nCatches only import statements executed by the code being analyzed.\nAutomatically excludes all system-loaded modules, so you don't have to weed through it.\nAlso repor... | [
4,
0,
0
] | [] | [] | [
"dependencies",
"detection",
"python",
"svn"
] | stackoverflow_0005215195_dependencies_detection_python_svn.txt |
Q:
in python for loop,, jump over values
time=0
gold=0
level=1
for time in range(100):
gold+=level
if gold>20*level:
level+=1
time+=10
with this program gold is added until it reaches a critical amount, then it takes 20s to upgrade a mine so it produces more gold. i'd like to skip those 20s (or 20 steps)... | in python for loop,, jump over values | time=0
gold=0
level=1
for time in range(100):
gold+=level
if gold>20*level:
level+=1
time+=10
with this program gold is added until it reaches a critical amount, then it takes 20s to upgrade a mine so it produces more gold. i'd like to skip those 20s (or 20 steps) in the loop? this works in c++, i'm not su... | [
"Don't do it in range(100). The for loop doesn't offer a way to skip ahead like that; time will be set to the next value in the list regardless of what you change it to in the body of the loop. Use a while loop instead, e.g.\ntime = 0\nwhile time < 100:\n gold += level\n if gold > 20 * level:\n level +=1\n... | [
17,
1,
1
] | [] | [] | [
"for_loop",
"python",
"range"
] | stackoverflow_0005215530_for_loop_python_range.txt |
Q:
Parsing atom response from InsertCalendar in Python on GAE (Calendar API)
Using the GData Calendar API via App Engine in Python, when you create an event there are handy little helper methods to parse the response:
new_event = calendar_service.InsertEvent(event, '/calendar/feeds/default/private/full')
helper = new... | Parsing atom response from InsertCalendar in Python on GAE (Calendar API) | Using the GData Calendar API via App Engine in Python, when you create an event there are handy little helper methods to parse the response:
new_event = calendar_service.InsertEvent(event, '/calendar/feeds/default/private/full')
helper = new_event.GetEditLink().href
When you create a new calendar:
new_calendar = gd_cl... | [
"I've never used the GData API, so I could be wrong, but...\nIt looks like GetLink() will return the link object for any specified rel. Seems like GetEditLink() just calls GetLink(), passing in the rel of the Edit link. So you should be able to call GetLink() on the response from InsertCalendar(), and pass in the... | [
0
] | [] | [] | [
"google_app_engine",
"google_calendar_api",
"google_data_api",
"python"
] | stackoverflow_0004948864_google_app_engine_google_calendar_api_google_data_api_python.txt |
Q:
Python to fill out web forum
I am trying to use python to login to this page(which i own!) http://ninitelist.yolasite.com/passprotected.php
and return true if a password is correct and false if the password is wrong. I am at a total loss of how to do this, oh and please dont suggest mechanize, i cant figure out ho... | Python to fill out web forum | I am trying to use python to login to this page(which i own!) http://ninitelist.yolasite.com/passprotected.php
and return true if a password is correct and false if the password is wrong. I am at a total loss of how to do this, oh and please dont suggest mechanize, i cant figure out how to install it. Thanks very much!... | [
"You can use Python's urllib to POST form data.\nimport urllib\ndef try_login(username, password):\n params = urllib.urlencode(\n {'username': username,\n 'password': password })\n f = urllib.urlopen(\"http://ninitelist.yolasite.com/passprotected.php\", params)\n return \"Invalid log... | [
2
] | [] | [] | [
"fill",
"forum",
"python"
] | stackoverflow_0005215657_fill_forum_python.txt |
Q:
python appscript module - creating k. type objects
I'm learning and enjoying the appscript module, but I'm a little confused
about how to instantiate basic k. type objects.
for example, if I want to create a variable that holds a k.boolean value to
use while scripting an application,
how do I create it, and then p... | python appscript module - creating k. type objects | I'm learning and enjoying the appscript module, but I'm a little confused
about how to instantiate basic k. type objects.
for example, if I want to create a variable that holds a k.boolean value to
use while scripting an application,
how do I create it, and then pass it to the set() method of a property
within that app... | [
"Appscript will perform casts from Python types to the Apple Event types internally, so you can use a normal Python bool variable:\nMake the layer visible:\nflag = True\nlayer.visible.set(flag)\n\nToggle the layer on/off:\nflag = not layer.visible.get()\nlayer.visible.set(flag)\n\nThe Python type -> AE type mapping... | [
2
] | [] | [] | [
"macos",
"py_appscript",
"python",
"sourceforge_appscript"
] | stackoverflow_0005209851_macos_py_appscript_python_sourceforge_appscript.txt |
Q:
Django 1.2.3 compatible with python 2.5.2 ? Weird django behaviour
Well main question of the day will django work correctly under python 2.5.2 ?
So why i am asking this question?
First of all i have some test class written , nothing special which renders a page. The problem is that everytime i access this page i ... | Django 1.2.3 compatible with python 2.5.2 ? Weird django behaviour | Well main question of the day will django work correctly under python 2.5.2 ?
So why i am asking this question?
First of all i have some test class written , nothing special which renders a page. The problem is that everytime i access this page i get random 3 different responses :
1)exceptions must be classes, instanc... | [
"Yes, it is compatible:\nhttp://docs.djangoproject.com/en/dev/releases/1.2/#python-compatibility\nPost your class -- there could be thousands of reasons it's not working correctly.\nPyCharm and your host not updating files on your host would have nothing to do with Python or Django, but rather PyCharm and how it's ... | [
0,
0,
0
] | [] | [] | [
"django",
"python",
"rendering"
] | stackoverflow_0005211338_django_python_rendering.txt |
Q:
Determine current Mac Chrome web page using Python
Is there a way to determine programmatically, using Python, which web page is currently active in Google Chrome?
A:
Google Chrome for Mac has added the AppleScripting method for getting the URL.
Here's the Chromium AppleScript SDK
https://sites.google.com/a/chro... | Determine current Mac Chrome web page using Python | Is there a way to determine programmatically, using Python, which web page is currently active in Google Chrome?
| [
"Google Chrome for Mac has added the AppleScripting method for getting the URL.\nHere's the Chromium AppleScript SDK\nhttps://sites.google.com/a/chromium.org/dev/developers/design-documents/applescript\nExample from the page linked below:\ntell application \"Google Chrome\"\n get URL of active tab of window 1\nen... | [
2,
0
] | [] | [] | [
"google_chrome",
"macos",
"python"
] | stackoverflow_0002425098_google_chrome_macos_python.txt |
Q:
Strange behavior from HTTP authentication with suds SOAP library
I have a working python program that is fetching a large volume of data via SOAP using suds. The web service is implemented with a paging function such that I can grab nnn rows with each fetch call and grab the next nnn with subsequent calls. If I ... | Strange behavior from HTTP authentication with suds SOAP library | I have a working python program that is fetching a large volume of data via SOAP using suds. The web service is implemented with a paging function such that I can grab nnn rows with each fetch call and grab the next nnn with subsequent calls. If I authenticate to the HTTP server with code like the following
client =... | [
"The problem seems to be that an urllib2.HTTPError is being raised from a lower level, and its fp attribute is None:\nLine 81 in suds.transport.http:\nexcept u2.HTTPError, e:\n if e.code in (202,204):\n result = None\n else:\n raise TransportError(e.msg, e.code, e.fp)\n\nThat exception eventuall... | [
10
] | [] | [] | [
"python",
"suds"
] | stackoverflow_0005201037_python_suds.txt |
Q:
app engine cron jobs not running in production
I just uploaded my application to app engine and everything seems to be working correctly except that the cron jobs are not running. I have a cron.yaml file in my root directory which is basically:
cron:
- description: do stuff
url: /cron/dostuff
schedule: every 1... | app engine cron jobs not running in production | I just uploaded my application to app engine and everything seems to be working correctly except that the cron jobs are not running. I have a cron.yaml file in my root directory which is basically:
cron:
- description: do stuff
url: /cron/dostuff
schedule: every 1 minutes
- description: do other stuff
url: /cron... | [
"Got it figured out. \"days\" on its own without a specified time is not a valid schedule. I needed to change that to \"every 24 hours\" or \"every day 00:00\". Would be great if the docs on cron.yaml were a little more clear about the options.\n"
] | [
3
] | [] | [] | [
"google_app_engine",
"python",
"yaml"
] | stackoverflow_0005214171_google_app_engine_python_yaml.txt |
Q:
python: wmi: Why Win32_Processor LoadPercentage on remote servers returns 'None'?
Why when I run this query on a remote server's CPU's LoadPercentage, it return 'None'?
import wmi
c = wmi.WMI('192.168.1.11',user='user',password='password')
x = [cpu.LoadPercentage for cpu in c.Win32_Processor()]
print str(x)
Retur... | python: wmi: Why Win32_Processor LoadPercentage on remote servers returns 'None'? | Why when I run this query on a remote server's CPU's LoadPercentage, it return 'None'?
import wmi
c = wmi.WMI('192.168.1.11',user='user',password='password')
x = [cpu.LoadPercentage for cpu in c.Win32_Processor()]
print str(x)
Returns: 'None'
The remote server is Win7 machine. What needs to be enabled in that particu... | [
"this worked: i.e. at cmd --> lodctr /r\n[link] http://answers.microsoft.com/en-us/windows/forum/windows_7-performance/perfmon-problems-unable-to-add-counters/e90f231d-0014-457d-8b1f-5f342971597a\n"
] | [
0
] | [] | [] | [
"processor",
"python",
"wmi"
] | stackoverflow_0005088947_processor_python_wmi.txt |
Q:
Custom Python string codec with different-length characters?
Is it possible to make a custom Python codec with pure-python code where a character of that codec can be more than one regular str or unicode character, like the way that in the "unicode" encoding in Python 2.x, two ASCII characters can be one unicode c... | Custom Python string codec with different-length characters? | Is it possible to make a custom Python codec with pure-python code where a character of that codec can be more than one regular str or unicode character, like the way that in the "unicode" encoding in Python 2.x, two ASCII characters can be one unicode character? (So, for example, '.' in '%.' would be false if '.' and ... | [
"You can certainly come up with a custom encoding which uses more than one byte to represent a single character. One example of this is UTF-8.\nThe Python str type stores bytes and has no knowledge of the encoding scheme used to produce those bytes. For example, UTF-8 uses 2 bytes to represent the unicode character... | [
2
] | [] | [] | [
"character_encoding",
"python"
] | stackoverflow_0005216188_character_encoding_python.txt |
Q:
unexpected EOF while parsing
while True:
no=input()
if no=='':
break
else:
split_change(no)
This gives EOF error, how to check for EOF while getting input from std input ?
A:
How about this:
while True:
try:
no=raw_input()
if no=='':
break
else:
... | unexpected EOF while parsing | while True:
no=input()
if no=='':
break
else:
split_change(no)
This gives EOF error, how to check for EOF while getting input from std input ?
| [
"How about this:\n while True:\n try:\n no=raw_input()\n if no=='':\n break\n else:\n split_change(no)\n except EOFError:\n break\n\nEDIT: changed input() to raw_input(), and realized that you have to use try/except otherwise you still get the error.\nEDIT2: Changed 1 to Tru... | [
2
] | [] | [] | [
"python"
] | stackoverflow_0005217258_python.txt |
Q:
Python - Add Formatted Number To String
Using Python v2, I have the following code:
print ("Total of the sale is: ${:,.2f}".format(TotalAmount))
This is taking the string called "TotalAmount" and formatting it so that it looks like this: $100.00, ie: a monetary value, no matter what the number is.
Is there a way ... | Python - Add Formatted Number To String | Using Python v2, I have the following code:
print ("Total of the sale is: ${:,.2f}".format(TotalAmount))
This is taking the string called "TotalAmount" and formatting it so that it looks like this: $100.00, ie: a monetary value, no matter what the number is.
Is there a way to write the formatted output to a string?
Th... | [
"yourVar = \"Total of the sale is: ${:,.2f}\".format(TotalAmount)\n\n",
"Just save it to a variable, instead of passing it to print.\n>>> dog = \"doggy\"\n>>> pets = \"cat and %s\" % dog\n>>> print pets\ncat and doggy\n\n",
"Try this to format with 2 digits after decimal pt:\nfor amt in (123.45, 5, 100):\n v... | [
5,
0,
0,
0
] | [] | [] | [
"format",
"python",
"string"
] | stackoverflow_0005214666_format_python_string.txt |
Q:
is python as capable as other languages like c++?
i am looking to start learning. people have told me it is juts as capable. though i haven't really seen any good looking games available. some decent ones on pygame, but none really stand out.
i would like to know if python really is as capable as other languages.
... | is python as capable as other languages like c++? | i am looking to start learning. people have told me it is juts as capable. though i haven't really seen any good looking games available. some decent ones on pygame, but none really stand out.
i would like to know if python really is as capable as other languages.
EDIT: thanks guys, is python good for game development?... | [
"Each language has strengths and weaknesses.\nAlso, each implementation of a language has strengths and weaknesses. CPython is not the same as Jython and PyPy is different again.\nPython is very good in the \"business logic-to-lines of code\" ratio: it has a pretty succinct way of putting things.\nC++ is good at lo... | [
5,
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0005217513_python.txt |
Q:
General approach for using Twisted in background to proxy TCP socket?
I'm looking for some general information on how I should approach a problem that I think Twisted is a great fit for. (I'm new to Twisted but not Python)
I have a home automation controller that can support a single TCP socket connection, sending... | General approach for using Twisted in background to proxy TCP socket? | I'm looking for some general information on how I should approach a problem that I think Twisted is a great fit for. (I'm new to Twisted but not Python)
I have a home automation controller that can support a single TCP socket connection, sending and receiving binary data. I'd like to use XMPP as a bridge to the socket ... | [
"One of the problems with a non-blocking IO engine is that its pretty much all-or-nothing. As soon as you introduce blocking code, you can quickly lose most of the benefits of the event-driven asynch approach. Wherever possible (as a rule of thumb), its best to have the entire app running off the same reactor.\nAs ... | [
1
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0005205107_python_twisted.txt |
Q:
Store jpg, gif, png, etc it gae-datastore
I found an example on how to store png in datastore:
img = images.Image(img_data)
# Basically, we just want to make sure it's a PNG
# since we don't have a good way to determine image type
# through the API, but the API throws an exception
# if you don't do any t... | Store jpg, gif, png, etc it gae-datastore | I found an example on how to store png in datastore:
img = images.Image(img_data)
# Basically, we just want to make sure it's a PNG
# since we don't have a good way to determine image type
# through the API, but the API throws an exception
# if you don't do any transforms, so go ahead and use im_feeling_lucky... | [
"The quick answer\nYou can store binary data of any file type by using db.BlobProperty() in your model.\nIf you use the Image API to manipulate the image data, you're limited to inputting .jpg, .png, .gif, .bmp, .tiff, and .ico types, and outputting to either .jpg or .png.\n\nStoring images\nTo simply store the im... | [
7,
3
] | [] | [] | [
"file_upload",
"google_app_engine",
"image",
"python"
] | stackoverflow_0005211780_file_upload_google_app_engine_image_python.txt |
Q:
How to parse code (in Python)?
I need to parse some special data structures. They are in some somewhat-like-C format that looks roughly like this:
Group("GroupName") {
/* C-Style comment */
Group("AnotherGroupName") {
Entry("some","variables",0,3.141);
Entry("other","variables",1,2.718);
... | How to parse code (in Python)? | I need to parse some special data structures. They are in some somewhat-like-C format that looks roughly like this:
Group("GroupName") {
/* C-Style comment */
Group("AnotherGroupName") {
Entry("some","variables",0,3.141);
Entry("other","variables",1,2.718);
}
Entry("linebreaks",
... | [
"Using pyparsing (Mark Tolonen, I was just about to click \"Submit Post\" when your post came thru), this is pretty straightforward - see comments embedded in the code below:\ndata = \"\"\"Group(\"GroupName\") { \n /* C-Style comment */ \n Group(\"AnotherGroupName\") { \n Entry(\"some\",\"variables\",0... | [
7,
2,
1
] | [] | [] | [
"data_structures",
"parsing",
"python"
] | stackoverflow_0005217386_data_structures_parsing_python.txt |
Q:
Python - slice array until certain condition is met
I need to slice an array from a given index until a certain condition is met.
>>> a = numpy.zeros((10), dtype='|S1')
>>> a[2] = 'A'
>>> a[4] = 'X'
>>> a[8] = 'B'
>>> a
array(['', '', 'A', '', 'X', '', '', '', 'B', ''], dtype='|S1')
For instance, for the above ar... | Python - slice array until certain condition is met | I need to slice an array from a given index until a certain condition is met.
>>> a = numpy.zeros((10), dtype='|S1')
>>> a[2] = 'A'
>>> a[4] = 'X'
>>> a[8] = 'B'
>>> a
array(['', '', 'A', '', 'X', '', '', '', 'B', ''], dtype='|S1')
For instance, for the above array I want a subset from a given index until first non-ze... | [
"If you set up your problem like this:\nimport numpy\na = numpy.zeros((10), dtype=str)\na[2] = 'A'\na[4] = 'X'\na[8] = 'B'\n\nYou can easily get the indices of non-empty strings like so:\ni = numpy.where(a!='')[0] # array([2, 4, 8])\n\nAlternatively, numpy.argwhere(..) also works well.\nThen you can slice away usi... | [
7,
6,
2,
0
] | [
"def getSlice(a, n):\n try:\n startindex = a[:n].nonzero()[0][-1]\n except IndexError:\n startindex = 0\n try:\n endindex = a[(n+1):].nonzero()[0][0] + n+1\n except IndexError:\n endindex = len(a)\n return a[startindex: endindex]\n\n"
] | [
-2
] | [
"arrays",
"numpy",
"python",
"slice"
] | stackoverflow_0005216260_arrays_numpy_python_slice.txt |
Q:
Find and append each reference to a html link - Python
I have a HTML file I got from Wikipedia and would like to find every link on the page such as /wiki/Absinthe and replace it with the current directory added to the front such as /home/fergus/wikiget/wiki/Absinthe so for:
<a href="/wiki/Absinthe">Absinthe</a>
... | Find and append each reference to a html link - Python | I have a HTML file I got from Wikipedia and would like to find every link on the page such as /wiki/Absinthe and replace it with the current directory added to the front such as /home/fergus/wikiget/wiki/Absinthe so for:
<a href="/wiki/Absinthe">Absinthe</a>
becomes:
<a href="/home/fergus/wikiget/wiki/Absinthe">Absint... | [
"If that's really all you have to do, you could do it with sed and its -i option to rewrite the file in-place:\nsed -e 's,href=\"/wiki,href=\"/home/fergus/wikiget/wiki,' wiki-file.html\n\nHowever, here's a Python solution using the lovely lxml API, in case you need to do anything more complex or you might have badl... | [
2,
1,
1,
0,
0
] | [] | [] | [
"beautifulsoup",
"html",
"python",
"regex"
] | stackoverflow_0005217760_beautifulsoup_html_python_regex.txt |
Q:
How to replace string values inside plpython?
Hi i need to replace value into null value in plpython, but how can i do that?Can somebody help?
for example inside plpython sql i wrote.
aa = 'World 123'
bb = aa.replace('World ', '')
rv = plpy.execute("SELECT id FROM ABC WHERE name ilike '" + bb + "';" )
But it do... | How to replace string values inside plpython? | Hi i need to replace value into null value in plpython, but how can i do that?Can somebody help?
for example inside plpython sql i wrote.
aa = 'World 123'
bb = aa.replace('World ', '')
rv = plpy.execute("SELECT id FROM ABC WHERE name ilike '" + bb + "';" )
But it doesnot work;
if i use replace (aa,''), it shows erro... | [
"replace is in the string namespace, so it can only be called on strings. Calling replace in the global namespace would not make much sense as you are not providing it with the original text upon which to perform the replacement.\n"
] | [
1
] | [] | [] | [
"plpgsql",
"python"
] | stackoverflow_0005218822_plpgsql_python.txt |
Q:
learn python the hard way exercise 18 help
i understand all the functions except the first one. whats the (*args) mean?
thanks
def print_twice(*args):
arg1, arg2 = args
print 'arg1: %r arg2: %r' % (arg1, arg2)
def print_twice_again(arg1, arg2):
print 'arg1: %r arg2: %r' % (arg1, arg2)
def print_once(... | learn python the hard way exercise 18 help | i understand all the functions except the first one. whats the (*args) mean?
thanks
def print_twice(*args):
arg1, arg2 = args
print 'arg1: %r arg2: %r' % (arg1, arg2)
def print_twice_again(arg1, arg2):
print 'arg1: %r arg2: %r' % (arg1, arg2)
def print_once(arg1):
print 'arg1: %r' % arg1
def print_no... | [
"One asterix specifies a list, two asterixes specify a dictionary.\n"
] | [
5
] | [] | [] | [
"python"
] | stackoverflow_0005218993_python.txt |
Q:
How to test twisted web resource with trial?
I'm developing a twisted.web server - it consists of some resources that apart from rendering stuff use adbapi to fetch some data and write some data to postgresql database. I'm trying to figoure out how to write a trial unittest that would test resource rendering witho... | How to test twisted web resource with trial? | I'm developing a twisted.web server - it consists of some resources that apart from rendering stuff use adbapi to fetch some data and write some data to postgresql database. I'm trying to figoure out how to write a trial unittest that would test resource rendering without using net (in other words: that would initializ... | [
"Here's a function that will render a request and convert the result into a Deferred that fires when rendering is complete:\ndef _render(resource, request):\n result = resource.render(request)\n if isinstance(result, str):\n request.write(result)\n request.finish()\n return succeed(None)\... | [
11,
0
] | [] | [] | [
"python",
"trial",
"twisted"
] | stackoverflow_0005210889_python_trial_twisted.txt |
Q:
How can I make a front end web page to login to a page using password and username using python bottle
Using python bottle create a login web page
A:
Bottle by itself does not provide any facility for managing authentication. You will have have to roll your own, or use a WSGI middleware like repoze.who to handle... | How can I make a front end web page to login to a page using password and username using python bottle | Using python bottle create a login web page
| [
"Bottle by itself does not provide any facility for managing authentication. You will have have to roll your own, or use a WSGI middleware like repoze.who to handle authentication.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0005219242_python.txt |
Q:
Dutch Grammar in python's NLTK
I am working on a Dutch corpus and I want to know if NLTK has dutch grammar embedded in it so I can parse my sentences? In general does NLTK only work on English? I know that it has the Alpino dutch copora, but there is no indication that the functions (like parsing using CFGs) are m... | Dutch Grammar in python's NLTK | I am working on a Dutch corpus and I want to know if NLTK has dutch grammar embedded in it so I can parse my sentences? In general does NLTK only work on English? I know that it has the Alpino dutch copora, but there is no indication that the functions (like parsing using CFGs) are made for Dutch also.
Thanks
| [
"This is a response to my mail from Steven Bird one of the writers of the NLTK book:\n\nNLTK can work for parsing Dutch if you supply the grammar rules. \n Please consult the NLTK book for guidance: \n http://www.nltk.org/book \n You might be able to use the Alpino corpus in order to develop the \n grammar (or ... | [
2,
0
] | [] | [] | [
"context_free_grammar",
"nlp",
"nltk",
"parsing",
"python"
] | stackoverflow_0004990936_context_free_grammar_nlp_nltk_parsing_python.txt |
Q:
Python - How To Rename A Text File With DateTime
I'm using Python v2.x and am wondering how I can rename a known text file, for my example say "text.txt", to include the current date and time.
Any help would be greatly appreciated.
A:
os.rename("text.txt", time.strftime("%Y%m%d%H%M%S.txt")). Note that you have t... | Python - How To Rename A Text File With DateTime | I'm using Python v2.x and am wondering how I can rename a known text file, for my example say "text.txt", to include the current date and time.
Any help would be greatly appreciated.
| [
"os.rename(\"text.txt\", time.strftime(\"%Y%m%d%H%M%S.txt\")). Note that you have to import os and time.\nHave a look over here for time stuff and over here for renaming files.\n",
"To get the current datetime use:\nimport datetime\ndt = str(datetime.datetime.now())\n\nThen to rename file:\nimport os\nnewname = '... | [
30,
11,
1,
1
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0005218261_datetime_python.txt |
Q:
How do I change the representation while storing a sparse matrix in python?
The sparse matrix representation is of the form:
(i,j) value
I want to store these values to a text file in 3 columns namely:
i j value
A:
If your sparse matrix is stored in a dictionary... | How do I change the representation while storing a sparse matrix in python? | The sparse matrix representation is of the form:
(i,j) value
I want to store these values to a text file in 3 columns namely:
i j value
| [
"If your sparse matrix is stored in a dictionary called dict then you can use:\nf = open('output.txt', 'w')\nfor (i, j), value in dict.items():\n f.write(\"%s\\t%s\\t%s\\n\" % (i, j, value))\n\nThis will output the data as a tab-delimited text file.\n"
] | [
0
] | [] | [] | [
"python",
"sparse_matrix",
"storage"
] | stackoverflow_0005218450_python_sparse_matrix_storage.txt |
Q:
How to convert string to datetime in python
I have a date string in following format 2011-03-07 how to convert this to datetime in python?
A:
Try the following code, which uses strptime from the datetime module:
from datetime import datetime
datetime.strptime('2011-03-07','%Y-%m-%d')
I note that this (and many ... | How to convert string to datetime in python | I have a date string in following format 2011-03-07 how to convert this to datetime in python?
| [
"Try the following code, which uses strptime from the datetime module:\nfrom datetime import datetime\ndatetime.strptime('2011-03-07','%Y-%m-%d')\n\nI note that this (and many other solutions) are trivially easy to find with Google ;)\n",
"You can use datetime.date:\n>>> import datetime\n>>> s = '2011-03-07'\n>>>... | [
18,
5,
3,
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0005219970_python.txt |
Q:
number of all subsets of a set
This is what I came up with to calculate all subsets of length 0, 1, ... , n of a set of length n with doubling single elements. Difficult to describe...
def subsets(seq, *args):
seqstart = [[seq[i] for i in args], ]
if len(args) == 0:
for i in range(len(seq)):
... | number of all subsets of a set | This is what I came up with to calculate all subsets of length 0, 1, ... , n of a set of length n with doubling single elements. Difficult to describe...
def subsets(seq, *args):
seqstart = [[seq[i] for i in args], ]
if len(args) == 0:
for i in range(len(seq)):
seqstart += subsets(seq, i)
... | [
"The number of multisets of size up to n of a set of size n is equal to the binomial coefficient\n/ 2n \\\n| |\n\\ n /\n\nThis follows by summing up the number of combinations with repetition for k from 0 to n.\nFor n=14, this yields 40116600 multisets.\n",
"For a given set A with N number of elements, the nu... | [
9,
1,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0005220087_algorithm_python.txt |
Q:
How to get the first element of an array Python, from HTML
I have an array called list, for example
list = [0,1,2,3]
in the HTML when i do this
<body>
{{ list }}
</body>
the output will be [0,1,2]
what i want is
{{ list[0] }}
but this statement is giving me error, how i can just print the first element
A:
If y... | How to get the first element of an array Python, from HTML | I have an array called list, for example
list = [0,1,2,3]
in the HTML when i do this
<body>
{{ list }}
</body>
the output will be [0,1,2]
what i want is
{{ list[0] }}
but this statement is giving me error, how i can just print the first element
| [
"If you're using Django, try this: {{ list.0 }} or for slicing: {{ list|slice:\":1\" }}\nDocs: http://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#slice\n"
] | [
6
] | [] | [] | [
"arrays",
"django",
"html",
"printing",
"python"
] | stackoverflow_0005220336_arrays_django_html_printing_python.txt |
Q:
get key value from a dictionary django/python
How to print the value of a key from the key itself
dict={}
dict.update({'aa':1})
dict.update({'ab':1})
dict.update({'ac':1})
return render_to_response(t.html, context_instance=RequestContext(request, {'dict':dict}))
So in this case i want to print the key alert('{{d... | get key value from a dictionary django/python | How to print the value of a key from the key itself
dict={}
dict.update({'aa':1})
dict.update({'ab':1})
dict.update({'ac':1})
return render_to_response(t.html, context_instance=RequestContext(request, {'dict':dict}))
So in this case i want to print the key alert('{{dict.aa}}'); i.e,without using any loop can we just ... | [
"Never call a dictionary dict, that would overwrite the builtin dict type name in the current scope.\nYou can access keys and values in the template like so:\n{% for item in d.items %}\n key = {{ item.0 }}\n value = {{ item.1 }}\n{% endfor %}\n\nor use d.keys if you only need the keys.\n",
"If you're doing ... | [
14,
1
] | [] | [] | [
"django",
"django_templates",
"python"
] | stackoverflow_0005220355_django_django_templates_python.txt |
Q:
How do I use Python in a Chrome extension?
I want to create a Chrome extension with Python. Is this possible or will I have to use JavaScript?
A:
You could look at Pyjamas as that would let you write in Python but compile your code down to Javascript.
A:
No. Not Directly. However there are some possibilities d... | How do I use Python in a Chrome extension? | I want to create a Chrome extension with Python. Is this possible or will I have to use JavaScript?
| [
"You could look at Pyjamas as that would let you write in Python but compile your code down to Javascript.\n",
"No. Not Directly. However there are some possibilities discussed here.\nNPAPI for Python - Chrome Extension \n"
] | [
1,
0
] | [] | [] | [
"google_chrome_extension",
"python"
] | stackoverflow_0005217042_google_chrome_extension_python.txt |
Q:
Finding appropriate cut-off values
I try to implement Hampel tanh estimators to normalize highly asymmetric data. In order to do this, I need to perform the following calculation:
Given x - a sorted list of numbers and m - the median of x, I need to find a such that approximately 70% of the values in x fall into t... | Finding appropriate cut-off values | I try to implement Hampel tanh estimators to normalize highly asymmetric data. In order to do this, I need to perform the following calculation:
Given x - a sorted list of numbers and m - the median of x, I need to find a such that approximately 70% of the values in x fall into the range (m-a; m+a). We know nothing abo... | [
"You need to first symmetrize your distribution by folding all values less than the mean over to the right. Then you can use the standard scipy.stats functions on this one-sided distribution: \nfrom scipy.stats import scoreatpercentile\nimport numpy as np\n\ntheList = np.log10(1+np.arange(.1, 100))\ntheMedian = np.... | [
2,
1,
0
] | [] | [] | [
"algorithm",
"numpy",
"python",
"sampling",
"scipy"
] | stackoverflow_0005218048_algorithm_numpy_python_sampling_scipy.txt |
Q:
list python packages consumed by an application
def get_pkgs():
pkgs = []
for importer, modname, ispkg in \
pkgutil.walk_packages(path=None, onerror=lambda x: None):
pkgs.append(modname)
return pkgs
Above code snippet gives me all python packages in distribution. Can someone suggest me... | list python packages consumed by an application | def get_pkgs():
pkgs = []
for importer, modname, ispkg in \
pkgutil.walk_packages(path=None, onerror=lambda x: None):
pkgs.append(modname)
return pkgs
Above code snippet gives me all python packages in distribution. Can someone suggest me a way to get all packages out of these used by a pyt... | [
"The simplest way is to use the Python dependency analysis tool snakefood.\n",
"Snakefood is nice, as already answered by Sven Marnach, but this gives all file dependencies and I'm not sure if it will just tell you what packages are used, versus every single file dependency.\nFor packages available in the Python ... | [
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0005219711_python.txt |
Q:
AttributeError: Queue instance has no attribute '_empty'
A customer has got this error with my software using Python 2.5.5. How can it be? Does _empty has disappeared from the queue? I don't understand this at all. I did not inherit from queue, there is just a normal instance of the Queue class. On my machine all ... | AttributeError: Queue instance has no attribute '_empty' | A customer has got this error with my software using Python 2.5.5. How can it be? Does _empty has disappeared from the queue? I don't understand this at all. I did not inherit from queue, there is just a normal instance of the Queue class. On my machine all seems to work fine, however, on the machine of the customer th... | [
"I'm not very familiar with this (and I don't know what version of Python you are using), but looking at the documentation I see no mention of an _empty attribute, but only an empty() method. Since the leading underscore is used to denote private attributes, it seems likely to me that its existence is not standardi... | [
5
] | [] | [] | [
"attributeerror",
"python",
"queue"
] | stackoverflow_0005221364_attributeerror_python_queue.txt |
Q:
Debugging SCons
I've written a rather complicated set of SCons scripts, and I have some errors I cannot find, for example intermediate files are removed or there are cyclic dependencies reported, and I want to know the reason. Unfortunately, I don't see any means to get good verbose debugging output of what SCons ... | Debugging SCons | I've written a rather complicated set of SCons scripts, and I have some errors I cannot find, for example intermediate files are removed or there are cyclic dependencies reported, and I want to know the reason. Unfortunately, I don't see any means to get good verbose debugging output of what SCons is doing and where. F... | [
"Ok, I've solved the problem. It seems the reason was that a directory slipped into the list of targets, and directories create their own set of implicit dependencies. At least that's what I think, because after removing the directory the scripts work as expected. Can anyone clarify if my assumption is correct?\nI ... | [
1
] | [] | [] | [
"circular_dependency",
"debugging",
"python",
"scons",
"trace"
] | stackoverflow_0005166700_circular_dependency_debugging_python_scons_trace.txt |
Q:
Linux/Python: encoding a unicode string for print
I have a fairly large python 2.6 application with lots of print statements sprinkled about. I'm using unicode strings throughout, and it usually works great. However, if I redirect the output of the application (like "myapp.py >output.txt"), then I occasionally get... | Linux/Python: encoding a unicode string for print | I have a fairly large python 2.6 application with lots of print statements sprinkled about. I'm using unicode strings throughout, and it usually works great. However, if I redirect the output of the application (like "myapp.py >output.txt"), then I occasionally get errors such as this:
UnicodeEncodeError: 'ascii' codec... | [
"If you're dumping to an ASCII terminal, encode manually using unicode.encode, and specify that errors should be ignored.\nu = u'\\xa0'\nu.encode('ascii') # This fails\nu.encode('ascii', 'ignore') # This replaces failed encoding attempts with empty string\n\nIf you want to store unicode files, try this:\nu = u'\\xa... | [
18,
5,
2
] | [] | [] | [
"encoding",
"linux",
"locale",
"python",
"unicode"
] | stackoverflow_0005109970_encoding_linux_locale_python_unicode.txt |
Q:
How can I make my classes usable as dict keys?
class A():
def __init__(self, data=''):
self.data = data
def __str__(self):
return str(self.data)
d = {}
elem = A()
d[elem] = 'abc'
elem2 = A()
print d[elem2] # KeyError
# actually elem2! was used not elem
how can I implement this ... | How can I make my classes usable as dict keys? | class A():
def __init__(self, data=''):
self.data = data
def __str__(self):
return str(self.data)
d = {}
elem = A()
d[elem] = 'abc'
elem2 = A()
print d[elem2] # KeyError
# actually elem2! was used not elem
how can I implement this without error?
I tried to get d[elem2] (not elem) wi... | [
"The answer is yes, you need to redefine __hash__() and __eq__():\n>>> class A(object):\n... def __init__(self, data=''):\n... self.data = data\n... def __eq__(self, another):\n... return hasattr(another, 'data') and self.data == another.data\n... def __hash__(self):\n... return hash(self.data)\n.... | [
30,
6
] | [] | [] | [
"dictionary",
"key",
"python"
] | stackoverflow_0005221236_dictionary_key_python.txt |
Q:
gaierror: [Errno -2] Name or service not known
def make_req(data, url, method='POST')
params = urllib.urlencode(data)
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain",
}
conn = httplib.HTTPSConnection(url)
conn.request(method, ... | gaierror: [Errno -2] Name or service not known | def make_req(data, url, method='POST')
params = urllib.urlencode(data)
headers = {"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain",
}
conn = httplib.HTTPSConnection(url)
conn.request(method, url, params, headers)
response = conn.getrespons... | [
"You need to call request() with the URI relative to the server. If url is www.google.com/images?q=test you have to do:\nconn = httplib.HTTPSConnection('www.google.com')\nconn.request('GET', '/images?q=test')\n\n"
] | [
7
] | [] | [] | [
"python",
"urllib",
"urllib2"
] | stackoverflow_0005221848_python_urllib_urllib2.txt |
Q:
python: sys.argv[0] meaning in official documentation
Quoting from docs.python.org:
"sys.argv The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line opt... | python: sys.argv[0] meaning in official documentation | Quoting from docs.python.org:
"sys.argv The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string '-c'. ... | [
"No, if you invoke Python with -c to run commands from the command line, your sys.argv[0] will be -c:\nC:\\Python27>python.exe -c \"import sys; print sys.argv[0]\"\n-c\n\n",
"When Python is invoked as python script.py then sys.argv[0] == 'script.py'. When you invoke python -c 'import sys; print sys.argv' then sys... | [
11,
7,
0
] | [] | [] | [
"argv",
"python",
"sys"
] | stackoverflow_0005222408_argv_python_sys.txt |
Q:
dictionary in django python
In the follwoing code Maps.objects.all() returns all the objects in the tables and get description will return two variables namely name,description.
Now my question i am constructing a dicetionary.If the name is not in the dictionary then i should add it.How this should be done.
EDIT
... | dictionary in django python | In the follwoing code Maps.objects.all() returns all the objects in the tables and get description will return two variables namely name,description.
Now my question i am constructing a dicetionary.If the name is not in the dictionary then i should add it.How this should be done.
EDIT
This needs to be done on python... | [
"From what I understand, you're trying to assign a value to a key in a dictionary if it doesn't exist. Here's a helpful page for dictionaries.\nNow, to address your question, this should do what you want:\nlabels = {}\nmaps = Maps.objects.all()\nfor lm in maps:\n name, description = getDescription(lm.name, lm.ty... | [
0,
0,
0
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0005218597_django_django_views_python.txt |
Q:
authentication in python script to run as root
I am doing a project in Linux at system level in Python.
So that, I want to know that if i am running my code as a normal user and
if i am accessing system files then it should have root permissions for it,
then how can i prompt for root password and run further code ... | authentication in python script to run as root | I am doing a project in Linux at system level in Python.
So that, I want to know that if i am running my code as a normal user and
if i am accessing system files then it should have root permissions for it,
then how can i prompt for root password and run further code as superuser.
I want to know that, how to run python... | [
"The other thing you can do is have your script automatically invoke sudo if it wasn't executed as root:\nimport os\nimport sys\n\neuid = os.geteuid()\nif euid != 0:\n print \"Script not started as root. Running sudo..\"\n args = ['sudo', sys.executable] + sys.argv + [os.environ]\n # the next line replaces... | [
31,
6
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0005222333_pygtk_python.txt |
Q:
Google app engine datastore tag cloud with python
We have some unstructured textual data in our app engine datastore. I wanted to create a 'one off' tag cloud of one property on a subset of the datastore objects. After a look around, I can't see any framework that will allow me to do this without writing it myself... | Google app engine datastore tag cloud with python | We have some unstructured textual data in our app engine datastore. I wanted to create a 'one off' tag cloud of one property on a subset of the datastore objects. After a look around, I can't see any framework that will allow me to do this without writing it myself.
The way I had in mind was:
Write a map (as in map re... | [
"Feed TagCloud and PyTagCloud are two possibilities.\n\nFeed TagCloud Generator Gadget for\nGoogle App Engine might fit your\nneeds. Unfortunately, it's\nundocumented. Fortunately it's\nrather simple, though I'm not sure\nhow well-suited it is to your needs.\nIt operates on a feed, and appears\nto be somewhat fle... | [
5
] | [] | [] | [
"google_app_engine",
"python",
"tag_cloud"
] | stackoverflow_0005219843_google_app_engine_python_tag_cloud.txt |
Q:
Python/Scipy 3D Bilinear Surface Mapped to Unit Square
I have a bilinear surface (surface defined by lines between the 4 vertices) in 3D. I want to map this surface to the unit square. I know how to do this mapping and I know how to calculate the x,y,z coordinates of a point given the parametric coordinates of t... | Python/Scipy 3D Bilinear Surface Mapped to Unit Square | I have a bilinear surface (surface defined by lines between the 4 vertices) in 3D. I want to map this surface to the unit square. I know how to do this mapping and I know how to calculate the x,y,z coordinates of a point given the parametric coordinates of the unit square (say r,s). However, I need to go the other w... | [
"This may answer your question. I described the issues I have with the code in a comment. This describes a method of getting coordinates which is an attempt to answer the text of the question, ignoring the code.\nThis is just one method to find a point on an arbitrary surface at height z_target. There are much m... | [
1,
1
] | [] | [] | [
"coordinates",
"mapping",
"python",
"scipy",
"transformation"
] | stackoverflow_0005201011_coordinates_mapping_python_scipy_transformation.txt |
Q:
Python inheritance and scoping question
Edited because I'm a moron. Should have said class originally.
I have the code that does something like this:
file1.py
class A(object):
def __init__(self):
stuff_here()
class B(object):
def func(self):
self.a = A()
file2.py
import file1
class A(file1.A):
def ... | Python inheritance and scoping question | Edited because I'm a moron. Should have said class originally.
I have the code that does something like this:
file1.py
class A(object):
def __init__(self):
stuff_here()
class B(object):
def func(self):
self.a = A()
file2.py
import file1
class A(file1.A):
def __init__(self):
file1.A(self)
self.th... | [
"You could use a class attribute to hold the class you would like to use. In the first file, use\nclass B(object):\n A = A\n def func(self):\n self.a = self.A()\n\nand in the second file, use\nclass B(file1.B):\n A = A\n\nProbably there is a better way of achieving whatever you want to achieve...\n... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0005223174_python.txt |
Q:
web2py Error :- unable to detect browser
i install a web2py on my machine. i simply click on web2py.exe then it asking for password then it says "unable to detect your browser".
Any help will be appreciable.
A:
This is not an error, it is just a warning message.
This message is being introduced by this line whic... | web2py Error :- unable to detect browser | i install a web2py on my machine. i simply click on web2py.exe then it asking for password then it says "unable to detect your browser".
Any help will be appreciable.
| [
"This is not an error, it is just a warning message.\nThis message is being introduced by this line which propose is just to open the web browser automatically.\nBut, even without webbrowser module you should be able to run web2py and ignore the warning message,\nIf you are unable to run web2py or having any troubl... | [
2,
1
] | [] | [] | [
"python",
"web2py"
] | stackoverflow_0005218786_python_web2py.txt |
Q:
How to write a regular expression to match a string literal where the escape is a doubling of the quote character?
I am writing a parser using ply that needs to identify FORTRAN string literals. These are quoted with single quotes with the escape character being doubled single quotes. i.e.
'I don''t understand wha... | How to write a regular expression to match a string literal where the escape is a doubling of the quote character? | I am writing a parser using ply that needs to identify FORTRAN string literals. These are quoted with single quotes with the escape character being doubled single quotes. i.e.
'I don''t understand what you mean'
is a valid escaped FORTRAN string.
Ply takes input in regular expression. My attempt so far does not work an... | [
"A string literal is:\n\nAn open single-quote, followed by:\nAny number of doubled-single-quotes and non-single-quotes, then\nA close single quote.\n\nThus, our regex is:\nr\"'(''|[^'])*'\"\n\n",
"You want something like this:\nr\"'([^']|'')*'\"\n\nThis says that inside of the single quotes you can have either do... | [
20,
4,
1,
0
] | [] | [] | [
"fortran",
"ply",
"python",
"regex"
] | stackoverflow_0002143235_fortran_ply_python_regex.txt |
Q:
How do I add colour to this and make it look better for the user?
I can Add boxs and Tables
Also the Quit button does not work can someone edit that part of the code please
import gtk
class helloworld:
def close(self,widget):
print "I'm outta here"
gtk.main_quit()
... | How do I add colour to this and make it look better for the user? | I can Add boxs and Tables
Also the Quit button does not work can someone edit that part of the code please
import gtk
class helloworld:
def close(self,widget):
print "I'm outta here"
gtk.main_quit()
def printit(self,widget,lab1):
print lab1.get_text... | [
"The \"quit\" button doesn't work because you connected the \"destroy\" signal to the button instead of the clicked signal\nquitb.connect(\"clicked\", gtk.main_quit)\n\nAlso, you forgot to connect the window destroy event (so the program will never exit when you click the window close button). Add\nwindow.connect(\... | [
0
] | [] | [] | [
"edit",
"gtk",
"pretty_print",
"python"
] | stackoverflow_0005222503_edit_gtk_pretty_print_python.txt |
Q:
Simple API's to play around with for Python/Django?
Does anyone know of simple and well documented API's with plenty of hand holding examples that assumes very little or no prior knowledge of web development?
I've been messing around with Pyfacebook and Facebook-Python-SDK in trying to create a simple photo displa... | Simple API's to play around with for Python/Django? | Does anyone know of simple and well documented API's with plenty of hand holding examples that assumes very little or no prior knowledge of web development?
I've been messing around with Pyfacebook and Facebook-Python-SDK in trying to create a simple photo display app but I haven't been able to make much headway after ... | [
"Best place to start is with tutorials on djangoproject.com.\n",
"Have you tried the Django tutorial? It is pretty basic, but touches on all important points required to develop your own basic app.\n",
"django-basic-apps contains a collection of apps you might enjoy reading.\nEdit: Check out this good list of w... | [
0,
0,
0,
0
] | [] | [] | [
"api",
"django",
"python"
] | stackoverflow_0005215697_api_django_python.txt |
Q:
Scrapy Crawler in python cannot follow links?
I wrote a crawler in python using the scrapy tool of python. The following is the python code:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
#from scra... | Scrapy Crawler in python cannot follow links? | I wrote a crawler in python using the scrapy tool of python. The following is the python code:
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import HtmlXPathSelector
#from scrapy.item import Item
from a11ypi.items import AYpiIt... | [
"From what I see, it looks like your rule is not an iterable. It looks like you were trying to make rules a tuple, you should read up on tuples in the python documentation.\nTo fix your problem, change this line:\n rules =(\n Rule(SgmlLinkExtractor(allow = ()) ,callback = 'parse_item')\n )\... | [
34
] | [] | [] | [
"python",
"scrapy"
] | stackoverflow_0005223531_python_scrapy.txt |
Q:
Django logging throws 500 internal server error
I am having problems logging in my Django project.
In my view.py in an "application" I am doing the following:
import logging
logging.basicConfig(filename="django.log",level=logging.DEBUG)
def request(request):
logging.debug("test debugging")
with a django.log... | Django logging throws 500 internal server error | I am having problems logging in my Django project.
In my view.py in an "application" I am doing the following:
import logging
logging.basicConfig(filename="django.log",level=logging.DEBUG)
def request(request):
logging.debug("test debugging")
with a django.log file in the same directory as the view.py file.
Now ... | [
"Could it be related to permissions? I can imagine that in a web-server environment, writing to a file may be restricted. In truth, I don't know, but please check the official Django logging documentation - it uses the standard logging module, but you may have to configure it differently.\n",
"Is that your entire... | [
1,
1
] | [] | [] | [
"django",
"logging",
"python"
] | stackoverflow_0005215593_django_logging_python.txt |
Q:
django csv header and row format problem
I am trying to create csv download ,but result download gives me in different format
def csv_download(request):
import csv
import calendar
from datetime import *
from dateutil.relativedelta import relativedelta
now=datetime.today()
month = datetime.... | django csv header and row format problem | I am trying to create csv download ,but result download gives me in different format
def csv_download(request):
import csv
import calendar
from datetime import *
from dateutil.relativedelta import relativedelta
now=datetime.today()
month = datetime.today().month
d = calendar.mdays[month]
... | [
"Please read the csv module documentation, particularly the writer object API.\nYou'll notice that the csv.writer object takes a list with elements representing their position in your delimited line. So to get the desired output, you would need to pass in a list like so:\nwriter = csv.writer(response)\nwriter.write... | [
0
] | [] | [] | [
"csv",
"django",
"django_views",
"export_to_csv",
"python"
] | stackoverflow_0005222841_csv_django_django_views_export_to_csv_python.txt |
Q:
python uuid weird bug
I first tried with the interpreter to produce uuid's with python's uuid module. I did the following:
>>>import uuid
>>>uuid.uuid1()
UUID('d8904cf8-48ea-11e0-ac43-109add570b60')
So far so good. I create a simple little function to produce the uuid's.
import uuid
def get_guid():
return u... | python uuid weird bug | I first tried with the interpreter to produce uuid's with python's uuid module. I did the following:
>>>import uuid
>>>uuid.uuid1()
UUID('d8904cf8-48ea-11e0-ac43-109add570b60')
So far so good. I create a simple little function to produce the uuid's.
import uuid
def get_guid():
return uuid.uuid1()
if __name__ ==... | [
"Your test file name is most likely named uuid.py \nWhen you went back to the interpreter, you launched the interpreter from the same directory, which by default, will first look for the module name to import in your current working directory.\nJust change your test file name to something else, i.e. uuid_test_snipp... | [
19
] | [] | [] | [
"python",
"uuid"
] | stackoverflow_0005223864_python_uuid.txt |
Q:
Unable to Extract Rich Text ---DOC, DOCX
Problem:
https://github.com/mikemaccana/python-docx only extracts plain text
I need:
A Python module for extracting rich text from doc/docx files.
Any ideas?
A:
If you feel brave and have time you can use uno & OpenOffice for that job http://wiki.services.openoffice.o... | Unable to Extract Rich Text ---DOC, DOCX | Problem:
https://github.com/mikemaccana/python-docx only extracts plain text
I need:
A Python module for extracting rich text from doc/docx files.
Any ideas?
| [
"If you feel brave and have time you can use uno & OpenOffice for that job http://wiki.services.openoffice.org/wiki/PyUNO_bridge I have used it from c#.\n"
] | [
0
] | [] | [] | [
"ms_word",
"python",
"python_docx",
"richtextbox"
] | stackoverflow_0005224103_ms_word_python_python_docx_richtextbox.txt |
Q:
Multiple values JSON string Python (Django)
We have the following code working for receiving JSON strings for one value:
def spo2_new(request):
if request.method == 'POST':
data = {}
fields = request.POST.copy()
spo2 = SPO2(user=User.objects.get(pk=1), spo2=fields['value'], time=fields['datetime']... | Multiple values JSON string Python (Django) | We have the following code working for receiving JSON strings for one value:
def spo2_new(request):
if request.method == 'POST':
data = {}
fields = request.POST.copy()
spo2 = SPO2(user=User.objects.get(pk=1), spo2=fields['value'], time=fields['datetime'])
spo2.save()
data['succes'] = True
... | [
"Since you are already using JSON why don't simply send a JSON-encoded array of values [(timestamp, value)]?\nPOST: values=[[datetime1, value1],[datetime2,value2],...]\n",
"Within your page you can build an array and post those values manually as stated below:\nvalues=[[datetime1, value1],[datetime2,value2]]\n\nO... | [
1,
0
] | [] | [] | [
"django",
"json",
"python"
] | stackoverflow_0005223324_django_json_python.txt |
Q:
file programming in python
read_file = open ('C:\Users\Mahya\Desktop\\automate\Autosupports\\at1.txt','r')
content = read_file.readlines()
for line in content:
if line.contains('===== BOOT TIME STATS ====='):
print found
I want to read '===== BOOT TIME STATS =====' this line and print the lines that ar... | file programming in python | read_file = open ('C:\Users\Mahya\Desktop\\automate\Autosupports\\at1.txt','r')
content = read_file.readlines()
for line in content:
if line.contains('===== BOOT TIME STATS ====='):
print found
I want to read '===== BOOT TIME STATS =====' this line and print the lines that are below till next line
please h... | [
"Without testing:\nread_file = open ('C:\\Users\\Mahya\\Desktop\\\\automate\\Autosupports\\\\at1.txt','r')\ncontent = read_file.readlines()\ni_found_the_block = False\nfor line in content:\n if \"===== BOOT TIME STATS =====\" in line:\n print (\"found\")\n i_found_the_block = True\n if i_found_the... | [
1,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005219600_python.txt |
Q:
movable and resizable text edit control like in mspaint using wxpython
Hi I am trying to add some text to an image, and want adjust font, size, etc.
Is there any way to implement a mspaint style text input control in wxpython?
It have a rectangle area you can input text in it, and with 8 handler in 4 corner and 4 ... | movable and resizable text edit control like in mspaint using wxpython | Hi I am trying to add some text to an image, and want adjust font, size, etc.
Is there any way to implement a mspaint style text input control in wxpython?
It have a rectangle area you can input text in it, and with 8 handler in 4 corner and 4 border to adjust size. I see many control like it in photoshop and other ima... | [
"Check out Whyteboard. I think it has one of those widgets and it's written in wxPython:\nhttp://whyteboard.org/\n"
] | [
0
] | [] | [] | [
"image_processing",
"python",
"textinput",
"wxpython"
] | stackoverflow_0005211308_image_processing_python_textinput_wxpython.txt |
Q:
PySVN - Determine if a repository exists
I'm writing a small script that manages several SVN repositories. Users pass through the ID of the repository they want to change (the root of the repos are of the form https://www.mydomain.com/).
I need to check if the given repo actually exists. I've tried using Client.li... | PySVN - Determine if a repository exists | I'm writing a small script that manages several SVN repositories. Users pass through the ID of the repository they want to change (the root of the repos are of the form https://www.mydomain.com/).
I need to check if the given repo actually exists. I've tried using Client.list to see if I can find any files, like so:
cl... | [
"I couldn't reproduce your hanging in credentials callback problem, so it might need an expanded description of the problem. I'm running pysvn 1.7.2 on Ubuntu 10.04, Python 2.6.6. \nWhen I try to list a non-existent remote repository with client.list() it raises an exception. You could also use client.info2() to c... | [
1,
1
] | [] | [] | [
"exists",
"python",
"repository",
"svn"
] | stackoverflow_0005218810_exists_python_repository_svn.txt |
Q:
Django Exclude in list_filter with custom filter
Im trying to do 2 filters so that they appear in the django admin filter sidebar,
the first one is the following
https://gist.github.com/739760c7de861f76657f
in this one I would like to do filter if Gold exclude that which starts with J and Silver is already workin... | Django Exclude in list_filter with custom filter | Im trying to do 2 filters so that they appear in the django admin filter sidebar,
the first one is the following
https://gist.github.com/739760c7de861f76657f
in this one I would like to do filter if Gold exclude that which starts with J and Silver is already working exclude all that does not start with J
The second fi... | [
"Got it done...\nclass GoldorSilverFilter(DateFieldFilterSpec):\n def __init__(self, f, request, params, model, model_admin):\n super(GoldorSilverFilter, self).__init__(f, request, params, model, model_admin)\n\n self.links = (\n (_('All'), {}),\n (_('Gold'), {'%s__regex' % se... | [
0
] | [] | [] | [
"django",
"django_admin",
"filter",
"filtering",
"python"
] | stackoverflow_0005200190_django_django_admin_filter_filtering_python.txt |
Q:
Gaebar and Bulkloader Exporting Datastore
I am trying to find a way that I can download my whole datastore into a file and upload it back to datastore not to lose information. So I have made some research about it and found that there are two existing ways to do this.
Gaebar which is another application.
The Bul... | Gaebar and Bulkloader Exporting Datastore | I am trying to find a way that I can download my whole datastore into a file and upload it back to datastore not to lose information. So I have made some research about it and found that there are two existing ways to do this.
Gaebar which is another application.
The Bulkloader of app engine itself.
The data that I ... | [
"You should probably use the App Engine bulk loader as it is the official tool. It works great for me and it's easy to just make a full backup.\nGaebar was created in 2008 and the App Engine bulk loader wasn't available at that time, as documented by the Revision History:\n\nMay 2009\nA bulk data downloader has bee... | [
2
] | [] | [] | [
"bulkloader",
"google_app_engine",
"python"
] | stackoverflow_0005217885_bulkloader_google_app_engine_python.txt |
Q:
Python + PIL screenshot comparing
I've made a program that compares screenshots grabbed by PIL, stored in a table and I use ImageChops.difference to compare them.
The program works pretty good but there is one problem. The exactly same screenshots (e.g if you take two screenshots of your desktop with 1 second int... | Python + PIL screenshot comparing | I've made a program that compares screenshots grabbed by PIL, stored in a table and I use ImageChops.difference to compare them.
The program works pretty good but there is one problem. The exactly same screenshots (e.g if you take two screenshots of your desktop with 1 second interval) don't have the exactly same pixe... | [
"I'm not sure which of your pixels are different, nor what differences you're looking for exactly, so it's a bit hard to give help.\nTurning off all animations and desktop effects should help with getting consistent screenshots, of course. I'm sure one can write a tool that does this.\nAlso, saving the screenshots ... | [
0,
0
] | [] | [] | [
"compare",
"python",
"python_imaging_library",
"screenshot"
] | stackoverflow_0005224433_compare_python_python_imaging_library_screenshot.txt |
Q:
what is the type of the variable
I am a very newbie in Python I have the following code:
from SOAPpy import WSDL
fichier_wsdl = 'http://geocoder.us/dist/eg/clients/GeoCoder.wsdl'
wsdl = WSDL.Proxy(fichier_wsdl)
callInfo = wsdl.methods['geocode']
ss = wsdl.geocode('1600 Pennsylvania Ave, Washington, DC.')
print(ss... | what is the type of the variable | I am a very newbie in Python I have the following code:
from SOAPpy import WSDL
fichier_wsdl = 'http://geocoder.us/dist/eg/clients/GeoCoder.wsdl'
wsdl = WSDL.Proxy(fichier_wsdl)
callInfo = wsdl.methods['geocode']
ss = wsdl.geocode('1600 Pennsylvania Ave, Washington, DC.')
print(ss)
The result is:
IMPORT: http://sche... | [
"You can just do type(variable name).\n",
"Let's reformat that output for readability:\n<<class 'SOAPpy.Types.typedArrayType'> results at 21824752>:\n\n[<SOAPpy.Types.structType item at 21818984>:\n {'city': 'Washington', 'prefix': '', 'suffix': 'NW', 'zip': 20502, 'number': 1600,\n 'long': -77.037684, '... | [
5,
2
] | [] | [] | [
"python",
"soappy"
] | stackoverflow_0005224400_python_soappy.txt |
Q:
My encryption algorithm
I was bored and made up an encryption algorithm using Python. I'm just curious to find out if anyone would be interested in trying to break it, or maybe point me in the right direction of a forum or website where I could test the strength of my algorithm. If you can help me with this please... | My encryption algorithm | I was bored and made up an encryption algorithm using Python. I'm just curious to find out if anyone would be interested in trying to break it, or maybe point me in the right direction of a forum or website where I could test the strength of my algorithm. If you can help me with this please respond to this question. Th... | [
"First, read this:\nhttp://en.wikipedia.org/wiki/Brute_force_attack\nThen follow the links.\nSpecifically, read this one: http://www.sciengines.com/copacobana/\nNow that you've done some reading, you can download a brute-force encryption\nbreaker and break your code.\nIt's that easy. We don't need to do it for you... | [
2
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0005224398_algorithm_python.txt |
Q:
AppEngine: Getting only 1KB when uploading from an fetched URL to S3
I´m trying to upload a file which is fetched from a server. But when the fetched file is bigger than 1MB there will be only a 1KB small file saved at S3. When it´s smaller than 1MB, the file will be saved properly.
I ´ve searched and tried differ... | AppEngine: Getting only 1KB when uploading from an fetched URL to S3 | I´m trying to upload a file which is fetched from a server. But when the fetched file is bigger than 1MB there will be only a 1KB small file saved at S3. When it´s smaller than 1MB, the file will be saved properly.
I ´ve searched and tried different ways, but none off them is working. Here is the class which is trigger... | [
"The maximum request size on app engine is 1mb for urlfetch. I'm guessing your S3Connection class uses that to do the actual transfer.\nResponses can be up to 32MB, that's why the download works.\n"
] | [
2
] | [] | [] | [
"amazon_s3",
"boto",
"google_app_engine",
"python",
"urlfetch"
] | stackoverflow_0005223905_amazon_s3_boto_google_app_engine_python_urlfetch.txt |
Q:
Fastest way to read comma separated files (including datetimes) in python
I have data stored in comma delimited txt files. One of the columns represents a datetime.
I need to load each column into separate numpy arrays (and decode the date into a python datetime object).
What is the fastest way to do this (in term... | Fastest way to read comma separated files (including datetimes) in python | I have data stored in comma delimited txt files. One of the columns represents a datetime.
I need to load each column into separate numpy arrays (and decode the date into a python datetime object).
What is the fastest way to do this (in terms of run time)?
NB. the files are several hundred MB of data and currently take... | [
"First, you should run your sample script with Python's built-in profiler to see where the problem actually might be. You can do this from the command-line:\npython -m cProfile myscript.py\n\nSecondly, what jumps at me at least, why is that loop at the bottom necessary? Is there a technical reason that it can't be ... | [
8,
3,
2,
1,
1
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0005223967_numpy_python.txt |
Q:
Python - 'object cannot be interpreted as an index' Error
I am having an error that I don't understand in my Dijkstra Algorithm code - here is the error message:
Traceback (most recent call last):
File "C:\Documents and Settings\Harvey\Desktop\algorithm.py", line 52, in <module>
tentativeDistance(currentNode... | Python - 'object cannot be interpreted as an index' Error | I am having an error that I don't understand in my Dijkstra Algorithm code - here is the error message:
Traceback (most recent call last):
File "C:\Documents and Settings\Harvey\Desktop\algorithm.py", line 52, in <module>
tentativeDistance(currentNode,populateNodeTable())
File "C:\Documents and Settings\Harvey\... | [
"Given the way for loops work in Python, you don't have to write\nfor currentNode in nodeTable:\n currentDistance = nodeTable[currentNode].distFromSource + network[currentNode][nearestNeighbour] #gets current distance from source\n\nYou should instead write:\nfor currentNode in nodeTable:\n currentDistance = ... | [
3
] | [] | [] | [
"dijkstra",
"python"
] | stackoverflow_0005224686_dijkstra_python.txt |
Q:
Python iterable map, range, etc
Why doesn't python have a __future__ library that replaces map with imap, range with xrange, etc.? Is it possible to write one?
A:
There is future_builtins module since Python 2.6:
from future_builtins import filter, map, zip
A:
A __future__ import is not necessary:
from iterto... | Python iterable map, range, etc | Why doesn't python have a __future__ library that replaces map with imap, range with xrange, etc.? Is it possible to write one?
| [
"There is future_builtins module since Python 2.6:\nfrom future_builtins import filter, map, zip\n\n",
"A __future__ import is not necessary:\nfrom itertools import imap as map\nrange = xrange\n\nEdit: If you want to do several of those in a single line, you can do\nfrom itertools import imap as map, ifilter as f... | [
8,
4,
2
] | [] | [] | [
"python"
] | stackoverflow_0005224373_python.txt |
Q:
Django Form Field missing on save
I have a user facing form, which is generated from a model. The model has a foreign key to a site “Section.” When I submit the form it returns an IntegrityError (null value in column "section_id" violates not-null constraint). I thought the issue was straightforward until I starte... | Django Form Field missing on save | I have a user facing form, which is generated from a model. The model has a foreign key to a site “Section.” When I submit the form it returns an IntegrityError (null value in column "section_id" violates not-null constraint). I thought the issue was straightforward until I started working on it. The bug only occurs on... | [
"Chris,\nThis sounds like an issue of your database's not being the same version. Did you sync your databases are separate times or are you using different databases on your development server and local machine? Can you also post the full model and form as an example?\n",
"Try this for your view:\ndef event_regis... | [
0,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005222533_django_python.txt |
Q:
C function passes a pointer and a length, and a Python callback needs to make an array and assign it
I'm wrapping a C library that uses callbacks as external memory allocators. Basically, instead of doing malloc and free itself, it exposes several callbacks for making buffers of specified sizes. Hooking those up... | C function passes a pointer and a length, and a Python callback needs to make an array and assign it | I'm wrapping a C library that uses callbacks as external memory allocators. Basically, instead of doing malloc and free itself, it exposes several callbacks for making buffers of specified sizes. Hooking those up with ctypes is fairly easy, and all that seems to be working. However, I can't seem to connect the array... | [
"If you want to return a pointer in a parameter, you need to pass in a pointer to a pointer:\nextern int alloc_int_buffer_callback(some_struct **buffer, uint32_t length);\n\nIf you simply pass in a pointer, changing the pointer inside the function does nothing, since you passed the pointer by value.\nInside your Py... | [
1
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0005224771_ctypes_python.txt |
Q:
Limit amount of writes to database using memcache
I am trying to modify the guestbook example webapp to reduce the amount of database writes.
What I am trying to achieve is to load all the guestbook entries into memcache which I have done.
However I want to be able to directly update the memcache with new guestbo... | Limit amount of writes to database using memcache | I am trying to modify the guestbook example webapp to reduce the amount of database writes.
What I am trying to achieve is to load all the guestbook entries into memcache which I have done.
However I want to be able to directly update the memcache with new guestbook entries and then write all changes to the database a... | [
"This is a recipe for lost data. I have a hard time believing that a guest book is causing enough write activity to be an issue. Also, the bookkeeping involved in this would be tricky, since memcache isn't searchable.\n",
"What are you trying to achieve is called Write-Behind Caching, and usually it's not so easy... | [
6,
2,
1
] | [] | [] | [
"caching",
"google_app_engine",
"google_cloud_datastore",
"memcached",
"python"
] | stackoverflow_0005221977_caching_google_app_engine_google_cloud_datastore_memcached_python.txt |
Q:
How to write this Python excerpt
Write a Python excerpt that gathers together words into no more than width character lines. You may assume words is a list of words, in order, to be output and width is the maximum number of characters a line may have. Print each line just when you can't add another word to the lin... | How to write this Python excerpt | Write a Python excerpt that gathers together words into no more than width character lines. You may assume words is a list of words, in order, to be output and width is the maximum number of characters a line may have. Print each line just when you can't add another word to the line without exceeding the character limi... | [
"Check out the textwrap module.\nimport textwrap\n\nwords = 'some words to print out'\nwidth = 10\n\nfor line in textwrap.wrap(words, width):\n print line\n\n",
"Ok, so let's assume you have a string like this:\nstring = 'the quick brown fox jumped over the lazy dog the quick brown fox jumped over the lazy dog... | [
3,
0,
0,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0005224703_python.txt |
Q:
learn python the hard way exercise 20 help
for the extras of exercise 20 i was told to comment what i think each line does. seek i found confusing. if anyone is willing to check out my comments on the source to see if i understand correctly. i could skip it but i feel its important i understand this.
thanks
from s... | learn python the hard way exercise 20 help | for the extras of exercise 20 i was told to comment what i think each line does. seek i found confusing. if anyone is willing to check out my comments on the source to see if i understand correctly. i could skip it but i feel its important i understand this.
thanks
from sys import argv #imports argv from sys moduel
s... | [
"Yes, it sets the file's current position to the first byte. This can be seen in the documentation for file.seek:\n\nfile.seek(offset[, whence])\nSets the file’s current position, like stdio‘s fseek(). The whence argument is optional and defaults to os.SEEK_SET or 0 (absolute file positioning); other values are os.... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0005225008_python.txt |
Q:
Curses window in Python without clearing the terminal
Is there a way to initialize curses in Python without clearing the existing text in the terminal? What I have in mind is, that when I will execute my application, it will either "push" the existing text up and executes at the bottom of the screen, or will draw ... | Curses window in Python without clearing the terminal | Is there a way to initialize curses in Python without clearing the existing text in the terminal? What I have in mind is, that when I will execute my application, it will either "push" the existing text up and executes at the bottom of the screen, or will draw itself over the existing text. I think curses' newterm func... | [
"For simple applications, e.g. when you just want to use colour, you can try the curses.setupterm function. The following example uses curses to print red and green text at the bottom of the screen:\nimport curses\n\ncurses.setupterm()\n\nblack_bg = curses.tparm(curses.tigetstr(\"setab\"), 0)\nred = curses.tparm(c... | [
2
] | [] | [] | [
"curses",
"python"
] | stackoverflow_0005217123_curses_python.txt |
Q:
FunkLoad one report for multiple requests
I am using FunkLoad to make some load test on my Django project.
One of the page (I will name it /customer/ ) that I am currently try to benchmark "does" an AJAX request on page load to (/customer/json/)
What I am currently doing in my benchmark is the following
self.get("... | FunkLoad one report for multiple requests | I am using FunkLoad to make some load test on my Django project.
One of the page (I will name it /customer/ ) that I am currently try to benchmark "does" an AJAX request on page load to (/customer/json/)
What I am currently doing in my benchmark is the following
self.get("/customer/", description="Customer page")
self.... | [
"This is not yet feasible but this feature is part of the FunkLoad todo list:\n\"Add a param to join to next request action\"\nI have not yet any precise schedule for this task, but I will defninitly implemenet it.\nRegards \nben\n"
] | [
1
] | [] | [] | [
"django",
"funkload",
"load_testing",
"python"
] | stackoverflow_0005170702_django_funkload_load_testing_python.txt |
Q:
How do I improve my parsing technique?
I am writing a pythonic parser for a custom language and as of now I have something like this:
re1 = re.compile(r"...")
re2 = re.compile(r"...")
re3 = re.compile(r"...")
re4 = re.compile(r"...")
...
...
Now I am reading the input file and for each line if I find a specific k... | How do I improve my parsing technique? | I am writing a pythonic parser for a custom language and as of now I have something like this:
re1 = re.compile(r"...")
re2 = re.compile(r"...")
re3 = re.compile(r"...")
re4 = re.compile(r"...")
...
...
Now I am reading the input file and for each line if I find a specific keyword then I am using a particular regular ... | [
"Rather than rolling your own parser using you could have a look at one of the many parser libraries available for Python.\n\nPLY\npyparsing\nANTLR\netc...\n\n",
"I don't think this is the answer you're looking for, but I think you'd be having a better time using an actual Lexer and Tokenizer for parsing your lan... | [
3,
2,
1
] | [] | [] | [
"parser_generator",
"programming_languages",
"python",
"regex"
] | stackoverflow_0005225053_parser_generator_programming_languages_python_regex.txt |
Q:
How do you grep through code that lives in many different directories?
I'm working on a Python program that makes heavy use of eggs (Plone). That means there are 198 directories full of Python code I might want to search through while debugging. Is there a good way to search only the .py files in only those direct... | How do you grep through code that lives in many different directories? | I'm working on a Python program that makes heavy use of eggs (Plone). That means there are 198 directories full of Python code I might want to search through while debugging. Is there a good way to search only the .py files in only those directories, avoiding unrelated code and large binary files?
| [
"find DIRECTORY -name \"*.py\" | xargs grep PATTERN\n\nBy the way, since writing this, I have discovered ack, which is a much better solution.\n(And since that edit, I have discovered ag).\n",
"grep -r -n \"PATTERN\" --include=\"*.py\" DIRECTORY\n\n",
"I would strongly recommend ack, a grep substitute, \"aimed ... | [
28,
21,
19,
7,
4,
4,
2,
2,
2,
2,
2,
1
] | [] | [] | [
"grep",
"plone",
"python",
"zope"
] | stackoverflow_0000865382_grep_plone_python_zope.txt |
Q:
Distorting an image using a height map?
I have a height map for an image, which tells me the offset of each pixel in the Z direction. My goal is to flatten a distorted image using only it's height map.
How would I go about doing this? I know the position of the camera, if that helps.
To do this, I was thinking ab... | Distorting an image using a height map? | I have a height map for an image, which tells me the offset of each pixel in the Z direction. My goal is to flatten a distorted image using only it's height map.
How would I go about doing this? I know the position of the camera, if that helps.
To do this, I was thinking about assuming that each pixel was a point on a... | [
"I ended up implementing my own solution:\nfor x in xrange(cv.GetSize(image)[0]):\n for y in xrange(cv.GetSize(image)[1]):\n\n a = Point(x, y, heights_top[x / 2] * (cv.GetSize(image)[1] - y) + heights_bottom[x / 2] * y)\n b = Point()\n\n d.x = costy * (sintz * (a.y - c.y) + costz * (a.x - c.x)) - sinty * ... | [
3,
0,
0
] | [] | [] | [
"c++",
"image_processing",
"opencv",
"python",
"unwarp"
] | stackoverflow_0005171787_c++_image_processing_opencv_python_unwarp.txt |
Q:
Plone and Python scripts
I'm using Plone with Python scripts, I understand scripts are restricted in Plone and I also understand that I might create Python scripts in the Extensions folder for a fully functional script.
But how do I send information between the two scripts? For example script1.py is located in th... | Plone and Python scripts | I'm using Plone with Python scripts, I understand scripts are restricted in Plone and I also understand that I might create Python scripts in the Extensions folder for a fully functional script.
But how do I send information between the two scripts? For example script1.py is located in the ZMI and has a directory whic... | [
"Python scripts in the Extensions folder are usually used as External Methods. This section of the Zope book explains External methods in more detail. Once this is created, you can call it by what id you give it in the ZMI by the other script or template in zope. You should be able to call it via your other script... | [
2,
2
] | [] | [] | [
"plone",
"python",
"scripting"
] | stackoverflow_0003087616_plone_python_scripting.txt |
Q:
Cross Platform App with Localization
I am interested in developing a simple language learning (French, German, etc) desktop application to assist users in learning vocabulary by seeing and listening (via MP3 files) to words simultaneously.
I done some programming when I was younger and see this as a long term proj... | Cross Platform App with Localization | I am interested in developing a simple language learning (French, German, etc) desktop application to assist users in learning vocabulary by seeing and listening (via MP3 files) to words simultaneously.
I done some programming when I was younger and see this as a long term project to get back into programming by develo... | [
"Tcl/tk has excellent unicode support, and a very workable message catalog library. It's also highly portable to all major platforms (and several not-so-major platforms). In addition, you have the option of packaging your whole app up as a platform-dependent runtime (tclkit) and platform-independent application fil... | [
0
] | [] | [] | [
"eclipse",
"monodevelop",
"netbeans",
"python",
"ruby"
] | stackoverflow_0005225155_eclipse_monodevelop_netbeans_python_ruby.txt |
Q:
Rosetta like localization for ASP.NET MVC web applications?
Recently, I used the python django framework and one aspect I liked there a lot is the django-rosetta module that allows you to extract the content of your website and create multi language translations with very a nice web interface.
I was wondering if ... | Rosetta like localization for ASP.NET MVC web applications? | Recently, I used the python django framework and one aspect I liked there a lot is the django-rosetta module that allows you to extract the content of your website and create multi language translations with very a nice web interface.
I was wondering if such thing exists for the ASP.NET framework or for ASP.NET MVC
| [
"Just use .NET Resources (for mvc, if you want access to your resources inside your controller, don't use App_Globalresources)\n"
] | [
0
] | [] | [] | [
".net",
"asp.net_mvc",
"django",
"python"
] | stackoverflow_0005209684_.net_asp.net_mvc_django_python.txt |
Q:
How do you safely and efficiently get the row id after an insert with mysql using MySQLdb in python?
I have a simple table in mysql with the following fields:
id -- Primary key, int, autoincrement
name -- varchar(50)
description -- varchar(256)
Using MySQLdb, a python module, I want to insert a name and descript... | How do you safely and efficiently get the row id after an insert with mysql using MySQLdb in python? | I have a simple table in mysql with the following fields:
id -- Primary key, int, autoincrement
name -- varchar(50)
description -- varchar(256)
Using MySQLdb, a python module, I want to insert a name and description into the table, and get back the id.
In pseudocode:
db = MySQLdb.connection(...)
queryString = "INSER... | [
"I think it might be\nnewID = db.insert_id()\n\n\nEdit by Original Poster\nTurns out, in the version of MySQLdb that I am using (1.2.2)\nYou would do the following:\nconn = MySQLdb(host...)\n\nc = conn.cursor()\nc.execute(\"INSERT INTO...\")\nnewID = c.lastrowid\n\nI am leaving this as the correct answer, since it ... | [
28,
2,
0
] | [
"The easiest way of all is to wrap your insert with a select count query into a single stored procedure and call that in your code. You would pass in the parameters needed to the stored procedure and it would then select your row count.\n"
] | [
-8
] | [
"mysql",
"python"
] | stackoverflow_0000706755_mysql_python.txt |
Q:
Custom Icon in gtk toggle_action
I have the following code which adds a toolbar icon "gtk-info" (from stock) to a python Gtk+ window. I would like to have a custom icon instead. How would I do that?
self.action = ('ActivateSqueezeboxMode','gtk-info', _('SqueezeboxTools'),
None, _('Activate ... | Custom Icon in gtk toggle_action | I have the following code which adds a toolbar icon "gtk-info" (from stock) to a python Gtk+ window. I would like to have a custom icon instead. How would I do that?
self.action = ('ActivateSqueezeboxMode','gtk-info', _('SqueezeboxTools'),
None, _('Activate Squeezebox mode'),
... | [
"Try this:\nself.action = ('ActivateSqueezeboxMode', None, _('SqueezeboxTools'),\n None, _('Activate Squeezebox mode'),\n self.activate_button_press, True)\nself.action_group = gtk.ActionGroup('SqueezeboxPluginActions')\nself.action_group.add_toggle_actions([self.action])\n# now get yo... | [
1
] | [] | [] | [
"gtk",
"python"
] | stackoverflow_0005211036_gtk_python.txt |
Q:
Creating Jinja variables/filters similar to loop.cycle()
I'm trying to create a custom Jinja variable that will cycle through a list of values each time it is used. This is similar to loop.cycle('a','b','c'), except that I'm not inside a for loop.
Example:
list = ['val1','val2','val3']
{{ list|next }}
{{ list... | Creating Jinja variables/filters similar to loop.cycle() | I'm trying to create a custom Jinja variable that will cycle through a list of values each time it is used. This is similar to loop.cycle('a','b','c'), except that I'm not inside a for loop.
Example:
list = ['val1','val2','val3']
{{ list|next }}
{{ list|next }}
{{ list|next }}
{{ list|next }}
Output:
val1 ... | [
"Jinja2, since v2.1, allows loop unbound cycling, as the documentation shows. \nIn your example, you would do something like this:\n{% set cycling_list = cycler('val1', 'val2', 'val3') %}\n{{ cycling_list.next() }} \n{{ cycling_list.next() }} \n{{ cycling_list.next() }}\n\nThere's also cycler.reset, and cycler.cu... | [
8
] | [] | [] | [
"jinja2",
"python",
"templates"
] | stackoverflow_0005225863_jinja2_python_templates.txt |
Q:
Recommended nomenclature: a better term than "parent"?
I am writing a connection-state keeping program based loosely on the "State" example here.
In the example, the class Radio passes a pointer (better term?) to AmState when instancing AmState:
class AmState(State):
def __init__(self, radio):
self.radio =... | Recommended nomenclature: a better term than "parent"? | I am writing a connection-state keeping program based loosely on the "State" example here.
In the example, the class Radio passes a pointer (better term?) to AmState when instancing AmState:
class AmState(State):
def __init__(self, radio):
self.radio = radio
...
class Radio(object):
def __init__(self):
... | [
"The usual term for this sort of composition is \"owner\". And the \"better term\" you're looking for is \"reference\".\n",
"I suppose GOF Design Patterns is the nearest thing to canon, and it uses 'context'.\n"
] | [
2,
1
] | [] | [] | [
"oop",
"python",
"terminology"
] | stackoverflow_0005225924_oop_python_terminology.txt |
Q:
Parse linux command line with pipes/redirection using python
Is there any existing utility that can parse a linux command line with recognition of basic piping and redirection: '|', '<', and, '>'? Preferably this can be used for as parameters for a subprocess call instead of using os.system.
shlex.split() does bas... | Parse linux command line with pipes/redirection using python | Is there any existing utility that can parse a linux command line with recognition of basic piping and redirection: '|', '<', and, '>'? Preferably this can be used for as parameters for a subprocess call instead of using os.system.
shlex.split() does basic parsing, but its output cannot always be used by subprocess.Pop... | [
"Hotwire seems like it can do this, this web page has some information on how this works.\nIPython IPipe also has a different way to do some of the same things as Hotwire.\n",
"Such a module would provide nothing that Popen with the shell=True option does not already provide. \nSee http://docs.python.org/library... | [
0,
-1
] | [] | [] | [
"command_line_arguments",
"python"
] | stackoverflow_0005225286_command_line_arguments_python.txt |
Q:
Writing a Binary String to a file
I am writing a huffman encoding program to compress a text file. I converted the text file to its huffman encoded value, and I need to write it to a file. I am currently using the python "BitVector" module, but it is far too slow when reading and writing from/to a file. Are there ... | Writing a Binary String to a file | I am writing a huffman encoding program to compress a text file. I converted the text file to its huffman encoded value, and I need to write it to a file. I am currently using the python "BitVector" module, but it is far too slow when reading and writing from/to a file. Are there any other ways of doing this(preferably... | [
"You might consider using the struct package from the python standard library.\n"
] | [
0
] | [] | [] | [
"bit",
"file_io",
"python"
] | stackoverflow_0005224292_bit_file_io_python.txt |
Q:
How can I match the url in html
<form action='/[0-9]+' method="POST">
<input type="submit" value="delete question" name="delete">
</form>
what above is the html template I am using for the appengine project. Besides that, i created a web request handler class to handle this request. ('/[0-9]+',QuestionViewer)... | How can I match the url in html | <form action='/[0-9]+' method="POST">
<input type="submit" value="delete question" name="delete">
</form>
what above is the html template I am using for the appengine project. Besides that, i created a web request handler class to handle this request. ('/[0-9]+',QuestionViewer), it is supposed to catch any url in ... | [
"That doesn't really make sense. You want to submit your form to a regex rule? What would it match against?\nNo, the form needs to submit to a specific url. Right now, it's trying to submit to /[0-9]+\nIf I understand what you are saying, and you want to submit from a url such as /13/ to your QuestionViewer at /[0-... | [
2,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0005225849_django_python.txt |
Q:
How to split string on '/' delimiter but prevent splitting when '/ ' occurs just after ' \ '
I am trying to split string data using Python which is delimited by the '/' character. The problem is that the string could have multiple occurrence of the '/' character but I want to split it only using '/' and not using... | How to split string on '/' delimiter but prevent splitting when '/ ' occurs just after ' \ ' | I am trying to split string data using Python which is delimited by the '/' character. The problem is that the string could have multiple occurrence of the '/' character but I want to split it only using '/' and not using '\/'
For example, I am trying to split the string '1\/2/CD' into '1\/2' and 'CD'
| [
"Use a negative lookbehind assertion in the regexp:\n>>> re.split(r'(?<!\\\\)/', r'1\\/2/CD')\n['1\\\\/2', 'CD']\n\nFrom the docs:\n\n(?<!...)\n\nMatches if the current position in the string is not preceded by a\n match for .... This is called a\n negative lookbehind assertion. Similar\n to positive lookbehind ... | [
5,
1,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0005226208_python_regex.txt |
Q:
Django/Python: How can i monitor mysql database and trigger email when timestamp = NOW()?
If i want to make an alerting system. How can I implement those feature?
I have a MySQL database storing user's message and timestamp (or datetime). I want to trigger sending email out to that user if timestamp is greater tha... | Django/Python: How can i monitor mysql database and trigger email when timestamp = NOW()? | If i want to make an alerting system. How can I implement those feature?
I have a MySQL database storing user's message and timestamp (or datetime). I want to trigger sending email out to that user if timestamp is greater than current timestamp.
How can i implement that feature using Django/python based web application... | [
"You should be able to do this within your view in Django, and really not need to have an external cron run on your database. To clarify a little, are you wanting the email to be sent when the message is processed in the view or does some other action cause messages to be created and then you want the message sent.... | [
1
] | [] | [] | [
"django",
"monitor",
"python",
"sql"
] | stackoverflow_0005226211_django_monitor_python_sql.txt |
Q:
Google App Engine using UserProperty to link data
I am writing an application in GAE. In order to link the currently logged in user to data in my application I have been relying on equality between users.get_current_user() and members.user (see model below). Where I run into trouble is when the user signs in wit... | Google App Engine using UserProperty to link data | I am writing an application in GAE. In order to link the currently logged in user to data in my application I have been relying on equality between users.get_current_user() and members.user (see model below). Where I run into trouble is when the user signs in with an email address using different capitalization than ... | [
"Don't use the username - call user.user_id(), and compare on that. It's guaranteed to remain the same, even if nickname or email address change.\n",
"Always convert username to lowercase and then do operations on it: when storing the first time and on later comparisons.\n"
] | [
4,
0
] | [] | [] | [
"capitalization",
"data_modeling",
"google_app_engine",
"python"
] | stackoverflow_0005211560_capitalization_data_modeling_google_app_engine_python.txt |
Q:
GAE: scheduled import of big gzipped file from a third party site
I'm working on a Python web app that needs to import big (in terms of GAE limits) gzipped files from a third party site on regular basis. Think of rdf exports DMOZ project is producing on regular intervals.
This means daily fetching of a 500+ MB gzi... | GAE: scheduled import of big gzipped file from a third party site | I'm working on a Python web app that needs to import big (in terms of GAE limits) gzipped files from a third party site on regular basis. Think of rdf exports DMOZ project is producing on regular intervals.
This means daily fetching of a 500+ MB gzip file, gunzipping, parsing, processing and storing the results in GAE'... | [
"The limit on downloaded file size in App Engine is currently 64MB. As a result, you've got two options:\n\nUse HTTP Range headers to download and process the file in chunks.\nUse an external service to do the download, split it into pieces, and send the pieces to your App Engine app.\n\n",
"My initial gut reacti... | [
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0005211129_google_app_engine_python.txt |
Q:
Loading django custom template tag at onece
I have my custom template tag. How to load it at once, without {% load tag %} in every template-file?
UPD:
As suggested by Yuji:
from django.template.loader import add_to_builtins
add_to_builtins('myapp.templatetags.mytagslib')
however, I don't use django, only template... | Loading django custom template tag at onece | I have my custom template tag. How to load it at once, without {% load tag %} in every template-file?
UPD:
As suggested by Yuji:
from django.template.loader import add_to_builtins
add_to_builtins('myapp.templatetags.mytagslib')
however, I don't use django, only templates - what should i write instead of myapp.template... | [
"Here you go: \nLoad a Django template tag library for all views by default\nFavorite Django Tips & Features?\nI will remember this one, thanks :) \n"
] | [
3
] | [] | [] | [
"django",
"python",
"tags",
"templates"
] | stackoverflow_0005226701_django_python_tags_templates.txt |
Q:
Unknown Python Error
The following code is from a python script I'm writing that is supposed to modify the daemons array in an Arch Linux rc.conf file. However when run, I get a ValueError saying that the operation:
for line in rc:
Cannot be performed on a closed file. I may be missing something, but as far as I ... | Unknown Python Error | The following code is from a python script I'm writing that is supposed to modify the daemons array in an Arch Linux rc.conf file. However when run, I get a ValueError saying that the operation:
for line in rc:
Cannot be performed on a closed file. I may be missing something, but as far as I can tell the file is not c... | [
"You reassign to tmp about 8 lines down. Then, tmp is no longer the file. At that point, its reference count may drop to zero, so Python closes it. All while you're still trying to loop over the lines in the other file.\nUse a different variable name here:\n...\ntmp = line[1:] # rename 'tmp' here\nline = [... | [
4,
0
] | [] | [] | [
"file",
"python"
] | stackoverflow_0005226502_file_python.txt |
Q:
Trying to monitor a number of remote MySQL connections
I'm trying to monitor a number of remote database connections.
How can I constantly monitor a GMail account for routing emails based on their header within the same application?
This will need to be standalone or basic package.
Should I build a Qt or .NET app ... | Trying to monitor a number of remote MySQL connections | I'm trying to monitor a number of remote database connections.
How can I constantly monitor a GMail account for routing emails based on their header within the same application?
This will need to be standalone or basic package.
Should I build a Qt or .NET app for this?
| [
"If you need to constantly monitor the account then you'll probably want to use an IMAP package for this, such as Python's imaplib. A tutorial which should help you read the header information is available here.\nYour question doesn't include enough information about what graphical functionality you want in your pr... | [
0
] | [] | [] | [
".net",
"c#",
"c++",
"java",
"python"
] | stackoverflow_0002854227_.net_c#_c++_java_python.txt |
Q:
Should I be using "global" or "self." for class scope variables in Python?
Both of these blocks of code work. Is there a "right" way to do this?
class Stuff:
def __init__(self, x = 0):
global globx
globx = x
def inc(self):
return globx + 1
myStuff = Stuff(3)
print myStuff.inc()
P... | Should I be using "global" or "self." for class scope variables in Python? | Both of these blocks of code work. Is there a "right" way to do this?
class Stuff:
def __init__(self, x = 0):
global globx
globx = x
def inc(self):
return globx + 1
myStuff = Stuff(3)
print myStuff.inc()
Prints "4"
class Stuff:
def __init__(self, x = 0):
self.x = x
def... | [
"You should use the second way, then every instance has a separate x\nIf you use a global variable then you may find you get surprising results when you have more than one instance of Stuff as changing the value of one will affect all the others.\nIt's normal to have explicit self's all over your Python code. If yo... | [
13,
10,
1
] | [] | [] | [
"class",
"function",
"python",
"variables"
] | stackoverflow_0005226572_class_function_python_variables.txt |
Q:
write a paragraph to a file
Ok this is simple, I want to write a huge paragraph of text to a file. I know I can do
f=open("blah.txt",'w')
f.write("blah blah \n")
f.write("bla blah blah ")
f.close()
but what is a little more elegant solution?
A:
f.write("""I’ve got a lovely bunch of coconuts
There they are all... | write a paragraph to a file | Ok this is simple, I want to write a huge paragraph of text to a file. I know I can do
f=open("blah.txt",'w')
f.write("blah blah \n")
f.write("bla blah blah ")
f.close()
but what is a little more elegant solution?
| [
"f.write(\"\"\"I’ve got a lovely bunch of coconuts\nThere they are all standing in a row\nBig ones, small ones, some as big as your head\nGive them a twist a flick of the wrist\nThat’s what the showman said\"\"\")\n\n",
"You can use the 3 quote string declaration like so.\n>>> a = '''blah blah blah blah\nblah bla... | [
18,
3
] | [] | [] | [
"python"
] | stackoverflow_0005226862_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.