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 can I query Google's Safebrowsing API to check a URL with Python? I have a list of domains that I need to check for malware. Is there a way I could use Python to query Google's Safebrowsing API to get that information without the need for a database? A: Google's Safe Browsing API page contains a Python refer...
How can I query Google's Safebrowsing API to check a URL with Python?
I have a list of domains that I need to check for malware. Is there a way I could use Python to query Google's Safebrowsing API to get that information without the need for a database?
[ "Google's Safe Browsing API page contains a Python reference client, take a look at that.\n" ]
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003056265_python.txt
Q: Gathering mac addresses with Python is there a good way to gather the mac addresses of machines on a local network using Python. If it helps I'm trying to execute this python script from the DHCP server for the network. I'm new to Python but would it be a bad idea to look at the DHCP leases file for this info? I'...
Gathering mac addresses with Python
is there a good way to gather the mac addresses of machines on a local network using Python. If it helps I'm trying to execute this python script from the DHCP server for the network. I'm new to Python but would it be a bad idea to look at the DHCP leases file for this info? I'd like to use this inside a Django app ev...
[ "Really a unix question (one will assume)\nYou can either look at the arp addresses registered \"/sbin/arp -a\" or a DHCP lease table. If you go the arp route you will on find addresses that your system has recently received/sent packets to, the DHCP lease table will give you the ability to see everything. Though...
[ 1, 1 ]
[]
[]
[ "django", "mac_address", "networking", "python" ]
stackoverflow_0003056324_django_mac_address_networking_python.txt
Q: How to correlate gtk.ListStore items with my own models I have a list of Project objects, that I display in a GtkTreeView. I am trying to open a dialog with a Project's details when the user double-clicks on the item's row in the TreeView. Right now I get the selected value from the TreeView (which is the name of...
How to correlate gtk.ListStore items with my own models
I have a list of Project objects, that I display in a GtkTreeView. I am trying to open a dialog with a Project's details when the user double-clicks on the item's row in the TreeView. Right now I get the selected value from the TreeView (which is the name of the Project) via get_selection(), and search for that Projec...
[ "Not with the default models. You could try using Py-gtktree models written specifically to use the same objects in backend and presentation.\nIts documentation outlines an alternative way to make this work with standard models (i.e. without using Py-gtktree at all), by the way, but I wouldn't call it elegant.\n",...
[ 1, 1 ]
[]
[]
[ "gtktreeview", "pygtk", "python" ]
stackoverflow_0003032905_gtktreeview_pygtk_python.txt
Q: Linking IronPython to WPF I just installed VS2010 and the great new IronPython Tools extension. Currently this extension doesn't yet generate event handlers in code upon double-clicking wpf visual controls. Is there anyone that can provide or point me to an example as to how to code wpf event handlers manually in ...
Linking IronPython to WPF
I just installed VS2010 and the great new IronPython Tools extension. Currently this extension doesn't yet generate event handlers in code upon double-clicking wpf visual controls. Is there anyone that can provide or point me to an example as to how to code wpf event handlers manually in python. I've had no luck findin...
[ "You can't use something like <Button Click=\"Foo\"> here, because there is no class in code corresponding to your window, and you can't get one, because IronPython classes do not directly map to CLR classes. Also, XamlReader, which is used to load the XAML file here, does not support event wireup. If you need even...
[ 5 ]
[]
[]
[ "ironpython", "python", "visual_studio_2010", "xaml" ]
stackoverflow_0003057044_ironpython_python_visual_studio_2010_xaml.txt
Q: Design an Application That Stores and Processes Files I'm tasked with writing an application that acts as a central storage point for files (usually document formats) as provided by other applications. It also needs to take commands like "file 395 needs a copy in X format", at which point some work is offloaded t...
Design an Application That Stores and Processes Files
I'm tasked with writing an application that acts as a central storage point for files (usually document formats) as provided by other applications. It also needs to take commands like "file 395 needs a copy in X format", at which point some work is offloaded to a 3rd party application. I'm having trouble coming up wi...
[ "What you need to research is a BPEL Rules engine. Here is a list of open source rules engines written in Java. There are alternatives in other languages as well, even Python. This is definitely not something you want to tackle re-inventing yourself. This problem domain gets very complicated very quickly, any \"sim...
[ 3, 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003057088_django_python.txt
Q: Continuous build framework for java+python+ruby? Our technology set includes java, python, and ruby code (no, we're not google ;-) ). Recommendations on good CI framework to use? Hudson? Other? dwh A: I would recommend Hudson. It's written in Java so it runs on most platforms, has a very pleasant web-interface...
Continuous build framework for java+python+ruby?
Our technology set includes java, python, and ruby code (no, we're not google ;-) ). Recommendations on good CI framework to use? Hudson? Other? dwh
[ "I would recommend Hudson. It's written in Java so it runs on most platforms, has a very pleasant web-interface and excellent usability, and plugins for Python and Ruby as well as supporting shell scripts out of the box. It integrates well with SCM - for example, it can be triggered by checking in changes to a repo...
[ 3, 0 ]
[]
[]
[ "continuous_integration", "java", "python", "ruby" ]
stackoverflow_0003056830_continuous_integration_java_python_ruby.txt
Q: Running Trac 0.12 on Ubuntu 10.04 - Error I've installed trac 0.12 on my ubuntu 10.04, running the tracd internal webserver. When i access the page at http://127.0.0.1/myTracProject, I get the error message: Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/tr...
Running Trac 0.12 on Ubuntu 10.04 - Error
I've installed trac 0.12 on my ubuntu 10.04, running the tracd internal webserver. When i access the page at http://127.0.0.1/myTracProject, I get the error message: Traceback (most recent call last): File "/usr/local/lib/python2.6/dist-packages/Trac-0.11.7-py2.6.egg/trac/web/api.py", line 376, in send_error 'te...
[ "You installed Trac 0.12? Your traceback shows \"Trac-0.11.7-py2.6.egg\". Looks like you need to do some cleanup.\n" ]
[ 0 ]
[]
[]
[ "python", "trac", "ubuntu_10.04" ]
stackoverflow_0003055850_python_trac_ubuntu_10.04.txt
Q: Python Regular Expression TypeError I am writing my first python program and I am running into a problem with regex. I am using regular expression to search for a specific value in a registry key. import _winreg import re key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"Software\\Microsoft\\Windows\\CurrentVersi...
Python Regular Expression TypeError
I am writing my first python program and I am running into a problem with regex. I am using regular expression to search for a specific value in a registry key. import _winreg import re key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE,"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{26A24AE4-039D-4CA4-87B4-2...
[ "The documentation for EnumValue explains that the 3-tuple returned is a string, an object that can be any of the Value Types, then an integer. As the error explained, you must pass in a string or a buffer, so that's why v.search(value) fails.\nYou should be able to get away with v.search(str(value)) to convert va...
[ 3 ]
[]
[]
[ "python" ]
stackoverflow_0003057365_python.txt
Q: A daemon to call a function every 2 minutes with start and stop capablities I am working on a django web application. A function 'xyx' (it updates a variable) needs to be called every 2 minutes. I want one http request should start the daemon and keep calling xyz (every 2 minutes) until I send another http request...
A daemon to call a function every 2 minutes with start and stop capablities
I am working on a django web application. A function 'xyx' (it updates a variable) needs to be called every 2 minutes. I want one http request should start the daemon and keep calling xyz (every 2 minutes) until I send another http request to stop it. Appreciate your ideas. Thanks Vishal Rana
[ "There are a number of ways to achieve this. Assuming the correct server resources I would write a python script that calls function xyz \"outside\" of your django directory (although importing the necessary stuff) that only runs if /var/run/django-stuff/my-daemon.run exists. Get cron to run this every two minutes....
[ 4, 2, 2 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003057507_django_python.txt
Q: Access to an "upper" instance of a class from another instance of a different class I'd like to know if there's a way to access to the class (or its fields) where an object is instantiated. Let's say I have: def Class1: def __init__(self): self.title = "randomTitle" self.anotherField = float() ...
Access to an "upper" instance of a class from another instance of a different class
I'd like to know if there's a way to access to the class (or its fields) where an object is instantiated. Let's say I have: def Class1: def __init__(self): self.title = "randomTitle" self.anotherField = float() self.class2Field = Class2() and the class whose type will be the class2Field: de...
[ "Yes, but don't do it. Pass the object explicitly.\n", "There's no \"class hierarchy\" to speak of, here. Your Class1 objects contain Class2 objects, but your Class2 objects don't know that.\nYou could define self.parent in Class2 to be the instance of Class1 that refers to the object in self.class2Field, and hav...
[ 4, 1, 0 ]
[]
[]
[ "field", "oop", "python" ]
stackoverflow_0003055200_field_oop_python.txt
Q: How do I set a property in python using its string name How can I set an object property given its name in a string? I have a dictionary being passed to me and I wish to transfer its values into namesake properties using code like this: for entry in src_dict: if entry.startswith('can_'): tgt_obj[en...
How do I set a property in python using its string name
How can I set an object property given its name in a string? I have a dictionary being passed to me and I wish to transfer its values into namesake properties using code like this: for entry in src_dict: if entry.startswith('can_'): tgt_obj[entry] = src_dict_profile[entry]
[ "setattr(some_object, 'some_attribute', 42)\n\n", "Sounds like you're looking for setattr.\nExample:\nfor entry in src_dict:\n if entry.startswith('can_'):\n setattr(tgt_obj, entry, src_dict_profile[entry])\n\n", "On objects that have \"dict\" property\nif \"__dict__\" in dir(obj):\n\nyou may do f...
[ 24, 7, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003053718_python.txt
Q: problem reading a csv file in python I am trying to read a very simple but somehow large(800Mb) csv file using the csv library in python. The delimiter is a single tab and each line consists of some numbers. Each line is a record, and I have 20681 rows in my file. I had some problems during my calculations using t...
problem reading a csv file in python
I am trying to read a very simple but somehow large(800Mb) csv file using the csv library in python. The delimiter is a single tab and each line consists of some numbers. Each line is a record, and I have 20681 rows in my file. I had some problems during my calculations using this file,it always stops at a certain row....
[ "800 million bytes in the file and 20681 rows means that the average row size is over 38 THOUSAND bytes. Are you sure? How many numbers do you expect in each line? How do you know that you have 20681 rows? That the file is 800 Mb?\n61722 rows is almost exactly 3 times 20681 -- is the number 3 of any significance e....
[ 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003057373_python.txt
Q: Converting Numpy Lstsq residual value to R^2 I am performing a least squares regression as below (univariate). I would like to express the significance of the result in terms of R^2. Numpy returns a value of unscaled residual, what would be a sensible way of normalizing this. field_clean,back_clean = rid_zeros(bac...
Converting Numpy Lstsq residual value to R^2
I am performing a least squares regression as below (univariate). I would like to express the significance of the result in terms of R^2. Numpy returns a value of unscaled residual, what would be a sensible way of normalizing this. field_clean,back_clean = rid_zeros(backscatter,field_data) num_vals = len(field_clean) x...
[ "See http://en.wikipedia.org/wiki/Coefficient_of_determination\nYour R2 value = \n1 - residual / sum((y - y.mean())**2) \n\nwhich is equivalent to \n1 - residual / (n * y.var())\n\nAs an example:\nimport numpy as np\n\n# Make some data...\nn = 10\nx = np.arange(n)\ny = 3 * x + 5 + np.random.random(n)\n\n# Note that...
[ 22 ]
[]
[]
[ "linear_regression", "numpy", "python" ]
stackoverflow_0003054191_linear_regression_numpy_python.txt
Q: Scipy interpolation on a numpy array I have a lookup table that is defined the following way: | <1 2 3 4 5+ -------|---------------------------- <10000 | 3.6 6.5 9.1 11.5 13.8 20000 | 3.9 7.3 10.0 13.1 15.9 20000+ | 4.5 9.2 12.2 14.8 18.2 TR_ua1 = np.array([ [3.6, 6.5, 9.1, 11.5, 13....
Scipy interpolation on a numpy array
I have a lookup table that is defined the following way: | <1 2 3 4 5+ -------|---------------------------- <10000 | 3.6 6.5 9.1 11.5 13.8 20000 | 3.9 7.3 10.0 13.1 15.9 20000+ | 4.5 9.2 12.2 14.8 18.2 TR_ua1 = np.array([ [3.6, 6.5, 9.1, 11.5, 13.8], [3.9, 7.3, 10.0, ...
[ "Edit: Updated things to reflect your clarifications above. Your question is much clearer now, thanks!\nBasically, you're just wanting to interpolate a 2D array at an arbitrary point.\nscipy.ndimage.map_coordinates is what you want....\nAs I understand your question, you have a 2D array of \"z\" values that ranges ...
[ 8 ]
[]
[]
[ "interpolation", "numpy", "python", "scipy" ]
stackoverflow_0003057015_interpolation_numpy_python_scipy.txt
Q: Data structure in python for 2d range counting queries I need a data structure for doing 2d range counting queries (i.e. how many points are in a given rectangle). I think my best bet is range tree (it can count in log^2, or even log after some optimizations). Does it sound like a good choice? Does anybody know a...
Data structure in python for 2d range counting queries
I need a data structure for doing 2d range counting queries (i.e. how many points are in a given rectangle). I think my best bet is range tree (it can count in log^2, or even log after some optimizations). Does it sound like a good choice? Does anybody know about a python implementation or will I have to write one mys...
[ "See scipy.spatial.KDTree for one implementation.\nThere's also a less generic (but occasionally more useful, particularly with regards to what you have in mind) implementation using shapelib's quadtree. See this blog and the corresponding package in PyPi.\nThere are probably other implementations, too, but those ...
[ 2 ]
[]
[]
[ "python", "spatial_query" ]
stackoverflow_0003058100_python_spatial_query.txt
Q: On Ubuntu, how do you install a newer version of python and keep the older python version? Background: I am using Ubuntu The newer python version is not in the apt-get repository (or synaptic) I plan on keeping the old version as the default python when you call "python" from the command line I plan on calling th...
On Ubuntu, how do you install a newer version of python and keep the older python version?
Background: I am using Ubuntu The newer python version is not in the apt-get repository (or synaptic) I plan on keeping the old version as the default python when you call "python" from the command line I plan on calling the new python using pythonX.X (X.X is the new version). Given the background, how do you install...
[ "When you install from source, by default, the installation goes in /usr/local -- the executable in particular becomes /usr/local/bin/pythonX.Y with a symlink to it that's named /usr/local/python. Ubuntu's own installation is in /usr/ (e.g., /usr/bin/python), so the new installation won't overwrite it. Take care t...
[ 10, 3, 1, 0 ]
[]
[]
[ "configure", "gnu", "installation", "python", "ubuntu" ]
stackoverflow_0003050512_configure_gnu_installation_python_ubuntu.txt
Q: Losing control of GUI upon playing a wav file I can't understand why I am loosing control of my GUI even though I am implementing a thread to play a .wav file. Can someone pin point what is incorrect? #!/usr/bin/env python import wx, pyaudio, wave, easygui, thread, time, os, sys, traceback, threading import w...
Losing control of GUI upon playing a wav file
I can't understand why I am loosing control of my GUI even though I am implementing a thread to play a .wav file. Can someone pin point what is incorrect? #!/usr/bin/env python import wx, pyaudio, wave, easygui, thread, time, os, sys, traceback, threading import wx.lib.delayedresult as inbg isPaused = False isSto...
[ "Your loadFile method, quite independently of the fact that it delegates song-playing to many threads (which it waits for in strange ways, but, that's another issue), is still monopolizing the wx event loop until it returns. Where you currently have a time.sleep, try adding app.Yield(True) (of course you need to m...
[ 2 ]
[]
[]
[ "python" ]
stackoverflow_0003058128_python.txt
Q: Where do I put utility functions in my Python project? I need to create a function to rotate a given matrix (list of lists) clockwise, and I need to use it in my Table class. Where should I put this utility function (called rotateMatrixClockwise) so I can call it easily from within a function in my Table class? A...
Where do I put utility functions in my Python project?
I need to create a function to rotate a given matrix (list of lists) clockwise, and I need to use it in my Table class. Where should I put this utility function (called rotateMatrixClockwise) so I can call it easily from within a function in my Table class?
[ "Make it a static function...\n\nadd the @staticmethod decorator\ndon't include 'self' as the first argument \n\nYour definition would be: \n@staticmethod\ndef rotateMatrixClockwise():\n # enter code here...\n\nWhich will make it callable everywhere you imported 'table' by calling:\ntable.rotateMatrixClockwise()...
[ 14, 4 ]
[]
[]
[ "function", "import", "python", "utilities" ]
stackoverflow_0003049569_function_import_python_utilities.txt
Q: Removing python and then re-installing on Mac OSX I was wondering if anyone had tips on how to completely remove a python installation form Mac OSX (10.5.8) ... including virtual environments and its related binaries. Over the past few years I've completely messed up the installed site-packages, virtual-environme...
Removing python and then re-installing on Mac OSX
I was wondering if anyone had tips on how to completely remove a python installation form Mac OSX (10.5.8) ... including virtual environments and its related binaries. Over the past few years I've completely messed up the installed site-packages, virtual-environments, etc. and the only way I can see to fix it is to ju...
[ "Just for everyone else's reference. I found this in the Python documentation here:\n\n\nMac OS X 10.5 comes with Python 2.5.1 pre-installed by Apple. If you wish, you are invited to install the\n most recent version of Python from the\n Python website\n (http://www.python.org). A current\n “universal ...
[ 1, 0 ]
[]
[]
[ "installation", "macos", "python" ]
stackoverflow_0003034304_installation_macos_python.txt
Q: Python CLI tool - general parsing question If possible I would like to use the following structure for a command however I can't seem to figure out how to achieve this in Python: ./somescript.py arg <optional argument> -- "some long argument" Would it be possible to achieve this in a feasible manner without too mu...
Python CLI tool - general parsing question
If possible I would like to use the following structure for a command however I can't seem to figure out how to achieve this in Python: ./somescript.py arg <optional argument> -- "some long argument" Would it be possible to achieve this in a feasible manner without too much dirty code? Or should I just reconsider the s...
[ "I think optparse can do this.\n", "If you don't want to use dashes in front of your arg and optional_argument, that's kind of strange by typical Unix command-line behavior, but I don't understand why every answer appears to believe you have to use the dashes. Avoiding them is kind of trivial, actually...:\nimpo...
[ 3, 1, 0 ]
[]
[]
[ "command_line_interface", "python", "shell" ]
stackoverflow_0003057805_command_line_interface_python_shell.txt
Q: How do I get user input to refer to a variable in Python? I would like to get user input to refer to some list in my code. I think it's called namespace? So, what would I have to do to this code for me to print whatever the user inputs, supposing they input 'list1' or 'list2'? list1 = ['cat', 'dog', 'juice'] list2...
How do I get user input to refer to a variable in Python?
I would like to get user input to refer to some list in my code. I think it's called namespace? So, what would I have to do to this code for me to print whatever the user inputs, supposing they input 'list1' or 'list2'? list1 = ['cat', 'dog', 'juice'] list2 = ['skunk', 'bats', 'pogo stick'] x = raw_input('which list w...
[ "In the cases I can think of right now it would probably be better to have a dictionary containing what you want the user to be able to reference, for example:\nmy_dict = {\n 'list1': ['cat', 'dog', 'juice']\n 'list2': ['skunk', 'bats', 'pogo stick']\n}\n\nkey = raw_input('which list would you like me to prin...
[ 4, 2 ]
[]
[]
[ "list", "namespaces", "python", "raw_input" ]
stackoverflow_0003058457_list_namespaces_python_raw_input.txt
Q: How to get bit rotation function to accept any bit size? i have these 2 functions i got from some other code def ROR(x, n): mask = (2L**n) - 1 mask_bits = x & mask return (x >> n) | (mask_bits << (32 - n)) def ROL(x, n): return ROR(x, 32 - n) and i wanted to use them in a program, where 16 bit ro...
How to get bit rotation function to accept any bit size?
i have these 2 functions i got from some other code def ROR(x, n): mask = (2L**n) - 1 mask_bits = x & mask return (x >> n) | (mask_bits << (32 - n)) def ROL(x, n): return ROR(x, 32 - n) and i wanted to use them in a program, where 16 bit rotations are required. however, there are also other functions ...
[ "Well, just look at what happens when you call ROL(x, n, 16). It calls ROR(x,16-n), which is equivalent to ROR(x,16-n,32), but what you really wanted was ROR(x, 16-n, 16).\n", "Basically, the implication of @GregS's correct answers are that you need to fix one detail in your second implementation:\ndef ROL(x, n, ...
[ 6, 3 ]
[]
[]
[ "math", "python", "rotation" ]
stackoverflow_0003057726_math_python_rotation.txt
Q: Python: What is the most feature-rich library for loading audio metadata from various formats? I'm looking for a good, feature-rich, library for reading metadata from various audio formats (MP3, FLAC, OGG, WAV, etc.). I have already looked at Mutagen, but the documentation is nearly nonexistent, and it seems incap...
Python: What is the most feature-rich library for loading audio metadata from various formats?
I'm looking for a good, feature-rich, library for reading metadata from various audio formats (MP3, FLAC, OGG, WAV, etc.). I have already looked at Mutagen, but the documentation is nearly nonexistent, and it seems incapable of loading basic information such as artist and audio title.
[ "Are the artist and audio title encoded properly? What particular formats is it failing one - often ID3 information is poorly encoded.\nhttp://wiki.python.org/moin/UsefulModules#ID3Handling (A List of ID3 modules)\nI would try ID3Reader, which has support for ID3v1, which Mutagen seems to be missing. \n", "see ta...
[ 1, 1, 1, 0 ]
[]
[]
[ "audio", "metadata", "python" ]
stackoverflow_0002985641_audio_metadata_python.txt
Q: scraping blog contents After obtaining the urls for various blogspots, tumblr and wordpress pages, I faced some problems processing the html pages. The thing is, i wish to distinguish between the content,title and date for each blog post. I might be able to get the date through regex, but there are so many custom ...
scraping blog contents
After obtaining the urls for various blogspots, tumblr and wordpress pages, I faced some problems processing the html pages. The thing is, i wish to distinguish between the content,title and date for each blog post. I might be able to get the date through regex, but there are so many custom scripts people are using now...
[ "If at all feasible, use the blogs' RSS or Atom feeds instead -- they're well-structured XML, rather than not-so-well structured HTML, and Universal Feed Parser is enormously helpful at getting to feeds' contents in Python.\nIf some blog lacks a feed (or the feed is really scarce), so you have to parse its HTML (si...
[ 3, 2, 1 ]
[]
[]
[ "python" ]
stackoverflow_0003058562_python.txt
Q: Python Numpy Structured Array (recarray) assigning values into slices The following example shows what I want to do: >>> test rec.array([(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)], dtype=[('ifAction', '|i1'), ('ifDocu', '|i1'), ('ifComedy', '...
Python Numpy Structured Array (recarray) assigning values into slices
The following example shows what I want to do: >>> test rec.array([(0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0), (0, 0, 0)], dtype=[('ifAction', '|i1'), ('ifDocu', '|i1'), ('ifComedy', '|i1')]) >>> test[['ifAction', 'ifDocu']][0] (0, 0) >>> test[['ifAction', ...
[ "When you say test['ifAction'] you get a view of the data.\nWhen you say test[['ifAction','ifDocu']] you are using fancy-indexing and thus get a copy of the data. The copy doesn't help you since modifying the copy leaves the original data unchanged.\nSo a way around this is to assign values to test['ifAction'] and...
[ 5 ]
[]
[]
[ "numpy", "python", "recarray", "slice" ]
stackoverflow_0003058602_numpy_python_recarray_slice.txt
Q: Is there a way to accept '%' as part of input that works both in python 2.6 & 3.0? In 2.6, if I needed to accept input that allowed a percent sign (such as "foo % bar"), I used raw_input() which worked as expected. In 3.0, input() accomplishes that same (with raw_input() having left the building). As an exercise, ...
Is there a way to accept '%' as part of input that works both in python 2.6 & 3.0?
In 2.6, if I needed to accept input that allowed a percent sign (such as "foo % bar"), I used raw_input() which worked as expected. In 3.0, input() accomplishes that same (with raw_input() having left the building). As an exercise, I'm hoping that I can have a backward-compatible version that will work with both 2.6 an...
[ "You can use sys.version_info to detect which version of Python is running.\nimport sys\nif sys.version_info[0] == 2:\n input = raw_input\n# Now you can use\ninput()\n\nAlternatively, if you don't want to override Python 2.X's builtin input function, you can write\nimport sys\nif sys.version_info[0] == 2:\n m...
[ 2, 2 ]
[]
[]
[ "python", "python_2.6" ]
stackoverflow_0003058649_python_python_2.6.txt
Q: represent binary search trees in python how do i represent binary search trees in python? A: class Node(object): def __init__(self, payload): self.payload = payload self.left = self.right = 0 # this concludes the "how to represent" asked in the question. Once you # represent a BST tree like ...
represent binary search trees in python
how do i represent binary search trees in python?
[ "class Node(object):\n\n def __init__(self, payload):\n self.payload = payload\n self.left = self.right = 0\n\n # this concludes the \"how to represent\" asked in the question. Once you\n # represent a BST tree like this, you can of course add a variety of\n # methods to modify it, \"walk\" over it...
[ 12 ]
[]
[]
[ "binary_search_tree", "binary_tree", "data_structures", "python" ]
stackoverflow_0003058665_binary_search_tree_binary_tree_data_structures_python.txt
Q: How to manually create a DBRef using pymongo? I want to create a DBRef manually so that I can add an additional field to it. However, when I try to pass the following: {'$ref': 'projects', '$id': '1029412409721', 'project_name': 'My Project'} Pymongo raises an error: pymongo.errors.InvalidName: key '$id' must no...
How to manually create a DBRef using pymongo?
I want to create a DBRef manually so that I can add an additional field to it. However, when I try to pass the following: {'$ref': 'projects', '$id': '1029412409721', 'project_name': 'My Project'} Pymongo raises an error: pymongo.errors.InvalidName: key '$id' must not start with '$' It would seem that pymongo reserv...
[ "Probably don't want to be creating them manually like that, since keys in DBRefs need to be ordered. We could add an option to create a DBRef instance w/ custom kwargs though, which would solve your problem. If you file a jira for this we should be able to get it out in an upcoming release.\n" ]
[ 3 ]
[]
[]
[ "dbref", "mongodb", "pymongo", "python" ]
stackoverflow_0003056809_dbref_mongodb_pymongo_python.txt
Q: How to substitute into a regular expression group in Python >>> s = 'foo: "apples", bar: "oranges"' >>> pattern = 'foo: "(.*)"' I want to be able to substitute into the group like this: >>> re.sub(pattern, 'pears', s, group=1) 'foo: "pears", bar: "oranges"' Is there a nice way to do this? A: For me works somet...
How to substitute into a regular expression group in Python
>>> s = 'foo: "apples", bar: "oranges"' >>> pattern = 'foo: "(.*)"' I want to be able to substitute into the group like this: >>> re.sub(pattern, 'pears', s, group=1) 'foo: "pears", bar: "oranges"' Is there a nice way to do this?
[ "For me works something like:\nrx = re.compile(r'(foo: \")(.*?)(\".*)')\ns_new = rx.sub(r'\\g<1>pears\\g<3>', s)\nprint(s_new)\n\nNotice ?in re, so it ends with first \", also notice \" in groups 1 and 3 because they must be in output.\nInstead of \\g<1> (or \\g<number>) you can use just \\1, but remember to use \"...
[ 10, 0 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003059151_python_regex.txt
Q: python streaming TCP server with RPC I have written a little streaming mp3 server in python. So far all it does is accept a ServerSocket connection, and begin streaming all mp3 data in its queue to the request using socket.send(). I have implemented this to chunk in stream icy metadata, so the name of the playin...
python streaming TCP server with RPC
I have written a little streaming mp3 server in python. So far all it does is accept a ServerSocket connection, and begin streaming all mp3 data in its queue to the request using socket.send(). I have implemented this to chunk in stream icy metadata, so the name of the playing song shows up in the client. I would lik...
[ "Your initial attempt might be easier if you use two separate ports, each with its own server running in a separate thread. However, managing synchronization between the threads might be an annoying task in the long run.\nICY and HTTP are very similar, and if you've already implemented ICY on top of SocketServer, ...
[ 0 ]
[]
[]
[ "python", "sockets", "xml_rpc" ]
stackoverflow_0003059374_python_sockets_xml_rpc.txt
Q: Django Template Inheritance -- Missing Images? I have got the following file heirarchy: project   other stuff   templates       images           images for site       app1           templates for app1       registration           login template       base.html (base for entire site)       style.css (for base.html)...
Django Template Inheritance -- Missing Images?
I have got the following file heirarchy: project   other stuff   templates       images           images for site       app1           templates for app1       registration           login template       base.html (base for entire site)       style.css (for base.html) In the login template, I am extending 'base.html.' ...
[ "I recommend not putting the styles and images there. For development, your MEDIA_ROOT may point to an arbitrary local directory on your machine containing the files, it need not even be below your django project's root folder (see http://docs.djangoproject.com/en/dev/ref/settings/#media-root).\nFor production, you...
[ 3 ]
[]
[]
[ "django", "image", "inheritance", "python", "templates" ]
stackoverflow_0003059713_django_image_inheritance_python_templates.txt
Q: Python, Thread never exiting I'm developing a small media player in Python. A problem I have run into is that my thread which plays the .wav file never exits. I've provided the thread class, and how I handle the create of thread below. class myThread (threading.Thread): def __init__(self, threadID, wf): ...
Python, Thread never exiting
I'm developing a small media player in Python. A problem I have run into is that my thread which plays the .wav file never exits. I've provided the thread class, and how I handle the create of thread below. class myThread (threading.Thread): def __init__(self, threadID, wf): self.threadID = threadID...
[ "Is it this code in the thread that never exits? Or the main while loop?\nwhile self.data != '':\n while isPaused != True:\n if isStopped == False:\n self.stream.write(self.data)\n self.data = self.waveFile.readframes(1024)\n elif isStopped == True:\n self.stream.close()\n self.p.term...
[ 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003053397_python.txt
Q: Traditional SQL vs MongoDB/CouchDB for simple python app Say I got an traditional SQL structure like so: create table tags (id PRIMARY KEY int, tag varchar(100)); create table files (id PRIMARY KEY int, filename varchar(500)); create table tagged_files (tag_id int, file_id int); I add some tags: insert into table...
Traditional SQL vs MongoDB/CouchDB for simple python app
Say I got an traditional SQL structure like so: create table tags (id PRIMARY KEY int, tag varchar(100)); create table files (id PRIMARY KEY int, filename varchar(500)); create table tagged_files (tag_id int, file_id int); I add some tags: insert into table tags (tag) values ('places'); insert into table tags (tag) va...
[ "For MongoDB.\nChances are you'd simply save them with the tags as:\ndb.Files.save({ \"fn\" : \"/tmp/somefile\", \"ts\" : [ { \"t\" : \"places\" }, { \"t\" : \"locations\" }] });\ndb.Files.save({ \"fn\" : \"/tmp/someotherfile\", \"ts\" : [ { \"t\" : \"locations\" }] });\n\nAlternative is to save tags separately (Ob...
[ 1 ]
[]
[]
[ "couchdb", "mongodb", "python", "sql" ]
stackoverflow_0003060189_couchdb_mongodb_python_sql.txt
Q: asynchronous writing and reading of a file I have two processes. One processes is redirecting output of some unix command to a file on server side.The data is always appended to the file. e.g. find / > tmp.txt Another process is opening and reading the same file and storing it in a string and sending the entire ...
asynchronous writing and reading of a file
I have two processes. One processes is redirecting output of some unix command to a file on server side.The data is always appended to the file. e.g. find / > tmp.txt Another process is opening and reading the same file and storing it in a string and sending the entire string to the client. Now, this things take sim...
[ "If what you want is having the Output of a Unix command in a file and displaying it at the same time, you can [tee][1] it to stdout and read it from there, like:\n>>> command_line = '/bin/find / |tee tmp.txt'\n>>> args = shlex.split(command_line)\n>>> p = subprocess.Popen(args,stdout=subprocess.PIPE)\n\nFrom there...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003058899_django_python.txt
Q: Adding contextual information to your logging output in Python 2.5 I am using Python 2.5. The Python logging module allows adding contextual information to your logging output. Is something similar possible in Python 2.5? A: You can simply rip off the source code of LoggerAdapter from Python 2.6 and plug it in y...
Adding contextual information to your logging output in Python 2.5
I am using Python 2.5. The Python logging module allows adding contextual information to your logging output. Is something similar possible in Python 2.5?
[ "You can simply rip off the source code of LoggerAdapter from Python 2.6 and plug it in your own source code to get the exact same functionality. This is how others do it.\n" ]
[ 2 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0003060242_logging_python.txt
Q: logger chain in python I'm writing python package/module and would like the logging messages mention what module/class/function they come from. I.e. if I run this code: import mymodule.utils.worker as worker w = worker.Worker() w.run() I'd like to logging messages looks like this: 2010-06-07 15:15:29 INFO mymo...
logger chain in python
I'm writing python package/module and would like the logging messages mention what module/class/function they come from. I.e. if I run this code: import mymodule.utils.worker as worker w = worker.Worker() w.run() I'd like to logging messages looks like this: 2010-06-07 15:15:29 INFO mymodule.utils.worker.Worker.run...
[ "I tend to use the logging module in my packages/modules like so:\nimport logging\nlog = logging.getLogger(__name__)\nlog.info(\"Whatever your info message.\")\n\nThis sets the name of your logger to the name of the module for inclusion in the log message. You can control where the name is by where %(name)s is foun...
[ 8, 2 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0002989398_logging_python.txt
Q: Python - add a column to an existing tab separated file I wish to add a column of data to a file. The file currently has three tab delimited columns. abbd 1234 0.987 affr 2345 0.465 I have a list of length 8,800 comprising floats. li = [-1.0099876, 34.87659] I wish to add this list as a fourth column...
Python - add a column to an existing tab separated file
I wish to add a column of data to a file. The file currently has three tab delimited columns. abbd 1234 0.987 affr 2345 0.465 I have a list of length 8,800 comprising floats. li = [-1.0099876, 34.87659] I wish to add this list as a fourth column to the file. abbd 1234 0.987 -1.0099876 Note - my ...
[ "import fileinput\n\nfor fl, line in zip(li, fileinput.input(['a.txt'], inplace=True)):\n print(line.strip() + '\\t' + str(fl))\n\n", "I'm with MattH, in-place operations are usually a bad idea. The alternative approach could be:\nimport itertools\n\ndef add_column(lines, values, column_delimiter=\"\\t\"):\n ...
[ 3, 1 ]
[]
[]
[ "append", "file", "python" ]
stackoverflow_0003060367_append_file_python.txt
Q: Where to get consumer secret required by buzz-python-client? I am using buzz-python-client and there is the following line in the examples: client.build_oauth_consumer('your-app.appspot.com', 'consumer_secret') Where can I get a 'consumer_secret'? A: as docs explain: secret (string) - Your consumer secret. Thi...
Where to get consumer secret required by buzz-python-client?
I am using buzz-python-client and there is the following line in the examples: client.build_oauth_consumer('your-app.appspot.com', 'consumer_secret') Where can I get a 'consumer_secret'?
[ "as docs explain:\n\nsecret (string) - Your consumer secret. This is issued to you by Google.\n\nOfficial guide to registration with Google.\n" ]
[ 6 ]
[]
[]
[ "google_buzz", "python" ]
stackoverflow_0003061188_google_buzz_python.txt
Q: Massage with BeautifulSoup or clean with Regex Could someone tell me whats a better way to clean up bad HTML so BeautifulSoup can handle it - should one use the massage methods of BeautifulSoup or clean it up using regular expressions? A: Thought I should reword my answer. The built-in massages are good for lig...
Massage with BeautifulSoup or clean with Regex
Could someone tell me whats a better way to clean up bad HTML so BeautifulSoup can handle it - should one use the massage methods of BeautifulSoup or clean it up using regular expressions?
[ "Thought I should reword my answer.\nThe built-in massages are good for light damage (extra whitespace, no closing slashes, etc). I would certainly try and get away with these before getting any more involved.\nYou can pass in your own massages and I would suggest you extend the default set:\nimport copy, re\n\nmyM...
[ 3, 2 ]
[]
[]
[ "beautifulsoup", "python" ]
stackoverflow_0003061245_beautifulsoup_python.txt
Q: Named pipe is using 100% CPU I'm starting the script with ./file.py < pipe >> logfile and the script is: while True: try: I = raw_input().strip().split() except EOFError: continue doSomething() How could I better handle named pipe? This script always run at 100% CPU and it need...
Named pipe is using 100% CPU
I'm starting the script with ./file.py < pipe >> logfile and the script is: while True: try: I = raw_input().strip().split() except EOFError: continue doSomething() How could I better handle named pipe? This script always run at 100% CPU and it need to be real-time so I cannot use t...
[ "At EOF you will loop forever getting yet another EOF. No more input will be done after EOF.\nEOF does not mean a \"gap\" in the data. It means the named socket was disconnected and can no longer be used.\nIf you want \"real-time\" data, you have to read individual bytes from the socket until you get a complete \...
[ 2, 2 ]
[]
[]
[ "python", "unix" ]
stackoverflow_0003062134_python_unix.txt
Q: How to set Content-Type automatically when i download the data that i uploaded. This is my code : import os from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db #from login import htm...
How to set Content-Type automatically when i download the data that i uploaded.
This is my code : import os from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.ext import db #from login import htmlPrefix,get_current_user class MyModel(db.Model): blob = db.BlobProperty() class ...
[ "See Nick's blog for a working example.\nBasically on upload you need to pull the file from self.request.POST instead of get in order to get the more useful cgi.FieldStorage object. You can then read the mime type from file.type, save the type string to your entity along with the blob, and write it out with the res...
[ 1, 0 ]
[]
[]
[ "content_type", "download", "google_app_engine", "python", "upload" ]
stackoverflow_0003059684_content_type_download_google_app_engine_python_upload.txt
Q: How to get the level of the logging record in a custom logging.Handler in Python? I would like to make custom logger methods either by a custom logging handlers or a custom logger class and dispatch the logging records to different targets. For example: log = logging.getLogger('application') log.progress('time re...
How to get the level of the logging record in a custom logging.Handler in Python?
I would like to make custom logger methods either by a custom logging handlers or a custom logger class and dispatch the logging records to different targets. For example: log = logging.getLogger('application') log.progress('time remaining %d sec' % i) custom method for logging to: - database status fi...
[ "record is an instance of LogRecord:\n>>> import logging\n>>> rec = logging.LogRecord('bob', 1, 'foo', 23, 'ciao', (), False)\n\nand your method can just access the attributes of interest (I'm splitting dir's result for ease of reading):\n>>> dir(rec)\n['__doc__', '__init__', '__module__', '__str__', 'args', 'creat...
[ 12 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0003061924_logging_python.txt
Q: LDAP query using Python: always no result I am trying to use python to query LDAP server, and it always returns me no result. and anyone help me find what wrong with my python code? it runs fine without excpetions, and it always has no result. i played around with the filter like "cn=partofmyname" but just no luck...
LDAP query using Python: always no result
I am trying to use python to query LDAP server, and it always returns me no result. and anyone help me find what wrong with my python code? it runs fine without excpetions, and it always has no result. i played around with the filter like "cn=partofmyname" but just no luck. thanks for help import ldap try: l = l...
[ "i found my problem.\nsimple_bind(\"cn=username,cn=Users,dc=domian, dc=net\",'password$R')\n\nshould be \n simple_bind(\"domain/username\",'password$R')\n\n", "I would highly recommend that you examine the network traffic using Wireshark (www.wireshark.org) to see what's happening at the protocol level. Also, ...
[ 2, 0 ]
[]
[]
[ "apache", "django", "ldap", "python" ]
stackoverflow_0003057039_apache_django_ldap_python.txt
Q: Python: Dennis Nedry - Security Has anyone seen Jurrassic Park where Dennis Nedry has protected the system with an animation that says 'You didn't say the magic word' where after the system goes down. Is it possible to do something similar ikn Python ? To describe it less humoristic: A response screen which waits...
Python: Dennis Nedry - Security
Has anyone seen Jurrassic Park where Dennis Nedry has protected the system with an animation that says 'You didn't say the magic word' where after the system goes down. Is it possible to do something similar ikn Python ? To describe it less humoristic: A response screen which waits for a condition fulfilled by the use...
[ "Yes, it is possible.\n", "In which I attempt to answer the implied question, \"And if so, how?\"\nI think this is really a Linux administration question. You'd have to figure out how to suspend a user's account on the system you're using and then log the current user out. It's likely going to involve the Python ...
[ 7, 1 ]
[]
[]
[ "code_access_security", "python" ]
stackoverflow_0003061459_code_access_security_python.txt
Q: how to get files as they are added to a remote server I am using a bash script (below) on a remote server (so far using ssh to connect) to execute a python script that downloads a lot of pdf files one at a time (getting the download locations from a text file with the URL's) in a loop. I would like to move the fil...
how to get files as they are added to a remote server
I am using a bash script (below) on a remote server (so far using ssh to connect) to execute a python script that downloads a lot of pdf files one at a time (getting the download locations from a text file with the URL's) in a loop. I would like to move the files from the remote server to my local computer as they are ...
[ "[Edited to reflect the fact that the original poster can't scp into his local computer from the server; I assume it's behind NAT or something of the sort]\n[Edit 2: I'm keeping the current tunnel-based answer, for reference; but, since the original poster is unable to ssh back into his local machine, I'll assume s...
[ 1 ]
[]
[]
[ "bash", "python", "scp", "ssh" ]
stackoverflow_0003063235_bash_python_scp_ssh.txt
Q: I created a Python egg; now what? I've finally figured out how to create a Python egg and gotten it to work. Now... what do I do with it? How do I use it? How do I ensure that everything was correctly included? (Simple steps please... not just redirection to another site. I've googled, but it's confusing me, and I...
I created a Python egg; now what?
I've finally figured out how to create a Python egg and gotten it to work. Now... what do I do with it? How do I use it? How do I ensure that everything was correctly included? (Simple steps please... not just redirection to another site. I've googled, but it's confusing me, and I was hoping someone could explain it in...
[ "I'd advise only using python setup.py sdist to create zips and/or tarballs, and skip eggs.\nIf you want to look at the egg it is a zip file; you can use unzip -v MyEgg-0.1.egg and see its contents to see if includes all the files you expect. You can also try installing it. Use virtualenv to create a new environm...
[ 6, 0 ]
[]
[]
[ "distribution", "egg", "python" ]
stackoverflow_0002968809_distribution_egg_python.txt
Q: Python: convert 2 ints to 32 float How can I combine 2 ints to a single 32bit IEEE floating point ? (each of the 2 ints represent 16 bit) And in the opposite direction: How can I transform a python float into 2 16 bit ints? (I need this because of modbus protocol - where 2x16 bit registers are treated as single 32...
Python: convert 2 ints to 32 float
How can I combine 2 ints to a single 32bit IEEE floating point ? (each of the 2 ints represent 16 bit) And in the opposite direction: How can I transform a python float into 2 16 bit ints? (I need this because of modbus protocol - where 2x16 bit registers are treated as single 32 floating point number)
[ "This code takes the 16 bits integers i1 and i2 and convert them to the floating point number 3.14, and vice versa.\nfrom struct import *\n# Two integers to a floating point\ni1 = 0xC3F5\ni2 = 0x4840\nf = unpack('f',pack('>HH',i1,i2))[0]\n\n# Floating point to two integers\ni1, i2 = unpack('>HH',pack('f',3.14))\n\n...
[ 5, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003063078_python.txt
Q: How do you suppress Python DeprecationWarnings on Linux Terminal? I installed i18ndude (an internationalization utility to be used in Plone) using easy_install. When I try to run the utility i18ndude on my terminal, I get: /usr/local/lib/python2.6/dist-packages/i18ndude-3.1.2-py2.6.egg/i18ndude/odict.py:7: Depreca...
How do you suppress Python DeprecationWarnings on Linux Terminal?
I installed i18ndude (an internationalization utility to be used in Plone) using easy_install. When I try to run the utility i18ndude on my terminal, I get: /usr/local/lib/python2.6/dist-packages/i18ndude-3.1.2-py2.6.egg/i18ndude/odict.py:7: DeprecationWarning: object.__init__() takes no parameters dict.__init__(self...
[ "Redirection can be used, but it would suppress all the messages sent to that \"stream\"; e.g.\ni178ndude 2>/dev/null\nsends to the null device the stream 2 (normally the stderr of a program, but deprecation warnings could be sent to other streams). This is the \"fix it even though you don't know how\" fix. Indeed ...
[ 5, 4, 3, 1 ]
[]
[]
[ "deprecated", "linux", "python", "warnings" ]
stackoverflow_0003063414_deprecated_linux_python_warnings.txt
Q: Running "source" from python I have a file a.txt with lines of commands I want to run, say: echo 1 echo 2 echo 3 If I was on csh (unix), I would have done source a.txt and it would run. From python I want to run os.execl with it, however I get: >>> os.execl("source", "a.txt") Traceback (most recent call last): ...
Running "source" from python
I have a file a.txt with lines of commands I want to run, say: echo 1 echo 2 echo 3 If I was on csh (unix), I would have done source a.txt and it would run. From python I want to run os.execl with it, however I get: >>> os.execl("source", "a.txt") Traceback (most recent call last): File "<stdin>", line 1, in <module...
[ "source is not an executable program, so you can't execute it directly. Rather, it is a builtin command in the shell. You would need to launch that shell instead if you really needed access to it. But if you just want to run the script, you don't need to use source at all – just have the shell execute your script d...
[ 2, 1, 1 ]
[]
[]
[ "csh", "os.execl", "python" ]
stackoverflow_0003063629_csh_os.execl_python.txt
Q: Day names or first 3 characters I want my regex to catch: monday mon thursday thu ... So it's possible to write something like this: (?P<day>monday|mon|thursday|thu ... But I guess that there should be a more elegant solution. A: You can write mon(day)?|tue(sday)?|wed(nesday)?, etc. The ? is "zero-or-one repet...
Day names or first 3 characters
I want my regex to catch: monday mon thursday thu ... So it's possible to write something like this: (?P<day>monday|mon|thursday|thu ... But I guess that there should be a more elegant solution.
[ "You can write mon(day)?|tue(sday)?|wed(nesday)?, etc.\nThe ? is \"zero-or-one repetition of\"; so it's sort of \"optional\".\nIf you don't need all the suffix captures, you can use the (?:___) non-capturing groups, so:\nmon(?:day)?|tue(?:sday)?|wed(?:nesday)?\nYou can group Monday/Friday/Sunday together if you wis...
[ 3 ]
[]
[]
[ "python", "regex" ]
stackoverflow_0003063818_python_regex.txt
Q: How do I export GUI mockups to Python GUI code (e.g. wxpython)? I want to take my mockups and export them to code using any python GUI library (wxpython, pyqt, etc). For example, this capability already exists for mockups->HTML/Javascript here: http://www.balsamiq.com/products/mockups/community I need a fast, easy...
How do I export GUI mockups to Python GUI code (e.g. wxpython)?
I want to take my mockups and export them to code using any python GUI library (wxpython, pyqt, etc). For example, this capability already exists for mockups->HTML/Javascript here: http://www.balsamiq.com/products/mockups/community I need a fast, easy, high level mockup tool like balsamiq, not a slow, low level tool li...
[ "You can use the Qt Designer tool to do your mock-ups and then use the pyuic4 command line tool to convert the .pro file into Python code.\nHere are some references if you get stuck:\nhttp://diotavelli.net/PyQtWiki/Creating_GUI_Applications_with_PyQt_and_Qt_Designer\nhttp://wiki.python.org/moin/JonathanGardnerPyQtT...
[ 2 ]
[]
[]
[ "mockups", "pyqt", "python", "user_interface", "wxpython" ]
stackoverflow_0003054186_mockups_pyqt_python_user_interface_wxpython.txt
Q: creating events in my classes, and allowing others to hook into them in my django app I want to create events for my classes. Say I create a CMS application that has a Article object. I create events like: OnEdit OnCreate OnDelete PreCreate PreDelete Now I want someone to be able to hook into these events, and ad...
creating events in my classes, and allowing others to hook into them in my django app
I want to create events for my classes. Say I create a CMS application that has a Article object. I create events like: OnEdit OnCreate OnDelete PreCreate PreDelete Now I want someone to be able to hook into these events, and add their custom functionality at each event they wish. I don't want them touching the core s...
[ "Signals are what you want. You can define custom signals in your application and send them when certain events happen, then users can get their code to listen to these signals and take any action they want.\n" ]
[ 1 ]
[]
[]
[ "django", "events", "plugins", "python" ]
stackoverflow_0003063911_django_events_plugins_python.txt
Q: Can't parse XML effectively using Python import urllib import xml.etree.ElementTree as ET def getWeather(city): #create google weather api url url = "http://www.google.com/ig/api?weather=" + urllib.quote(city) try: # open google weather api url f = urllib.urlopen(url) except: ...
Can't parse XML effectively using Python
import urllib import xml.etree.ElementTree as ET def getWeather(city): #create google weather api url url = "http://www.google.com/ig/api?weather=" + urllib.quote(city) try: # open google weather api url f = urllib.urlopen(url) except: # if there was an error opening the url, r...
[ "Instead of \ntree=ET.parse(s)\n\ntry\ntree=ET.fromstring(s)\n\nAlso, your path to the data you want is incorrect. It should be: weather/current_conditions/condition\nThis should work:\nimport urllib\nimport xml.etree.ElementTree as ET\ndef getWeather(city):\n\n #create google weather api url\n url = \"http:/...
[ 3, 0 ]
[]
[]
[ "elementtree", "python", "xml" ]
stackoverflow_0003064247_elementtree_python_xml.txt
Q: Python: disabling $HOME/.python-eggs? Is there an easy way to disable Python egg caching? We have the situation where a system account needs to run a python program which imports a module. Since this is a non-login robot account, it does not have a home directory, and dies trying to create the directory /.python-...
Python: disabling $HOME/.python-eggs?
Is there an easy way to disable Python egg caching? We have the situation where a system account needs to run a python program which imports a module. Since this is a non-login robot account, it does not have a home directory, and dies trying to create the directory /.python-eggs. What's the best way to fix this? Can...
[ "The best way to fix it is by creating a directory where it can write it's egg cache. You can specify the directory with the PYTHON_EGG_CACHE variable.\n[edit]\nAnd yes, you can convert your apps so they won't need an egg-cache. If you install the python packages with easy_install you can use easy_install -Z so it ...
[ 3 ]
[]
[]
[ "egg", "python" ]
stackoverflow_0003064405_egg_python.txt
Q: Python and Plone help Im using the plone cms and am having trouble with a python script. I get a name error "the global name 'open' is not defined". When i put the code in a seperate python script it works fine and the information is being passed to the python script becuase i can print the query. Code is below: ...
Python and Plone help
Im using the plone cms and am having trouble with a python script. I get a name error "the global name 'open' is not defined". When i put the code in a seperate python script it works fine and the information is being passed to the python script becuase i can print the query. Code is below: #Import a standard funct...
[ "Python Scripts in Plone are restricted and have no access to the filesystem. The open call is thus not available. You'll have to use an External Method or full python module to have full access to the filesystem.\n" ]
[ 3 ]
[]
[]
[ "nameerror", "plone", "python" ]
stackoverflow_0003064272_nameerror_plone_python.txt
Q: Display form in Django not based on Models/Form My view calls some backend classes which need some user input. When user input is required, i halt processing and store the questions into the session - request.session['questions']. request.session['questions'] is a list of dictionaries. e.g. request.session['questi...
Display form in Django not based on Models/Form
My view calls some backend classes which need some user input. When user input is required, i halt processing and store the questions into the session - request.session['questions']. request.session['questions'] is a list of dictionaries. e.g. request.session['question'] = [] request.session['question'].append({'questi...
[ "You could use forms that aren't associated with models, like this:\nclass QuestionForm(forms.Form):\n answer = forms.CharField()\n\ndef questions(request):\n if request.method == 'POST':\n form = QuestionForm(request.POST) \n if form.is_valid():\n # Process the data in form.cleaned_d...
[ 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003065002_django_python.txt
Q: Python: Cannot concatenate str and NoneType objects sql = """ INSERT INTO [SCHOOLINFO] VALUES( '""" + self.accountNo + """', '""" + self.altName + """', '""" + self.address1 + """', '""" + self.address2 + """', '""" + self.city + """', ...
Python: Cannot concatenate str and NoneType objects
sql = """ INSERT INTO [SCHOOLINFO] VALUES( '""" + self.accountNo + """', '""" + self.altName + """', '""" + self.address1 + """', '""" + self.address2 + """', '""" + self.city + """', '""" + self.state + """', '""" + s...
[ "Use bind variables instead. Here's the spec for working with DBs in Python: PEP 249: Python Database API Specification v2.0.\nUPDATE: Based on the docs for pymssql, you need something like:\nsql = \"\"\"\n INSERT INTO [SCHOOLINFO] \n VALUES(\n %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %d, %s, %s...
[ 4, 3, 1, 1, 0 ]
[]
[]
[ "python", "sql" ]
stackoverflow_0003064233_python_sql.txt
Q: Python what's the data structure for triple data I've got a set of data that has three attributes, say A, B, and C, where A is kind of the index (i.e., A is used to look up the other two attributes.) What would be the best data structure for such data? I used two dictionaries, with A as the index of each. Howeve...
Python what's the data structure for triple data
I've got a set of data that has three attributes, say A, B, and C, where A is kind of the index (i.e., A is used to look up the other two attributes.) What would be the best data structure for such data? I used two dictionaries, with A as the index of each. However, there's key errors when the query to the data doesn...
[ "Could you use a dictionary with A as the key, and the item in the dictionary as a 2-item tuple or list? If you're working with any of that data in a consistent way, you could also consider storing a class that has 2 properties in the dictionary.\n", "AtoB = {\"A1\":\"B1\", \"A2\":\"B2\"}\nAtoB.get(\"A3\", None)\...
[ 3, 3, 2, 0 ]
[]
[]
[ "data_structures", "python" ]
stackoverflow_0003064169_data_structures_python.txt
Q: AES Encryption. From Python (pyCrypto) to .NET I am currently trying to port a legacy Python app over to .NET which contains AES encrpytion using from what I can tell pyCrpyto. I have very limited Python and Crypto experience. The code uses the snippet from the following page. http://www.djangosnippets.org/snippet...
AES Encryption. From Python (pyCrypto) to .NET
I am currently trying to port a legacy Python app over to .NET which contains AES encrpytion using from what I can tell pyCrpyto. I have very limited Python and Crypto experience. The code uses the snippet from the following page. http://www.djangosnippets.org/snippets/1095/ So far I believe I have managed to work out ...
[ "AES (and Rijndael) requires a mode and an IV. The IV may be a vector of zeroes, but it is still an IV. the mode may not be explicitly specified... but if it's using AES, there's still a mode.\nTry this answer for some background:\nWhich AES library to use in Ruby/Python?\n" ]
[ 1 ]
[]
[]
[ ".net", "aes", "c#", "pycrypto", "python" ]
stackoverflow_0002973546_.net_aes_c#_pycrypto_python.txt
Q: How to implement python to find value between xml tags? I am using google site to retrieve weather information , I want to find values between XML tags. Following code give me weather condition of a city , but I am unable to obtain other parameters such as temperature and if possible explain working of split funct...
How to implement python to find value between xml tags?
I am using google site to retrieve weather information , I want to find values between XML tags. Following code give me weather condition of a city , but I am unable to obtain other parameters such as temperature and if possible explain working of split function implied in the code: import urllib def getWeather(city):...
[ "USE\nA\nPARSER\nYou can't parse XML using regex(es), so don't try. Here's a start to finding an XML parser in Python. Here's a good site for learning about parsing XML in Python.\nUPDATE: Given the new info about PyS60, here's the documentation for using XML from Nokia's website.\nUPDATE 2: @Nas Banov has requeste...
[ 8, 4, 2, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003063319_python.txt
Q: What Is The Replace Function In Python I want to write a python code that open a text file and Replace with a word that i want send to it . May you give me an example ? Thanks . A: surprised that MarteliBot has not replied yet :-) (i learned about fileinput from him here in some other thread) - so in a hurry,...
What Is The Replace Function In Python
I want to write a python code that open a text file and Replace with a word that i want send to it . May you give me an example ? Thanks .
[ "surprised that MarteliBot has not replied yet :-) (i learned about fileinput from him here in some other thread) - so in a hurry, you can do the following:\nimport fileinput\nfor line in fileinput.input('somefile.txt', inplace=1):\n print line.replace('OldWord', 'NewWord'),\n\nps. this actually redirects stdout...
[ 2, 1, 0, 0, 0 ]
[]
[]
[ "file_io", "python", "replace" ]
stackoverflow_0003064392_file_io_python_replace.txt
Q: Assignment in python for loop possible? I have a dictionary d (and a seperate sorted list of keys, keys). I wanted the loop to only process entries where the value is False - so i tried the following: for key in keys and not d[key]: #do foo I suppose my understanding of python sytax is not what i thought it was ...
Assignment in python for loop possible?
I have a dictionary d (and a seperate sorted list of keys, keys). I wanted the loop to only process entries where the value is False - so i tried the following: for key in keys and not d[key]: #do foo I suppose my understanding of python sytax is not what i thought it was - because the assignment doesnt suppose to ha...
[ "Use a genex for this.\nfor key in (k for k in keys if not d[k]):\n ....\n\n", "If you dict was opposite (True iff the value should be scanned) you could use:\nfor key in filter(d.get, keys):\n ...\n\n", "import itertools as it\n\nfor key in it.ifilterfalse(d.get, keys):\n ...\n\nitertools often offers t...
[ 5, 2, 2 ]
[]
[]
[ "python", "syntactic_sugar" ]
stackoverflow_0003066668_python_syntactic_sugar.txt
Q: How to speed-up nested loop? I'm performing a nested loop in python that is included below. This serves as a basic way of searching through existing financial time series and looking for periods in the time series that match certain characteristics. In this case there are two separate, equally sized, arrays rep...
How to speed-up nested loop?
I'm performing a nested loop in python that is included below. This serves as a basic way of searching through existing financial time series and looking for periods in the time series that match certain characteristics. In this case there are two separate, equally sized, arrays representing the 'close' (i.e. the pr...
[ "Update: (almost) completely vectorized version below in \"new_function2\"... \nI'll add comments to explain things in a bit. \nIt gives a ~50x speedup, and a larger speedup is possible if you're okay with the output being numpy arrays instead of lists. As is:\nIn [86]: %timeit new_function2(close, volume, INTER...
[ 7, 3, 1 ]
[]
[]
[ "finance", "numpy", "python", "scipy" ]
stackoverflow_0003065624_finance_numpy_python_scipy.txt
Q: Python access an object byref / Need tagging I need to suck data from stdin and create a object. The incoming data is between 5 and 10 lines long. Each line has a process number and either an IP address or a hash. For example: pid=123 ip=192.168.0.1 - some data pid=123 hash=ABCDEF0123 - more data hash=ABCDEF123 - ...
Python access an object byref / Need tagging
I need to suck data from stdin and create a object. The incoming data is between 5 and 10 lines long. Each line has a process number and either an IP address or a hash. For example: pid=123 ip=192.168.0.1 - some data pid=123 hash=ABCDEF0123 - more data hash=ABCDEF123 - More data ip=192.168.0.1 - even more data I need ...
[ "Python only has references.\nCreate the object once, and add it to all relevant keys at once.\nclass MyData(object):\n def __init__(self, pid, ip, hash):\n self.pid = pid\n ...\n\nfor line in sys.stdin:\n pid, ip, hash = process(line)\n obj = MyData(pid=pid, ip=ip, hash=hash)\n if pid:\n mydict[pid] ...
[ 2, 2 ]
[]
[]
[ "byref", "object", "python", "tags" ]
stackoverflow_0003067220_byref_object_python_tags.txt
Q: Render page initially and update via AJAX using the same template HTML Let's say you have a view called "View Story" which is just a web page rendered on the backend via Python/Django. On that page there's a list of comments at the bottom rendered as part of the "View Story" template using Django's templating sys...
Render page initially and update via AJAX using the same template HTML
Let's say you have a view called "View Story" which is just a web page rendered on the backend via Python/Django. On that page there's a list of comments at the bottom rendered as part of the "View Story" template using Django's templating system (in a loop). This page also allows you to add a comment to the list. T...
[ "Here is what you should do:\nview_story.html:\nbla bla bla\n\nComments:\n<ul id=\"comments\">\n{% for comment in comments %}\n <li>{% include \"comment_item.html\" %}</li>\n{% endfor %}\n</ul>\n<from>Ajax form here</form>\n\nthan you need to create view for adding comments(ajax):\ndef add_comment(request):\n ...
[ 6, 3, 1 ]
[]
[]
[ "ajax", "django", "javascript", "python" ]
stackoverflow_0001718784_ajax_django_javascript_python.txt
Q: Update facebook status using pyfacebook offline access I'm trying to update a user status from a django python app. The user went thru facebook connect and registers to the app. I got sessionkey and fbuid. fb = Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY) if fbsessionkey: fb.session_key = fbsessi...
Update facebook status using pyfacebook offline access
I'm trying to update a user status from a django python app. The user went thru facebook connect and registers to the app. I got sessionkey and fbuid. fb = Facebook(FACEBOOK_API_KEY, FACEBOOK_SECRET_KEY) if fbsessionkey: fb.session_key = fbsessionkey fb.uid = fbuid fb.auth.createToken() ...
[ "You have to add signature. It is MD5 hash of the current request and your secret key. I was mistaken about the issue first sorry :p\nPlease check http://wiki.developers.facebook.com/index.php/Users.setStatus and know about how to get the signature\n" ]
[ 0 ]
[]
[]
[ "facebook", "python" ]
stackoverflow_0003002308_facebook_python.txt
Q: Not getting exact result in python with the values leading zero. Please tell me what is going on there zipcode = 02132 print zipcode result = 1114 A: A leading zero means octal. 2132 in octal equals 1114 in decimal. They removed this behavior in Python 3.0. A: In Python 2.x, number with a leading zero is inte...
Not getting exact result in python with the values leading zero. Please tell me what is going on there
zipcode = 02132 print zipcode result = 1114
[ "A leading zero means octal. 2132 in octal equals 1114 in decimal.\nThey removed this behavior in Python 3.0.\n", "In Python 2.x, number with a leading zero is interpreted as octal (base-eight). Python 3.x requires a leading \"0o\" to indicate an octal number. You probably want to treat a zipcode as a string to k...
[ 15, 9, 6, 5, 3, 2 ]
[]
[]
[ "python" ]
stackoverflow_0003067409_python.txt
Q: How to transfer url parameters to repoze custom predicate checkers I would like to create a repoze custom predicate checker that is capable to access url parameters and validate something. But I would like to use allow_only to set this permission checker in all the controller's scope. Something like: class MyContr...
How to transfer url parameters to repoze custom predicate checkers
I would like to create a repoze custom predicate checker that is capable to access url parameters and validate something. But I would like to use allow_only to set this permission checker in all the controller's scope. Something like: class MyController(BaseController): allow_only = All(not_anonymous(msg=l_(u'You ...
[ "May be you need to use ControllerProtector\nfrom repoze.what.plugins.pylonshq import ControllerProtector\n\nallow_only = All(not_anonymous(msg=l_(u'You must be logged on')),\n my_custom_predicate(msg=l_(u'something wrong')))\n\n@ControllerProtector(allow_only)\nclass MyController(BaseController...
[ 0 ]
[]
[]
[ "authentication", "permissions", "python", "repoze.who", "turbogears2" ]
stackoverflow_0003064576_authentication_permissions_python_repoze.who_turbogears2.txt
Q: Extending Django Flatpages to accept template tags I use django flatpages for a lot of content on our site, I'd like to extend it to accept django template tags in the content as well. I found this snippet but after much larking about I couldn't get it to work. Am I correct in assuming that you would need too "sub...
Extending Django Flatpages to accept template tags
I use django flatpages for a lot of content on our site, I'd like to extend it to accept django template tags in the content as well. I found this snippet but after much larking about I couldn't get it to work. Am I correct in assuming that you would need too "subclass" the django flatpages app to get this to work? Is ...
[ "1. A simple page view wich will render template tags by loading a template for each page:\nin url.py\nurl(r'^page/(?P<slug>.*)/$','my_app.views.page_detail', name='page_url'),\n\nin my_app/views.py\ndef page_detail (request, slug):\n return render_to_response('page/' + slug + '.html', {},\n ...
[ 8, 0 ]
[]
[]
[ "django", "django_flatpages", "python" ]
stackoverflow_0003066270_django_django_flatpages_python.txt
Q: Jython java call throws exception asking for 2 args when only one arg is coded I have an Java method I want to call within my Jython servlet running on tomcat5. It looks like this: @SuppressWarnings("unchecked") public School loadByName(String name) { List<School> school; school = getHibernateT...
Jython java call throws exception asking for 2 args when only one arg is coded
I have an Java method I want to call within my Jython servlet running on tomcat5. It looks like this: @SuppressWarnings("unchecked") public School loadByName(String name) { List<School> school; school = getHibernateTemplate().find("from " + getPersistentClass().getName() + " where name = ?", name); ...
[ "loadByName is not static.\nYou need a instance to call it.\nsdh = SchoolDAOHibernate(...) # ... any args for construction ??\nsdh.loadByName('Univeristy') # 2 args :-) self (sdh) and 'University'\n\nclearer ?\n", "Because the loadByName method isn't static, Jython might be expecting the first argument to be an i...
[ 2, 1 ]
[]
[]
[ "java", "jython", "python", "tomcat" ]
stackoverflow_0003067731_java_jython_python_tomcat.txt
Q: Screen overlay with Python, paint over an active window with background python script I'm writing a python script that runs in the background and takes screenshots of another application that is active. Then it analyses the screenshots and now it should overlay a certain image over the active app or the screen. I ...
Screen overlay with Python, paint over an active window with background python script
I'm writing a python script that runs in the background and takes screenshots of another application that is active. Then it analyses the screenshots and now it should overlay a certain image over the active app or the screen. I still need to be able to make mouse and keyboard inputs in the active app. So I need a way ...
[ "http://www.michaelfogleman.com/2009/12/drawing-on-the-windows-desktop-using-python-and-wxpython/\nSeems to do what you want, but is windows only, as are some other answers to similar questions here on stackoverflow\n" ]
[ 4 ]
[]
[]
[ "macos", "overlay", "paint", "python", "screen" ]
stackoverflow_0003067812_macos_overlay_paint_python_screen.txt
Q: Jython saying "No visible constructors for class" I have a jython servlet as part of a large application running in tomcat5. I tested a few Spring Framework classes and create the objects in the Jython servlet. When I try to create objects of classes in the application I catch an Exception message "No visible cons...
Jython saying "No visible constructors for class"
I have a jython servlet as part of a large application running in tomcat5. I tested a few Spring Framework classes and create the objects in the Jython servlet. When I try to create objects of classes in the application I catch an Exception message "No visible constructors for class". These java classes do have a publi...
[ "doublep / cluch answered the question :-) in the comment \nadding just a little info:\nFrom the Jython FAQ :\n3.3 Why can't I execute a 'protected' or 'private' Java instance method or access a 'protected' or 'private' attribute in a Java package?\nBy default, as in Java, these methods are protected from extern...
[ 3 ]
[]
[]
[ "java", "jython", "python", "servlets", "tomcat" ]
stackoverflow_0003065573_java_jython_python_servlets_tomcat.txt
Q: A set union find algorithm I have thousands of lines of 1 to 100 numbers, every line define a group of numbers and a relationship among them. I need to get the sets of related numbers. Little Example: If I have this 7 lines of data T1 T2 T3 T4 T5 T6 T1 T5 T4 T3 T4 T7 I need a not so slow algorithm to know that t...
A set union find algorithm
I have thousands of lines of 1 to 100 numbers, every line define a group of numbers and a relationship among them. I need to get the sets of related numbers. Little Example: If I have this 7 lines of data T1 T2 T3 T4 T5 T6 T1 T5 T4 T3 T4 T7 I need a not so slow algorithm to know that the sets here are: T1 T2 T6 (beca...
[ "Once you have built the data structure, exactly what queries do you want to run against it? Show us your existing code. What is a T(x)? You talk about \"groups of numbers\" but your sample data shows T1, T2, etc; please explain.\nHave you read this: http://en.wikipedia.org/wiki/Disjoint-set_data_structure\nTry loo...
[ 16, 14, 5, 1, 0 ]
[]
[]
[ "algorithm", "python", "set" ]
stackoverflow_0003067529_algorithm_python_set.txt
Q: get n records at a time from a temporary table I have a temporary table with about 1 million entries. The temporary table stores the result of a larger query. I want to process these records 1000 at a time, for example. What's the best way to set up queries such that I get the first 1000 rows, then the next 1000, ...
get n records at a time from a temporary table
I have a temporary table with about 1 million entries. The temporary table stores the result of a larger query. I want to process these records 1000 at a time, for example. What's the best way to set up queries such that I get the first 1000 rows, then the next 1000, etc.? They are not inherently ordered, but the tempo...
[ "Use a cursor and fetch the to rows you need. Offset ... limit will become slow when you have a lot of records, a cursor will do a much better job.\nhttp://www.postgresql.org/docs/8.4/interactive/sql-fetch.html\n", "Perhaps you could use something like this (we use when batch updating a table with +20 million row...
[ 4, 1 ]
[]
[]
[ "database", "postgresql", "python", "sql" ]
stackoverflow_0003065826_database_postgresql_python_sql.txt
Q: How to build a index table (python dict like) in python with sqlite3 Suppose I have one string list may have duplicated items: A B C A A C D E F F I want to make a list can assign an unique index for each item, looks like: 1 A 2 B 3 C 4 D 5 E 6 F now I created sqlite3 database with below SQL statemen...
How to build a index table (python dict like) in python with sqlite3
Suppose I have one string list may have duplicated items: A B C A A C D E F F I want to make a list can assign an unique index for each item, looks like: 1 A 2 B 3 C 4 D 5 E 6 F now I created sqlite3 database with below SQL statement: CREATE TABLE aa ( myid INTEGER PRIMARY KEY AUTOINCREMENT, ...
[ "You could use a set, to filter double entries in your list and just insert the values:\n>>> set(['A', 'B', 'C', 'D', 'A', 'A', 'A', 1, 2, 1, 3, object(), object()])\nset(['A', 1, 'C', 'B', 'D', 2, <object object at 0x100274590>, 3, <object object\n at 0x1002746a0>])\n\nor use a try-except clause on each commit to ...
[ 1, 1 ]
[]
[]
[ "dictionary", "python", "sqlite" ]
stackoverflow_0003067494_dictionary_python_sqlite.txt
Q: python: sending information between two scripts I have two Python scripts in two different locations and cannot be moved. What is the best way to send information between the two scripts? say for example in script1.py i had a string e.g. x = 'teststring' then i need variable 'x' passed to script2.py, which saves...
python: sending information between two scripts
I have two Python scripts in two different locations and cannot be moved. What is the best way to send information between the two scripts? say for example in script1.py i had a string e.g. x = 'teststring' then i need variable 'x' passed to script2.py, which saves the variable 'x' to a text file? Any ideas?
[ "You just import it. \n#script2.py\nfrom script1 import x\n\nTo make the script2 find the script1, the script1 file must be in the module search path\nedit\nHere's an example:\nFirst we create a dir and display the value of the module search path:\n$mkdir some_dir\n$echo $PYTHONPATH\n\nIt's nothig. Then we create a...
[ 3, 0, 0 ]
[]
[]
[ "python" ]
stackoverflow_0003066951_python.txt
Q: i can use this 'zipme' to download source code from gae , but can not i download another file around me i follow this article : zipme and i download my file successful , and i want to download another file that ex: the parent file so i change this: dirname=os.path.dirname folder = dirname(__file__) to dirname=...
i can use this 'zipme' to download source code from gae , but can not i download another file around me
i follow this article : zipme and i download my file successful , and i want to download another file that ex: the parent file so i change this: dirname=os.path.dirname folder = dirname(__file__) to dirname=os.path.dirname folder = dirname(dirname(__file__)) but the error is : firefox can't find the file why ? th...
[ "You get the error, because something fails in the script and it won't return a valid ZIP file back in the response.\nThe most probable reason is because your zipme.py will be in the root of your application. So if you try to get the parent folder of your root folder (returned by dirname(__file__)) it will fail bec...
[ 1 ]
[]
[]
[ "download", "google_app_engine", "parent", "python", "zip" ]
stackoverflow_0003068503_download_google_app_engine_parent_python_zip.txt
Q: can i upload all data to gae without bulkloader i can use this code to download all data from my app on gae : appcfg.py download_data --application=zjm1126 --url=http://zjm1126.appspot.com/remote_api --filename=a.csv it is not use bulkloader , so can i upload all data without bulkloader , thanks A: Yes, you ca...
can i upload all data to gae without bulkloader
i can use this code to download all data from my app on gae : appcfg.py download_data --application=zjm1126 --url=http://zjm1126.appspot.com/remote_api --filename=a.csv it is not use bulkloader , so can i upload all data without bulkloader , thanks
[ "Yes, you can use the upload_data command as described here, but this and your download_data command are deprecated from SDK 1.3.4 onwards. So it's better to look into using the bulkloader API as described here.\n" ]
[ 1 ]
[]
[]
[ "bulkloader", "google_app_engine", "python" ]
stackoverflow_0003068675_bulkloader_google_app_engine_python.txt
Q: Display image in Django Form I need to display an image in a Django form. My Django form is quite simple - a single text input field. When I initialise my Django form in a view, I would like to pass the image path as a parameter, and the form when rendered in the template displays the image. Is is possible with Dj...
Display image in Django Form
I need to display an image in a Django form. My Django form is quite simple - a single text input field. When I initialise my Django form in a view, I would like to pass the image path as a parameter, and the form when rendered in the template displays the image. Is is possible with Django forms or would i have to disp...
[ "This template responsibility to display this image in your case, I believe.\nIf you form need to be able to send image related information (path, url..), you'll need to create a dedicated widget.\n", "If the image is related to the form itself, not to any field in particular, then you can make a custom form clas...
[ 1, 1 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003068827_django_python.txt
Q: Creating a tiled map with blender I'm looking at creating map tiles based on a 3D model made in blender, The map is 16 x 16 in blender. I've got 4 different zoom levels and each tile is 100 x 100 pixels. The entire map at the most zoomed out level is 4 x 4 tiles constructing an image of 400 x 400. The most zoomed...
Creating a tiled map with blender
I'm looking at creating map tiles based on a 3D model made in blender, The map is 16 x 16 in blender. I've got 4 different zoom levels and each tile is 100 x 100 pixels. The entire map at the most zoomed out level is 4 x 4 tiles constructing an image of 400 x 400. The most zoomed in level is 256 x 256 obviously constr...
[ "This was relatively simple in the end. \nI scaled up the model so that 1 tile on the map was 1 grid in blender.\nSet the camera to be orthographic.\nSet the scale on the camera to 1 for the highest zoom, 4 for the next one, 16 for the next one and so on.\nUpdated the start coordinates and move values accordingly.\...
[ 0 ]
[]
[]
[ "blender", "blender_2.49", "map", "python", "scripting" ]
stackoverflow_0002957702_blender_blender_2.49_map_python_scripting.txt
Q: Is there a way to watch all COM activity on a computer? I'm trying to deal with a piece of specialized hardware, that presents it's interface as a COM object, using win32com in Python. However, the documentation for how to actually set up the hardware through the COM object is sparse (it requires a significant amo...
Is there a way to watch all COM activity on a computer?
I'm trying to deal with a piece of specialized hardware, that presents it's interface as a COM object, using win32com in Python. However, the documentation for how to actually set up the hardware through the COM object is sparse (it requires a significant amount of initialization), and entirely oriented at using a bunc...
[ "Try Deviare COM Spy Console.\n\nCom Spy Console allows users to\n monitor applications using Component\n Object Model's interfaces. You are\n able to spy which interfaces are being\n created and see how the applications\n are using them by intercepting the\n calls to its member functions.\nSpy on any ActiveX...
[ 3, 0 ]
[]
[]
[ "com", "python", "visual_studio" ]
stackoverflow_0003067784_com_python_visual_studio.txt
Q: How fast are App Engine db.get(keys) and A.all(keys_only=True).filter('b =', b).fetch(1000)? A db.get() of 50 keys seems to take me 5-6 seconds. Is that normal? What is the time a function of? I also did a A.all(keys_only=True).filter('b =', b).fetch(1000) where A.b is a ReferenceProperty. I did 50 such round trip...
How fast are App Engine db.get(keys) and A.all(keys_only=True).filter('b =', b).fetch(1000)?
A db.get() of 50 keys seems to take me 5-6 seconds. Is that normal? What is the time a function of? I also did a A.all(keys_only=True).filter('b =', b).fetch(1000) where A.b is a ReferenceProperty. I did 50 such round trips to the datastore, with different values of b, and the total time was only 3-4 seconds. How is th...
[ "\nA db.get() of 50 keys seems to take me\n 5-6 seconds. Is that normal? What is\n the time a function of?\n\nNo. It should take a couple of hundred milliseconds. How are you timing it, though?\n\nI also did a\n A.all(keys_only=True).filter('b =',\n b).fetch(1000) where A.b is a\n ReferenceProperty. I did 50 s...
[ 3, 2 ]
[]
[]
[ "google_app_engine", "python" ]
stackoverflow_0003066300_google_app_engine_python.txt
Q: Django -- User.DoesNotExist does not exist? I'm trying to get hold of Django. I use Pydev on Eclipse. I have written a simple signup page that I can't get to work. Eclipse complains that User.DoesNotExist is undefined. Most likely, I am missing something trivial. Here's the relevant portion of the code: from djang...
Django -- User.DoesNotExist does not exist?
I'm trying to get hold of Django. I use Pydev on Eclipse. I have written a simple signup page that I can't get to work. Eclipse complains that User.DoesNotExist is undefined. Most likely, I am missing something trivial. Here's the relevant portion of the code: from django.contrib.auth.models import User ... class SignU...
[ "The problem is really with PyDev, not your code. What you have done is absolutely correct, but IDEs will always have difficulty resolving attributes in a dynamic language like Python. In the case of the DoesNotExist exception, it is added via a __metaclass__ rather than through normal object inheritance, so PyDev ...
[ 26, 19, 8, 2, 2, 1, 1 ]
[]
[]
[ "authentication", "django", "django_models", "pydev", "python" ]
stackoverflow_0000851628_authentication_django_django_models_pydev_python.txt
Q: new to mac and textmate, can someone explain these shortcuts? I'm using textmate for the first time basically, and I am lost as to what keys map to these funny symbols. using python bundles, what keys do I press for: run run with tests run project unit tests Also, with textmate, do I actually define a project in t...
new to mac and textmate, can someone explain these shortcuts?
I'm using textmate for the first time basically, and I am lost as to what keys map to these funny symbols. using python bundles, what keys do I press for: run run with tests run project unit tests Also, with textmate, do I actually define a project in textmate or do I just work on the files and textmate doesn't create ...
[ "Check out this link for some of the translations to some of the keyboard symbols. This should help you out :)\nAlso here is a link from the Apple site for an exhaustive list of shortcuts.\n\n(source: osxkeyboardshortcuts.com) \n", "\nAlso, with textmate, do I actually define a project in textmate or do I just wo...
[ 6, 2 ]
[]
[]
[ "python", "textmate" ]
stackoverflow_0003034640_python_textmate.txt
Q: Why don't we require interfaces in dynamic languages? Is it just because of dynamic typing we don't require a concept of interfaces(like in Java and C#) in python? A: The interface as a keyword and artifact was introduced by Java1 ( and C# took it from there ) to describe what the contract an object must adhere...
Why don't we require interfaces in dynamic languages?
Is it just because of dynamic typing we don't require a concept of interfaces(like in Java and C#) in python?
[ "The interface as a keyword and artifact was introduced by Java1 ( and C# took it from there ) to describe what the contract an object must adhere was. \nBut, interface has always been a key part of Object Oriented Paradigm and basically it represents the methods an object has to respond. Java just enforces this ...
[ 23, 5, 2, 1, 1, 1, 1, 0, 0 ]
[]
[]
[ "c#", "dynamic_languages", "java", "python" ]
stackoverflow_0003062701_c#_dynamic_languages_java_python.txt
Q: How to store an integer leaded by zeros in django I'm trying to store a number in django that looks like this: 000001 My problem is that if I type this inside an IntegerField it gets converted to "1" without the leading zeros. I've tried also with a DecimalField with the same result. How can I store the leading z...
How to store an integer leaded by zeros in django
I'm trying to store a number in django that looks like this: 000001 My problem is that if I type this inside an IntegerField it gets converted to "1" without the leading zeros. I've tried also with a DecimalField with the same result. How can I store the leading zeros whithout using a CharField? (I need to manipulate ...
[ "Don't store it with the leading zeros. Format it on output instead:\n(in view: value = 1)\n{{ value|stringformat:\"04d\" }} # displays as 0001\n\n", "I think you should use a CharField and do something like that :\ntry:\n value = int(field)\n # do something with value\nexcept valueError:\n # raise a Val...
[ 21, 2 ]
[]
[]
[ "django", "django_admin", "django_models", "python" ]
stackoverflow_0003069989_django_django_admin_django_models_python.txt
Q: Reduce list of Python objects to dict of object.id -> object You have list of objects and each of them has an id property. Here's my way to convert it to dict where keys are ids and values are objects: reduce( lambda x,y: dict(x.items() + { y.id : y}.items()), list, {} ) Suggest better way to do it. A: In...
Reduce list of Python objects to dict of object.id -> object
You have list of objects and each of them has an id property. Here's my way to convert it to dict where keys are ids and values are objects: reduce( lambda x,y: dict(x.items() + { y.id : y}.items()), list, {} ) Suggest better way to do it.
[ "In Python 3.x:\nobject_dict = {x.id: x for x in object_list}\n\nIn both Python 3.x and Python 2.4+:\nobject_dict = dict((x.id, x) for x in object_list)\n\n(x.id, x) for x in object_list is a generator comprehension (and, nicely, does not need to be wrapped in parentheses like a list comprehension needs to be wrapp...
[ 107, 13, 6 ]
[]
[]
[ "dictionary", "lambda", "python" ]
stackoverflow_0003070242_dictionary_lambda_python.txt
Q: Python Logging across multiple classes and files; how to configure so as to be easily disabled? Currently, I have osmething like this in all of my classes: # Import logging to log information import logging # Set up the logger LOG_FILENAME = 'log.txt' logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)...
Python Logging across multiple classes and files; how to configure so as to be easily disabled?
Currently, I have osmething like this in all of my classes: # Import logging to log information import logging # Set up the logger LOG_FILENAME = 'log.txt' logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG) This works well, and I get the output I want, but I would really like to have all this sort of info...
[ "To disable all logging from the root logger (which is all you're setting up with basicConfig),\nlogging.getLogger().setLevel(logging.CRITICAL)\n\nIf you want, you can encapsulate that into a function of your myLogger module, but that hardly seems worth it.\n", "To simply the setting up of logging, check out logg...
[ 3, 3 ]
[]
[]
[ "logging", "python" ]
stackoverflow_0003070331_logging_python.txt
Q: multiline checkbox in wxpython I'm working with wxpython (2.8) with python 2.5. is it possible to force a wx.CheckBox to display its label on multiple lines? I'd like to be able to do the same as wx.StaticText.Wrap(width) See the attached example: the wx.CheckBox is 200 px wide, but it's label does not fit in this...
multiline checkbox in wxpython
I'm working with wxpython (2.8) with python 2.5. is it possible to force a wx.CheckBox to display its label on multiple lines? I'd like to be able to do the same as wx.StaticText.Wrap(width) See the attached example: the wx.CheckBox is 200 px wide, but it's label does not fit in this space. Any help is really appreciat...
[ "what about something like this? Flex!\n(I've made it a radio button to show that it still behaves like one)\nimport wx\nimport textwrap\n\nclass MultilineRadioButton(wx.RadioButton):\n def __init__(self, parent, id=-1, label=wx.EmptyString, wrap=10, pos=wx.DefaultPosition, size=wx.DefaultSize, style=0, vali...
[ 3, 1, 1 ]
[]
[]
[ "python", "wxpython" ]
stackoverflow_0001466140_python_wxpython.txt
Q: Can I use python ast module for this? I'd like to write a program that modify python programs in this way: change "some literal string %" % SOMETHING to functioncall("some literal string %") % SOMETHING Thanks, A: It may be simpler with tokenize -- adapting the example in the docs, import cStringIO import tokeni...
Can I use python ast module for this?
I'd like to write a program that modify python programs in this way: change "some literal string %" % SOMETHING to functioncall("some literal string %") % SOMETHING Thanks,
[ "It may be simpler with tokenize -- adapting the example in the docs,\nimport cStringIO\nimport tokenize\n\nclass Lookahead(object):\n\n def __init__(self, s):\n self._t = tokenize.generate_tokens(cStringIO.StringIO(s).readline)\n self.lookahead = next(self._t, None)\n\n def __iter__(self):\n return self...
[ 2, 1, 0, 0 ]
[]
[]
[ "parsing", "python" ]
stackoverflow_0003069695_parsing_python.txt
Q: Access static class variable of parent class in Python I have someting like this class A: __a = 0 def __init__(self): A.__a = A.__a + 1 def a(self): return A.__a class B(A): def __init__(self): # how can I access / modify A.__a here? A.__a = A.__a + 1 # does not work def a(self): ret...
Access static class variable of parent class in Python
I have someting like this class A: __a = 0 def __init__(self): A.__a = A.__a + 1 def a(self): return A.__a class B(A): def __init__(self): # how can I access / modify A.__a here? A.__a = A.__a + 1 # does not work def a(self): return A.__a Can I access the __a class variable in B? It's po...
[ "So, __a isn't a static variable, it's a class variable. And because of the double leading underscore, it's a name mangled variable. That is, to make it pseudo-private, it's been automagically renamed to _<classname>__<variablename> instead of __<variablename>. It can still be accessed by instances of that class on...
[ 11, 3, 1 ]
[]
[]
[ "class", "inheritance", "python", "static_variables" ]
stackoverflow_0003070543_class_inheritance_python_static_variables.txt
Q: Does REGEX differ from PHP to Python I found this post: Python Regex vs PHP Regex but I actually did not get if Python's REGEX syntax matches PHP's REGEX syntax. I started to convert some of my old PHP code to python (due to g's appengine etc.), and now I would like to know whether the regex is 100% convertable, b...
Does REGEX differ from PHP to Python
I found this post: Python Regex vs PHP Regex but I actually did not get if Python's REGEX syntax matches PHP's REGEX syntax. I started to convert some of my old PHP code to python (due to g's appengine etc.), and now I would like to know whether the regex is 100% convertable, by simple copy & paste. regards,
[ "Python uses a syntax similar to the Perl syntax and PHP uses the Perl Compatible Regular Expressions syntax, so it should be nearly the same. Read about the possible differences.\nThe only real difference is that in PHP, the expression must be enclosed in delimiters.\n", "They are compatible for the most part. T...
[ 11, 11, 1, 1, 1, 1 ]
[]
[]
[ "php", "python", "regex" ]
stackoverflow_0003070655_php_python_regex.txt
Q: Some kind of event functionality in Django? I have a view my Django application which when invoked calls my backend. My backend logic sometimes reaches a point when it needs user input to continue. When this happens, I pickle dump my backend data into the session so that i can resume it later on. Currently i have ...
Some kind of event functionality in Django?
I have a view my Django application which when invoked calls my backend. My backend logic sometimes reaches a point when it needs user input to continue. When this happens, I pickle dump my backend data into the session so that i can resume it later on. Currently i have defined the scenario when user input is required ...
[ "Personnaly, I use the exception mechanism for this kind of stuff and I don't really see why I shouldn't\n", "I'd say there are two ways: You assume that data should be present and if they are not, custom exception should be raised as mentioned.\nHowever, if it's part of expected workflow and it may just be prese...
[ 0, 0 ]
[]
[]
[ "django", "python" ]
stackoverflow_0003069583_django_python.txt
Q: Joining the previous and next sentence using python I'm trying to join a set of sentences contained in a list. I have a function which determines whether a sentence in worth saving. However, in order to keep the context of the sentence I need to also keep the sentence before and after it. In the edge cases, whe...
Joining the previous and next sentence using python
I'm trying to join a set of sentences contained in a list. I have a function which determines whether a sentence in worth saving. However, in order to keep the context of the sentence I need to also keep the sentence before and after it. In the edge cases, where its either the first or last sentence then, I'll just ...
[ "Appending an empty string to the beginning and end of the list is actually a good idea, but there is actually no need to use fancy list comprehension or such. You can build a generator very easily:\ndef yieldContext(l, func):\n l = [''] + l + ['']\n for i, s in enumerate(l):\n if func(s):\n ...
[ 4, 1, 1, 0 ]
[]
[]
[ "iterator", "python" ]
stackoverflow_0003070695_iterator_python.txt
Q: Problem accessing config files within a Python egg I have a Python project that has the following structure: package1 class.py class2.py ... package2 otherClass.py otherClass2.py ... config dev_settings.ini prod_settings.ini I wrote a setup.py file that converts this into an egg with the same file...
Problem accessing config files within a Python egg
I have a Python project that has the following structure: package1 class.py class2.py ... package2 otherClass.py otherClass2.py ... config dev_settings.ini prod_settings.ini I wrote a setup.py file that converts this into an egg with the same file structure. (When I examine it using a zip program the s...
[ "The problem is, the config files are not files anymore - they're packaged within the egg. It's not easy to find the answer in the docs, but it is there. From the setuptools developer's guide:\n\nTypically, existing programs manipulate a package's __file__ attribute in order to find the location of data files. Howe...
[ 12, 2 ]
[]
[]
[ "egg", "file", "python" ]
stackoverflow_0003071327_egg_file_python.txt
Q: Yield only as many are required from a generator I wish to yield from a generator only as many items are required. In the following code a, b, c = itertools.count() I receive this exception: ValueError: too many values to unpack I've seen several related questions, however I have zero interest in the remaining i...
Yield only as many are required from a generator
I wish to yield from a generator only as many items are required. In the following code a, b, c = itertools.count() I receive this exception: ValueError: too many values to unpack I've seen several related questions, however I have zero interest in the remaining items from the generator, I only wish to receive as man...
[ "You need to make sure that the number of items on both sides matches. One way is to use islice from the itertools module:\nfrom itertools import islice\na, b, c = islice(itertools.count(), 3)\n\n", "You need a deep bytecode hack - what you request cannot be done at Python source code level, but (if you're willin...
[ 6, 6, 3, 1 ]
[]
[]
[ "generator", "python", "python_2.x", "yield" ]
stackoverflow_0003070164_generator_python_python_2.x_yield.txt
Q: How to use float ** from C in Python? after having no success with my question on How to use float ** in Python with Swig?, I started thinking that swig might not be the weapon of choice. I need bindings for some c functions. One of these functions takes a float**. What would you recomend? Ctypes? Interface file: ...
How to use float ** from C in Python?
after having no success with my question on How to use float ** in Python with Swig?, I started thinking that swig might not be the weapon of choice. I need bindings for some c functions. One of these functions takes a float**. What would you recomend? Ctypes? Interface file: extern int read_data(const char *file,int *...
[ "I've used ctypes for several projects now and have been quite happy with the results. I don't think I've personally needed a pointer-to-pointer wrapper yet but, in theory, you should be able to do the following:\nfrom ctypes import *\n\nyour_dll = cdll.LoadLibrary(\"your_dll.dll\")\n\nPFloat = POINTER(c_float)\nPI...
[ 2 ]
[]
[]
[ "c", "ctypes", "pointers", "python", "swig" ]
stackoverflow_0003069967_c_ctypes_pointers_python_swig.txt
Q: How do I get all of the values from a GWT multiselect ListBox on a post? I have a multiselect ListBox in a FormPanel in GWT. I have set the name of the listbox to "foo" via ListBox.setName(). When I post the form, I see that all of the selected values get posted, but all are bound to the same name "foo". So I seem...
How do I get all of the values from a GWT multiselect ListBox on a post?
I have a multiselect ListBox in a FormPanel in GWT. I have set the name of the listbox to "foo" via ListBox.setName(). When I post the form, I see that all of the selected values get posted, but all are bound to the same name "foo". So I seemingly cannot get each of the posted values (I am using Django/Python server-si...
[ "Use params.getlist('foo').\nSee the documentation for QueryDict objects.\n" ]
[ 0 ]
[]
[]
[ "django", "gwt", "listbox", "post", "python" ]
stackoverflow_0003071449_django_gwt_listbox_post_python.txt
Q: Convert python variables into javascript variables I want to use Google Chart API using javascript. (I don't want to use the python wrapper) So how do I send data from my python code into the javascript to create graphs? A: You can translate Python data to Javascript data types with JSON ( http://docs.python.org...
Convert python variables into javascript variables
I want to use Google Chart API using javascript. (I don't want to use the python wrapper) So how do I send data from my python code into the javascript to create graphs?
[ "You can translate Python data to Javascript data types with JSON ( http://docs.python.org/library/json.html ). I assume you're using this alongside a Python-based web server?\n" ]
[ 2 ]
[]
[]
[ "google_visualization", "javascript", "python" ]
stackoverflow_0003071411_google_visualization_javascript_python.txt
Q: Cookie not accepted on IE when authenticating with Graph API (oauth) - iframe app I started playing with the new graph api with the python sdk. I'm trying to use the python-sdk in an iframe app to make the authentication (I successfully did it with JS - although the popup is blocked on IE and chrome by default). I...
Cookie not accepted on IE when authenticating with Graph API (oauth) - iframe app
I started playing with the new graph api with the python sdk. I'm trying to use the python-sdk in an iframe app to make the authentication (I successfully did it with JS - although the popup is blocked on IE and chrome by default). I'm following this example: http://github.com/facebook/python-sdk/blob/master/examples/o...
[ "IE\nMake sure the P3P header is set on all responses served through the iframe\nSafari\nDon't know. Some indicate that there is no better way than what you've already figured out.\n", "response.headers['P3P'] = 'CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"'\n\n" ]
[ 0, 0 ]
[]
[]
[ "facebook", "oauth", "python" ]
stackoverflow_0003071462_facebook_oauth_python.txt