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:
Can't install python module "pycrypto" on Debian lenny
I tried to install pycrypto module by downloading the source code and executing the following command python setup.py install, then an error came
running install
running build
running build_py
running build_ext
warning: GMP library not found; Not building Cry... | Can't install python module "pycrypto" on Debian lenny | I tried to install pycrypto module by downloading the source code and executing the following command python setup.py install, then an error came
running install
running build
running build_py
running build_ext
warning: GMP library not found; Not building Crypto.PublicKey._fastmath.
building 'Crypto.Hash.MD2' extensio... | [
"Don't install it from source. Install the Debian package instead:\naptitude install python-crypto\n\nAnd to install the python dev files (which you won't need anyway if you follow my above advice):\naptitude install python-dev\n\n"
] | [
24
] | [] | [] | [
"debian",
"lenny",
"pycrypto",
"python",
"python_2.6"
] | stackoverflow_0007913140_debian_lenny_pycrypto_python_python_2.6.txt |
Q:
Results for Observer() seemingly not accounting for elevation effects in PyEphem
I've a query on the results given by the PyEphem module relating to Observer() queries, and the effects of elevation. I understand from a couple of sources (such as http://curious.astro.cornell.edu/question.php?number=388) that the el... | Results for Observer() seemingly not accounting for elevation effects in PyEphem | I've a query on the results given by the PyEphem module relating to Observer() queries, and the effects of elevation. I understand from a couple of sources (such as http://curious.astro.cornell.edu/question.php?number=388) that the elevation of the observer has a marked effect on sunset time. However in the following c... | [
"The elevation of an observer means the elevation above sea level of their location — like the altitude of Flagstaff, Arizona, for example. But it is presumed that not only the observer and their telescope or binoculars is this distance above sea level; it is presumed that the ground — and thus the horizon — are al... | [
6
] | [] | [] | [
"astronomy",
"pyephem",
"python"
] | stackoverflow_0007662543_astronomy_pyephem_python.txt |
Q:
make list python have key pair
I have
list('327VUQ56156TX374');
['3', '2', '7', 'V', 'U', 'Q', '5', '6', '1', '5', '6', 'T', 'X', '3', '7', '4']
I want to get the array associative like this , its index.[ 1=>'3',... 16=>'4' ]
anyone can tell me please thanks
A:
dict(enumerate('327VUQ56156TX374'))
If you want... | make list python have key pair | I have
list('327VUQ56156TX374');
['3', '2', '7', 'V', 'U', 'Q', '5', '6', '1', '5', '6', 'T', 'X', '3', '7', '4']
I want to get the array associative like this , its index.[ 1=>'3',... 16=>'4' ]
anyone can tell me please thanks
| [
"dict(enumerate('327VUQ56156TX374'))\n\nIf you want starting count from 1 (and have a good reason for this :-)), you can use this (but it's only for >= 2.6)\ndict(enumerate('327VUQ56156TX374', start=1))\n\n",
"I think enumerate will do what you want:\n>>> data = list('327VUQ56156TX374')\n>>> [(i+1,d) for i,d in e... | [
9,
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0007913248_python.txt |
Q:
Python and Django coding style (PEP)
I write code with Python using Django framework.
Now I have read about all these coding style advices, but encountered a vague thing.
In djangoproject section here https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style/#python-style it says that ... | Python and Django coding style (PEP) | I write code with Python using Django framework.
Now I have read about all these coding style advices, but encountered a vague thing.
In djangoproject section here https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style/#python-style it says that function comments should say like:
Does t... | [
"There is no true code style rule. Every framework, library and software can redefine some style rule for its own project.\nIn my personal code I prefer to use the more general code style rule (in this case the official Python one) but you should specify this in your documentation.\n",
"PEP 8 follows the first pe... | [
2,
2
] | [] | [] | [
"coding_style",
"pep",
"python"
] | stackoverflow_0007913386_coding_style_pep_python.txt |
Q:
Python in the enterprise: Pros and cons
I have been exploring and developing an application in Python for mission critical work in the commercial banking arena.
Banks are way conservative in selecting new applications.
I need real proof of stability and others using.
Have looked at the Python site but now I'm ho... | Python in the enterprise: Pros and cons | I have been exploring and developing an application in Python for mission critical work in the commercial banking arena.
Banks are way conservative in selecting new applications.
I need real proof of stability and others using.
Have looked at the Python site but now I'm hoping this crowd can tell me more.
So far I do... | [
"Banca d'Italia (roughly the Italian equivalent of the Fed, except that, since the introduction of the Euro, all countries using euros as their currency, including of course Italy, have \"outsourced\" monetary policy to the European Central Bank) uses Python, is very happy with it, and plans to extend its use. The ... | [
34,
6,
4,
3,
2,
2,
1,
0
] | [
"I'll try again.\nMy employer (we're huge) did a study to resolve an internal conflict over what 'platform' to standardize to. Platforms were judged on technical depth, business alignment, and company viability. The one that won was middle of the road technically and had superior business alignment and company vi... | [
-3,
-5
] | [
"banking",
"enterprise",
"onlinebanking",
"python"
] | stackoverflow_0001358084_banking_enterprise_onlinebanking_python.txt |
Q:
Segmentation fault of ImageMagick + Python ctypes
I am using ImageMagick library with Python ctypes. I wrote a following simple code, but it crashes with segmentation fault (KERN_INVALID_ADDRESS) in Mac:
from ctypes import *
from ctypes.util import find_library
lib = CDLL(find_library('MagickWand'))
lib.MagickWan... | Segmentation fault of ImageMagick + Python ctypes | I am using ImageMagick library with Python ctypes. I wrote a following simple code, but it crashes with segmentation fault (KERN_INVALID_ADDRESS) in Mac:
from ctypes import *
from ctypes.util import find_library
lib = CDLL(find_library('MagickWand'))
lib.MagickWandGenesis()
wand = lib.NewMagickWand()
lib.MagickReadIma... | [
"I changed the following code:\nlib.MagickReadImage(wand, 'mona-lisa.jpg')\n\nto:\nf2 = lib.MagickReadImage\nf2.argtypes = [c_void_p, c_char_p]\nf2(wand, 'mona-lisa.jpg')\n\nSo, it works well.\n",
"Most likely this is a 32/64 bit issue. Is the Mac version the only 64 bit process that you've tested? Or perhaps you... | [
1,
0
] | [] | [] | [
"ctypes",
"imagemagick",
"macos",
"python",
"segmentation_fault"
] | stackoverflow_0007911986_ctypes_imagemagick_macos_python_segmentation_fault.txt |
Q:
how to send instance to ModelForms and fill form with that instance
I have this form:
class TourForm(ModelForm):
class Meta:
model = Tour
I wanna design a edit page,so i send tour_id to page and get tour with that tour_id,now I wanna fill this form with tour instance I've gotton.some thing like this in... | how to send instance to ModelForms and fill form with that instance | I have this form:
class TourForm(ModelForm):
class Meta:
model = Tour
I wanna design a edit page,so i send tour_id to page and get tour with that tour_id,now I wanna fill this form with tour instance I've gotton.some thing like this in views.py:
tour=Tour.objects.get(pk=tour_id)
tform = TourForm(request.POS... | [
"I think that you should not pass instance nad request.POSt at the same time. Try to do something like this:\nif request.method == \"POST\":\n tform = TourForm(request.POST, request.FILES)\nelse\n tform = TourForm(instance=tour)\n\n"
] | [
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007913232_django_python.txt |
Q:
Is there a Generic python library to consume REST based services?
Ok. I want to consume REST based services.
I'd like to use python. In fact, I am going to use python.
The way I'd like to use it is from the command line/ipython, to try out different REST services, with intention of formally coding it later. ( m... | Is there a Generic python library to consume REST based services? | Ok. I want to consume REST based services.
I'd like to use python. In fact, I am going to use python.
The way I'd like to use it is from the command line/ipython, to try out different REST services, with intention of formally coding it later. ( my usage of the REST service not the generic api thing )
I'm looking fo... | [
"The problem with having a \"plush\" REST client library is that REST itself isn't that well-defined. REST, in and of itself, just means that you want to use HTTP standards whenever possible, but other than that, the field is wide open.\nIs the data encoded with JSON? What are the URL schemes and what do they mean?... | [
16,
4,
2
] | [] | [] | [
"python",
"rest"
] | stackoverflow_0004355997_python_rest.txt |
Q:
Can I overwrite the string form of a namedtuple?
For example:
>>> Spoken = namedtuple("Spoken", ["loudness", "pitch"])
>>> s = Spoken(loudness=90, pitch='high')
>>> str(s)
"Spoken(loudness=90, pitch='high')"
What I want is:
>>> str(s)
90
That is I want the string representation to display the loudness attribute.... | Can I overwrite the string form of a namedtuple? | For example:
>>> Spoken = namedtuple("Spoken", ["loudness", "pitch"])
>>> s = Spoken(loudness=90, pitch='high')
>>> str(s)
"Spoken(loudness=90, pitch='high')"
What I want is:
>>> str(s)
90
That is I want the string representation to display the loudness attribute.
Is this possible ?
| [
"Yes, it is not hard to do and there is an example for it in the namedtuple docs.\nThe technique is to make a subclass that adds its own str method:\n>>> from collections import namedtuple\n>>> class Spoken(namedtuple(\"Spoken\", [\"loudness\", \"pitch\"])):\n __slots__ = ()\n def __str__(self):\n ... | [
76,
19,
4
] | [] | [] | [
"python"
] | stackoverflow_0007914152_python.txt |
Q:
python bottle persistent cookie not working
I have a site im working on, i want to store a value in a cookie
this is an number, when the user comes to the website, i want to know what the number was on their last visit, so I'm thinking of having a persistant cookie that stores the current value, when the user come... | python bottle persistent cookie not working | I have a site im working on, i want to store a value in a cookie
this is an number, when the user comes to the website, i want to know what the number was on their last visit, so I'm thinking of having a persistant cookie that stores the current value, when the user comes to the site, if there is no session cookie, the... | [
"Bottle uses http://docs.python.org/library/cookie.html to implement cookie support. This implementation requires the expires parameter to be a string in the Wdy, DD-Mon-YY HH:MM:SS GMT format. Passing datetime or date objects fails silently.\nI'll fix that in future versions of Bottle (hi, I'm the author) but for ... | [
9
] | [] | [] | [
"bottle",
"cookies",
"python"
] | stackoverflow_0007913169_bottle_cookies_python.txt |
Q:
Python: all possible combinations of "dynamic" list
I really can't find this out. I tried to use itertools, tried all kind of looping, but still i can't achieve what I want. Here is what i need:
I have list such as:
list = [("car", 2), ("plane", 3), ("bike", 1)]
This list is each time different, there can be 5 di... | Python: all possible combinations of "dynamic" list | I really can't find this out. I tried to use itertools, tried all kind of looping, but still i can't achieve what I want. Here is what i need:
I have list such as:
list = [("car", 2), ("plane", 3), ("bike", 1)]
This list is each time different, there can be 5 different items in it each time and what I need is to get s... | [
"You could use itertools.product():\nmy_list = [(\"car\", 2), (\"plane\", 3), (\"bike\", 1)]\na = itertools.product(*([name + str(i + 1) for i in range(length)] \n for name, length in my_list))\nfor x in a:\n print x\n\nprints\n('car1', 'plane1', 'bike1')\n('car1', 'plane2', 'bike1')\n('ca... | [
7,
2,
1
] | [
"For implementing something like this the complexity of the program would be very high. try reworking out the logic so that you can reduce the complexity ..\n"
] | [
-1
] | [
"combinations",
"iteration",
"list",
"permutation",
"python"
] | stackoverflow_0007914613_combinations_iteration_list_permutation_python.txt |
Q:
How do I make a multienterbox in Easygui?
This is my best attempt at a multienterbox with Easygui and Python.
Would someone please give me a working example?
import easgui
(fieldNames= ['Year','Month','Day','Time Hour','Time Minute', 'AM or PM'])
log = easygui.multenterbox(msg='Fill in the blanks',title='log', fi... | How do I make a multienterbox in Easygui? | This is my best attempt at a multienterbox with Easygui and Python.
Would someone please give me a working example?
import easgui
(fieldNames= ['Year','Month','Day','Time Hour','Time Minute', 'AM or PM'])
log = easygui.multenterbox(msg='Fill in the blanks',title='log', fieldNames)
I am running Python 2.5 on OS X 10.6... | [
"\nThere are parentheses around your first line - this isn't allowed.\nYou've haven't used the keyword syntax for your third argument, but you use if for the first two.\n\nEither\nlog = easygui.multenterbox(msg='Fill in the blanks',title='log', fieldnames=fieldNames)\n\nor\nlog = easygui.multenterbox('Fill in the b... | [
3
] | [] | [] | [
"easygui",
"python",
"tkinter"
] | stackoverflow_0007910936_easygui_python_tkinter.txt |
Q:
List "quirk" in python
I was trying out some things with lists in the interactive interpreter and I noticed this:
>>> list = range(1, 11)
>>> for i in list:
... list.remove(i)
...
>>> list
[2, 4, 6, 8, 10]
Can anyone explain why it left even numbers? This is confusing me right now... Thanks a lot.
A:
It isn... | List "quirk" in python | I was trying out some things with lists in the interactive interpreter and I noticed this:
>>> list = range(1, 11)
>>> for i in list:
... list.remove(i)
...
>>> list
[2, 4, 6, 8, 10]
Can anyone explain why it left even numbers? This is confusing me right now... Thanks a lot.
| [
"It isn't safe to modify a list that you are iterating over.\n",
"My guess is that the for loop is implemented like the following:\nlist = range(1, 11)\n\ni = 0\nwhile i < len(list):\n list.remove(list[i])\n i += 1\n\nprint(list)\n\nEvery time an element is removed, the \"next\" element slides into its spot... | [
7,
4,
3,
2
] | [] | [] | [
"list",
"python"
] | stackoverflow_0007909794_list_python.txt |
Q:
Remove repeated elements from list and HTML Tag
I have list like this:
[' name = Badmash Gujjar\n',
' image = \n',
' image =\n',
' caption =\n',
' director = Sameer Butt\n',
' producer =\n',
' writer = Nasir Adeeb\n',
' starring = Saima<br>Shaan... | Remove repeated elements from list and HTML Tag | I have list like this:
[' name = Badmash Gujjar\n',
' image = \n',
' image =\n',
' caption =\n',
' director = Sameer Butt\n',
' producer =\n',
' writer = Nasir Adeeb\n',
' starring = Saima<br>Shaan (actor)Shaan<br>',
' music = Robin Ghosh\n... | [
"d = dict(map(str.strip, a.split('=', 1)) for a in l)\n\nwill create the following dictionary (which is probably what you want, since a dictionary doesn't have repeated keys):\n{'caption': '',\n 'cinematography': '',\n 'director': 'Sameer Butt',\n 'distributor': '',\n 'editing': '',\n 'image': '',\n 'music': 'Robin... | [
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0007912711_python.txt |
Q:
More Pythonic way to repeat some actions for a number of attributes
I have a Django app that allows the user to create variables and name them
class Product(models.Model):
name = models.CharField(max_length=40, unique=True)
int1_name = models.CharField(max_length=60, blank=True, null=True)
int1_default... | More Pythonic way to repeat some actions for a number of attributes | I have a Django app that allows the user to create variables and name them
class Product(models.Model):
name = models.CharField(max_length=40, unique=True)
int1_name = models.CharField(max_length=60, blank=True, null=True)
int1_default = models.IntegerField(blank=True, null=True)
int2_name = models.Char... | [
"Don't use exec for this! getattr is perfectly adequate, much safer, and readable too.\nclass ItemDataForm(ModelForm):\n def __init__(self,product,*args,**kwargs):\n super(ItemDataForm, self).__init__(*args, **kwargs)\n del self.fields['created']\n fields = 'int1', 'int2', 'float1', 'float2'... | [
10,
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0007914453_django_django_models_python.txt |
Q:
Display additional data while iterating over a Django formset
I have a list of soccer matches for which I'd like to display forms. The list comes from a remote source.
matches = ["A vs. B", "C vs. D", "E vs, F"]
matchFormset = formset_factory(MatchForm,extra=len(matches))
formset = MatchFormset()
On the template ... | Display additional data while iterating over a Django formset | I have a list of soccer matches for which I'd like to display forms. The list comes from a remote source.
matches = ["A vs. B", "C vs. D", "E vs, F"]
matchFormset = formset_factory(MatchForm,extra=len(matches))
formset = MatchFormset()
On the template side, I would like to display the formset with the according title ... | [
"I believe that in the Django template language there is no built-in filter for indexing, but there is one for slicing (slice) -- and therefore I think that, in a pinch, you could use a 1-item slice (with forloop.counter0:forloop.counter) and .first on it to extract the value you want.\nOf course it would be easier... | [
6,
2
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0002985183_django_django_forms_python.txt |
Q:
Which is more Pythonic way?
I want to write a function to create an empty square matrix have size NxN.
I have 2 ways to write this:
1:
s_matrix = []
create_empty_square_matrix(s_matrix, N)
2:
s_matrix = empty_square_matrix(N)
(Ofcourse, 2 two functions will different a bit. Function create_empty_square_matrix is... | Which is more Pythonic way? | I want to write a function to create an empty square matrix have size NxN.
I have 2 ways to write this:
1:
s_matrix = []
create_empty_square_matrix(s_matrix, N)
2:
s_matrix = empty_square_matrix(N)
(Ofcourse, 2 two functions will different a bit. Function create_empty_square_matrix is like a procedure - only manipula... | [
"I'd always prefer the second way.\nThe problem with the first is that you pass the object that you want to write to as the paramenter (s_matrix), and the caller of the function will have to know that it must be passed an empty list. What happens if the caller passes a dict, or a list that is not empty?\nBy the way... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0007914041_python.txt |
Q:
mechanize.Browser() downloads corrupt JPG under Windows, works fine in Linux?
I have the following code:
self.bg_br = mechanize.Browser()
self.bg_br.retrieve(self.bg_imageurl, "image2.jpg")
self.bg_file2 = open("image.jpg", mode="w")
self.bg_image = self.bg_br.open(self.bg_imageurl).read()
self.bg_file2.write... | mechanize.Browser() downloads corrupt JPG under Windows, works fine in Linux? | I have the following code:
self.bg_br = mechanize.Browser()
self.bg_br.retrieve(self.bg_imageurl, "image2.jpg")
self.bg_file2 = open("image.jpg", mode="w")
self.bg_image = self.bg_br.open(self.bg_imageurl).read()
self.bg_file2.write(self.bg_image)
self.bg_file2.close()
The problem is that the image.jpg (the one t... | [
"You need to open the file using the 'wb' mode for your bg_file2 operation. Under Unix, Python doesn't differentiate between text and binary files, but on Windows it does. To support platform independence, just use the 'wb' mode to write your image in a binary format. I don't know the internals of mechanize, but my... | [
2
] | [] | [] | [
"mechanize",
"pyqt",
"python"
] | stackoverflow_0007915024_mechanize_pyqt_python.txt |
Q:
how can I input a file and run an asynchronously command on it in python?
I'm trying to write a script that asks for an input file and then runs some command on it. when I run the script it askes me for filename and when I give the file (e.g example.bam) then I get this error:
NameError: name 'example.bam' is no... | how can I input a file and run an asynchronously command on it in python? | I'm trying to write a script that asks for an input file and then runs some command on it. when I run the script it askes me for filename and when I give the file (e.g example.bam) then I get this error:
NameError: name 'example.bam' is not defined
I tried many things but I couldn't fix it. Can someone tell me what ... | [
"input is equivalent to eval(raw_input(prompt)). So what your script currently tries to do is interpret your input (\"example\", in your case), and execute as if it were a statement in your script. For user input (and might I simply say \"for any input\" -- unless you know what you're doing), always use the raw_inp... | [
3
] | [] | [] | [
"input",
"python",
"subprocess"
] | stackoverflow_0007915160_input_python_subprocess.txt |
Q:
Python PLY parser
I've tried to search around for the answer to this question, but can't seem to find one.
I'm trying to write a parser in Python using PLY for a made up language. A simplified version of my BNF looks like this:
statement-list -> statement ',' statement-list |
'print' expr
stateme... | Python PLY parser | I've tried to search around for the answer to this question, but can't seem to find one.
I'm trying to write a parser in Python using PLY for a made up language. A simplified version of my BNF looks like this:
statement-list -> statement ',' statement-list |
'print' expr
statement -> ident 'was' 'a' t... | [
"I can't speak for a PLY solution, but here is one using pyparsing. Sometimes, a pyparsing example can be useful even if you eventually want to implement your parser using some other library, as a quick-and-dirty prototype/exercise. Unfortunately, this example makes heavy use of the operatorPrecedence method, which... | [
7,
3
] | [] | [] | [
"parsing",
"ply",
"python",
"yacc"
] | stackoverflow_0007908898_parsing_ply_python_yacc.txt |
Q:
python ttk: force screen update
How can I force ttk to update the screen? I'm running a long loop and would like to display some interim results, but ttk waits until it finishes the loop to update the screen.
I tried inserting sleep and after calls in the loop, but that didn't help.
A:
update_idletasks() appear... | python ttk: force screen update | How can I force ttk to update the screen? I'm running a long loop and would like to display some interim results, but ttk waits until it finishes the loop to update the screen.
I tried inserting sleep and after calls in the loop, but that didn't help.
| [
"update_idletasks() appears to be the answer. For example adding \n relevant_widget.update_idletasks()\n\nin the loop works.\n"
] | [
1
] | [] | [] | [
"python",
"ttk"
] | stackoverflow_0007905973_python_ttk.txt |
Q:
Python Suds: how to get an xsd:timeInstant instead of xsd:date in request?
I am trying to work with a webservice that needs xsd:timeInstant in a request (see WSDL):
<xsd:complexType name="QueryParams">
<xsd:all>
<xsd:element name="start" type="xsd:timeInstant" minOccurs="0"/>
<xsd:e... | Python Suds: how to get an xsd:timeInstant instead of xsd:date in request? | I am trying to work with a webservice that needs xsd:timeInstant in a request (see WSDL):
<xsd:complexType name="QueryParams">
<xsd:all>
<xsd:element name="start" type="xsd:timeInstant" minOccurs="0"/>
<xsd:element name="stop" type="xsd:timeInstant" minOccurs="0"/>
... | [
"Think I've found the solution, so might as well post the answer for future reference.\nIn the suds/xsd/sxbuiltin.py file, there is a Factory class\nclass Factory:\n\n tags =\\\n {\n # any\n 'anyType' : XAny,\n ...\n # dates & times\n ...\n 'gMonth' : XString,\n\nUnde... | [
0
] | [] | [] | [
"python",
"soap",
"suds"
] | stackoverflow_0007899677_python_soap_suds.txt |
Q:
Convert text into dict
Hello I have text in following format. But I want to convert into dict. I'm using this code to convert into dict. But it is not working.
dict( (n,int(v)) for n,v in (a.split('=') for a in string.split() ) )
Please anybody help me? thanks
name = Kurradu
image =
image_size =
producer = P... | Convert text into dict | Hello I have text in following format. But I want to convert into dict. I'm using this code to convert into dict. But it is not working.
dict( (n,int(v)) for n,v in (a.split('=') for a in string.split() ) )
Please anybody help me? thanks
name = Kurradu
image =
image_size =
producer = P. Kiran
writer =
starring ... | [
"A few hours ago you needed just a list and now you need a dict?\ntext = \"\"\" name = Kurradu\n image =\n image_size =\n producer = P. Kiran\n writer =\n starring = Varun Sandesh,Neha Sharma\n music = Achu\n cinematography = Sarvesh Murari\n editing =\n distributor =\n released = 12 November 2009\n studio =\n coun... | [
2,
1
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0007915620_dictionary_python.txt |
Q:
How to display a list?
I'm building a simple function that works (delete the files). But In the end I want to return the list of the files that were effectively deleted.
This is the function:
def deleteFiles(files):
# empty list
RemovedFiles = list()
for file in files:
# Delete the file
... | How to display a list? | I'm building a simple function that works (delete the files). But In the end I want to return the list of the files that were effectively deleted.
This is the function:
def deleteFiles(files):
# empty list
RemovedFiles = list()
for file in files:
# Delete the file
if os.remove(file):
... | [
"The problem is that os.remove does not return anything.\nYou can however try and except:\nfor filename in filenames:\n try:\n # try to remove the file\n os.remove(filename)\n except OSError:\n pass\n # file not removed (maybe does not exist or is write-protected)\n # you ma... | [
4,
3,
3,
2
] | [] | [] | [
"file_io",
"python"
] | stackoverflow_0007915666_file_io_python.txt |
Q:
Python regex for module-level constants
I have looked back and forward for a possible solution to my issue, but I guess my google-fu is very poor today. Not to mention my knowledge of regular expressions, which is close to zero.
I am trying to retrieve the definition of some "constants" (i.e., module-level global... | Python regex for module-level constants | I have looked back and forward for a possible solution to my issue, but I guess my google-fu is very poor today. Not to mention my knowledge of regular expressions, which is close to zero.
I am trying to retrieve the definition of some "constants" (i.e., module-level global variables) from a series of Python files usi... | [
"I don't think there is an easy way to achieve this using regular expressions. It's possible to compile the Python modules and walk down the AST to find variable definitions. See the documentation at http://docs.python.org/library/functions.html#compile and http://docs.python.org/library/ast.html#module-ast.\nEDIT:... | [
3,
3,
0
] | [] | [] | [
"full_text_search",
"python",
"regex"
] | stackoverflow_0007915732_full_text_search_python_regex.txt |
Q:
ImportError: No module named lines
from lines import lines
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
import lines
ImportError: No module named lines
This is taken from this example for Pycha. How I can install this Module?
A:
The module lines.py is part of the Pycha exam... | ImportError: No module named lines | from lines import lines
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
import lines
ImportError: No module named lines
This is taken from this example for Pycha. How I can install this Module?
| [
"The module lines.py is part of the Pycha examples. You can find a copy of that module in that directory.\nTo follow the example correctly, you should call the examples/barchart.py example while still maintaining the rest of the examples directory. Then it will work.\nIf you want to create an own script based on th... | [
3,
1
] | [] | [] | [
"importerror",
"python",
"python_import"
] | stackoverflow_0007915490_importerror_python_python_import.txt |
Q:
Regex replace text nodes in an html document
I have a string that represents an html document. I'm trying to replace text in that document, excluding the markup and attribute values ofcourse with some replacement html. I thought it would be simple, but it is incredibly tedious when you want to replace the text wit... | Regex replace text nodes in an html document | I have a string that represents an html document. I'm trying to replace text in that document, excluding the markup and attribute values ofcourse with some replacement html. I thought it would be simple, but it is incredibly tedious when you want to replace the text with markup. For example, to replace somekeyword with... | [
"This might be the solution you are lookin for:\nfrom HTMLParser import HTMLParser\n\nclass MyParser(HTMLParser):\n def __init__(self,link, keyword):\n HTMLParser.__init__(self)\n self.__html = []\n self.link = link\n self.keyword = keyword\n\n def handle_data(self, data):\n text = data.strip()... | [
3
] | [] | [] | [
"html",
"lxml",
"python",
"regex",
"replace"
] | stackoverflow_0007915812_html_lxml_python_regex_replace.txt |
Q:
What would be the proper naming convention for a Python module, class and instance variable having the same base name?
First, I am fully aware about PEP8, but sometimes it isn't very clear about how should you name things.
Let's assume we have ABC as an abbreviation.
Module should be named: abc
Class inside the m... | What would be the proper naming convention for a Python module, class and instance variable having the same base name? | First, I am fully aware about PEP8, but sometimes it isn't very clear about how should you name things.
Let's assume we have ABC as an abbreviation.
Module should be named: abc
Class inside the module should be named: Abc or ABC? (not sure)
Instance variable should be named abc
# abc.py
CONSTANT = "foo"
class Abc(ob... | [
"Module: abc\nClass: Abc\nInstance: the instance can be named like the class, but it is definitively not required.\nIn your case, I'd give the variable a name describing the instance to avoid the naming clash!\nExample:\nclass Car:\n pass\naudi = Car()\nmyCar = Car()\nmyBrothersCar = Car()\n\n",
"Class name co... | [
1,
0
] | [] | [] | [
"naming_conventions",
"python"
] | stackoverflow_0007915251_naming_conventions_python.txt |
Q:
Removing path from a zip file using python
I have a zip file that has a path. When I unzip the file using python and put it in my target folder, it then creates all of the files in the path inside my target folder.
Target: d:\unzip_files
zip file has a path and file name of: \NIS\TEST\Files\tnt.png
What happens: ... | Removing path from a zip file using python | I have a zip file that has a path. When I unzip the file using python and put it in my target folder, it then creates all of the files in the path inside my target folder.
Target: d:\unzip_files
zip file has a path and file name of: \NIS\TEST\Files\tnt.png
What happens: d:\unzip_files\NIS\TEST\Files\tnt.png
Is there a... | [
"How about reading file as binary and dump it? Need to deal cases where there is pre-existing file.\nfor name in zfile.namelist():\n\n fname = os.path.join(zipdir, os.path.basename(name))\n fout = open(fname, 'wb')\n fout.write(zfile.read(name))\n\n"
] | [
1
] | [] | [] | [
"path",
"python",
"unzip"
] | stackoverflow_0007915851_path_python_unzip.txt |
Q:
Why *.pyc files are being deleted when the associated *.py file is deleted
See update at the end.
I am using Ubuntu Linux 11.10, Python 3.
I wrote a Python script which converts some Qt *.ui files to *.py using pyuic4. Then i want to compile the obtained *.py file to *.pyc and delete the *.py file.
For some reaso... | Why *.pyc files are being deleted when the associated *.py file is deleted | See update at the end.
I am using Ubuntu Linux 11.10, Python 3.
I wrote a Python script which converts some Qt *.ui files to *.py using pyuic4. Then i want to compile the obtained *.py file to *.pyc and delete the *.py file.
For some reason when i delete a converted *.py file, the *.pyc version is also deleted:
try:
... | [
"You can set sysctl -w vm.block_dump=1 to see every file system action in dmesg. (high volume, so disable again afterwards)\n",
"You may use inotify to detect filesystem activity. See the manual. Quoting the manual:\n IN_DELETE File/directory deleted from watched directory (*).\n IN_DELETE_SEL... | [
6,
1,
1,
0
] | [] | [] | [
"file",
"linux",
"process",
"python",
"ubuntu"
] | stackoverflow_0007914933_file_linux_process_python_ubuntu.txt |
Q:
Python/HTML Integration Error
I am receiving this error when trying to use Python Server Pages with Mod_Python in Apache:
File "/usr/lib/python2.7/dist-packages/mod_python/importer.py", line 1537, in HandlerDispatch
default=default_handler, arg=req, silent=hlist.silent)
File "/usr/lib/python2.7/dist-packages/mod_... | Python/HTML Integration Error | I am receiving this error when trying to use Python Server Pages with Mod_Python in Apache:
File "/usr/lib/python2.7/dist-packages/mod_python/importer.py", line 1537, in HandlerDispatch
default=default_handler, arg=req, silent=hlist.silent)
File "/usr/lib/python2.7/dist-packages/mod_python/importer.py", line 1229, in ... | [
"Looks like your index.psp file either has a __future__ import that isn't at the top of the file, or (more likely imo) the file that is including your index.psp for processing is doing a bunch of work before the __future__ import is hit causing the error.\n",
"from __future__ import print_function\n\nI don't thin... | [
1,
0
] | [] | [] | [
"html",
"python"
] | stackoverflow_0007916824_html_python.txt |
Q:
python issues with MySQL in eclipse
Example:
import MySQLdb
conn = MySQLdb.connect(passwd="passwd", db="mydb")
cursor = conn.cursor()
cursor.execute("""SELECT * FROM table""")
records = cursor.fatchone()
print records
provides the next error:
Traceback (most recent call last): File
"/Applications/eclipse/plu... | python issues with MySQL in eclipse | Example:
import MySQLdb
conn = MySQLdb.connect(passwd="passwd", db="mydb")
cursor = conn.cursor()
cursor.execute("""SELECT * FROM table""")
records = cursor.fatchone()
print records
provides the next error:
Traceback (most recent call last): File
"/Applications/eclipse/plugins/org.python.pydev.debug_2.2.2.2011100... | [
"The error seems to be here:\n\nLibrary not loaded: libmysqlclient.18.dylib Referenced from:\n\nMake sure you install the mysqldb library.\nSee: How to install MySQLdb package? (ImportError: No module named setuptools)\nand/or: http://www.mangoorange.com/2008/08/01/installing-python-mysqldb-122-on-mac-os-x/\nYou al... | [
2
] | [] | [] | [
"eclipse",
"mysql",
"mysql_python",
"pydev",
"python"
] | stackoverflow_0007915727_eclipse_mysql_mysql_python_pydev_python.txt |
Q:
Django class based DetailView/ListView ajax decorator?
1
Is there a conveinient way to ajax decorate generic class based views?
2
Is there a different approach for ListViews compared to DetailViews?
i.e.
if not request.is_ajax():
raise Http404
A:
To decorate all class based views, decorate the dispatch method... | Django class based DetailView/ListView ajax decorator? | 1
Is there a conveinient way to ajax decorate generic class based views?
2
Is there a different approach for ListViews compared to DetailViews?
i.e.
if not request.is_ajax():
raise Http404
| [
"To decorate all class based views, decorate the dispatch method. \nclass MyView(View):\n @decorate\n def dispatch(self, *args, **kwargs):\n return super(MyView, self).dispatch(*args, **kwargs)\n\n"
] | [
2
] | [] | [] | [
"ajax",
"django",
"python"
] | stackoverflow_0007915488_ajax_django_python.txt |
Q:
Define a function using a variable?
I am trying to define a function that will include a variable n where n will be a string of numbers e.g. "3884892993", the definition of the function starts as is_true(n), however if n is going to be a string should it be is_true(n) and then once the string is defined I can test... | Define a function using a variable? | I am trying to define a function that will include a variable n where n will be a string of numbers e.g. "3884892993", the definition of the function starts as is_true(n), however if n is going to be a string should it be is_true(n) and then once the string is defined I can test the function with an example string such... | [
"Quotes are only used for string literals, you wouldn't enclose a variable or parameter name in quotes to indicate that it will be a string. The function definition would look like:\ndef is_true(n):\n\nAnd then in the body of the function you use n to reference the value that is passed in by the caller.\nTo call t... | [
4,
1,
1,
0,
0,
0
] | [] | [] | [
"digits",
"integer",
"python",
"string"
] | stackoverflow_0007908802_digits_integer_python_string.txt |
Q:
Parsing a user defined protocol from C and Python
I need to define a binary protocol and use it from both C and Python written application.
My question is, what is the right tool for the job so I won't need to implement the protocol parsing and building code in C and Python? I heard about Google's Protocol Buffers... | Parsing a user defined protocol from C and Python | I need to define a binary protocol and use it from both C and Python written application.
My question is, what is the right tool for the job so I won't need to implement the protocol parsing and building code in C and Python? I heard about Google's Protocol Buffers but their C implementation is not mature enough for th... | [
"Look for state machine compilers like Ragel. They will generate compilable code based on a state machine specification.\n",
"Take a look at MessagePack.\n"
] | [
1,
1
] | [] | [] | [
"c",
"protocol_buffers",
"python",
"serialization"
] | stackoverflow_0007859217_c_protocol_buffers_python_serialization.txt |
Q:
How to create multiple dialog boxes with wx python and how to close all of them at once
How would be able to open lets say 5 dialog boxes and have the last one open close all the dialog boxes.
A:
Each dialog will have to open the next dialog since dialogs tend to block the main loop when shown modally. You could... | How to create multiple dialog boxes with wx python and how to close all of them at once | How would be able to open lets say 5 dialog boxes and have the last one open close all the dialog boxes.
| [
"Each dialog will have to open the next dialog since dialogs tend to block the main loop when shown modally. You could use PubSub to send a message in the closing event of the last dialog to the previous dialog that it too should close and do the same thing in that dialog and so forth. Each dialog emits a message t... | [
1
] | [] | [] | [
"python",
"random",
"wxpython"
] | stackoverflow_0007917539_python_random_wxpython.txt |
Q:
Python: unwanted change of variable occurs
Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
Okay, so basically I have this code:
# Our Rule type.
class Rule(object):
"""An object to represent a rule and include
methods to apply these rules."""
def __init__(self,bind... | Python: unwanted change of variable occurs |
Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument
Okay, so basically I have this code:
# Our Rule type.
class Rule(object):
"""An object to represent a rule and include
methods to apply these rules."""
def __init__(self,bind="F",rule=["F"]):
self.bind = bind
... | [
"Default arguments are evaluated once when the function is defined, and reused later.\ndef f(x, a = [])\n a.append(x)\n return a\nprint f(0)\nprint f(1)\n\nprints\n[0]\n[0, 1]\n\nThe usual way to avoid this problem is to use None as default parameter:\ndef f(x, a = None):\n if a is None:\n a = []\n ... | [
2,
2,
2,
1
] | [] | [] | [
"class",
"list",
"python"
] | stackoverflow_0007917301_class_list_python.txt |
Q:
Python argument types C++ signature
I have 2 questions, both relating to how arguments between Python and C++ mix... I have a function in C++ which I am calling from python, and my function takes dates and strings.
Is a python str the same as a C++
class std::basic_string<char,struct std::char_traits<char>,class ... | Python argument types C++ signature | I have 2 questions, both relating to how arguments between Python and C++ mix... I have a function in C++ which I am calling from python, and my function takes dates and strings.
Is a python str the same as a C++
class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >
And secondly, my ... | [
"Assuming that you are using boost::python, let me give you an idea of how to proceed in these cases. Rather than letting boost::python automatically wrap your function, you provide your own wrapping:\n namespace {\n\n void Foo_methodUsingDate( Foo* pointer, const object& dateObject )\n {\n ... | [
1,
1
] | [] | [] | [
"c++",
"python",
"signature",
"types"
] | stackoverflow_0007917178_c++_python_signature_types.txt |
Q:
How can I determine which version of virtualenvwrapper is installed?
I know that which virtualenvwrapper.sh will locate the virtualenvwrapper bash script.
But, how can I determine which version of virtualenvwrapper is installed?
A:
Updated Answer 02-Jun-17
Using pip:
$ pip list | grep virtualenvwrapper
virtuale... | How can I determine which version of virtualenvwrapper is installed? | I know that which virtualenvwrapper.sh will locate the virtualenvwrapper bash script.
But, how can I determine which version of virtualenvwrapper is installed?
| [
"Updated Answer 02-Jun-17\nUsing pip:\n$ pip list | grep virtualenvwrapper\nvirtualenvwrapper (4.7.2)\n\nOriginal Answer\nNot an elegant solution, but here's how I determined that I have version 2.10.1 of virtualenvwrapper installed:\n$ which virtualenvwrapper.sh\n/Library/Frameworks/Python.framework/Versions/2.7/b... | [
8
] | [] | [] | [
"python",
"virtualenvwrapper"
] | stackoverflow_0007505414_python_virtualenvwrapper.txt |
Q:
How to display a file owned by another thread?
I'm trying to build an application that displays in a GUI the contents of a log file, written by a separate program that I call through subprocess. The application runs in Windows, and is a binary that I have no control over. Also, this application (Actel Designer if ... | How to display a file owned by another thread? | I'm trying to build an application that displays in a GUI the contents of a log file, written by a separate program that I call through subprocess. The application runs in Windows, and is a binary that I have no control over. Also, this application (Actel Designer if anyone cares) will write its output to a log file re... | [
"You should register for notifications on file change, the way tail -f does (you can find out what system calls it uses by executing strace tail -f logfile).\npyinotify provides a Python interface for these file change notifications.\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0007917660_python.txt |
Q:
Django model fields. Custom field value setter
Is there any way to do in django custom property setter like this?
class MyModel(models.Model):
myfield = models.CharField(length = 250)
@myfield.setter
def set_password(self, value):
self.password = encrypt(value)
A:
You will really set the val... | Django model fields. Custom field value setter | Is there any way to do in django custom property setter like this?
class MyModel(models.Model):
myfield = models.CharField(length = 250)
@myfield.setter
def set_password(self, value):
self.password = encrypt(value)
| [
"You will really set the value on saving the model, so it's better to override save() method (ot use pre_save signal).\n",
"What's wrong with a method?\ninstance.set_password('my_pw')\n\nYou can use @property to define setters:\nhttp://docs.python.org/library/functions.html#property\n### Pasted from docs\n\nclass... | [
1,
1
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007913108_django_python.txt |
Q:
Django Memcache : Compare and Set
Over here at the Django groups Tom Evans explains the method to do compare and set in Django as shown below
You can access the memcached client via django though:
>>> from django.core import cache
>>> c=cache.get_cache('default')
>>> help(c._client.cas)
But somehow I couldn’... | Django Memcache : Compare and Set | Over here at the Django groups Tom Evans explains the method to do compare and set in Django as shown below
You can access the memcached client via django though:
>>> from django.core import cache
>>> c=cache.get_cache('default')
>>> help(c._client.cas)
But somehow I couldn’t get it to work.
>>> from django.core... | [
"after looking at the source code! i find this at BaseMemcachedCache:\n@property\ndef _cache(self):\n \"\"\"\n Implements transparent thread-safe access to a memcached client.\n \"\"\"\n if getattr(self, '_client', None) is None:\n self._client = self._lib.Client(self._servers)\n\n return self... | [
3
] | [] | [] | [
"caching",
"django",
"memcached",
"python"
] | stackoverflow_0007917604_caching_django_memcached_python.txt |
Q:
python calling a subprocess that runs in parallel
I have code that calls a commercial program to run as a subprocess using the subprocess module.
The commercial program is capable of running in parallel, but I have noticed that only 1 processor is being used when the subprocess is running.
Is there a simple way ... | python calling a subprocess that runs in parallel | I have code that calls a commercial program to run as a subprocess using the subprocess module.
The commercial program is capable of running in parallel, but I have noticed that only 1 processor is being used when the subprocess is running.
Is there a simple way to run a serial python program that requests more resou... | [
"If the subprocess is really capable of multicore operation, it shouldn't matter how you spawn it. You don't (and generally, can't) \"request\" more cores for it -- the OS will automatically give it whatever resources are available.\nI suspect the answer lies with the commercial program in question rather than with... | [
1
] | [] | [] | [
"parallel_processing",
"python",
"subprocess"
] | stackoverflow_0007918395_parallel_processing_python_subprocess.txt |
Q:
"If" function used for array in Python
I have this function:
def q(x,y):
r2 = (x/2.)**2 + (2.0*y)**2
if (r2 > 0.04):
return 0.
else:
return 1.5
and I want to call it using something like
from pylab import *
dl=0.025
X, Y = mgrid[-0.5:0.5:dl, -0.5:0.5:dl]
g(X,Y)
but obviously this gi... | "If" function used for array in Python | I have this function:
def q(x,y):
r2 = (x/2.)**2 + (2.0*y)**2
if (r2 > 0.04):
return 0.
else:
return 1.5
and I want to call it using something like
from pylab import *
dl=0.025
X, Y = mgrid[-0.5:0.5:dl, -0.5:0.5:dl]
g(X,Y)
but obviously this gives an error in the comparison.
Can this be ... | [
"The expression r2 > 0.04 evaluates to a NumPy array of Boolean values, so you can't use it in an if statement. You can have it automatically reinterpreted as numbers, though:\ndef q(x,y):\n r2 = (x/2.)**2 + (2.0*y)**2\n return 1.5 * (r2 <= 0.04)\n\n",
"You may use map to apply your function to each couple... | [
3,
0
] | [] | [] | [
"matplotlib",
"numpy",
"python"
] | stackoverflow_0007917913_matplotlib_numpy_python.txt |
Q:
assign values to symbols in python debugger (pdb)
Using pdb.set_trace(), I am trying to debug a series of expression in which j is used as an indexing variable. statements such as j = 0 are not allowed since j is a reserved symbol for pdb. How can I get around this?
A:
!j = 0
From the docs:
[!]statement
Execut... | assign values to symbols in python debugger (pdb) | Using pdb.set_trace(), I am trying to debug a series of expression in which j is used as an indexing variable. statements such as j = 0 are not allowed since j is a reserved symbol for pdb. How can I get around this?
| [
"!j = 0\n\nFrom the docs:\n\n[!]statement\nExecute the (one-line) statement in the context of the current stack frame. The exclamation point can be omitted unless the first\n word of the statement resembles a debugger command.\n\n"
] | [
25
] | [] | [] | [
"pdb",
"python"
] | stackoverflow_0007918490_pdb_python.txt |
Q:
How do I update the screen (canvas) of a Tkinter window
I have searched quite extensively and haven't found the answer.
I have tracked down and reduced my problem to this example.
from Tkinter import *
class A:
def __init__(self):
self.var = True
obj = A()
def meth():
obj.var = False
paintGu... | How do I update the screen (canvas) of a Tkinter window | I have searched quite extensively and haven't found the answer.
I have tracked down and reduced my problem to this example.
from Tkinter import *
class A:
def __init__(self):
self.var = True
obj = A()
def meth():
obj.var = False
paintGui()
def paintGui():
master = Tk()
w = Canvas(mas... | [
"Every time you call paintGui it is creating a brand new window. That's because you are calling Tk(), creating new widgets, and running a new mainloop. These things only need to happen once, so take them out of the paintGui function.\nThis minimally modified version of your code does what you want.\nfrom Tkinter ... | [
5
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0007918295_python_tkinter_user_interface.txt |
Q:
Importing methods from file into a class
I am making an IRC bot with Twisted and I have run into a problem. I want to import functions from a seperate file into my main class (the one that inherits irc.IRCClient) so they can be used as methods. I have thought of two possible solutions, but they both seem a bit new... | Importing methods from file into a class | I am making an IRC bot with Twisted and I have run into a problem. I want to import functions from a seperate file into my main class (the one that inherits irc.IRCClient) so they can be used as methods. I have thought of two possible solutions, but they both seem a bit newbish and they both have problems.
Solution 1: ... | [
"class mainClass(irc.IRCClient):\n\n from othermodule import a, b, c\n # othermodule.a, b, and c are now methods of mainClass\n\n from anothermodule import *\n # everything in anothermodule is now in mainClass\n\n # if there are name conflicts, last import wins!\n\nThis works because import simply im... | [
2,
1
] | [] | [] | [
"function",
"irc",
"oop",
"python",
"twisted"
] | stackoverflow_0007918495_function_irc_oop_python_twisted.txt |
Q:
How to automatically maximize a pylab plot window in python?
In python (under Ubuntu Linux), I'm using pylab to make plots.
When I call:
pylab.savefig(filename)
It saves the figure at the current screen resolution. The looks terrible if I have lots of subplots, so I usually have to manually maximize the window be... | How to automatically maximize a pylab plot window in python? | In python (under Ubuntu Linux), I'm using pylab to make plots.
When I call:
pylab.savefig(filename)
It saves the figure at the current screen resolution. The looks terrible if I have lots of subplots, so I usually have to manually maximize the window before I call 'savefig'.
Examples:
-- Without maximizing the window
... | [
"You can change resolution this way:\npylab.savefig('new.png', dpi = 500)\n\n"
] | [
1
] | [] | [] | [
"matplotlib",
"python",
"resize",
"window"
] | stackoverflow_0007918594_matplotlib_python_resize_window.txt |
Q:
Does sentry send errors over http to a central location?
Little confused how sentry works, does it send errors from various servers over to a central server?
A:
From the documentation:
The recommended configuration of Sentry involves setting up a separate web server to handle your error logging. This means that... | Does sentry send errors over http to a central location? | Little confused how sentry works, does it send errors from various servers over to a central server?
| [
"From the documentation:\n\nThe recommended configuration of Sentry involves setting up a separate web server to handle your error logging. This means that any number of Sentry clients simply pass on this information to your primary Sentry server.\n\nYou can also configure it to have just one client and server, bot... | [
1
] | [] | [] | [
"python",
"sentry"
] | stackoverflow_0007917736_python_sentry.txt |
Q:
How to build debian package with CPack to execute setup.py?
Until now, my project had only .cpp files that were compiled into different binaries and I managed to configure CPack to build a proper debian package without any problems.
Recently I wrote a couple of python applications and added them to the project, a... | How to build debian package with CPack to execute setup.py? | Until now, my project had only .cpp files that were compiled into different binaries and I managed to configure CPack to build a proper debian package without any problems.
Recently I wrote a couple of python applications and added them to the project, as well as some custom modules that I would also like to incorpora... | [
"I figured out a way to do it but it's not very simple. I'll do my best to explain the procedure so please be patient.\nThe idea of this approach is to use postinst and prerm to install and remove the python application from the system.\nIn the CMakeLists.txt that defines the project, you need to state that CPACK i... | [
13,
0
] | [] | [] | [
"cmake",
"cpack",
"deb",
"package",
"python"
] | stackoverflow_0007249440_cmake_cpack_deb_package_python.txt |
Q:
Play audio and video with gnonlin
I've been messing around with Gstreamer and Gnonlin lately, I've been concatenating segments of video files but when I dynamically connect the src pad on the composition, I can choose either the audio or video portion of the files, producing silent playback or videoless audio. How... | Play audio and video with gnonlin | I've been messing around with Gstreamer and Gnonlin lately, I've been concatenating segments of video files but when I dynamically connect the src pad on the composition, I can choose either the audio or video portion of the files, producing silent playback or videoless audio. How can I attach my composition to an audi... | [
"Yes, gnonlin compositions work on one media type at a time. Audio and Video are treated separately.\n"
] | [
0
] | [] | [] | [
"gnonlin",
"gstreamer",
"multimedia",
"python",
"streaming"
] | stackoverflow_0007630251_gnonlin_gstreamer_multimedia_python_streaming.txt |
Q:
Python - Tips on Rewrite of BeautifulSoup function to be more elegant
The code is working but I am looking for tips on how this could be written a little more properly, especially the use of if's. As you can tell I am not a programmer by nature... just a sys admin doing a little fiddling in python. Thanks for any ... | Python - Tips on Rewrite of BeautifulSoup function to be more elegant | The code is working but I am looking for tips on how this could be written a little more properly, especially the use of if's. As you can tell I am not a programmer by nature... just a sys admin doing a little fiddling in python. Thanks for any advice you can provide.
def findallWileyLinks():
pagebase = 'http://online... | [
"One thing that jumps out at me is that you have a lot of code of the form:\ntags = parenttag.findAll('tag')\n\nif tags:\n for tag in tags:\n # do something to tag\n\nYou are guaranteed that tags is a list here, so the if tags: line is redundant. If you use an empty list in a for loop then the body of the... | [
3,
1,
0,
0
] | [] | [] | [
"beautifulsoup",
"conditional_operator",
"if_statement",
"python"
] | stackoverflow_0007918401_beautifulsoup_conditional_operator_if_statement_python.txt |
Q:
gstreamer: play audio file backwards in
I want to play audio files with different playback rates using GStreamer. This already works fine. However, in contrast to the Python GStreamer reference, negative rates do not play the audio file backwards.
Does anybody know how to accomplish my goal? Has this something ... | gstreamer: play audio file backwards in | I want to play audio files with different playback rates using GStreamer. This already works fine. However, in contrast to the Python GStreamer reference, negative rates do not play the audio file backwards.
Does anybody know how to accomplish my goal? Has this something to do with filesrc or decodebin2 not being ab... | [
"It seems the debug output says:\n0:00:00.447509530 6848 0x10d6e30 DEBUG wavparse gstwavparse.c:1020:gst_wavparse_perform_seek:<wavparse0> negative playback rates are not supported yet.\n\nso you should file a bug to request this be implemented, or implement it.\n"
] | [
0
] | [] | [] | [
"audio",
"gstreamer",
"playback",
"python"
] | stackoverflow_0007299093_audio_gstreamer_playback_python.txt |
Q:
Urllib2 mobile useragent
If I use Urllib2 to open a url using this:
import urllib
import urllib2
url = 'http://www.bbc.co.uk'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {}
headers = { 'User-Agent' : user_agent }
data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)... | Urllib2 mobile useragent | If I use Urllib2 to open a url using this:
import urllib
import urllib2
url = 'http://www.bbc.co.uk'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {}
headers = { 'User-Agent' : user_agent }
data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(re... | [
"Your problem is redirect responses of your request.\nTry this lib to help you to handle redirect urls:\nhttp://pypi.python.org/pypi/requests/0.7.3\nor\nhttp://wwwsearch.sourceforge.net/mechanize/\n"
] | [
1
] | [] | [] | [
"python",
"urllib2"
] | stackoverflow_0007918981_python_urllib2.txt |
Q:
wxPython change mouse cursor to notify a long running operation
I am building a Python program that searches things on a remote website.
Sometimes the operation takes many seconds and I believe that the user will not notice the status bar message "Search Operation in progress".
Therefore, I would like to change t... | wxPython change mouse cursor to notify a long running operation | I am building a Python program that searches things on a remote website.
Sometimes the operation takes many seconds and I believe that the user will not notice the status bar message "Search Operation in progress".
Therefore, I would like to change the mouse cursor to highlight that the program is still waiting for a ... | [
"I asked Robin Dunn, the maker of wxPython about this, and it looks like this should work, but doesn't. However, if you call the panel's SetCursor(), it DOES work or so I'm told. Here's an example you can try:\nimport wx\n\n########################################################################\nclass MyForm(wx.Fr... | [
6
] | [] | [] | [
"mouse_cursor",
"python",
"wxpython"
] | stackoverflow_0007918129_mouse_cursor_python_wxpython.txt |
Q:
Django 1.3 autocompletion
I would like to know if there was a way to enable auto-completion for django class-based views.
I really like the new way to build views. It saves me a lot of time.
The thing is, i rewrite a lot the class methods :
dispatch
get_context_data
get_queryset
...
I lose time redefining these ... | Django 1.3 autocompletion | I would like to know if there was a way to enable auto-completion for django class-based views.
I really like the new way to build views. It saves me a lot of time.
The thing is, i rewrite a lot the class methods :
dispatch
get_context_data
get_queryset
...
I lose time redefining these methods with super, args ...
I'... | [
"There is a way extending classes. Check this class for creating a view that dispatches based on request.method or this.\nIsn't autocomplete or an IDE, but you can avoid a lot of \"code typing\".\n",
"You can probably create a template for that in PyDev if it's always the same thing... See: http://pydev.org/manua... | [
0,
0,
0
] | [] | [] | [
"autocomplete",
"class",
"django",
"python",
"views"
] | stackoverflow_0007914510_autocomplete_class_django_python_views.txt |
Q:
Python 2.5.2- what was instead of 'with' statement
I wrote my code for python 2.7 but the server has 2.5. How do i rewrite the next code so it will run in python 2.5.2:
gzipHandler = gzip.open(gzipFile)
try:
with open(txtFile, 'w') as out:
for line in gzipHandler:
out.write(line)
except:
... | Python 2.5.2- what was instead of 'with' statement | I wrote my code for python 2.7 but the server has 2.5. How do i rewrite the next code so it will run in python 2.5.2:
gzipHandler = gzip.open(gzipFile)
try:
with open(txtFile, 'w') as out:
for line in gzipHandler:
out.write(line)
except:
pass
Right now, when i try to run my script I get t... | [
"In Python 2.5, you actually can use the with statement -- just import it from __future__:\nfrom __future__ import with_statement\n\n",
"If you can't, or don't want to use with, then use finally:\ngzipHandler = gzip.open(gzipFile)\nout = open(txtFile, 'w')\ntry:\n for line in gzipHandler:\n out.write(li... | [
20,
3
] | [
"The \"old\" version of the code inside your try/except block would be:\nout = open(txtFile, 'w')\nfor line in gzipHandler:\n out.write(line)\nout.close()\n\nThe with open() ... context manager is effectively the same thing here. Python closes files automatically when their objects are garbage collected (see que... | [
-1
] | [
"gzip",
"python",
"with_statement"
] | stackoverflow_0007918745_gzip_python_with_statement.txt |
Q:
Pythonic way to handle a method on network data structure
So, another question on what is Pythonic! The application domain in this case is network algorithms (as in, nodes, edges, Dijkstra, that kind of thing...), something I have only previously coded in strongly typed languages where we can be very certain what... | Pythonic way to handle a method on network data structure | So, another question on what is Pythonic! The application domain in this case is network algorithms (as in, nodes, edges, Dijkstra, that kind of thing...), something I have only previously coded in strongly typed languages where we can be very certain what everything is.
Meanwhile in Python, I've got a class Net; a si... | [
"The duck-typing solution is by far more Pythonic. However, rather than testing the argument to see whether it's an ID or an edge, just treat it as if it were the more common case first, and if that doesn't work, try it the other way.\nIf you do use explicit type-checking, which is sometimes the only way, use isint... | [
4,
2,
1
] | [] | [] | [
"algorithm",
"duck_typing",
"python",
"typechecking"
] | stackoverflow_0007919133_algorithm_duck_typing_python_typechecking.txt |
Q:
Batch downloading text and images from URL with Python / urllib / beautifulsoup?
I have been browsing through several posts here but I just cannot get my head around batch-downloading images and text from a given URL with Python.
import urllib,urllib2
import urlparse
from BeautifulSoup import BeautifulSoup
import ... | Batch downloading text and images from URL with Python / urllib / beautifulsoup? | I have been browsing through several posts here but I just cannot get my head around batch-downloading images and text from a given URL with Python.
import urllib,urllib2
import urlparse
from BeautifulSoup import BeautifulSoup
import os, sys
def getAllImages(url):
query = urllib2.Request(url)
user_agent = "Moz... | [
"The OS you are using doesn't know how to write to the file path you are passing it in src. Make sure that the name you use to save the file to disk is one the OS can actually use:\nsrc = \"abc.com/alpha/beta/charlie.jpg\"\nwith open(src, \"wb\") as f:\n # IOError - cannot open file abc.com/alpha/beta/charlie.j... | [
1
] | [] | [] | [
"beautifulsoup",
"python",
"urllib",
"urllib2"
] | stackoverflow_0007918239_beautifulsoup_python_urllib_urllib2.txt |
Q:
Python AppIndicator bindings -> howto check if the menu is open?
Here is a minimal example of an AppIndicator:
#!/usr/bin/python
import gobject
import gtk
import appindicator
if __name__ == "__main__":
ind = appindicator.Indicator("example-simple-client", "gtk-execute", appindicator.CATEGORY_APPLICATION_STAT... | Python AppIndicator bindings -> howto check if the menu is open? | Here is a minimal example of an AppIndicator:
#!/usr/bin/python
import gobject
import gtk
import appindicator
if __name__ == "__main__":
ind = appindicator.Indicator("example-simple-client", "gtk-execute", appindicator.CATEGORY_APPLICATION_STATUS)
ind.set_status (appindicator.STATUS_ACTIVE)
menu = gtk.Men... | [
"It looks like the answer is no unfortunately.\nprint gobject.signal_list_names(ind)\n('new-icon', 'new-attention-icon', 'new-status', 'new-label', 'x-ayatana-new-label', 'connection-changed', 'new-icon-theme-path')\n\nI tried all of them and none of them appear to activate when the indicator is clicked. For what ... | [
8,
2
] | [] | [] | [
"appindicator",
"pygtk",
"python",
"ubuntu_unity"
] | stackoverflow_0007063743_appindicator_pygtk_python_ubuntu_unity.txt |
Q:
Insert data from a Python dictionary to MySQL
I want to insert dictionary data into mysql each key in its own field. I tried following code. But its wrong. Can any one help? I really appreciate. thanks so much :-)
d = {"spam": "1", etc,etc,"egg": "2"}
cols = d.keys()
vals = d.values()
stmt = "INSERT INTO table (%... | Insert data from a Python dictionary to MySQL | I want to insert dictionary data into mysql each key in its own field. I tried following code. But its wrong. Can any one help? I really appreciate. thanks so much :-)
d = {"spam": "1", etc,etc,"egg": "2"}
cols = d.keys()
vals = d.values()
stmt = "INSERT INTO table (%s) VALUES(%s)" % (
",".join(cols), ",".join(len(val... | [
"Why do you call len(vals) ? Your code should work by simply removing that.\n"
] | [
2
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0007919544_mysql_python.txt |
Q:
Python - package installed with easy_install is not being detected (PIL 1.1.7)
I installed PIL with easy_install but for some reason when I run a file that uses it, I get:
ImportError: No module named PIL
Does anyone know why this could be?
I think it's also worth mentioning that I installed web.py through easy_i... | Python - package installed with easy_install is not being detected (PIL 1.1.7) | I installed PIL with easy_install but for some reason when I run a file that uses it, I get:
ImportError: No module named PIL
Does anyone know why this could be?
I think it's also worth mentioning that I installed web.py through easy_install and it's working fine.
| [
"I have the same problem. To me, it looks like a bug in PIL easy_install process. The library is installed, but you have to leave out PIL from imports (aka import Image works), which is obviously wrong. \nTo solve, don't use easy_install to perform the install. Download the tar package and python setup.py install i... | [
7,
4,
3,
2,
1
] | [] | [] | [
"easy_install",
"python",
"python_imaging_library",
"setuptools"
] | stackoverflow_0005085229_easy_install_python_python_imaging_library_setuptools.txt |
Q:
multiple values in a dictionary python
I have data in following form (saved in a list)
id, price, date, category
Now, I basically want to seperate items based on the category..
basically a dictionary where key is the category and rest of the stuff (id, price, data) are its values
I have already created a datastru... | multiple values in a dictionary python | I have data in following form (saved in a list)
id, price, date, category
Now, I basically want to seperate items based on the category..
basically a dictionary where key is the category and rest of the stuff (id, price, data) are its values
I have already created a datastructure so lets a datastructre 'item' has the ... | [
"output = defaultdict(list)\nfor item, cat in ((x[:-1], x[-1]) for x in data):\n output[cat].append(item)\n\nor, without defaultdict:\noutput = {}\nfor item, cat in ((x[:-1], x[-1]) for x in data):\n output.setdefault(cat, []).append(item)\n\nExample output:\n>>> data = [\n... (1, 123, \"somedate\", \"boy... | [
4,
4,
2
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0007919557_dictionary_python.txt |
Q:
Concordances with Python
Your goals are to prompt the user for a text file to analyze. You will also be provided
with a file of stop words—words that will be ignored when you analyze the file. After
creating the concordance, print the concordance results as indicated in the example
output below. For each word ... | Concordances with Python | Your goals are to prompt the user for a text file to analyze. You will also be provided
with a file of stop words—words that will be ignored when you analyze the file. After
creating the concordance, print the concordance results as indicated in the example
output below. For each word in the concordance you will pr... | [
"Well one thing you need is a counter you increment on each iteration of the outer loop, because you are asked to provide some information about line numbers.\nThen the next step is to have a dictionary. Outside the loop\nwords = {}\n\nEach time you encounter a word, check if it is already a key in the dictionary.\... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0007918722_python.txt |
Q:
How to extract value with simplejson?
I have the following json string:
{"response":[[{"uid":123456,"name":"LA_"}],[{"cid":"1","name":"Something"}],[{"cid":1,"name":"Something-else"}]]}
How can I get Something value?
I do the following
jstr = json.loads(my_string)
if jstr.get('response'):
jstr_response = jstr... | How to extract value with simplejson? | I have the following json string:
{"response":[[{"uid":123456,"name":"LA_"}],[{"cid":"1","name":"Something"}],[{"cid":1,"name":"Something-else"}]]}
How can I get Something value?
I do the following
jstr = json.loads(my_string)
if jstr.get('response'):
jstr_response = jstr.get('response')[1].get('name')
but it doe... | [
"Try this.\njstr = json.loads(my_string)\nif jstr.get('response'):\n jstr_response = jstr.get('response')[1][0].get('name')\n\n"
] | [
3
] | [] | [] | [
"python",
"simplejson"
] | stackoverflow_0007919942_python_simplejson.txt |
Q:
Select rows from one table where certain field is equal to a field in a row from another table, with Python and SQLite3
I have a small database which is legacy from an almost defunct project. This database has a "Patients" table with individual personal data and an unique "Id" field, and an "Exams" table with some... | Select rows from one table where certain field is equal to a field in a row from another table, with Python and SQLite3 | I have a small database which is legacy from an almost defunct project. This database has a "Patients" table with individual personal data and an unique "Id" field, and an "Exams" table with some fields for each exam, one of these fields being "Patient_Id".
What I want is, for a given patient (row from "Pacientes" tabl... | [
"I think the following should do what you want:\n...\nc = conn.cursor()\n\nc.execute('SELECT * FROM Pacientes')\nfor row in c.fetchall():\n Nome = row['nome']\n ID = row['Id']\n c.execute('SELECT File FROM Exames WHERE Id_Paciente=?', [ID])\n for exam in c:\n print exam['File']\n\n"
] | [
1
] | [] | [] | [
"python",
"select",
"sqlite"
] | stackoverflow_0007919798_python_select_sqlite.txt |
Q:
How to strip "()," from Python, PyODBC, SQL Returns?
I grabbed a bunch of SQL IDs I need to update with Python and PyODBC:
import pyodbc
cnxn = pyodbc.connect('DSN=YesOne;PWD=xxx')
cursor = cnxn.cursor()
cursor.execute("SELECT ID FROM One.dbo.Two WHERE STATUS = 'OnGoing' AND ID = ''")
I have a second bit of code ... | How to strip "()," from Python, PyODBC, SQL Returns? | I grabbed a bunch of SQL IDs I need to update with Python and PyODBC:
import pyodbc
cnxn = pyodbc.connect('DSN=YesOne;PWD=xxx')
cursor = cnxn.cursor()
cursor.execute("SELECT ID FROM One.dbo.Two WHERE STATUS = 'OnGoing' AND ID = ''")
I have a second bit of code that updates the IDs:
cursor.execute("Update One.dbo.Two S... | [
"First of all:\nrows = [x[0] for x in cursor.fetchall()]\n\nThen abandon your terrible while loop:\nfor row in rows:\n print 'SELECT ID FROM One.dbo.Two WHERE ID = %s' % row\n\n",
"I believe the issue is that you are accessing a tuple from within a list, so need to specify location in list and location in tuple:... | [
8,
2
] | [] | [] | [
"pyodbc",
"python",
"sql_server"
] | stackoverflow_0003614277_pyodbc_python_sql_server.txt |
Q:
How to put a progress bar (guage) in the statusbar area and lock the gui size
I'm using wxPython to search all the files in a particular directory. As it searches the files, progress (number of files) is sent to the progress bar, just to give a little background. What I want to do is to move the progress bar down ... | How to put a progress bar (guage) in the statusbar area and lock the gui size | I'm using wxPython to search all the files in a particular directory. As it searches the files, progress (number of files) is sent to the progress bar, just to give a little background. What I want to do is to move the progress bar down to the bottom of the frame where SetStatusText usually show a name. But, when a sea... | [
"There are a couple of different ways to do this. I think the simplest is to just use the EnhancedStatusBar widget: http://wiki.wxpython.org/EnhancedStatusBar\nHowever, this thread also mentions a way to do it with the normal StatusBar: http://wxpython-users.1045709.n5.nabble.com/Add-a-progressbar-in-a-statusbar-td... | [
4
] | [] | [] | [
"progress_bar",
"python",
"wxpython"
] | stackoverflow_0007919564_progress_bar_python_wxpython.txt |
Q:
In google app engine, how to iterate through form fields (python, wsgiref.handlers)
Using python and wsgiref.handlers, I can get a single variable from a form with self.handler.request.get(var_name), but how do I iterate through all form variables, be they from GET and POST? Is it something like this?
for field in... | In google app engine, how to iterate through form fields (python, wsgiref.handlers) | Using python and wsgiref.handlers, I can get a single variable from a form with self.handler.request.get(var_name), but how do I iterate through all form variables, be they from GET and POST? Is it something like this?
for field in self.handler.request.fields:
value = self.handler.request.get(field)
Again, it shoul... | [
"http://code.google.com/appengine/docs/python/tools/webapp/requestclass.html#Request_arguments\nfor field in self.request.arguments():\n value = self.request.get(field)\n\n",
"A modification of Drew's answer worked great for me: \nparams = {}\nfor field in self.request.arguments():\n params[field] = self.reque... | [
5,
0
] | [] | [] | [
"google_app_engine",
"python",
"wsgiref"
] | stackoverflow_0002981078_google_app_engine_python_wsgiref.txt |
Q:
How to install Python module on Ubuntu
I just wrote a function on Python. Then, I wanted to make it module and install on my Ubuntu 11.04. Here is what I did.
Created setup.py along with function.py file.
Built distribution file using $Python2.7 setup.py sdist
Then installed it $Python2.7 setup.py install
All wa... | How to install Python module on Ubuntu | I just wrote a function on Python. Then, I wanted to make it module and install on my Ubuntu 11.04. Here is what I did.
Created setup.py along with function.py file.
Built distribution file using $Python2.7 setup.py sdist
Then installed it $Python2.7 setup.py install
All was going fine. But, later I wanted to use the... | [
"Most installation requires:\nsudo python setup.py install\nOtherwise, you won't be able to write to the installation directories.\nI'm pretty sure that (unless you were root), you got an error when you did\npython2.7 setup.py install\n",
"I could not install any modules or eggs until I used the package manager t... | [
24,
3
] | [] | [] | [
"python",
"python_module"
] | stackoverflow_0007426677_python_python_module.txt |
Q:
What is the recommended way to replace multiple strings in one large string in Python?
I have many string pairs and one large string (which is the content of a file). I need to replace each and every occurrence of the first member in each pair with the respective second one.
For instance, having pairs ("AA", "BB")... | What is the recommended way to replace multiple strings in one large string in Python? | I have many string pairs and one large string (which is the content of a file). I need to replace each and every occurrence of the first member in each pair with the respective second one.
For instance, having pairs ("AA", "BB") and ("qq", "rt") I need to replace every occurrence of AA with BB and of qq with rt.
The st... | [
"There's something else wrong with your proposed solution: after the first replacement is made the resulting string could match and the same characters could be replaced again. For example your solution would not give the desired result if you tried to swap 'qq' and 'ff' by setting pairs = [('qq','ff'), ('ff','qq')... | [
3
] | [] | [] | [
"python",
"string"
] | stackoverflow_0007920480_python_string.txt |
Q:
class in python with method acting on self. inheritance
I guess it would be easy for me to explain the question with an examply
Suppose I want to write my own vector class.
And in that class let say i want to define a method to add 2 vectors
something like:
class vector:
.....
def add(self,other):
----some co... | class in python with method acting on self. inheritance | I guess it would be easy for me to explain the question with an examply
Suppose I want to write my own vector class.
And in that class let say i want to define a method to add 2 vectors
something like:
class vector:
.....
def add(self,other):
----some code
so basically what this will do is.. if a vector is vec
th... | [
"If you want to add two classes, I'd look at the __add__ function, which allows you to do normal addition (and not call .add()):\na + b\n\nAs for your question, I'm not exactly sure about what you're asking. I wrote my Vector() class like this:\nclass Vector:\n def __init__(self, x = 0, y = 0, z = 0):\n self.x ... | [
3,
2,
1
] | [] | [] | [
"inheritance",
"python"
] | stackoverflow_0007920492_inheritance_python.txt |
Q:
Python String encoding - file name
str(file.key) = '1011/101011/file_name'
newFileName = str(file.key)
But, when I run the code i get:
UnicodeEncodeError: 'ascii' codec can't encode characters in position
x-y: ordinal not in range(128)
I need to do some parsing on the file name and then download it from s3 se... | Python String encoding - file name | str(file.key) = '1011/101011/file_name'
newFileName = str(file.key)
But, when I run the code i get:
UnicodeEncodeError: 'ascii' codec can't encode characters in position
x-y: ordinal not in range(128)
I need to do some parsing on the file name and then download it from s3 server.
How do I get just 'file_name'?
| [
"You've posted far to little context to give a decent answer, but I'll try anyway.\nThe filename you are trying to create seems to contain non-ascii characters, which cannot be automatically be converted into a standard str in python 2.x.\nIf you replace str with unicode you can avoid the need for conversion alltog... | [
2
] | [] | [] | [
"amazon_s3",
"encoding",
"linux",
"python"
] | stackoverflow_0007920771_amazon_s3_encoding_linux_python.txt |
Q:
How to properly parse JSON with simplejson?
I can have the following JSON string:
{ "response" : [ [ { "name" : "LA_",
"uid" : 123456
} ],
[ { "cid" : "1",
"name" : "Something"
} ],
[ { "cid" : 1,
"name" : "Something-else"
} ]
] }
or one of the... | How to properly parse JSON with simplejson? | I can have the following JSON string:
{ "response" : [ [ { "name" : "LA_",
"uid" : 123456
} ],
[ { "cid" : "1",
"name" : "Something"
} ],
[ { "cid" : 1,
"name" : "Something-else"
} ]
] }
or one of the following:
{"error":"some-error"}
{ "response"... | [
"You're not guaranteed that the ordering of your inner objects will be the same every time you parse it, so indexing is not a safe bet to reference the index of the object with the name attribute set to Something.\nInstead of nesting all those if statements, you can get away with using a list comprehension. Observe... | [
2
] | [] | [] | [
"json",
"python",
"simplejson"
] | stackoverflow_0007920278_json_python_simplejson.txt |
Q:
Using exec in a for loop in python
I am trying to run a for loop that goes through each line of the output of a command. For ex:
for line in exec 'lspci | grep VGA':
count = count + 1
To try and get the amount of video cards installed in a system. But it doesn't seem to line the syntax on the for loop line.
... | Using exec in a for loop in python | I am trying to run a for loop that goes through each line of the output of a command. For ex:
for line in exec 'lspci | grep VGA':
count = count + 1
To try and get the amount of video cards installed in a system. But it doesn't seem to line the syntax on the for loop line.
Do I have to import a library for exec? ... | [
"exec executes Python code, not an external command. You're looking for subprocess.Popen():\nimport subprocess\np = subprocess.Popen('lspci', stdout=subprocess.PIPE)\nfor line in p.stdout:\n if 'VGA' in line:\n print line.strip()\np.wait()\n\nOn my box, this prints out\n01:00.0 VGA compatible controller: nVidia... | [
6,
5,
0,
0
] | [] | [] | [
"exec",
"python"
] | stackoverflow_0007920858_exec_python.txt |
Q:
strange mysql insert error
I'm trying to insert dict values into database. But i'm getting error .here is my dictionary. I'm using this code .
`cols = filter_dict.keys()
vals = filter_dict.values()
("INSERT INTO table (%s) VALUES (%s)", [cols, vals])
`
When I only print this query ("INSERT ... | strange mysql insert error | I'm trying to insert dict values into database. But i'm getting error .here is my dictionary. I'm using this code .
`cols = filter_dict.keys()
vals = filter_dict.values()
("INSERT INTO table (%s) VALUES (%s)", [cols, vals])
`
When I only print this query ("INSERT INTO table (%s) VALUES (%s)", [c... | [
"The backslashes are likely due to your debugger. Are you running your code in the interactive prompt?\nAnyway, the actual problems are:\n\ntable is a reserved word. You should put table in backticks.\nIf your table contains more than one column, you need to have multiple %s and multiple values.\n\nFor example:\n\"... | [
2
] | [] | [] | [
"dictionary",
"mysql",
"python"
] | stackoverflow_0007921146_dictionary_mysql_python.txt |
Q:
Python library for computing spatial derivatives of optical flow
I'm trying to compute a differential image velocity invariants (e.g. curl, divergence, deformation, etc) from a video using OpenCV in Python. To do that, I need to compute the spatial derivatives in the x,y directions of the optical flow. Unfortunate... | Python library for computing spatial derivatives of optical flow | I'm trying to compute a differential image velocity invariants (e.g. curl, divergence, deformation, etc) from a video using OpenCV in Python. To do that, I need to compute the spatial derivatives in the x,y directions of the optical flow. Unfortunately, OpenCV only seems to supply the APIs for computing optical flow, n... | [
"This is the way I see it (I've worked with optical flow a little bit):\nYou want to compute the individual partial derivatives of the optical flow field; one for the x direction, and one for the y.\nI'd attempt to solve the problem like so:\n\nSplit your flow array/matrix into two matrices: x and y flow.\nFor each... | [
0
] | [] | [] | [
"image_processing",
"opencv",
"opticalflow",
"python"
] | stackoverflow_0007920988_image_processing_opencv_opticalflow_python.txt |
Q:
How can I plot maximum likelihood estimate in Python
I am drawing some samples from an exponential distribution. In my first experiment, I am drawing 1000 samples and for the second, I am drawing 10,000 samples from this distribution. (with numpy.random.exponential)
I would like to visually compare the difference ... | How can I plot maximum likelihood estimate in Python | I am drawing some samples from an exponential distribution. In my first experiment, I am drawing 1000 samples and for the second, I am drawing 10,000 samples from this distribution. (with numpy.random.exponential)
I would like to visually compare the difference of the maximum likelihood estimate of my two experiments. ... | [
"Given the remarks in the comments, I guess something like the following is what you're looking for:\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef plot_exponential_density(mu, xmax, fmt, label):\n x = np.arange(0, xmax, 0.1)\n y = 1/mu * np.exp(-x/mu)\n plt.plot(x, y, fmt, label=l... | [
4
] | [] | [] | [
"machine_learning",
"numpy",
"python",
"statistics"
] | stackoverflow_0007897251_machine_learning_numpy_python_statistics.txt |
Q:
Extending __str__() rather than replacing it
I want to extend the __str__() method of my object. The str(obj) currently reads:
<mymodule.Test object at 0x2b1f5098f2d0>
I like the address as a unique identifier, but I want to add some attributes. What's the best way to extend this while still keeping the address... | Extending __str__() rather than replacing it | I want to extend the __str__() method of my object. The str(obj) currently reads:
<mymodule.Test object at 0x2b1f5098f2d0>
I like the address as a unique identifier, but I want to add some attributes. What's the best way to extend this while still keeping the address portion? I'd like to look something like this:
<... | [
"You can get the address with id(obj). You probably want to change the __repr__() method instead of __str__(). Here's code that will do this in Python 2.6+:\nclass Test(object):\n def __repr__(self):\n repr_template = (\"<{0.__class__.__module__}.{0.__class__.__name__}\"\n \" objec... | [
5,
1
] | [] | [] | [
"python",
"python_2.4"
] | stackoverflow_0007921736_python_python_2.4.txt |
Q:
python pipe subprocess i/o over socket
I know there are similar questions out there, but I'm having trouble with this concrete example, and haven't found a good answer. I'm trying to set up a remote backup server for dar, along these lines. I've asked a separate question about doing this by invoking netcat with ... | python pipe subprocess i/o over socket | I know there are similar questions out there, but I'm having trouble with this concrete example, and haven't found a good answer. I'm trying to set up a remote backup server for dar, along these lines. I've asked a separate question about doing this by invoking netcat with subprocess.Popen, but I'd prefer to set up t... | [
"\nIt looks like the dar_xform command on the server is failing...\n\nTry providing a full path to the dar_xform command to subprocess.Popen(...) and see if you continue to have a problem. What you've described looks suspiciously like a PATH issue, especially since it works at the shell prompt.\n"
] | [
0
] | [] | [] | [
"python",
"python_sockets",
"subprocess"
] | stackoverflow_0007922035_python_python_sockets_subprocess.txt |
Q:
What is the correct callback signature for a function called using ctypes in python?
I have to define a callback function in Python, one that will be called from a DLL.
BOOL setCallback (LONG nPort, void ( _stdcall *pFileRefDone) (DWORD nPort, DWORD nUser), DWORD nUser);
I tried this code, that seems to work in P... | What is the correct callback signature for a function called using ctypes in python? | I have to define a callback function in Python, one that will be called from a DLL.
BOOL setCallback (LONG nPort, void ( _stdcall *pFileRefDone) (DWORD nPort, DWORD nUser), DWORD nUser);
I tried this code, that seems to work in Python 2.5 but with Python 2.7 it crashes and I assume I did something wrong.
import ctypes... | [
"Your CB_Func(cbFunc) parameter gets garbage-collected right after the setCallback function. That object has to persist as long as the callback can be called (15.17.1.17. Callback functions, last paragraph). Assign it to a variable and keep it around. Here's my working example:\nDLL\ntypedef unsigned int DWORD;\... | [
4,
3
] | [] | [] | [
"callback",
"ctypes",
"python",
"stdcall"
] | stackoverflow_0007901890_callback_ctypes_python_stdcall.txt |
Q:
Can you have more than one python in terminal?
I'm a bit confused with what is happening to run my django apps. When I use the command python manage.py runserver I don't get the appropriate response from the server. However, when I use python2.6 manage.py runserver the server actually runs.
Can someone help me wi... | Can you have more than one python in terminal? | I'm a bit confused with what is happening to run my django apps. When I use the command python manage.py runserver I don't get the appropriate response from the server. However, when I use python2.6 manage.py runserver the server actually runs.
Can someone help me with this confusion and also suggest to me how I can s... | [
"Yes, you can have multiple versions of Python sitting side-by-side on your computer.\nIt sounds like python on your host is symbolically linked to a version other than python2.6. You can find out this version by running:\npython --version \n\n...or...\npython -V\n\n...if that does not work.\nSetting the default Py... | [
2,
2,
2
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007922397_django_python.txt |
Q:
Finding an exact position of a smaller list inside a list (python)
So i Have a list which is something like this:
list=[10.0, 10.0, 10.0, 9.9, 9.9, 9.9, 10.0, 9.9, 10.0, 10.0, 10.0, 10.0, 9.9, 9.9, 9.9, 9.9, 9.9, 9.9, 10.0, 10.0, 10.0, 10.2, 10.0, 9.9, 9.9, 9.9, 9.9, 10.0, 10.2, 10.0, 9.9, 10.0, 10.0, 10.0, 10.0, ... | Finding an exact position of a smaller list inside a list (python) | So i Have a list which is something like this:
list=[10.0, 10.0, 10.0, 9.9, 9.9, 9.9, 10.0, 9.9, 10.0, 10.0, 10.0, 10.0, 9.9, 9.9, 9.9, 9.9, 9.9, 9.9, 10.0, 10.0, 10.0, 10.2, 10.0, 9.9, 9.9, 9.9, 9.9, 10.0, 10.2, 10.0, 9.9, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.1, 10.0, 10.0, 10.0, 10.0, 10.0, ... | [
"How about:\nl = [10.0, 10.0, 10.0, 9.9, 9.9, 9.9, 10.0, 9.9, 10.0, 10.0, 10.0, 10.0, 9.9, 9.9, 9.9, 9.9, 9.9, 9.9, 10.0, 10.0, 10.0, 10.2, 10.0, 9.9, 9.9, 9.9, 9.9, 10.0, 10.2, 10.0, 9.9, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.0, 10.1, 10.0, 10.0, 10.0, 10.0, 10.0, 10.1, 10.1, 10.1, 10.1, 10.1, 1... | [
3,
2,
1,
1
] | [] | [] | [
"find",
"indexing",
"list",
"nested_lists",
"python"
] | stackoverflow_0007921434_find_indexing_list_nested_lists_python.txt |
Q:
python multiprocessing pickle protocol
I am using the Python multiprocessing module to place objects onto a queue and have them processed by several workers. My first issue was getting bound instance methods to pickle, which I have working, but now I'm running into a separate issue caused by the fact that the obj... | python multiprocessing pickle protocol | I am using the Python multiprocessing module to place objects onto a queue and have them processed by several workers. My first issue was getting bound instance methods to pickle, which I have working, but now I'm running into a separate issue caused by the fact that the objects are using __slots__.
When the mp modul... | [
"If it's not possible to change the pickle protocol the multiprocessing package uses, then define __getstate__ and __setstate__ for your objects:\nimport pickle\n\nclass Foo(object):\n __slots__ = ['this', 'that', 'other']\n\n def __init__(self):\n self.this = 1\n self.that = 2\n self.oth... | [
11
] | [] | [] | [
"multiprocessing",
"python"
] | stackoverflow_0007920601_multiprocessing_python.txt |
Q:
Python property to restrict access
I have the following code :
class C:
def __init__(self, dx = 1):
self._dx = dx
def get_dx(self):
return self._dx
dx = property(get_dx,None,None)
c = C()
print c.dx
c.dx = 42
print c.dx # this shows 42
This should work (see here). However, it is not a... | Python property to restrict access | I have the following code :
class C:
def __init__(self, dx = 1):
self._dx = dx
def get_dx(self):
return self._dx
dx = property(get_dx,None,None)
c = C()
print c.dx
c.dx = 42
print c.dx # this shows 42
This should work (see here). However, it is not and my questions are as follows :
Is it... | [
"property with no setter defined is read-only. The only reason this might not work is that you're using Python 2 and defined an old-style class. Remember to always derive from object in Python 2.x:\nclass C(object):\n @property\n def dx(self):\n return self._dx\n\n def __init__(self, dx = 1):\n ... | [
4,
0
] | [] | [] | [
"properties",
"python"
] | stackoverflow_0007922822_properties_python.txt |
Q:
Python color output and paging output
Python 2.4.x - I cannot install any non-standard modules.
*nix environment.
So I've got an output that I have some color in using ansi coloring. Works great. But the output is so long I needed to either pipe to less or use pydoc's page()
Once I do either - the color turns i... | Python color output and paging output | Python 2.4.x - I cannot install any non-standard modules.
*nix environment.
So I've got an output that I have some color in using ansi coloring. Works great. But the output is so long I needed to either pipe to less or use pydoc's page()
Once I do either - the color turns into
ESC[1;36m TEXT TO FOLLOW: ESC[1;37m
I ... | [
"Use the -R flag with less. This will cause it to output ANSI color escape sequences as they are instead of changing them. It appears to be supported on both my Debian box and my Mac OS X box, which is a good indication that -R is widely supported.\n"
] | [
9
] | [] | [] | [
"colors",
"python"
] | stackoverflow_0007922973_colors_python.txt |
Q:
Adding testcase results to Quality Center Run from a outside Python Script
I want to try to add all the step details - Expected, Actual, Status,
etc. to a QC Run for a testcase of a TestSet from a Python Script
living outside the Quality Center.
I have come till here (code given below) and I don't know how to a... | Adding testcase results to Quality Center Run from a outside Python Script | I want to try to add all the step details - Expected, Actual, Status,
etc. to a QC Run for a testcase of a TestSet from a Python Script
living outside the Quality Center.
I have come till here (code given below) and I don't know how to add
Step Expected and Step Actual Result. If anyone knows how do it,
please hel... | [
"As Ethan Furman answered in your previous question:\n\nIn Python () represent calls to functions, while [] represent indexing and mapping.\n\nSo in other words, you probably want to do step1.Field['ST_ACTUAL'] = 'My actual result'\n",
"Found the answer after a lot of Google Search :)\nSimple -> Just do this:\nst... | [
2,
2
] | [] | [] | [
"hp_quality_center",
"python"
] | stackoverflow_0007773430_hp_quality_center_python.txt |
Q:
Integrate with RBS WorldPay Hosted Payment Page (XML Redirect) using Python
Does anyone have any example code for integrating with RBS WorldPay using Python? Specifically posting the XML order to WorldPay
A:
It's an HTTP POST with Basic Authentication. Basic Authentication is described in the official Fetch Int... | Integrate with RBS WorldPay Hosted Payment Page (XML Redirect) using Python | Does anyone have any example code for integrating with RBS WorldPay using Python? Specifically posting the XML order to WorldPay
| [
"It's an HTTP POST with Basic Authentication. Basic Authentication is described in the official Fetch Internet Resources Using urllib2 HOWTO. So, where XML is the XML you're sending, URL is the URL you're posting to, and MERCHANT_CODE and PASSWORD are self explanatory, the following works:\nimport urllib2\npassword... | [
1
] | [] | [] | [
"payment",
"payment_gateway",
"python",
"worldpay"
] | stackoverflow_0004461781_payment_payment_gateway_python_worldpay.txt |
Q:
Python: Why is Xpath seemingly only processing the first element in this tree?
Suppose I have this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML LANG="ja">
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<META name="GENERATOR" content="snanail Version 2.18">
... | Python: Why is Xpath seemingly only processing the first element in this tree? | Suppose I have this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML LANG="ja">
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=Shift_JIS">
<META name="GENERATOR" content="snanail Version 2.18">
<TITLE>-www.example.org-</TITLE>
<STYLE type="text/css">
<!--
H1.TITLE {
font-size ... | [
"Using the example html file and this script:\nfrom lxml import etree\n\nparser = etree.HTMLParser(encoding='utf8')\ntree = etree.parse('source.html', parser)\nprint tree.xpath('//a/@href')\n\nGives:\n['001.html', '002.html']\n\n",
"did you try declaring your document as XHTML ?\nthe doctype at the beginning of y... | [
1,
0
] | [] | [] | [
"html",
"python",
"xpath"
] | stackoverflow_0007922135_html_python_xpath.txt |
Q:
Create dir with datetime name and subfiles within directory (Python)
I'm currently looking to create a directory on Linux using Python v2.7 with the directory name as the date and time (ie. 27-10-2011 23:00:01). My code for this is below:-
import time
import os
dirfmt = "/root/%4d-%02d-%02d %02d:%02d:%02d"
dirnam... | Create dir with datetime name and subfiles within directory (Python) | I'm currently looking to create a directory on Linux using Python v2.7 with the directory name as the date and time (ie. 27-10-2011 23:00:01). My code for this is below:-
import time
import os
dirfmt = "/root/%4d-%02d-%02d %02d:%02d:%02d"
dirname = dirfmt % time.localtime()[0:6]
os.mkdir(dirname)
This code works fine... | [
"Sure, just save the time in a variable and then use that variable for the substitutions:\nnow = time.localtime()[0:6]\ndirname = dirfmt % now\ncsvafile = os.path.join(dirname, csvafmt % now)\ncsvbfile = os.path.join(dirname, csvbfmt % now)\nlogfile = os.path.join(dirname, logfmt % now)\n\nEdited to include creatin... | [
2,
0
] | [] | [] | [
"createfile",
"python"
] | stackoverflow_0007923453_createfile_python.txt |
Q:
404 on HTTP-Basic authentication?
I have the following scenario:
I have a ShoutCast-ish server which serves out radio station XML info.
I have a Flash Player client which needs to fetch it.
Flash Player can't fetch things over HTTP-Basic auth when using GET.
So I'm building a Python CGI script to handle the auth... | 404 on HTTP-Basic authentication? | I have the following scenario:
I have a ShoutCast-ish server which serves out radio station XML info.
I have a Flash Player client which needs to fetch it.
Flash Player can't fetch things over HTTP-Basic auth when using GET.
So I'm building a Python CGI script to handle the authentication and re-serve the information... | [
"It may require a User-Agent or Accepts header as well. \nTry comparing/copying some of the http headers sent by your browser using Firebug or LiveHTTP Headers in Firefox, or Chrome dev tools. Compare your hexed password to confirm it is correct. Then add other headers one at a time until you've discovered the i... | [
2
] | [] | [] | [
"basic_authentication",
"http",
"python"
] | stackoverflow_0007923413_basic_authentication_http_python.txt |
Q:
Django request QueryDict Errors on pop()
Looking at dir(request.GET), I notice that pop is listed as a method. I also believe i've popped off attributes from request in the past.
Is that accurate? If so, why would this fail?
request.GET.pop('key')
A:
request.GET and request.POST are immutable QueryDict instan... | Django request QueryDict Errors on pop() | Looking at dir(request.GET), I notice that pop is listed as a method. I also believe i've popped off attributes from request in the past.
Is that accurate? If so, why would this fail?
request.GET.pop('key')
| [
"request.GET and request.POST are immutable QueryDict instances. This means you cannot change their attributes directly.\nCopying a QueryDict, returns a mutable QueryDict. You can then call the pop method of the copy without raising an error.\nrequest.GET\nGET = request.GET.copy()\nGET.pop('key') \n\n"
] | [
20
] | [] | [] | [
"django",
"django_views",
"python"
] | stackoverflow_0007923315_django_django_views_python.txt |
Q:
Python: swap list elements in a copied list without affecting the original list
I have a list a and a list b which is (should be) a copy of list a.
a = [[['a'], ['b'], ['c']], [['A'], ['B'], ['C']]]
b = a[:][:]
b[0][1], b[0][2] = b[0][2], b[0][1]
If I now look at a and b I get the following:
a = [[['a'], ['c'], [... | Python: swap list elements in a copied list without affecting the original list | I have a list a and a list b which is (should be) a copy of list a.
a = [[['a'], ['b'], ['c']], [['A'], ['B'], ['C']]]
b = a[:][:]
b[0][1], b[0][2] = b[0][2], b[0][1]
If I now look at a and b I get the following:
a = [[['a'], ['c'], ['b']], [['A'], ['B'], ['C']]]
b = [[['a'], ['c'], ['b']], [['A'], ['B'], ['C']]]
Why... | [
"b = a[:][:] is just b = (a[:])[:] or a copy of a copy of the original list. The lists inside the original list are still referenced and when you change them it shows in both lists. \nYou can do\nb = [l[:] for l in a] # a new list, consisting of copies each sublist\n\nor \nfrom copy import deepcopy\nb = deepcopy(a... | [
4,
0
] | [] | [] | [
"list",
"multidimensional_array",
"python"
] | stackoverflow_0007923521_list_multidimensional_array_python.txt |
Q:
How to include docs directory in python distribution
I have a python project with the following structure:
Clustering (project name)
clustering (package)
clustering.py and other modules
tests (sub-package)
test_clustering.py and other such files
docs/
bin/
I would like to include the docs d... | How to include docs directory in python distribution | I have a python project with the following structure:
Clustering (project name)
clustering (package)
clustering.py and other modules
tests (sub-package)
test_clustering.py and other such files
docs/
bin/
I would like to include the docs directory in my distribution, but I can not seem to do that... | [
"You'll need to create a MANIFEST.in file and include some simple instructions on what extra files you want to include (See MANIFEST.in Template)\nExample (to include docs dir and all files directly underneath):\ninclude docs/*\n\nor, to include all files in the doc dir (recursively):\nrecursive-include docs *\n\n"... | [
47
] | [] | [] | [
"python",
"setup.py"
] | stackoverflow_0007923509_python_setup.py.txt |
Q:
Implementing "is open now" filter for the list of venues in web app
I need to implement "is open now" filter for my website that lists venues, but I don't know where to start. My website is implemented using Python, webpy, MySQL database.
I have to store the opening hours for every venue and select venues that are... | Implementing "is open now" filter for the list of venues in web app | I need to implement "is open now" filter for my website that lists venues, but I don't know where to start. My website is implemented using Python, webpy, MySQL database.
I have to store the opening hours for every venue and select venues that are open now.
An example of opening hours: "Works from 9:30am to 11pm on wee... | [
"I've used an app called django-schedule which has some similar features.\nIf you dig in to the source, you'll see it uses python-dateutil (see rrules) underneath. It keeps a list of schedule rules for each event in the database.\nYou could use a similar tactic. When venue-open-status is queried see if the curren... | [
2
] | [] | [] | [
"mysql",
"python",
"web.py"
] | stackoverflow_0007923402_mysql_python_web.py.txt |
Q:
Create numpy array from matrix declared inside .m matlab file
A coworker left some data files I want to analyze with Numpy.
Each file is a matlab file, say data.m, and have the following formatting (but with a lot more columns and rows):
values = [-24.92 -23.66 -22.55 ;
-24.77 -23.56 -22.45 ;
-24.54 -23.64 -22.56 ... | Create numpy array from matrix declared inside .m matlab file | A coworker left some data files I want to analyze with Numpy.
Each file is a matlab file, say data.m, and have the following formatting (but with a lot more columns and rows):
values = [-24.92 -23.66 -22.55 ;
-24.77 -23.56 -22.45 ;
-24.54 -23.64 -22.56 ;
];
which is the typical explicit matrix creation syntax used by ... | [
"Here are a couple options, although neither is built in.\nThe solution you probably do not find acceptable\nThis solution probably falls into your \"quick and dirty\" category, but it helps lead in to the next solution.\nRemove the values = [, the last line (];), and globally replace all ; with nothing to get:\n-2... | [
2,
1
] | [] | [] | [
"matlab",
"matrix",
"numpy",
"python"
] | stackoverflow_0007923214_matlab_matrix_numpy_python.txt |
Q:
Use Imagemagick to find areas of similar colour
Is there any way to use ImageMagick (or something similar, anything that will work!) to find areas of an image where the pixels beside each other are a similar color?
Thanks in advance,
A:
Photoshop, Gimp and Plenty of other image processors will do this for you. P... | Use Imagemagick to find areas of similar colour | Is there any way to use ImageMagick (or something similar, anything that will work!) to find areas of an image where the pixels beside each other are a similar color?
Thanks in advance,
| [
"Photoshop, Gimp and Plenty of other image processors will do this for you. Programmatically, here is some code in python that accomplishes this:\nfrom PIL import Image, ImageDraw\n\ndef inImage(im, px):\n x,y = px\n return x < im.size[0] and y < im.size[1] and x > 0 and y > 0\n\ndef meetsThreshold(im, px, st... | [
1
] | [] | [] | [
"colors",
"image",
"imagemagick",
"pixel",
"python"
] | stackoverflow_0007922281_colors_image_imagemagick_pixel_python.txt |
Q:
Confirmation box on file transfer over sockets using PyQT
I have a confirmation box which gets called when sending a file over the network. However, the function for the Signal is in the MainWindow class and uses variables from the Worker thread. But it doesn't work because the variables in the worker thread are n... | Confirmation box on file transfer over sockets using PyQT | I have a confirmation box which gets called when sending a file over the network. However, the function for the Signal is in the MainWindow class and uses variables from the Worker thread. But it doesn't work because the variables in the worker thread are not in the right scope.
Any idea how I can pass the msg variable... | [
"I think I don't understand exactly your situation.\nHowever, did you try to define a new (custom) signal?\nIf you define a new signal with pyqtSignal,\nyou can emit the signal with parameters.\nDocumentation on signal and slots (new style).\n"
] | [
0
] | [] | [] | [
"pyqt",
"pyqt4",
"python"
] | stackoverflow_0007923646_pyqt_pyqt4_python.txt |
Q:
How to handle when webpage does not load on BeautifulSoup
Currently if there is an error retrieving the webpage then soup will not be populated with the page but gets the default return from beautifulsoup.
I am looking for a way to check for this so that if there is an error getting the webpage I can skip a chunk ... | How to handle when webpage does not load on BeautifulSoup | Currently if there is an error retrieving the webpage then soup will not be populated with the page but gets the default return from beautifulsoup.
I am looking for a way to check for this so that if there is an error getting the webpage I can skip a chunk of code like
if soup:
do stuff
but I do not want to termina... | [
"Structure the code so that one function encapsulates the entire process of data retrieval from the url, and another that encapsulates the processing of that data:\nimport urllib2, httplib\nfrom BeautifulSoup import BeautifulSoup\n\ndef append_log(message):\n print message\n\ndef get_web_page(address):\n try:... | [
3,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0007922362_beautifulsoup_python.txt |
Q:
Generating random numbers under very specific constraints
I am faced with the following programming problem. I need to generate n (a, b) tuples for which the sum of all a's is a given A and sum of all b's is a given B and for each tuple the ratio of a / b is in the range (c_min, c_max). A / B is within the same ra... | Generating random numbers under very specific constraints | I am faced with the following programming problem. I need to generate n (a, b) tuples for which the sum of all a's is a given A and sum of all b's is a given B and for each tuple the ratio of a / b is in the range (c_min, c_max). A / B is within the same range, too. I am also trying to make sure there is no bias in the... | [
"We look for tuples a_i and b_i such that\n\n(a_1, ... a_n) and (b_1, ... b_n) have a distribution which is invariant under permutation of indices (what you would call \"unbiased\")\nthe ratios a_i / b_i are uniformly distributed on [cmin, cmax]\nsum(a_i) = A, sum(b_i) = B\n\nIf c_min and c_max are not too ill cond... | [
3,
2,
2,
1,
1,
0
] | [] | [] | [
"algorithm",
"python",
"random"
] | stackoverflow_0007908800_algorithm_python_random.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.