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:
How to execute JS from Python, that uses 'Document' and/or 'Window'
I am currently working on getting JavaScript to execute successfully from within Python. I have implemented a JS engine (v8) using the PyV8 package. From here I can execute primitive JavaScript ("1+2", etc). However, for JavaScript that uses refer... | How to execute JS from Python, that uses 'Document' and/or 'Window' | I am currently working on getting JavaScript to execute successfully from within Python. I have implemented a JS engine (v8) using the PyV8 package. From here I can execute primitive JavaScript ("1+2", etc). However, for JavaScript that uses references to "document" or "window" the code will throw an error. I am lookin... | [
"I was having the same problem when using Spidermonkey (a command-line JavaScript interpreter) and trying to run a script that relied on the non-existent document and window objects.\nI solved it by using the Env-JS project, which sets up independent \"fake\" objects for them.\n"
] | [
3
] | [] | [] | [
"javascript",
"python",
"v8"
] | stackoverflow_0003182034_javascript_python_v8.txt |
Q:
Python - render HTML content to GIF image
How can I render HTML content to GIF image?
I found how to render it to PDF using reportlab, but no luck with GIF.
I want something like xhtml2pdf.com but final result should be not in pdf, but in image.
A:
There's a similar SO question, Python library for rendering HTML... | Python - render HTML content to GIF image | How can I render HTML content to GIF image?
I found how to render it to PDF using reportlab, but no luck with GIF.
I want something like xhtml2pdf.com but final result should be not in pdf, but in image.
| [
"There's a similar SO question, Python library for rendering HTML and javascript , but I'm not sure the answers are satisfying.\nI might try two-stage rendering: HTML -> pdf -> gif. In that case, reportlab gets you pdf, and PythonMagick (http://wiki.python.org/moin/ImageMagick) can convert the pdf to GIF.\n"
] | [
2
] | [] | [] | [
"gif",
"html",
"python"
] | stackoverflow_0003159367_gif_html_python.txt |
Q:
Django File Uploads and Model FileField
I'm sooo close... but I don't quite see the connection from the upload view to the model. When I use the callback in the model's FileField the upload works, but I'm not sure where the actual file copy is taking place. The goal is to make sure that chunking is happening, but ... | Django File Uploads and Model FileField | I'm sooo close... but I don't quite see the connection from the upload view to the model. When I use the callback in the model's FileField the upload works, but I'm not sure where the actual file copy is taking place. The goal is to make sure that chunking is happening, but the file copy action seems to be hidden somew... | [
"The storing happens here: http://code.djangoproject.com/browser/django/trunk/django/db/models/fields/files.py#L90. Django uses it's own API for accessing the file storage: http://docs.djangoproject.com/en/dev/ref/files/storage/. But if chunking is what you need you can go with Bartek's proposal!\n"
] | [
1
] | [] | [] | [
"django",
"file",
"python",
"upload"
] | stackoverflow_0003181574_django_file_python_upload.txt |
Q:
How do I make it so a two top level widgets can't be open simultaneously?
I have a top level widget that is created when a button is pressed. How do I make it so when that same button is pressed again, while the top level widget is still open it simply moves the top level widget into focus?
A:
Imagine you have... | How do I make it so a two top level widgets can't be open simultaneously? | I have a top level widget that is created when a button is pressed. How do I make it so when that same button is pressed again, while the top level widget is still open it simply moves the top level widget into focus?
| [
"Imagine you have the following method in a class. This method is called when you press the button. You will also have an instance attribute defined in the __init__ method: self.toplevel = None.\ndef button_press(self):\n if self.toplevel is None:\n self.toplevel = ... # another method to create toplevel ... | [
1
] | [] | [] | [
"python",
"tkinter"
] | stackoverflow_0003182198_python_tkinter.txt |
Q:
Retrieving flickr favorites
I can't get this to work... what could be the problem?
import flickrapi
api_key = '1234...'
flickr = flickrapi.FlickrAPI(api_key)
user = '43699959@N02'
favs = flickr.favorites_getPublicList(user_id = user)
>>> favs.items()
[('stat', 'ok')]
>>> favs.text
'\n'
Where are my favorite p... | Retrieving flickr favorites | I can't get this to work... what could be the problem?
import flickrapi
api_key = '1234...'
flickr = flickrapi.FlickrAPI(api_key)
user = '43699959@N02'
favs = flickr.favorites_getPublicList(user_id = user)
>>> favs.items()
[('stat', 'ok')]
>>> favs.text
'\n'
Where are my favorite photo's?
Note: It does work via th... | [
"The result is correct -- as per the URL you gave, the XML nodes are empty (plus/minus newline and whitespace characters, apparently). favs.text would return the content, but what you're looking for is in the attributes. Try this:\nfor photo in favs.find('photos').findall('photo'):\n print photo.get('id')\n\nRes... | [
4
] | [] | [] | [
"api",
"flickr",
"python"
] | stackoverflow_0003182269_api_flickr_python.txt |
Q:
What is a good first-implementation for learning machine learning?
I find learning new topics comes best with an easy implementation to code to get the idea. This is how I learned genetic algorithms and genetic programming. What would be some good introductory programs to write to get started with machine learni... | What is a good first-implementation for learning machine learning? | I find learning new topics comes best with an easy implementation to code to get the idea. This is how I learned genetic algorithms and genetic programming. What would be some good introductory programs to write to get started with machine learning?
Preferably, let any referenced resources be accessible online so the... | [
"What language(s) will you develop in? If you are flexible, I recommend Matlab, python and R as good candidates. These are some of the more common languages used to develop and evaluate algorithms. They facilitate rapid algorithm development and evaluation, data manipulation and visualization. Most of the popul... | [
12,
4,
1,
1
] | [
"There is something called books; are you familiar with those? When I was exploring AI two decades ago, there were many books. I guess now that the internet exists, books are archaic, but you can probably find some in an ancient library.\n"
] | [
-8
] | [
"artificial_intelligence",
"computer_science",
"machine_learning",
"python"
] | stackoverflow_0003176967_artificial_intelligence_computer_science_machine_learning_python.txt |
Q:
add append update and extend in python
Is there an article or forum discussion or something somewhere that explains why lists use append/extend but sets and dicts use add/update.
I frequently find myself converting lists into sets and this difference makes that quite tedious so for my personal sanity I'd like to k... | add append update and extend in python | Is there an article or forum discussion or something somewhere that explains why lists use append/extend but sets and dicts use add/update.
I frequently find myself converting lists into sets and this difference makes that quite tedious so for my personal sanity I'd like to know what the rationalization is.
The need to... | [
"append has a popular definition of \"add to the very end\", and extend can be read similarly (in the nuance where it means \"...beyond a certain point\"); sets have no \"end\", nor any way to specify some \"point\" within them or \"at their boundaries\" (because there are no \"boundaries\"!), so it would be highly... | [
6,
3,
2
] | [] | [] | [
"dictionary",
"list",
"python",
"set"
] | stackoverflow_0003182760_dictionary_list_python_set.txt |
Q:
Displaying other language characters in PyQt
Is there a way to display other language characters in PyQt4?
and if there is, what's the approach/direction that I should take?
Thanks in advance.
A:
Qt uses Unicode and should be able to display (Unicode) text in any language you have a suitable font for. For examp... | Displaying other language characters in PyQt | Is there a way to display other language characters in PyQt4?
and if there is, what's the approach/direction that I should take?
Thanks in advance.
| [
"Qt uses Unicode and should be able to display (Unicode) text in any language you have a suitable font for. For example, Roberto Alesina's simple \"Hello World\" program on the PyQt Wiki -- which I transcribe for readability (and w/o the comments for brevity) since it's pretty unreadable in the wiki -- should let ... | [
5
] | [] | [] | [
"pyqt",
"pyqt4",
"python",
"unicode"
] | stackoverflow_0003183044_pyqt_pyqt4_python_unicode.txt |
Q:
Any reason not to modify another class's variables?
Forms have Fields. Fields have a Widget. If a Field name is omitted, it takes the variable name specified in the form. For example,
MyForm(Form):
username = Field(name=None, widget=MyWidget(args))
The field name would become "username". However, this can't b... | Any reason not to modify another class's variables? | Forms have Fields. Fields have a Widget. If a Field name is omitted, it takes the variable name specified in the form. For example,
MyForm(Form):
username = Field(name=None, widget=MyWidget(args))
The field name would become "username". However, this can't be established until the form is constructed. Would it be ... | [
"Some OO purists might perhaps object, but IMHO there is really no problem in setting public attributes in instances of other classes -- worst case, if later on you find that instance needs to take some action when certain attributes are set, you'll just turn the attribute into a property, so that a \"setter method... | [
3
] | [] | [] | [
"design_patterns",
"python"
] | stackoverflow_0003183150_design_patterns_python.txt |
Q:
reading file data mixing strings and numbers in python
I would like to read different files in one directory with the following structure:
# Mj = 1.60 ff = 7580.6 gg = 0.8325
I would like to read the numbers from each file and associate every one to a vector.
If we assume I have 3 files, I will ... | reading file data mixing strings and numbers in python | I would like to read different files in one directory with the following structure:
# Mj = 1.60 ff = 7580.6 gg = 0.8325
I would like to read the numbers from each file and associate every one to a vector.
If we assume I have 3 files, I will have 3 components for vector Mj, ...
How can I do it in Pyth... | [
"I'd use a regular expression to take the line apart:\nimport re\nlineRE = re.compile(r'''\n \\#\\s*\n Mj\\s*=\\s*(?P<Mj>[-+0-9eE.]+)\\s*\n ff\\s*=\\s*(?P<ff>[-+0-9eE.]+)\\s*\n gg\\s*=\\s*(?P<gg>[-+0-9eE.]+)\n ''', re.VERBOSE)\n\nfor filename in filenames:\n for line in file(filename, 'r'):\n ... | [
1,
0
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0003181460_file_io_python.txt |
Q:
Using python function callbacks with PyObjC?
I'm trying to use an Objective-C class made in Python to do this but Objective-C can't call the method which calls the python function.
Here's the framework code which the Objective-C code:
//
// scalelib.h
// Scalelib Cocoa Framework
//
// Created by Matthew Mitchel... | Using python function callbacks with PyObjC? | I'm trying to use an Objective-C class made in Python to do this but Objective-C can't call the method which calls the python function.
Here's the framework code which the Objective-C code:
//
// scalelib.h
// Scalelib Cocoa Framework
//
// Created by Matthew Mitchell on 04/07/2010.
// Copyright 2010 __MyCompanyNam... | [
"My guess would be retain counts.\nYou don't retain the result of create_callback() that you pass into the addPyFunc_\nAs such, it probably gets garbage collected away before you call it.\n"
] | [
2
] | [] | [] | [
"cocoa",
"objective_c",
"pyobjc",
"python",
"segmentation_fault"
] | stackoverflow_0003180385_cocoa_objective_c_pyobjc_python_segmentation_fault.txt |
Q:
Where to store field data and how to provide access to it?
Forms have Fields, Fields have a value. However, they only get a value after the form has been submitted.
How should I store this value? Should I give every field a value attribute, field.value,
leave it as None prior to posting, and fill it in afterwor... | Where to store field data and how to provide access to it? | Forms have Fields, Fields have a value. However, they only get a value after the form has been submitted.
How should I store this value? Should I give every field a value attribute, field.value,
leave it as None prior to posting, and fill it in afterwords?
Omit it completely, and dynamically add it?
Store it on t... | [
"It really depends on how you interact with the structures in question. Do you manipulate Form and Field objects prior to assigning them values? Do you need to frequently iterate over all the given Fields? Do you need Form once it's been submitted? Etc.\nI'd suggest writing some/all of the code that uses Form and f... | [
1,
1
] | [] | [] | [
"design_patterns",
"python"
] | stackoverflow_0003183431_design_patterns_python.txt |
Q:
Unable to modify a global int, but can modify a list. How?
LISTL = []
VAR1 = 0
def foo():
... VAR1 += 1
... return VAR1
...
On calling foo(), I get this error:
UnboundLocalError: local variable 'VAR1' referenced before assignment
However, consider the list LISTL... | Unable to modify a global int, but can modify a list. How? |
LISTL = []
VAR1 = 0
def foo():
... VAR1 += 1
... return VAR1
...
On calling foo(), I get this error:
UnboundLocalError: local variable 'VAR1' referenced before assignment
However, consider the list LISTL
>>> def foo(x):
... LISTL.append(x)
... return LIS... | [
"The reason for this difference has to do with how Python namespaces the names. If you're inside a function definition (def foo():), and you ACCESS a name (VAR1 or LISTL), it will first search your local namespace, where it will find nothing, and then it will search the namespace of the module the function was defi... | [
5,
4
] | [] | [] | [
"python"
] | stackoverflow_0003183633_python.txt |
Q:
How do I upload data to Google App Engine periodically?
I'm writing an aggregation application which scrapes data from a couple of web sources and displays that data with a novel interface. The sites from which I'm scraping update every couple of minutes, and I want to make sure the data on my aggregator is up-to-... | How do I upload data to Google App Engine periodically? | I'm writing an aggregation application which scrapes data from a couple of web sources and displays that data with a novel interface. The sites from which I'm scraping update every couple of minutes, and I want to make sure the data on my aggregator is up-to-date.
What's the best way to periodically submit fresh data t... | [
"Write a Task Queue task or an App Engine cron job to handle this. I'm not sure where you heard that there's a limit of 1 second on any sort of App Engine operations - requests are limited to 30 seconds, and URL fetches have a maximum deadline of 10 seconds.\n",
"The only way to get data into AppEngine is to call... | [
3,
0,
0,
0,
0
] | [] | [] | [
"automation",
"google_app_engine",
"python",
"security"
] | stackoverflow_0001689570_automation_google_app_engine_python_security.txt |
Q:
Python and C coupling
I tried loading C shared library .so in Python using ctypes.CDLL class (Linux). Here is the link to which tells what I did. As I see the documentation it says CDLL class assumes that function returns int types. I've a doubt here what if I need to return variable of type other than the int typ... | Python and C coupling | I tried loading C shared library .so in Python using ctypes.CDLL class (Linux). Here is the link to which tells what I did. As I see the documentation it says CDLL class assumes that function returns int types. I've a doubt here what if I need to return variable of type other than the int type from a function in C?.
A... | [
"By default, it assumes int, but you can set restype to any of the supported types to override that. E.g., from the docs:\nstrchr.restype = c_char_p\n\nThis means that strchr returns a pointer to a char, which corresponds to a Python string (or None, for a NULL pointer).\n"
] | [
4
] | [] | [] | [
"c",
"python"
] | stackoverflow_0003183740_c_python.txt |
Q:
Calling custom Objective-C from a pyobjc application?
This question is basically the inverse of this other question: Calling Python from Objective-C
I have implemented my iPhone application logic in Objective-C (obviously), and am now trying to re-use as much as possible from my XCode project in the server compone... | Calling custom Objective-C from a pyobjc application? | This question is basically the inverse of this other question: Calling Python from Objective-C
I have implemented my iPhone application logic in Objective-C (obviously), and am now trying to re-use as much as possible from my XCode project in the server component to save on double-implementation. I have successfully l... | [
"If your Objective-C code is in a framework and you would like to essentially write a Python application that uses your framework, then you can use objc.loadBundle, and then use objc.lookUpClass or NSClassFromString to get access to your classes. From there, you can use your classes like any other bridged Objective... | [
1
] | [] | [] | [
"iphone",
"objective_c",
"pyobjc",
"python"
] | stackoverflow_0003180574_iphone_objective_c_pyobjc_python.txt |
Q:
Using variables in Django urlpatterns
The components of the URLs of the Django app I'm working on are very 'pluggable', and different combinations of them get used in various urlpatterns, so our urls.py looks something like:
rev = r'(/R\.(?P<rev>\d+))?'
repo_type= r'^(?P<repo_type>svn|hg)/'
path = r'/dir/(?P<path>... | Using variables in Django urlpatterns | The components of the URLs of the Django app I'm working on are very 'pluggable', and different combinations of them get used in various urlpatterns, so our urls.py looks something like:
rev = r'(/R\.(?P<rev>\d+))?'
repo_type= r'^(?P<repo_type>svn|hg)/'
path = r'/dir/(?P<path>.*)$'
# etc.
urlpatterns = patterns('',
... | [
"I found that this pattern works for redirects and might help in your case (unless I am interpreting your question incorrectly). I couldn't reverse a pattern within the same tuple but if I defined a new tuple and then concatenated a new tuple to the original Djanogo would reflect without issue.\nex:\n urlpatterns ... | [
1,
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003174174_django_python.txt |
Q:
Is it OK to exchange tuples between Python modules?
I have a small Python program consisting of very few modules (about 4 or so). The main module creates a list of tuples, thereby representing a number of records. These tuples are available to the other modules through a simple function that returns them (say, ge... | Is it OK to exchange tuples between Python modules? | I have a small Python program consisting of very few modules (about 4 or so). The main module creates a list of tuples, thereby representing a number of records. These tuples are available to the other modules through a simple function that returns them (say, get_records()).
I am not sure if this is good design howev... | [
"http://docs.python.org/library/collections.html#namedtuple-factory-function-for-tuples-with-named-fields\n",
"i do not see any overhead or complexity in passing objects over tuples(tuples are also objects)\nIMO if tuple serves your purpose easily use it, but as you have seen the constraints just switch to a clas... | [
5,
4,
0
] | [] | [] | [
"coupling",
"python",
"tuples"
] | stackoverflow_0003184089_coupling_python_tuples.txt |
Q:
Google App Engine with local Django 1.1 gets Intermittent Failures
I'm using the Windows Launcher development environment for Google App Engine.
I have downloaded Django 1.1.2 source, and un-tarrred the "django" subdirectory to live within my application directory (a peer of app.yaml)
At the top of each .py source... | Google App Engine with local Django 1.1 gets Intermittent Failures | I'm using the Windows Launcher development environment for Google App Engine.
I have downloaded Django 1.1.2 source, and un-tarrred the "django" subdirectory to live within my application directory (a peer of app.yaml)
At the top of each .py source file, I do this:
import settings
import os
os.environ["DJANGO_SETTINGS_... | [
"Firstly, although django is now a LOT more compatible with app engine than it once, some major incompatibilities still exist between the two platforms, meaning that you can't just dump a stock copy of django into your appengine directory and have it work out of the box. Things will error in strange ways.\nThere ar... | [
1,
0
] | [] | [] | [
"debugging",
"django",
"google_app_engine",
"intermittent",
"python"
] | stackoverflow_0002986258_debugging_django_google_app_engine_intermittent_python.txt |
Q:
Alternate host/IP for python script
I want my Python script to access a URL through an IP specified in the script instead of through the default DNS for the domain. Basically I want the equivalent of adding an entry to my /etc/hosts file, but I want the change to apply only to my script instead of globally on the ... | Alternate host/IP for python script | I want my Python script to access a URL through an IP specified in the script instead of through the default DNS for the domain. Basically I want the equivalent of adding an entry to my /etc/hosts file, but I want the change to apply only to my script instead of globally on the whole server. Any ideas?
| [
"Whether this works or not will depend on whether the far end site is using HTTP/1.1 named-based virtual hosting or not.\nIf they're not, you can simply replace the hostname part of the URL with their IP address, per @Greg's answer.\nIf they are, however, you have to ensure that the correct Host: header is sent as ... | [
2,
0
] | [] | [] | [
"dns",
"hosts",
"python",
"urllib"
] | stackoverflow_0003183617_dns_hosts_python_urllib.txt |
Q:
Zooming into a Clutter CairoTexture while re-drawing
I am using python-clutter 1.0
My question in the form of a challenge
Write code to allow zooming up to a CairoTexture actor, by pressing a key, in steps such that at each the actor can be re-drawn (by cairo) so that the image remains high-res but still scales as... | Zooming into a Clutter CairoTexture while re-drawing | I am using python-clutter 1.0
My question in the form of a challenge
Write code to allow zooming up to a CairoTexture actor, by pressing a key, in steps such that at each the actor can be re-drawn (by cairo) so that the image remains high-res but still scales as expected, without re-sizing the actor.
Think of something... | [
"Well, despite all my tests and hacks, it was right under my nose all along. \nThanks to Neil on the clutter-project list, here's the scoop:\nCT = SomeCairoTextureActor()\n\n# record the old height, once:\nold_width, old_height = CT.get_size()\n\nStart a loop:\n# Do stuff to the depth of CT (or it's parent)\n...\n\... | [
2
] | [] | [] | [
"cairo",
"clutter",
"python",
"scaletransform",
"zooming"
] | stackoverflow_0003176011_cairo_clutter_python_scaletransform_zooming.txt |
Q:
Python List Division/Splitting
Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
Hello,
I'm trying to find a simpler way to do the following:
def list_split(list, size):
result = [[]]
while len(list) > 0:
if len(result[-1]) >= size: result.append([])
result[-1].append(li... | Python List Division/Splitting |
Possible Duplicate:
How do you split a list into evenly sized chunks in Python?
Hello,
I'm trying to find a simpler way to do the following:
def list_split(list, size):
result = [[]]
while len(list) > 0:
if len(result[-1]) >= size: result.append([])
result[-1].append(list.pop(0))
return result
Example... | [
"You could use slices to get subsets of a list.\nExample:\n>>> L = [0, 1, 2, 3, 4, 5, 6]\n>>> n = 3\n>>> [L[i:i+n] for i in range(0, len(L), n)]\n[[0, 1, 2], [3, 4, 5], [6]]\n>>>\n\n",
"def list_split(L, size):\n return [L[i*size:(i+1)*size] for i in range(1+((len(L)-1)//size))]\n\nIf you prefer a generator in... | [
9,
1,
1,
0
] | [] | [] | [
"list",
"python",
"split"
] | stackoverflow_0003183919_list_python_split.txt |
Q:
Tree matching algorithm?
I am working on a tree library, and part of the required functionality, is to be able to search a node for child nodes that match a pattern.
A 'pattern' is a specification (or criteria) that lays out the structure, as well as attributes of nodes in the subtree(s) to be matched.
For example... | Tree matching algorithm? | I am working on a tree library, and part of the required functionality, is to be able to search a node for child nodes that match a pattern.
A 'pattern' is a specification (or criteria) that lays out the structure, as well as attributes of nodes in the subtree(s) to be matched.
For example, suppose a tree represents da... | [
"What's wrong with writing a Lisp Sexpression with wildcards to describe the tree match? Parentheses group a node. Elements from left to right match the root followed by the children. Subtree matches use nested Sexpressions to describe the subtree.\nThe following would match a tree with arbitrary root node, first... | [
5,
3
] | [] | [] | [
"algorithm",
"python",
"tree"
] | stackoverflow_0003185530_algorithm_python_tree.txt |
Q:
Alternatives to my slow method of using BeautifulSoup and Python to parse Amazon API XML?
As the title says, I'm using the BS module in Python to parse XML pages that I access from the Amazon API (i create the signed url, load it with liburl2, and then parse with BS).
It takes about 4 seconds to do two pages, but ... | Alternatives to my slow method of using BeautifulSoup and Python to parse Amazon API XML? | As the title says, I'm using the BS module in Python to parse XML pages that I access from the Amazon API (i create the signed url, load it with liburl2, and then parse with BS).
It takes about 4 seconds to do two pages, but there has to be a faster way
Would PHP be faster? What's making it slow, the BS parsing or the ... | [
"If you want to find out what's making it slow, use one of the profilers. I suspect it's the network access (and their underlying database retrieval) that's slower than the rest.\n"
] | [
2
] | [] | [] | [
"beautifulsoup",
"parsing",
"python",
"xml"
] | stackoverflow_0003185747_beautifulsoup_parsing_python_xml.txt |
Q:
Controlling Linux Compiz Brightness Programmatically with Python or Vala
Several laptops on the market have problems with Linux for brightness controls. However, recently I found out that you can use CompizConfig settings to dim at least a particular window. Many people, however, want to dim all windows. I know Co... | Controlling Linux Compiz Brightness Programmatically with Python or Vala | Several laptops on the market have problems with Linux for brightness controls. However, recently I found out that you can use CompizConfig settings to dim at least a particular window. Many people, however, want to dim all windows. I know Compiz can do this in the API somewhere because look what happens when you do Su... | [
"You want to look into gnome-compiz especially into gtk-window-decorator and gnome-xgl-settings.\n"
] | [
1
] | [] | [] | [
"compiz",
"gnome",
"python",
"vala"
] | stackoverflow_0003177057_compiz_gnome_python_vala.txt |
Q:
python threading and queues for infinite data input (stream)
I would like to use thread to process a streaming input.
How can make the below code for an infinite input generate for example by using itertools.count
The code below will work if:
'for i in itertools.count():' is replaced by 'for i in xrange(5):'
fro... | python threading and queues for infinite data input (stream) | I would like to use thread to process a streaming input.
How can make the below code for an infinite input generate for example by using itertools.count
The code below will work if:
'for i in itertools.count():' is replaced by 'for i in xrange(5):'
from threading import Thread
from Queue import Queue, Empty
import it... | [
"The problem is that itertools.count generates an infinite sequence. This means the for loop will never end. You should put that in it's own function and make it a separate thread. This way you will have the queue growing while the worker threads get data off the queue.\n",
"You need to fill the queue with a thre... | [
2,
2,
1
] | [] | [] | [
"multiprocessing",
"multithreading",
"python",
"queue"
] | stackoverflow_0003185261_multiprocessing_multithreading_python_queue.txt |
Q:
shuffling a word
How do I shuffle a word's letters randomly in python?
For example, the word "cat" might be changed into 'act', 'tac' or 'tca'.
I would like to do this without using built-in functions
A:
import random
word = "cat"
shuffled = list(word)
random.shuffle(shuffled)
shuffled = ''.join(shuffled)
print(... | shuffling a word | How do I shuffle a word's letters randomly in python?
For example, the word "cat" might be changed into 'act', 'tac' or 'tca'.
I would like to do this without using built-in functions
| [
"import random\nword = \"cat\"\nshuffled = list(word)\nrandom.shuffle(shuffled)\nshuffled = ''.join(shuffled)\nprint(shuffled)\n\n...or done in a different way, inspired by Dominic's answer...\nimport random\nshuffled = ''.join(random.sample(word, len(word)))\n\n",
"Take a look at the Fisher-Yates shuffle. It's ... | [
10,
7,
4,
3,
1,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0003182964_python.txt |
Q:
Convert HTTP Proxy to HTTPS Proxy in Twisted
Recently I have been playing around with the HTTP Proxy in twisted. After much trial and error I think I finally I have something working. What I want to know though, is how, if it is possible, do I expand this proxy to also be able to handle HTTPS pages? Here is what I... | Convert HTTP Proxy to HTTPS Proxy in Twisted | Recently I have been playing around with the HTTP Proxy in twisted. After much trial and error I think I finally I have something working. What I want to know though, is how, if it is possible, do I expand this proxy to also be able to handle HTTPS pages? Here is what I've got so far:
from twisted.internet import react... | [
"If you want to connect to an HTTPS website via an HTTP proxy, you need to use the CONNECT HTTP verb (because that's how a proxy works for HTTPS). In this case, the proxy server simply connects to the target server and relays whatever is sent by the server back to the client's socket (and vice versa). There's no ca... | [
15,
2
] | [] | [] | [
"http",
"https",
"proxy",
"python",
"twisted"
] | stackoverflow_0003118602_http_https_proxy_python_twisted.txt |
Q:
How to initialize model with calculated value
I have a Django model Reminder related to Event model.
class Reminder(models.Model):
email = models.EmailField("e-mail")
event = models.ForeignKey(Event, unique=True, related_name='event',)
date = models.DateTimeField(_(u"Remind date"), auto_now_add=False,)... | How to initialize model with calculated value | I have a Django model Reminder related to Event model.
class Reminder(models.Model):
email = models.EmailField("e-mail")
event = models.ForeignKey(Event, unique=True, related_name='event',)
date = models.DateTimeField(_(u"Remind date"), auto_now_add=False,)
class Event(models.Model):
date = models.Date... | [
"I don't know what exactly you need, but:\n1) If you need Reminder.date always return Event.date - 7\nimport datetime\n\n\nclass Reminder(models.Model):\n email = models.EmailField(\"e-mail\")\n event = models.ForeignKey(Event, unique=True, related_name='event',)\n\n def date(self):\n return self.ev... | [
2,
1
] | [] | [] | [
"django",
"django_models",
"initialization",
"python"
] | stackoverflow_0003183133_django_django_models_initialization_python.txt |
Q:
Python regex \w doesn't match combining diacritics?
I have a UTF8 string with combining diacritics. I want to match it with the \w regex sequence. It matches characters that have accents, but not if there is a latin character with combining diacritics.
>>> re.match("a\w\w\wz", u"aoooz", re.UNICODE)
<_sre.SRE_Match... | Python regex \w doesn't match combining diacritics? | I have a UTF8 string with combining diacritics. I want to match it with the \w regex sequence. It matches characters that have accents, but not if there is a latin character with combining diacritics.
>>> re.match("a\w\w\wz", u"aoooz", re.UNICODE)
<_sre.SRE_Match object at 0xb7788f38>
>>> print u"ao\u00F3oz"
aoóoz
>>> ... | [
"I've just noticed a new \"regex\" package on pypi. (if I understand correctly, it is a test version of a new package that will someday replace the stdlib re package). \nIt seems to have (among other things) more possibilities with regard to unicode. For example, it supports \\X, which is used to match a single gra... | [
7,
2
] | [] | [] | [
"diacritics",
"python",
"regex",
"unicode",
"unicode_normalization"
] | stackoverflow_0003141032_diacritics_python_regex_unicode_unicode_normalization.txt |
Q:
Boost.Python on Mac OS X: "TypeError: Attribute name must be string"
I recently installed Boost using MacPorts, with the intent to do some Python embedding in C++. I then decided to check if I configured Xcode correctly with an example found on Python's website:
#include <boost/python.hpp>
using namespace boost::... | Boost.Python on Mac OS X: "TypeError: Attribute name must be string" | I recently installed Boost using MacPorts, with the intent to do some Python embedding in C++. I then decided to check if I configured Xcode correctly with an example found on Python's website:
#include <boost/python.hpp>
using namespace boost::python;
int main( int argc, char ** argv )
{
try
{
Py_I... | [
"Your code worked for me with the following configuration:\n\nSnow Leopard \ngcc version 4.2.1 (AppleInc. build 5646) \nBoost 1.41.0 installed to /usr/local/boost/1_41_0/\nStock OSX Python 2.5\n\nCompiled using:\ng++ -I/Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/Python.framework/Versions/2.6/include/py... | [
1
] | [] | [] | [
"boost_python",
"c++",
"python"
] | stackoverflow_0003089586_boost_python_c++_python.txt |
Q:
Python scripts (curses + pysqlite) hanging after parent shell goes away
I've written a python script which does some curses and pysqlite stuff, but I've noticed that in occasions where I've been running this script over ssh when that ssh session is killed for whatever reason the python script doesn't actually exit... | Python scripts (curses + pysqlite) hanging after parent shell goes away | I've written a python script which does some curses and pysqlite stuff, but I've noticed that in occasions where I've been running this script over ssh when that ssh session is killed for whatever reason the python script doesn't actually exit, instead it ends up as being a child of init and just stays there forever. I... | [
"Well, the reason they're not shutting down when your ssh session terminates is because HUP is the signal used by a parent to inform its children that they should shut down. If you're overriding the behavior of this signal, then your processes will not automatically shut down when the SSH session is closed. As for ... | [
1
] | [] | [] | [
"exit",
"python",
"signals",
"ssh"
] | stackoverflow_0003184974_exit_python_signals_ssh.txt |
Q:
how to parse a string to spider from another script
I am new to python and scrapy .
I am running the scrapy-ctl.py from another python script using
subprocess module.But I want to parse the 'start url' to the spider from
this script itself.Is it possible to parse start_urls(which are
determined in the script f... | how to parse a string to spider from another script | I am new to python and scrapy .
I am running the scrapy-ctl.py from another python script using
subprocess module.But I want to parse the 'start url' to the spider from
this script itself.Is it possible to parse start_urls(which are
determined in the script from which scrapy-ctl is run) to the spider?
I will be gr... | [
"You can override the start_requests() method in your spider to get the starting requests (which, by default, are generated using the urls in the start_urls attribute).\n"
] | [
2
] | [] | [] | [
"python",
"scrapy",
"web_crawler",
"windows"
] | stackoverflow_0003179979_python_scrapy_web_crawler_windows.txt |
Q:
one field with different data types [SQLAlchemy]
I have a value that can be integer, float or string, and I created different columns:
#declarative
class MyClass(Base):
#id and other Columns
_value_str = Column(String(100))
_value_int = Column(Integer)
_value_float = Column(Float)
def __ini... | one field with different data types [SQLAlchemy] | I have a value that can be integer, float or string, and I created different columns:
#declarative
class MyClass(Base):
#id and other Columns
_value_str = Column(String(100))
_value_int = Column(Integer)
_value_float = Column(Float)
def __init__(self,...,value):
self._value_str = value i... | [
"Probably a design problem - a bit of a mismatch between your DB and Python. In SQL variables (columns) have a type, whereas in python values have the type.\nOne possibility would be to use a single column (a string), but pickle the value before you store it.\nThis can be accomplished automatically with a sqlalchem... | [
4
] | [] | [] | [
"database_design",
"python",
"sqlalchemy"
] | stackoverflow_0003167842_database_design_python_sqlalchemy.txt |
Q:
migrating django 1.1.1 -> 1.2.1: {% url %} doesn't work
I am migrating a django project from 1.1.1 to 1.2.1
Now neither the {% url %} tag works nor the @models.permalink-decorated get_absulute_url works
i.e. I get
TemplateSyntaxError at /
Caught TypeError while rendering: __init__() got an unexpected keyword argum... | migrating django 1.1.1 -> 1.2.1: {% url %} doesn't work | I am migrating a django project from 1.1.1 to 1.2.1
Now neither the {% url %} tag works nor the @models.permalink-decorated get_absulute_url works
i.e. I get
TemplateSyntaxError at /
Caught TypeError while rendering: __init__() got an unexpected keyword argument 'error_message'
for
<li><a href="{% url archive_talks %... | [
"This problem has nothing to do with the actual {% url %} tag. The reason you're hitting it on that tag is that the process of URL reversing actually imports all your Django views, and there is an error in a completely different place: the BlogForm class. \nWithout the code of that form it's hard to tell exactly wh... | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003186502_django_python.txt |
Q:
Django without additional tables?
is it possible to write Django apps, for example for internal/personal use with existing databases, without having the 'overhead' of Djangos own tables that are usually installed when starting a project? I would like to use existing tables via models, but not have all the other st... | Django without additional tables? | is it possible to write Django apps, for example for internal/personal use with existing databases, without having the 'overhead' of Djangos own tables that are usually installed when starting a project? I would like to use existing tables via models, but not have all the other stuff that is surely useful on normal web... | [
"Django doesn't install any tables by itself. It comes with some pre-fabricated applications, which install tables, but those are easily disabled by removing them from the INSTALLED_APPS setting.\n",
"You can also just add an extra database (set it as default) for keeping the extra django overhead stuff in:\nDATA... | [
3,
2,
1,
0,
0
] | [] | [] | [
"database",
"django",
"python"
] | stackoverflow_0001313362_database_django_python.txt |
Q:
is it possible to connect a href link in QTextBrowser to a slot?
is it possible to connect a href link in QTextBrowser to a slot?
I want to make something that looks like a link in a QTextBrowser, but when user clicked on it, it will call one of the methods.
Is that possible?
if that is not, what is a good alterna... | is it possible to connect a href link in QTextBrowser to a slot? | is it possible to connect a href link in QTextBrowser to a slot?
I want to make something that looks like a link in a QTextBrowser, but when user clicked on it, it will call one of the methods.
Is that possible?
if that is not, what is a good alternative?
Thanks in advance.
| [
"i finally found out how.\nthere's a signal call anchorClicked(QUrl)\nthat should do the trick :)\n"
] | [
1
] | [] | [] | [
"pyqt4",
"python"
] | stackoverflow_0003186576_pyqt4_python.txt |
Q:
Organizing multiple Python applications and shared library packages
Suppose that I am writing two applications for my employer, we'll call them App1 and App2. These applications depend on some packages containing code needed by both. Let's say that App1 depends on PackageA and PackageB. App2 depends on PackageB an... | Organizing multiple Python applications and shared library packages | Suppose that I am writing two applications for my employer, we'll call them App1 and App2. These applications depend on some packages containing code needed by both. Let's say that App1 depends on PackageA and PackageB. App2 depends on PackageB and PackageC. The organizing strategy that seems natural to me would be to ... | [
"One solution you can use for this is to have a virtualenv for each of your apps, and then use a relative .pth file to point to the Packages. This gives you fine control over the environment each of the apps is being developed in and avoids the \"but I've got package_x on my machine!\" problems in testing.\n",
"v... | [
3,
1
] | [] | [] | [
"package",
"python"
] | stackoverflow_0003187064_package_python.txt |
Q:
How do I call a Python/Perl script in bin folder from a Bash script?
I previously used to copy Python/Perl scripts to access from my bash script. Duplication is not a good idea I know! Is there a way to call them from bin or libs folder that we have set up?
For instance :
My python script resides in /home/ThinkC... | How do I call a Python/Perl script in bin folder from a Bash script? | I previously used to copy Python/Perl scripts to access from my bash script. Duplication is not a good idea I know! Is there a way to call them from bin or libs folder that we have set up?
For instance :
My python script resides in /home/ThinkCode/libs/python/script.py
My bash script resides in /home/ThinkCode/NewPro... | [
"Make this the first line of your python script (bash will then know this is a python script and it should be run with python):\n#/usr/bin/env python\n\nEDIT: my bad, it should be #!/usr/bin/env python not #!/usr/bin/python. It is better to do it this way.\nThen chmod your script with u+x (if not a+x). \nNow your p... | [
4,
3,
1
] | [] | [] | [
"bash",
"perl",
"python"
] | stackoverflow_0003187301_bash_perl_python.txt |
Q:
How can I get the CPU temperature in Python?
Possible Duplicate:
Getting CPU temperature using Python?
What is the simplest method of going about this? Also preferably in Celsius.
A:
There's no standard Python library for this, but on various platforms you may be able to use a Python bridge to a platform API ... | How can I get the CPU temperature in Python? |
Possible Duplicate:
Getting CPU temperature using Python?
What is the simplest method of going about this? Also preferably in Celsius.
| [
"There's no standard Python library for this, but on various platforms you may be able to use a Python bridge to a platform API to access this information.\nFor example on Windows this is available through the Windows Management Instrumentation (WMI) APIs, which are available to Python through the PyWin32 library. ... | [
5,
0
] | [] | [] | [
"cpu",
"python",
"temperature"
] | stackoverflow_0003184012_cpu_python_temperature.txt |
Q:
what is the system function in python
I want to play with system command in python . for example we have this function in perl : system("ls -la"); and its run ls -la what is the system function in python ?
Thanks in Advance .
A:
It is os.system:
import os
os.system('ls -la')
But this won't give you any output.... | what is the system function in python | I want to play with system command in python . for example we have this function in perl : system("ls -la"); and its run ls -la what is the system function in python ?
Thanks in Advance .
| [
"It is os.system:\nimport os\nos.system('ls -la')\n\nBut this won't give you any output. So subprocess.check_output is probably more what you want:\n>>> import subprocess\n>>> subprocess.check_output([\"ls\", \"-l\", \"/dev/null\"])\n'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\\n'\n\n",
"import os\nos.sys... | [
6,
1,
1
] | [] | [] | [
"function",
"python"
] | stackoverflow_0003187933_function_python.txt |
Q:
combinations/permutations with no repeats across groupings
I'm looking for C or Python code to implement either of the two pseudocode functions:
function 1:
list1 = [0,1,2] #any list of single-integer elements
list2 = [0,3,4]
list3 = [0,2,4]
function1(list1, list2, list3)
>>> (0,3,2),(0,3,4),(0,4,2),(1,0,2),(1,... | combinations/permutations with no repeats across groupings | I'm looking for C or Python code to implement either of the two pseudocode functions:
function 1:
list1 = [0,1,2] #any list of single-integer elements
list2 = [0,3,4]
list3 = [0,2,4]
function1(list1, list2, list3)
>>> (0,3,2),(0,3,4),(0,4,2),(1,0,2),(1,0,4),(1,3,0),(1,3,2),(1,3,4),
(1,4,0),(1,4,2),(2,0,4),(2,3,0... | [
"from itertools import product\ndef function1(*seqs):\n return (x for x in product(*seqs) if len(x) == len(set(x)))\n\n>>> list(function1([0,1,2], [0,3,4], [0,2,4]))\n[(0, 3, 2), (0, 3, 4), (0, 4, 2), (1, 0, 2), (1, 0, 4), (1, 3, 0), (1, 3, 2), (1, 3, 4), (1, 4, 0), (1, 4, 2), (2, 0, 4), (2, 3, 0), (2, 3, 4), (2, ... | [
4,
3,
1,
1,
0
] | [] | [] | [
"c",
"combinatorics",
"permutation",
"python"
] | stackoverflow_0003177409_c_combinatorics_permutation_python.txt |
Q:
Is there a fast XML parser in Python that allows me to get start of tag as byte offset in stream?
I am working with potentially huge XML files containing complex trace information from on of my projects.
I would like to build indexes for those XML files so that one can quickly find sub sections of the XML document... | Is there a fast XML parser in Python that allows me to get start of tag as byte offset in stream? | I am working with potentially huge XML files containing complex trace information from on of my projects.
I would like to build indexes for those XML files so that one can quickly find sub sections of the XML document without having to load it all into memory.
If I have created a "shelve" index that could contains info... | [
"Since locators return line and column numbers in lieu of offset, you need a little wrapping to track line ends -- a simplified example (could have some offbyones;-)...:\nimport cStringIO\nimport re\nfrom xml import sax\nfrom xml.sax import handler\n\nrelinend = re.compile(r'\\n')\n\ntxt = '''<foo>\n <ti... | [
3
] | [] | [] | [
"indexing",
"parsing",
"python",
"sax",
"xml"
] | stackoverflow_0003187964_indexing_parsing_python_sax_xml.txt |
Q:
Can i use dictionaries as matrices in python?
I am just a beginner in python. Recently i am learning to use dictionaries but my knowledge in it is still limited. I have this idea popping out from my head but i am not sure whether it is workable in python.
I have 3 document looks like this:
DOCNO= 5
nanofluids :0... | Can i use dictionaries as matrices in python? | I am just a beginner in python. Recently i am learning to use dictionaries but my knowledge in it is still limited. I have this idea popping out from my head but i am not sure whether it is workable in python.
I have 3 document looks like this:
DOCNO= 5
nanofluids :0.6841
introduction:0.2525
module :0.0000
to... | [
"First, you should look at the Python documentation for arrays. There are three things wrong with your sample code:\n\nYou've imported the array module, but not the array class. Try this:\nfrom array import array\nYou've got 0.0000.0000 as a float in your list.\narray takes two arguments; a typecode and the initi... | [
3,
0
] | [] | [] | [
"arrays",
"python"
] | stackoverflow_0003188058_arrays_python.txt |
Q:
Split field to array when accessed
I have Django model that looks like this:
class Categories(models.Model):
"""
Model for storing the categories
"""
name = models.CharField(max_length=8)
keywords = models.TextField()
spamwords = models.TextField()
translations = models.TextField()
... | Split field to array when accessed | I have Django model that looks like this:
class Categories(models.Model):
"""
Model for storing the categories
"""
name = models.CharField(max_length=8)
keywords = models.TextField()
spamwords = models.TextField()
translations = models.TextField()
def __unicode__(self):
return s... | [
"You can easily add an instance method to your Categories class like this:\nclass Categories(models.Model):\n ... rest of your definition ...\n\n def get_spamwords_as_list(self):\n return self.spamwords.split(',')\n\nYou could use it like this:\ncat = Categories.objects.get(id=1)\nprint cat.get_spamwords_... | [
1,
0
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0003187961_django_django_models_python.txt |
Q:
Generation of 8 bit palette from png file via Python
What would be the best python based library for generating 8-bit palette from the given .png file.
As in photoshop generating under .pal format.
PS: Input PNG is already in 8 bit format. (paletted)
Regards
A:
I've not been able to find a spec for .PAL (Photosh... | Generation of 8 bit palette from png file via Python | What would be the best python based library for generating 8-bit palette from the given .png file.
As in photoshop generating under .pal format.
PS: Input PNG is already in 8 bit format. (paletted)
Regards
| [
"I've not been able to find a spec for .PAL (Photoshop calls it \"Microsoft PAL\"), but the format is easily reverse-engineered. This works:\ndef extractPalette(infile,outfile):\n im=Image.open(infile)\n pal=im.palette.palette\n if im.palette.rawmode!='RGB':\n raise ValueError(\"Invalid mode in PNG ... | [
3,
1
] | [] | [] | [
"color_palette",
"palette",
"png",
"python"
] | stackoverflow_0003184821_color_palette_palette_png_python.txt |
Q:
Python regular expression style
Is there a Pythonic 'standard' for how regular expressions should be used?
What I typically do is perform a bunch of re.compile statements at the top of my module and store the objects in global variables... then later on use them within my functions and classes.
I could define the ... | Python regular expression style | Is there a Pythonic 'standard' for how regular expressions should be used?
What I typically do is perform a bunch of re.compile statements at the top of my module and store the objects in global variables... then later on use them within my functions and classes.
I could define the regexs within the functions I would b... | [
"One way that would be a lot cleaner is using a dictionary:\nPATTERNS = {'pattern1': re.compile('foo.*baz'),\n 'snake': re.compile('python'),\n 'knight': re.compile('[Aa]rthur|[Bb]edevere|[Ll]auncelot')}\n\nThat would solve your problem of having a polluted namespace, plus it's pretty obvious ... | [
6,
4,
1
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003188024_python_regex.txt |
Q:
Python and JSON: using object_hook to do class hinting for multiple different classes
Using the json module in python 2.6, I'm experiencing some unexpected behavior when passing a function to object_hook. I'm attempting to turn a json object into a class defined in my code. This class requires that instances of a ... | Python and JSON: using object_hook to do class hinting for multiple different classes | Using the json module in python 2.6, I'm experiencing some unexpected behavior when passing a function to object_hook. I'm attempting to turn a json object into a class defined in my code. This class requires that instances of a different class as arguments. Something like this:
class OuterClass:
def __init__(self,... | [
"Not every time create_OuterClass is called will __OuterClass__ be a key in dct. Therefore, your create_OuterClass should handle this case as well. The default is to return dct:\ndef create_OuterClass(dct):\n # print('create_OuterClass: {0}'.format(dct)) \n if '__OuterClass__' in dct:\n arg = dct['... | [
2
] | [] | [] | [
"json",
"python"
] | stackoverflow_0003188416_json_python.txt |
Q:
Python MySQL Performance: Runs fast in mysql command line, but slow with cursor.execute
I'm writing a script for exporting some data.
Some details about the environment:
The project is Django based
I'm using raw/custom SQL for the export
The database engine is MySQL.
The database and code are on the same box.-
D... | Python MySQL Performance: Runs fast in mysql command line, but slow with cursor.execute | I'm writing a script for exporting some data.
Some details about the environment:
The project is Django based
I'm using raw/custom SQL for the export
The database engine is MySQL.
The database and code are on the same box.-
Details about the SQL:
A bunch of inner joins
A bunch of columns selected, some with a basic ... | [
"Two ideas: \n\nMySQL may have query caching enabled, which makes it difficult to get accurate timing when you run the same query repeatedly. Try changing the ID in your query to make sure that it really does run in 3-4 seconds consistently.\nTry using strace on the python process to see what it is doing during th... | [
0
] | [] | [] | [
"mysql",
"performance",
"python"
] | stackoverflow_0003188289_mysql_performance_python.txt |
Q:
Python Google App Engine: A better way of saying, "If an object does not exist in the datastore, do something"?
I am asking because the way I have it right now seems really strange. Basically, I am saying, "If there is an exception thrown, do something. Else, do nothing." Here is some sample code:
try:
d... | Python Google App Engine: A better way of saying, "If an object does not exist in the datastore, do something"? | I am asking because the way I have it right now seems really strange. Basically, I am saying, "If there is an exception thrown, do something. Else, do nothing." Here is some sample code:
try:
db.get(db.Key(uid))
except:
newUser = User(key_name=str(uid))
newUser.first_name = self.request.get(... | [
"Use User.get_by_key_name(str(uid)) instead. It will return None if the entity doesn't exist. \nSee http://code.google.com/appengine/docs/python/datastore/modelclass.html#Model_get_by_key_name for details.\nUser.get_or_insert(str(uid)) might also be a good fit for what you're trying to do.\n",
"Does db.Key return... | [
6,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003188436_google_app_engine_python.txt |
Q:
Picking a front-end/interpreter for a scientific code
The simulation tool I have developed over the past couple of years, is written in C++ and currently has a tcl interpreted front-end. It was written such that it can be run either in an interactive shell, or by passing an input file. Either way, the input file... | Picking a front-end/interpreter for a scientific code | The simulation tool I have developed over the past couple of years, is written in C++ and currently has a tcl interpreted front-end. It was written such that it can be run either in an interactive shell, or by passing an input file. Either way, the input file is written in tcl (with many additional simulation-specifi... | [
"I was a strong Tcl/Tk proponent from pre-release, until I did a largish project with it and found how unmaintainable it is. Unfortunately, since prototypes are so easy in Tcl, you wind up with \"one-off\" scripts taking on lives of their own.\nHaving adopted Python in the last few months, I'm finding it to be all ... | [
5,
3,
0
] | [] | [] | [
"c++",
"interpreter",
"matlab",
"python",
"tcl"
] | stackoverflow_0003167661_c++_interpreter_matlab_python_tcl.txt |
Q:
Using Env.js with Python
I am having a bit of difficulty getting Env.js working with my Python application. The documentation on the website states:
develop bridges for running Envjs in Ruby, Python, and other host languages with the SpiderMonkey and V8 javascript engines
However, I have been unable to find any... | Using Env.js with Python | I am having a bit of difficulty getting Env.js working with my Python application. The documentation on the website states:
develop bridges for running Envjs in Ruby, Python, and other host languages with the SpiderMonkey and V8 javascript engines
However, I have been unable to find any bridges to Python in either t... | [
"Yeah, not sure where that text came from. I'm a committer on env.js and haven't heard of any integration efforts with python against V8 or SpiderMonkey.\nLooks like NoseJS has some integration, but it doesn't look too general. Looks to be against the Rhino port of env.js with some tentative comments about using Py... | [
1
] | [] | [] | [
"envjs",
"javascript",
"python"
] | stackoverflow_0003188541_envjs_javascript_python.txt |
Q:
Compress XML column in Sqlite with Python is SLOW!
I'm new to Python and Sqlite, so I'm sure there's a better way to do this. I have a DB with 6000 rows, where 1 column is a 14K XML string. I wanted to compress all those XML strings to make the DB smaller. Unfortunately, the script below is much, much slower than ... | Compress XML column in Sqlite with Python is SLOW! | I'm new to Python and Sqlite, so I'm sure there's a better way to do this. I have a DB with 6000 rows, where 1 column is a 14K XML string. I wanted to compress all those XML strings to make the DB smaller. Unfortunately, the script below is much, much slower than this simple command line (which takes a few seconds).
sq... | [
"Not sure you can increase the performance by doing an update after the fact. there's too much overhead between doing the compress and updating the record. you won't gain any space savings unless you do a vacuum after you're done with the updates. the best solution would probably be to do the compress when the reco... | [
2,
2,
1
] | [] | [] | [
"compression",
"performance",
"python",
"sqlite",
"xml"
] | stackoverflow_0003187755_compression_performance_python_sqlite_xml.txt |
Q:
How to make two directory-entries refer always to the same float-value
Consider this:
>>> foo = {}
>>> foo[1] = 1.0
>>> foo[2] = foo[1]
>>> foo
{1: 0.0, 2: 0.0}
>>> foo[1] += 1.0
{1: 1.0, 2: 0.0}
This is what happens. However, what I want would be that the last line reads:
{1: 1.0, 2: 1.0}
Meaning that both ref... | How to make two directory-entries refer always to the same float-value | Consider this:
>>> foo = {}
>>> foo[1] = 1.0
>>> foo[2] = foo[1]
>>> foo
{1: 0.0, 2: 0.0}
>>> foo[1] += 1.0
{1: 1.0, 2: 0.0}
This is what happens. However, what I want would be that the last line reads:
{1: 1.0, 2: 1.0}
Meaning that both refer to the same value, even when that value changes. I know that the above wo... | [
"The easier way to have a kind of pointer in python is pack you value in a list.\n>>> foo = {}\n>>> foo[1] = [1.0]\n>>> foo[2] = foo[1]\n\n>>> foo\n{1: [1.0], 2: [1.0]}\n\n>>> foo[1][0]+=100 # note the [0] to write in the list\n\n>>> foo\n{1: [101.0], 2: [101.0]}\n\nWorks !\n",
"It is possible only with mutable o... | [
1,
1
] | [] | [] | [
"dictionary",
"immutability",
"python",
"reference"
] | stackoverflow_0003188925_dictionary_immutability_python_reference.txt |
Q:
Why import when you need to use the full name?
In python, if you need a module from a different package you have to import it. Coming from a Java background, that makes sense.
import foo.bar
What doesn't make sense though, is why do I need to use the full name whenever I want to use bar? If I wanted to use the fu... | Why import when you need to use the full name? | In python, if you need a module from a different package you have to import it. Coming from a Java background, that makes sense.
import foo.bar
What doesn't make sense though, is why do I need to use the full name whenever I want to use bar? If I wanted to use the full name, why do I need to import? Doesn't using the ... | [
"The thing is, even though Python's import statement is designed to look similar to Java's, they do completely different things under the hood. As you know, in Java an import statement is really little more than a hint to the compiler. It basically sets up an alias for a fully qualified class name. For example, whe... | [
25,
6,
4,
3,
3,
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003188929_python.txt |
Q:
Duplicate Google Spreadsheet on Demand
I've created a pretty complex Google spreadsheet. I would like a user to be able to click a button or follow a link, and get a copy of this spreadsheet where they can fill in data. I would later check process this data manually.
Is there anyway I can do this via a complicat... | Duplicate Google Spreadsheet on Demand | I've created a pretty complex Google spreadsheet. I would like a user to be able to click a button or follow a link, and get a copy of this spreadsheet where they can fill in data. I would later check process this data manually.
Is there anyway I can do this via a complicated link, or some Javascript, or possibly eve... | [
"You have a few options:\n\nRather than force a user to create a spreadsheet that you verify, you can email them a form to fill out with Google forms, and the answers get aggregated back on your spreadsheet.\nUse the docs API to copy documents.\nUse Google Apps Script to automate the process (it's essentially javas... | [
4,
0
] | [] | [] | [
"google_apps_script",
"google_sheets",
"java",
"javascript",
"python"
] | stackoverflow_0003189012_google_apps_script_google_sheets_java_javascript_python.txt |
Q:
twisted: one client, many servers
I'm trying to use twisted to create a cluster of computers that run one program on a piece of a larger dataset.
My "servers" receive a chunk of data from the client and run command x on it.
My "client" connects to multiple servers giving them each a chunk of data and telling them ... | twisted: one client, many servers | I'm trying to use twisted to create a cluster of computers that run one program on a piece of a larger dataset.
My "servers" receive a chunk of data from the client and run command x on it.
My "client" connects to multiple servers giving them each a chunk of data and telling them what parameters to run command x with.
... | [
"Just call connectTCP multiple times.\nThe trick, of course, is that reactor.run() blocks \"forever\" (the entire run-time of your program) so you don't want to call that multiple times.\nYou have several options; you can set up a timed call to make future connections, or you can start new connections from events o... | [
9
] | [] | [] | [
"python",
"twisted"
] | stackoverflow_0003189222_python_twisted.txt |
Q:
Python: cannot print (execution flow ?)
I am interested in a small python application, which can be downloaded here:
https://launchpad.net/treemap
If you run it, like this:
python treemap-basic.py examle-world-population.txt
It works just fine.
The problem is that even if I type a print command in the "treemap-ba... | Python: cannot print (execution flow ?) | I am interested in a small python application, which can be downloaded here:
https://launchpad.net/treemap
If you run it, like this:
python treemap-basic.py examle-world-population.txt
It works just fine.
The problem is that even if I type a print command in the "treemap-basic.py" file:
print "Hello World !" @ treemap... | [
"I downloaded this script, and inserted\nprint \"Hello World\"\n\non line 64. When simply trying ./treemap-basic.py on the terminal, you get an IndexError since treemap-basic.py expects a command line argument. When you specify a file to work on:\n./treemap-basic examle-world-population.txt\n\nYou see a bunch of ou... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0003188656_python.txt |
Q:
python - recursive call
I have a class model designed for a person class in python. where a person is a student and can have 0,1 or many advisors.A person can also have other attributes like name,school,year of graduation,classification he worked on,degree he obtained and so on.
I have set and get methods for each... | python - recursive call | I have a class model designed for a person class in python. where a person is a student and can have 0,1 or many advisors.A person can also have other attributes like name,school,year of graduation,classification he worked on,degree he obtained and so on.
I have set and get methods for each of these attributes in the c... | [
"You could write a method on your class with something like:\nhas_advisor(self, advisor):\n if not self.advisor:\n return False\n elif advisor in self.advisor:\n return True\n else\n return self.advisor.has_advisor(advisor)\n\nThat would let you query things like:\ne = people['e']\ne_i... | [
1
] | [] | [] | [
"python",
"scripting"
] | stackoverflow_0003189759_python_scripting.txt |
Q:
I am attempting to use google app engine (python) to save a url with # character
My class looks like this:
class Post(db.Model):
link = db.LinkProperty()
I am getting the url parameter and populating the class like this:
newpost = Post(
link = cgi.escape(self.request.get('link')))
newpost.put()
If I send ... | I am attempting to use google app engine (python) to save a url with # character | My class looks like this:
class Post(db.Model):
link = db.LinkProperty()
I am getting the url parameter and populating the class like this:
newpost = Post(
link = cgi.escape(self.request.get('link')))
newpost.put()
If I send a regular link it works fine.
If I send a link like this (with a hash): http://www.ur... | [
"The hash component of a URL is never sent to the server.\nThis behavior is used in some AJAX patterns because of this property.\nI would recommend URL-encoding the hash in the URL to %23:\nhttp://example.com/whatever%23afterHash\n",
"If db.LinkProperty won't work, just use db.StringProperty.\n"
] | [
4,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003189692_google_app_engine_python.txt |
Q:
parse xml file and create a list of files
there is an info.xml file under every /var/packs/{many folders}/info.xml where are different directories but with the dirs's info in info.xml
I need to parse through every {many folders} and create a list of the filepath which is inside the Path tags if the file type is "... | parse xml file and create a list of files | there is an info.xml file under every /var/packs/{many folders}/info.xml where are different directories but with the dirs's info in info.xml
I need to parse through every {many folders} and create a list of the filepath which is inside the Path tags if the file type is "config" which can be found by checking if "conf... | [
"Here is very basic example with no errors processing and works with very strictly defined XML files, but you should take it as a start and continue with the following links:\n\nhttp://docs.python.org/library/xml.dom.html\nhttp://docs.python.org/library/xml.dom.minidom.html\nhttp://docs.python.org/library/os.path.h... | [
2,
1,
0
] | [] | [] | [
"parsing",
"python",
"xml"
] | stackoverflow_0003189311_parsing_python_xml.txt |
Q:
How Ruby's authlogic is compared to Python's repoze.what/who library?
I am trying to understand architecture of authlogic and repoze.what/who libraries but I could get the first level architectural definition. repoze packages seems to use the zope modules at some level..
Are there any equivalent or easier authent... | How Ruby's authlogic is compared to Python's repoze.what/who library? | I am trying to understand architecture of authlogic and repoze.what/who libraries but I could get the first level architectural definition. repoze packages seems to use the zope modules at some level..
Are there any equivalent or easier authentication framework like authlogic available in python? (I do not use Django.... | [
"After a quick look at authlogic's homepage, I would say it can be compared to repoze.who because they both handle authentication. On the other hand, repoze.what handles authorization. For more information, you may want to see this:\nhttp://gustavonarea.net/blog/posts/repoze-auth/\nHTH.\nPS: Neither repoze.who or r... | [
1
] | [] | [] | [
"authentication",
"authlogic",
"python",
"repoze.who",
"ruby"
] | stackoverflow_0003188894_authentication_authlogic_python_repoze.who_ruby.txt |
Q:
What are the pros and cons in Python of using a c library vs a native python one
Are there any downsides in Python to using a library that is just a binding to a C library? Does that hurt the portability of your application? Anything else I should look out for?
A:
Of course using a C library hurts portability. I... | What are the pros and cons in Python of using a c library vs a native python one | Are there any downsides in Python to using a library that is just a binding to a C library? Does that hurt the portability of your application? Anything else I should look out for?
| [
"Of course using a C library hurts portability. It also prohibites you (in general) to use Jython or IronPython. I would only use a C library if I had no other option. This could happen if direct access to hardware is necessary or if special efficiency requirements apply.\n",
"C library is likely to have better p... | [
4,
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0003190013_python.txt |
Q:
How to do this in a pythonic way?
Consider this Python snippet:
for a in range(10):
if a == 7:
pass
if a == 8:
pass
if a == 9:
pass
else:
print "yes"
How can it be written shorter?
#Like this or...
if a ?????[7,8,9]:
pass
A:
Use the in operator:
if a in (7,8,... | How to do this in a pythonic way? | Consider this Python snippet:
for a in range(10):
if a == 7:
pass
if a == 8:
pass
if a == 9:
pass
else:
print "yes"
How can it be written shorter?
#Like this or...
if a ?????[7,8,9]:
pass
| [
"Use the in operator:\nif a in (7,8,9):\n pass\n\n",
"To test if a falls within a range:\nif 7 <= a <= 9:\n pass\n\nTo test if a is in a given sequence:\nif a in [3, 5, 42]:\n pass\n\n",
"for a in range(10):\n if a > 6:\n continue\n print('yes')\n\n",
"Based on your original code the direct ... | [
17,
15,
2,
2,
1,
1,
1,
1
] | [] | [] | [
"python",
"syntax"
] | stackoverflow_0002636656_python_syntax.txt |
Q:
Python - Call a function in a module dynamically
I'm pretty new to Python and I have a situation where I have a variable representing a function inside of a module and I'm wondering how to call it dynamically. I have filters.py:
def scale(image, width, height):
pass
And then in another script I have something... | Python - Call a function in a module dynamically | I'm pretty new to Python and I have a situation where I have a variable representing a function inside of a module and I'm wondering how to call it dynamically. I have filters.py:
def scale(image, width, height):
pass
And then in another script I have something like:
import filters
def process_images(method='scal... | [
"you need built-in getattr:\ngetattr(filters, method)(**options)\n\n",
"To avoid the problem, you could pass the function directly, instead of \"by name\":\ndef process_images(method=filters.scale, options):\n method(**options)\n\nIf you have a special reason to use a string instead, you can use getattr as sug... | [
25,
9,
0
] | [] | [] | [
"python"
] | stackoverflow_0003190583_python.txt |
Q:
Python .xlsx (Office OpenXML) reader as simple as csv module?
I know some Python xlsx readers are emerging, but from what I've seen they don't seem nearly as intuitive as the built-in csv module.
What I want is a module that can do something like this:
reader = xlsx.reader(open('/path/to/file'))
for sheet in read... | Python .xlsx (Office OpenXML) reader as simple as csv module? | I know some Python xlsx readers are emerging, but from what I've seen they don't seem nearly as intuitive as the built-in csv module.
What I want is a module that can do something like this:
reader = xlsx.reader(open('/path/to/file'))
for sheet in reader:
print 'In %s we have the following employees:' % (sheet.nam... | [
"xlrd has xlsx handling for basic data extraction, using the same APIs as for xls, in alpha test at the moment. Send me private e-mail if interested.\n",
"Well, maybe not for the xlsx format, but certainly for xls. Grab xlrd from here:\nhttp://www.python-excel.org/\nHere's some example code to get a feel for how... | [
4,
2
] | [] | [] | [
"module",
"openxml",
"python",
"xlsx",
"xmlreader"
] | stackoverflow_0003189244_module_openxml_python_xlsx_xmlreader.txt |
Q:
Running a Python Script on a server (Does it have to be in /cgi-bin/)?
Right now I have a script thats
http://www.example.com/cgi-bin/foo?var1=A&var2=B
Is there a way that I can have it run outside of the cgi-bin directory? Like could I have
http://www.example.com/foo/?var1=A&var2=B
A:
In Apache you can change ... | Running a Python Script on a server (Does it have to be in /cgi-bin/)? | Right now I have a script thats
http://www.example.com/cgi-bin/foo?var1=A&var2=B
Is there a way that I can have it run outside of the cgi-bin directory? Like could I have
http://www.example.com/foo/?var1=A&var2=B
| [
"In Apache you can change the directories that can contain executable scripts with the ScriptAlias directive in httpd.conf (or whatever file holds your configuration).\nYou can also use mod_rewrite to rewrite URLs to point to the scripts you want to execute. Mod_rewrite also allows you to pass variables and stuff i... | [
2,
0
] | [] | [] | [
"cgi_bin",
"html",
"python",
"scripting"
] | stackoverflow_0003190772_cgi_bin_html_python_scripting.txt |
Q:
__init__ method for form with additional arguments
I'm calling my form, with additional parameter 'validate :
form = MyForm(request.POST, request.FILES, validate=True)
How should I write form's init method to have access to this parameter inside body of my form (for example in _clean method) ? This is what I came ... | __init__ method for form with additional arguments | I'm calling my form, with additional parameter 'validate :
form = MyForm(request.POST, request.FILES, validate=True)
How should I write form's init method to have access to this parameter inside body of my form (for example in _clean method) ? This is what I came up with :
def __init__(self, *args, **kwargs):
try:
... | [
"The validate=True argument is a keyword argument, so it will show up in the kwargsdict. (Only positional arguments show up in args.)\nYou can use kwargs.pop to try to get the value of kwargs['validate'].\nIf validate is a key in kwargs, then kwargs.pop('validate') will return the associated value. It also has the ... | [
9
] | [] | [] | [
"django",
"django_forms",
"initialization",
"python"
] | stackoverflow_0003191443_django_django_forms_initialization_python.txt |
Q:
Decorating arithmetic operators | should I be using a metaclass?
I'd like to implement an object, that bounds values within a given range after arithmetic operations have been applied to it. The code below works fine, but I'm pointlessly rewriting the methods. Surely there's a more elegant way of doing this. Is a ... | Decorating arithmetic operators | should I be using a metaclass? | I'd like to implement an object, that bounds values within a given range after arithmetic operations have been applied to it. The code below works fine, but I'm pointlessly rewriting the methods. Surely there's a more elegant way of doing this. Is a metaclass the way to go?
def check_range(_operator):
def decorator... | [
"It is possible to use a metaclass to apply a decorator to a set of function names, but I don't think that this is the way to go in your case. Applying the decorator in the class body on a function-by-function basis as you've done, with the @decorator syntax, I think is a very good option. (I think you've got a bu... | [
2,
1
] | [] | [] | [
"metaclass",
"python"
] | stackoverflow_0003191125_metaclass_python.txt |
Q:
Form class __init__ not working
I have this form class :
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
self.notvalidate = kwargs.pop('notvalidate',False)
super(MyForm, self).__init__(*args, **kwargs)
email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,max... | Form class __init__ not working | I have this form class :
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
self.notvalidate = kwargs.pop('notvalidate',False)
super(MyForm, self).__init__(*args, **kwargs)
email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,maxlength=75)))
(...)
if not no... | [
"Move the if not notvalidate into the clean_email method, and reference it using self.notvalidate.\n def clean_email(self):\n if not self.notvalidate: \n email = self.cleaned_data.get(\"email\")\n if email and User.objects.filter(email=email).count() > 0:\n raise forms.... | [
2,
1,
0
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0003191648_django_django_forms_python.txt |
Q:
Decorate a whole library in Python
I'm new to the ideas of decorators (and still trying to wrap my head around them), but I think I've come across a problem that would be well suited for them. I'd like to have class that is decorated across all of the functions in the math library. More specifically my class has t... | Decorate a whole library in Python | I'm new to the ideas of decorators (and still trying to wrap my head around them), but I think I've come across a problem that would be well suited for them. I'd like to have class that is decorated across all of the functions in the math library. More specifically my class has two members, x and flag. When flag is tru... | [
"You can use decorators for this, although you won't need the @decorator syntax.\nThe following code imports each function you list from the math module into the current module's namespace, wrapping it in the defined decorator. It should give you the basic idea.\nfrom functools import wraps\ndef check_flag(func):\... | [
6,
6
] | [] | [] | [
"decorator",
"python"
] | stackoverflow_0003191799_decorator_python.txt |
Q:
Python scipy.weave and STANN C++ Library
I'm trying out scipy.weave to build a fast minimal spanning tree program in Python. Unfortunately, using scipy.weave with a C++ library that I found, STANN, is more difficult that I had assumed. Here's the link to the STANN library: http://sites.google.com/a/compgeom.com/st... | Python scipy.weave and STANN C++ Library | I'm trying out scipy.weave to build a fast minimal spanning tree program in Python. Unfortunately, using scipy.weave with a C++ library that I found, STANN, is more difficult that I had assumed. Here's the link to the STANN library: http://sites.google.com/a/compgeom.com/stann/
Below is the Python with scipy.weave scri... | [
"Wrapping external code with weave is a fragile and hacky affair. You should take a look at Cython -- it's great at this sort of stuff.\n"
] | [
0
] | [] | [] | [
"c++",
"numpy",
"python",
"scipy"
] | stackoverflow_0003146264_c++_numpy_python_scipy.txt |
Q:
Bash equivalent to Python's string literal for utf string conversion
I'm writing a bash script that needs to parse html that includes special characters such as @!'ó. Currently I have the entire script running and it ignores or trips on these queries because they're returned from the server as decimal unicode like... | Bash equivalent to Python's string literal for utf string conversion | I'm writing a bash script that needs to parse html that includes special characters such as @!'ó. Currently I have the entire script running and it ignores or trips on these queries because they're returned from the server as decimal unicode like this: '. I've figured out how to parse and convert to hexadecimal and... | [
"The printf builtin in Bash doesn't support Unicode codes, but the external printf (at least on my GNU-based system) does:\n$ /usr/bin/printf \"\\u0410\\u043b\\u0438\\u0441\\u0410\"\nАлисА\n\nor this, which selects printf from your path in case it's not in /usr/bin:\n$ $(type -P printf) \"\\u0410\\u043b\\u0438\\u04... | [
2,
1
] | [] | [] | [
"bash",
"python",
"utf_8"
] | stackoverflow_0003191110_bash_python_utf_8.txt |
Q:
Streaming 1GB File in Python
How long should it take to stream a 1GB file in python on say a 2Ghz Intel Core 2 Duo machine?
fp = open('publisher_feed_8663.xml')
for line in fp:
a = line.split('<')
I suppose I wasn't specific enough. This process takes 20+ minutes which is abnormally long. Based on empirical da... | Streaming 1GB File in Python | How long should it take to stream a 1GB file in python on say a 2Ghz Intel Core 2 Duo machine?
fp = open('publisher_feed_8663.xml')
for line in fp:
a = line.split('<')
I suppose I wasn't specific enough. This process takes 20+ minutes which is abnormally long. Based on empirical data, what is a reasonable time?
| [
"Your answer:\nstart = time.time()\nfp = open('publisher_feed_8663.xml')\nfor line in fp:\n a = line.split('<')\nprint time.time() - start\n\nYou will require a 1GB file named publisher_feed_8663.xml, python and a 2Ghz Intel Core 2 Duo machine.\nFor parsing of XML, you probably want to use an event based stream p... | [
8,
3,
1
] | [] | [] | [
"python"
] | stackoverflow_0003189490_python.txt |
Q:
Python regex for fixing Australian/New Zealand Phone Numbers
I have a Python script that we're using to parse CSV files with user-entered phone numbers in it - ergo, there are quite a few weird format/errors. We need to parse these numbers into their separate components, as well as fix some common entry errors.
Ou... | Python regex for fixing Australian/New Zealand Phone Numbers | I have a Python script that we're using to parse CSV files with user-entered phone numbers in it - ergo, there are quite a few weird format/errors. We need to parse these numbers into their separate components, as well as fix some common entry errors.
Our phone numbers are for Sydney or Melbourne (Australia), or Auckla... | [
"Don't use complicated regexes. Delete EVERYTHING except digits -- non-digits are error-prone cruft. If the third digit is 0, delete it.\nExpect 61 followed by valid AUS area code ([23478] for generality NB 4 is for mobiles) then 8 digits\nor 64 followed by valid NZL area code (whatever that is) followed by 7 digit... | [
5,
3,
0
] | [] | [] | [
"phone_number",
"python",
"regex"
] | stackoverflow_0003191936_phone_number_python_regex.txt |
Q:
Get the key of logged-in user with no DB access in Django on Google App Engine?
I'm using Django on GAE. When I say user = request.user, I believe it hits the datastore to fetch the User entity.
I would like to just get the key for the currently logged in user, because that will allow me to get the user-related da... | Get the key of logged-in user with no DB access in Django on Google App Engine? | I'm using Django on GAE. When I say user = request.user, I believe it hits the datastore to fetch the User entity.
I would like to just get the key for the currently logged in user, because that will allow me to get the user-related data I need from the memcache.
| [
"You probably are still going to hit the DB once to get the session record, which is where the user_id field is stored. Then you may need to side-step the lazy evaluation done in the django.contrib.auth.middleware code. It's not difficult, but you need to read the code and find exactly the info you want and then ge... | [
1
] | [] | [] | [
"django",
"google_app_engine",
"python"
] | stackoverflow_0003188274_django_google_app_engine_python.txt |
Q:
Uninstantiated class attribute
Hello I need an uninstantiated class attribute and I am doing this:
>>> class X:
... def __init__(self, y=None):
... self.y = list()
Is this ok? If no, is there another way of doing it. I can't instantiate this attribute in __init__ cause I would be appending to this... | Uninstantiated class attribute | Hello I need an uninstantiated class attribute and I am doing this:
>>> class X:
... def __init__(self, y=None):
... self.y = list()
Is this ok? If no, is there another way of doing it. I can't instantiate this attribute in __init__ cause I would be appending to this later.
| [
"Define the y var on the class-level attribute. You will need to initialize it to something, even it's an empty list (as you were doing before).\n>>> class X:\n... y = [] \n... def __init__(self):\n... pass\n\nUpdate based on your comments:\nYou mentioned that you were mixed on the terminology (I'm... | [
4,
2,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0003192211_python.txt |
Q:
How do I register a protocol to work with my program?
I'd like my program to be summoned when a browser tries to open a page with the protocol "tf2emp://xxxxx".
The program will then have to download content based on the 5 digit number given in said protocol.
My program is written in python, and I'm using wx for t... | How do I register a protocol to work with my program? | I'd like my program to be summoned when a browser tries to open a page with the protocol "tf2emp://xxxxx".
The program will then have to download content based on the 5 digit number given in said protocol.
My program is written in python, and I'm using wx for the gui.
| [
"This page from Mozilla should help you register protocols for Mozilla Firefox on WIndows and Linux. Similar info exists for other browsers/platforms, Google is your friend. :)\n",
"Have a peek at Microsoft's page on the subject:\nhttp://msdn.microsoft.com/en-us/library/aa767914(VS.85).aspx\n"
] | [
3,
2
] | [] | [] | [
"protocols",
"python"
] | stackoverflow_0003192530_protocols_python.txt |
Q:
What encoding does the unicode function in BeautifulSoup convert from?
When I use the unicode function in BeautifulSoup - what encoding does it convert to Unicode from? Does it automatically use the soup.originalEncoding?
from BeautifulSoup import BeautifulSoup
doc = "<html><h1>Heading</h1><p>Text"
soup = Beautifu... | What encoding does the unicode function in BeautifulSoup convert from? | When I use the unicode function in BeautifulSoup - what encoding does it convert to Unicode from? Does it automatically use the soup.originalEncoding?
from BeautifulSoup import BeautifulSoup
doc = "<html><h1>Heading</h1><p>Text"
soup = BeautifulSoup(doc)
print unicode(soup)
Thanks
| [
"unicode() is a Python builtin, not part of BeautifulSoup. See the docs here.\n\nunicode([object[, encoding[, errors]]])\nIf encoding and/or errors are given,\n unicode() will decode the object which\n can either be an 8-bit string or a\n character buffer using the codec for\n encoding. The encoding parameter i... | [
1
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0003192547_beautifulsoup_python.txt |
Q:
An inheritance example in Python
I'm not clear how to pose this question. If I did, I'd probably be a lot closer to a solution.. I need some insight into inheritance.
I want to make a custom subtype of float. But I want the instance of this subtype to re-evaluate its value before performing any of the normal fl... | An inheritance example in Python | I'm not clear how to pose this question. If I did, I'd probably be a lot closer to a solution.. I need some insight into inheritance.
I want to make a custom subtype of float. But I want the instance of this subtype to re-evaluate its value before performing any of the normal float methods (__add__,__mul__, etc..). ... | [
"class FactorFloat(float):\n def _factor_scale(f):\n def wrapper(self, *args, **kwargs):\n scaled = float.__mul__(self, FACTOR)\n result = f(scaled, *args, **kwargs)\n # if you want to return FactorFloats when possible:\n if isinstance(result, float):\n ... | [
5,
1,
1
] | [] | [] | [
"inheritance",
"python"
] | stackoverflow_0003192032_inheritance_python.txt |
Q:
How do I protect my Python codebase so that guests can't see certain modules but so it still works?
We're starting a new project in Python with a few proprietary algorithms and sensitive bits of logic that we'd like to keep private. We also will have a few outsiders (select members of the public) working on the co... | How do I protect my Python codebase so that guests can't see certain modules but so it still works? | We're starting a new project in Python with a few proprietary algorithms and sensitive bits of logic that we'd like to keep private. We also will have a few outsiders (select members of the public) working on the code. We cannot grant the outsiders access to the small, private bits of code, but we'd like a public versi... | [
"In the __init__ method of the foo package you can change __path__ to make it look for its modules in other directories.\nSo create a directory called secret and put it in your private Subversion repository. In secret put your proprietary bar.py. In the __init__.py of the public foo package put in something like:... | [
3,
2,
0
] | [] | [] | [
"modularity",
"project_management",
"python",
"repository",
"svn"
] | stackoverflow_0001443146_modularity_project_management_python_repository_svn.txt |
Q:
ctypes calling function with windows datatypes arguments
Could someone help me how should I call the following function using ctypes python library:
DWORD myfunc(LPCSTR a,BYTE b, LPBYTE c, LPDWORD d, LPCBYTE *e,DWORD LEN)
How should I declare and initialize the arguments of the mentioned functions? Could someone ... | ctypes calling function with windows datatypes arguments | Could someone help me how should I call the following function using ctypes python library:
DWORD myfunc(LPCSTR a,BYTE b, LPBYTE c, LPDWORD d, LPCBYTE *e,DWORD LEN)
How should I declare and initialize the arguments of the mentioned functions? Could someone provide an example?
| [
"Try:\nfrom ctypes.wintypes import *\n\nIt has most of the types you want.\n"
] | [
3
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0002913076_ctypes_python.txt |
Q:
Python newbie - help needed in choosing modules/libraries
i am learning python.. i want to do certain kind of scripting in python.. like,
i want to communicate 'wmic' commands through dos promt.. store the result a file..
access some sqlite database, take the data it has and compare with the result i stored..
now,... | Python newbie - help needed in choosing modules/libraries | i am learning python.. i want to do certain kind of scripting in python.. like,
i want to communicate 'wmic' commands through dos promt.. store the result a file..
access some sqlite database, take the data it has and compare with the result i stored..
now, what i dont get is that, how should i proceed? is there any sp... | [
"One of the particularly attractive features of Python is the \"batteries included\" philosophy: The standard library is huge, and extremely well thought out in 90% of the modules I've ever used. Conversely, this means that a good approach is to learn it first before branching out and installing third-party librari... | [
0,
0
] | [] | [] | [
"module",
"python"
] | stackoverflow_0003192815_module_python.txt |
Q:
unknown array length in python ctypes
I'm calling a C function using ctypes from Python. It returns a pointer to a struct, in memory allocated by the library (the application calls another function to free it later). I'm having trouble figuring out how to massage the function call to fit with ctypes. The struct... | unknown array length in python ctypes | I'm calling a C function using ctypes from Python. It returns a pointer to a struct, in memory allocated by the library (the application calls another function to free it later). I'm having trouble figuring out how to massage the function call to fit with ctypes. The struct looks like:
struct WLAN_INTERFACE_INFO_LIS... | [
"Modifying Scott's answer to remove the resize() call worked:\ndef customresize(array, new_size):\n return (array._type_*new_size).from_address(addressof(array))\n\n"
] | [
4
] | [] | [] | [
"arrays",
"ctypes",
"pointers",
"python",
"winapi"
] | stackoverflow_0003192638_arrays_ctypes_pointers_python_winapi.txt |
Q:
Python: How to find path to the script running a python script
Lets say i have a python script at homedir/codes/py/run.py
I also have a bash script at homedir/codes/run.sh
This bash script runs run.py by python py/run.py.
The thing is that i need to be able to find out, in run.py, the path to the calling script ru... | Python: How to find path to the script running a python script | Lets say i have a python script at homedir/codes/py/run.py
I also have a bash script at homedir/codes/run.sh
This bash script runs run.py by python py/run.py.
The thing is that i need to be able to find out, in run.py, the path to the calling script run.sh. If run.sh is run from its own directory, i can just use os.get... | [
"To get the absolute path of the current script in bash, do:\nSCRIPT=$(readlink -f \"$0\")\n\nNow, pass that variable as the last argument to the python script. You can get the argument from python as:\nsys.argv[-1]\n\n",
"you can get the absolute qualified path with:\nos.path.join(os.path.abspath(os.curdir))\n\... | [
3,
3
] | [] | [] | [
"path",
"python"
] | stackoverflow_0003192853_path_python.txt |
Q:
Python - use of 'self' - noob here going crazy trying to understand it
I have a simple socket class: MySocketLib.py ..
import socket
class socklib():
def create_tcp_serversocket(self,port):
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind((socket.gethostname()... | Python - use of 'self' - noob here going crazy trying to understand it | I have a simple socket class: MySocketLib.py ..
import socket
class socklib():
def create_tcp_serversocket(self,port):
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind((socket.gethostname(), port))
serversocket.listen(5)
return serversocket
de... | [
"Don't use tabs in Python source code. Configure your editor to always use spaces.\nself is not a Python keyword, it's a convention. It's the usual name for the \"instance\" of a class you're using. Example:\nclass X:\n def __init__(self, v): self.v = v\n\na = X(1)\nb = X(2)\nprint a.v, b.v\n\nWhen this code run... | [
4,
2,
0
] | [] | [] | [
"class",
"python"
] | stackoverflow_0003193411_class_python.txt |
Q:
Python Case Insensitive Replace without hurting re cache
related question: Case insensitive replace
What's the best way to do a case insensitive replace WITHOUT HURTING THE CACHE in the re module? I'm monitoring carefully the cache to make sure my favorite regexes stay there (speed, of course).
I just notice that ... | Python Case Insensitive Replace without hurting re cache | related question: Case insensitive replace
What's the best way to do a case insensitive replace WITHOUT HURTING THE CACHE in the re module? I'm monitoring carefully the cache to make sure my favorite regexes stay there (speed, of course).
I just notice that my code:
ner_token_result = re.sub('(?i)'+leftover, corrected_... | [
"If your other expressions are pre-compiled it means you did something like this:\nregex = re.compile(leftover, re.I)\n\nWhich means you will be able to refer to regex regardless of cache overloading. If you didn't do this, do it for those regexes that need to be re-used throughout your code.\n",
"Obviously the d... | [
2,
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003193605_python_regex.txt |
Q:
Multiple text nodes in Python's ElementTree? HTML generation
I'm using ElementTree to generate some HTML, but I've run into the problem that ElementTree doesn't store text as a Node, but as the text and tail properties of Element. This is a problem if I want to generate something that would require multiple text n... | Multiple text nodes in Python's ElementTree? HTML generation | I'm using ElementTree to generate some HTML, but I've run into the problem that ElementTree doesn't store text as a Node, but as the text and tail properties of Element. This is a problem if I want to generate something that would require multiple text nodes, for example:
<a>text1 <b>text2</b> text3 <b>text4</b> text5<... | [
"To generate the above string with ElementTree you can use the following code. The trick to this is that the text is the very first lot of text before the next element and the tail is all the text after the element up to the next element.\nimport xml.etree.ElementTree as ET\nroot = ET.Element(\"a\")\nroot.text = '... | [
14
] | [] | [] | [
"elementtree",
"html_generation",
"python"
] | stackoverflow_0003145015_elementtree_html_generation_python.txt |
Q:
Python+Scipy+Integration: dealing with precision errors in functions with spikes
I am trying to use scipy.integrate.quad to integrate a function over a very large range (0..10,000). The function is zero over most of its range but has a spike in a very small range (e.g. 1,602..1,618).
When integrating, I would exp... | Python+Scipy+Integration: dealing with precision errors in functions with spikes | I am trying to use scipy.integrate.quad to integrate a function over a very large range (0..10,000). The function is zero over most of its range but has a spike in a very small range (e.g. 1,602..1,618).
When integrating, I would expect the output to be positive, but I guess that somehow quad's guessing algorithm is g... | [
"You might want to try other integration methods, such as the integrate.romberg() method.\nAlternatively, you can get the location of the point where your function is large, with weighted_ftag_2(x_samples).argmax(), and then use some heuristics to cut the integration interval around the maximum of your function (wh... | [
3,
1
] | [] | [] | [
"integrate",
"numerical_methods",
"precision",
"python",
"scipy"
] | stackoverflow_0003186196_integrate_numerical_methods_precision_python_scipy.txt |
Q:
Date calculations in Python
I am relatively new to Python, and I am experimenting with writing the following date calc functions
find the date that is/was Monday for a specified datetime
find the first non-weekend day of the month in a specified datetime
find the first non-weekend day of the year in a specified d... | Date calculations in Python | I am relatively new to Python, and I am experimenting with writing the following date calc functions
find the date that is/was Monday for a specified datetime
find the first non-weekend day of the month in a specified datetime
find the first non-weekend day of the year in a specified datetime
find the Nth [day of week... | [
"find_month_first_monday\nI'd use a different algorithm. First, find the first day of the month.\nfirst_day_of_month = datetime.date.today().replace(day=1)\n\nand find the week day of first_day_of_month, \nweek_day = first_day_of_month.weekday()\n\nand add days if necessary.\nif week_day:\n first_day_of_month += d... | [
4,
4
] | [] | [] | [
"datetime",
"python"
] | stackoverflow_0003194036_datetime_python.txt |
Q:
How to create a pop window using pygtk?
Todo:
On button click in main window, open a popup dialog
Framework:
pygtk
Experience:
Beginner
A:
import gtk
d = gtk.Dialog()
d.add_buttons(gtk.STOCK_YES, 1, gtk.STOCK_NO, 2)
label = gtk.Label('Do you like GTK?')
label.show()
d.vbox.pack_start(label)
answer = d.run()... | How to create a pop window using pygtk? | Todo:
On button click in main window, open a popup dialog
Framework:
pygtk
Experience:
Beginner
| [
"import gtk\n\nd = gtk.Dialog()\nd.add_buttons(gtk.STOCK_YES, 1, gtk.STOCK_NO, 2)\n\nlabel = gtk.Label('Do you like GTK?')\nlabel.show()\nd.vbox.pack_start(label)\n\nanswer = d.run()\nd.destroy()\n\nprint answer\n\n\n"
] | [
6
] | [] | [] | [
"linux",
"pygtk",
"python"
] | stackoverflow_0003194436_linux_pygtk_python.txt |
Q:
django django_authopenid.openid_store error in apache
I am getting the following error on my website:
Error importing openid store django_authopenid.openid_store: "No ElementTree library found. You may need to install one. Tried importing ['lxml.etree', 'xml.etree.cElementTree', 'xml.etree.ElementTree', 'cElementT... | django django_authopenid.openid_store error in apache | I am getting the following error on my website:
Error importing openid store django_authopenid.openid_store: "No ElementTree library found. You may need to install one. Tried importing ['lxml.etree', 'xml.etree.cElementTree', 'xml.etree.ElementTree', 'cElementTree', 'elementtree.ElementTree']"
I have commented all the... | [
"this one is fixed, there was an url in the urls.py file and i commented that and now everything is working fine.\n"
] | [
0
] | [] | [] | [
"apache",
"django",
"openid",
"python"
] | stackoverflow_0003194261_apache_django_openid_python.txt |
Q:
Code based unique constraint Django Model
I have a Django model that looks like this:
class Categories(models.Model):
"""
Model for storing the categories
"""
name = models.CharField(max_length=8)
keywords = models.TextField()
spamwords = models.TextField()
translations = models.TextFie... | Code based unique constraint Django Model | I have a Django model that looks like this:
class Categories(models.Model):
"""
Model for storing the categories
"""
name = models.CharField(max_length=8)
keywords = models.TextField()
spamwords = models.TextField()
translations = models.TextField()
def save(self, force_insert=False, force_... | [
"In your model definition you can tell Django that 'name' should be unique:\nname = models.CharField(max_length=8, unique=True)\n\nA django.db.IntegrityError will be raised if you attempt to save two records with the same name.\n"
] | [
8
] | [
"in the view\ntry:\n Category.objects.get(name='name')\nexcept Category.DoesNotExist:\n # call the save method of model\n\n"
] | [
-1
] | [
"django",
"django_models",
"python"
] | stackoverflow_0003194650_django_django_models_python.txt |
Q:
Building a list of months by iterating between two dates in a list (Python)
I have an ordered (i.e. sorted) list that contains dates sorted (as datetime objects) in ascending order.
I want to write a function that iterates through this list and generates another list of the first available dates for each month.
Fo... | Building a list of months by iterating between two dates in a list (Python) | I have an ordered (i.e. sorted) list that contains dates sorted (as datetime objects) in ascending order.
I want to write a function that iterates through this list and generates another list of the first available dates for each month.
For example, suppose my sorted list contains the following data:
A = [
'2001/01/01'... | [
">>> import itertools\n>>> [min(j) for i, j in itertools.groupby(A, key=lambda x: x[:7])]\n['2001/01/01', '2001/02/04', '2001/03/01', '2001/04/10', '2001/05/07', '2001/07/01', '2002/03/01', '2002/04/01']\n\n",
"Searching lists is a O(n) operation. I think you can simply check whether the key is new:\ndef extract_... | [
7,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003194682_python.txt |
Q:
Python Encoding issue
Why am I getting this issue? and how do I resolve it?
UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 24: unexpected code byte
Thank you
A:
Somewhere, perhaps subtly, you are asking Python to turn a stream of bytes into a "string" of characters.
Don't think of a string ... | Python Encoding issue | Why am I getting this issue? and how do I resolve it?
UnicodeDecodeError: 'utf8' codec can't decode byte 0x92 in position 24: unexpected code byte
Thank you
| [
"Somewhere, perhaps subtly, you are asking Python to turn a stream of bytes into a \"string\" of characters.\nDon't think of a string as \"bytes\". A string is a list of numbers, each number having an agreed meaning in Unicode. (#65 = Latin Capital A. #19968 = Chinese Character \"One\"/\"First\") .\nThere are ma... | [
1,
0,
0
] | [] | [] | [
"encoding",
"python"
] | stackoverflow_0003188895_encoding_python.txt |
Q:
Django \u characters in my UTF8 strings
I am adding UTF-8 data to a database in Django.
As the data goes into the database, everything looks fine - the characters (for example): “Hello” are UTF-8 encoded.
My MySQL database is UTF-8 encoded. When I examine the data from the DB by doing a select, my example string l... | Django \u characters in my UTF8 strings | I am adding UTF-8 data to a database in Django.
As the data goes into the database, everything looks fine - the characters (for example): “Hello” are UTF-8 encoded.
My MySQL database is UTF-8 encoded. When I examine the data from the DB by doing a select, my example string looks like this: ?Hello?. I assume this is sho... | [
"u'\\u201cHello World\\u201d'\n\nIs the correct Python representation of the Unicode text “Hello World”. The smartquote characters are being displayed using a \\uXXXX hex escape rather than verbatim because there are often problems with writing Unicode characters to the terminal, particularly on Windows. (It looks ... | [
6
] | [] | [] | [
"django",
"python",
"utf_8"
] | stackoverflow_0003194801_django_python_utf_8.txt |
Q:
AttributeError: 'datetime.date' object has no attribute 'date'
I have a script like this:
import datetime
# variable cal_start_of_week_date has type <type 'datetime.date'>
# variable period has type <type 'datetime.timedelta'>
cal_prev_monday = (cal_start_of_week_date - period).date()
When the above statement ... | AttributeError: 'datetime.date' object has no attribute 'date' | I have a script like this:
import datetime
# variable cal_start_of_week_date has type <type 'datetime.date'>
# variable period has type <type 'datetime.timedelta'>
cal_prev_monday = (cal_start_of_week_date - period).date()
When the above statement is executed, I get the error:
AttributeError: 'datetime.date' object... | [
"Stop trying to call the date() method of a date object. It's already a date.\n",
".date() method exists only on datetime.datetime objects. You have object of datetime.date type.\nRemove method call and be happy.\n"
] | [
31,
7
] | [] | [] | [
"python"
] | stackoverflow_0003195405_python.txt |
Q:
External use of Django DB module failed because of settings module loading
I am facing a problem with using Django DB module in an external gateway script.
I have the following python file under
myproject/myapplication/lib.py
#<path>/myproject/myapplication/lib.py
from django.db import connection
from django.db ... | External use of Django DB module failed because of settings module loading | I am facing a problem with using Django DB module in an external gateway script.
I have the following python file under
myproject/myapplication/lib.py
#<path>/myproject/myapplication/lib.py
from django.db import connection
from django.db import settings
#SOME METHODS ARE HERE
which is using django db module.
I need... | [
"your project directory, myproject has to be in python path to set the settings module as myproject.settings\nyou can set the project directory on python in the gateway.py file by\nimport sys\nsys.path.insert(0, 'absolute/path/to/project')\n\nbefore the line \nos.environ['DJANGO_SETTINGS_MODULE'] = \"myproject.sett... | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003195738_django_python.txt |
Q:
How to get checkbox data using python on gae
This is my HTML:
<div id='automail'>
<form action = "/admin/mail" method = "get">
auto mail when user :<br/><br/>
<div>
<input type="checkbox" name="automail" value ="signup">signUp</input><br/>
<input type="checkbox" name="au... | How to get checkbox data using python on gae | This is my HTML:
<div id='automail'>
<form action = "/admin/mail" method = "get">
auto mail when user :<br/><br/>
<div>
<input type="checkbox" name="automail" value ="signup">signUp</input><br/>
<input type="checkbox" name="automail" value ="login">login</input><br/>
... | [
"If multiple arguments have the same name, self.request.get returns the first one.\nYou want get_all.\n"
] | [
6
] | [] | [] | [
"checkbox",
"google_app_engine",
"python"
] | stackoverflow_0003195647_checkbox_google_app_engine_python.txt |
Q:
To send Chat Invitation, to GTalk using Google App Engine(Python)?
How can i send Chat invitation over GTalk using Google App Engine(Python), i was searching for code in documentation of GAE, but i didnt get it. As i am new to Python, please post me the code too...
A:
http://code.google.com/appengine/docs/python... | To send Chat Invitation, to GTalk using Google App Engine(Python)? | How can i send Chat invitation over GTalk using Google App Engine(Python), i was searching for code in documentation of GAE, but i didnt get it. As i am new to Python, please post me the code too...
| [
"http://code.google.com/appengine/docs/python/xmpp/overview.html\nfrom google.appengine.api import xmpp\nfrom google.appengine.ext import webapp\nfrom google.appengine.ext.webapp.util import run_wsgi_app\n\nclass FooHandler(webapp.RequestHandler):\n def get(self):\n xmpp.send_invite('example@gmail.com')\n... | [
3
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003192792_google_app_engine_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.