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:
Copy the contents of an ImageField to a new file path in Django
I have a Django model object that has a few normal attributes, and it has a ImageField for the logo. I want to write a method that'll copy this object to a new object. It's easy enough to instanciate the new object, then loop over all the attributes a... | Copy the contents of an ImageField to a new file path in Django | I have a Django model object that has a few normal attributes, and it has a ImageField for the logo. I want to write a method that'll copy this object to a new object. It's easy enough to instanciate the new object, then loop over all the attributes and copy from the old to new (e.g. new_object.name = old_object.name).... | [
"Why not create a function that is fun on the save signal which copies the image file to whereever you want, then creates a new object with a new image field? \nmodels.py\nclass ObjectOne(models.Model):\n logo = models.ImageField(...)\n\nclass ObjectTwo(models.Model):\n logo = models.ImageField(...)\n\nfrom d... | [
3
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0007596039_django_django_models_python.txt |
Q:
Web2py AJAX autofilling of form
i've a from an i want to fill it automatically based on information from a data base and filled fields :
in db_wizard.py
db.define_table('sender',
Field('name'), # e.g. Daniel
Field('email'),# e.g. daniel@daniel.com
Field('opening'), # e.g. Dear Daniel
...)
db.d... | Web2py AJAX autofilling of form | i've a from an i want to fill it automatically based on information from a data base and filled fields :
in db_wizard.py
db.define_table('sender',
Field('name'), # e.g. Daniel
Field('email'),# e.g. daniel@daniel.com
Field('opening'), # e.g. Dear Daniel
...)
db.define_table('receiver',
Field('name... | [
"If the 'opening' text should be filled in instantly when the user selects a recipient, then you'll probably want to use Ajax. Check out this lazy options widget. You'll have to modify it to fill in a string input instead of an options list, but otherwise it should do what you want.\n"
] | [
0
] | [] | [] | [
"autofill",
"python",
"web2py"
] | stackoverflow_0007540824_autofill_python_web2py.txt |
Q:
Python - Reading BLOB type from SQLite3 DB
This is a follow on from: Python - Converting Hex to INT/CHAR
I now have a working solution for converting the stored hex value of an IP from an sqlite3 db into a readable and usable format. However up until now I have been testing by copying and pasting the values direct... | Python - Reading BLOB type from SQLite3 DB | This is a follow on from: Python - Converting Hex to INT/CHAR
I now have a working solution for converting the stored hex value of an IP from an sqlite3 db into a readable and usable format. However up until now I have been testing by copying and pasting the values directly from a sqlite3 db viewer.
I have been trying ... | [
"After checking the link, it seems the most likely explanation is an empty row. On line 29 you set up a for loop to go over the results of a query. In python this means you have a list:\n[item,item2,item3] and each time you go through the loop, your row variable points to the next item.\nWithin the loop, you are ch... | [
4
] | [] | [] | [
"binary",
"hex",
"python",
"sqlite"
] | stackoverflow_0007597736_binary_hex_python_sqlite.txt |
Q:
Websocket server for Python3 outside HTTP server
I am searching for a websocket server implementation for Python3.
There are some projects on the web, but they all run in HTTP-context.
I need a server that is started on command line, not by an HTTP-server (No HTTP-Handler object available)
Ideally, the code should... | Websocket server for Python3 outside HTTP server | I am searching for a websocket server implementation for Python3.
There are some projects on the web, but they all run in HTTP-context.
I need a server that is started on command line, not by an HTTP-server (No HTTP-Handler object available)
Ideally, the code should not require any bigger third party-project (like twis... | [
"My websockify project support python3. The websocket.py module that websockify is built on implements a generic python WebSocket server. It currently requires the numpy module if you want to use the new versions (HyBi-07+) of the protocol (I will probably implement a slower generic fallback in the next couple of d... | [
2
] | [] | [] | [
"html",
"python",
"python_3.x",
"websocket"
] | stackoverflow_0007583780_html_python_python_3.x_websocket.txt |
Q:
Handling NoneType when using addition
Im trying to add some values up but some of the values have a NoneType value. Now I looked at this question but I need some help. Im hoping someone can explain to me how I can get this to work with django.
Here is my for loop in my views.py:
next_il = Investment.objects.all(... | Handling NoneType when using addition | Im trying to add some values up but some of the values have a NoneType value. Now I looked at this question but I need some help. Im hoping someone can explain to me how I can get this to work with django.
Here is my for loop in my views.py:
next_il = Investment.objects.all().filter(plan = plan).order_by('financial_i... | [
"for inv in next_il:\n total_m2 += inv.maturity_amount or 0\n\nAnd may be you should set default=0 for maturity_amount field.\nAnd it's better to use DB aggregation here:\nfrom django.db.models import Sum\n\ntotal_m2 = Investment.objects.filter(plan = plan).order_by('financial_institution').filter(maturity_date__... | [
6,
0
] | [] | [] | [
"django",
"django_models",
"django_views",
"python"
] | stackoverflow_0007597817_django_django_models_django_views_python.txt |
Q:
Executing a Python Script From Python Shell
I am trying to access the Amazon Advertising through Python and I created a Python script to automate the authentication process. This file, called amazon.py is located in ~/PROJECT/APP/amazon.py.
I want to be able to play around with the API, so I launched python manag... | Executing a Python Script From Python Shell | I am trying to access the Amazon Advertising through Python and I created a Python script to automate the authentication process. This file, called amazon.py is located in ~/PROJECT/APP/amazon.py.
I want to be able to play around with the API, so I launched python manage.py shell from the ~/PROJECT directory to enter ... | [
"Normally, you just import the file and call a function within it:\nimport APP.amazon\nAPP.amazon.main() \n\nThis would only work if amazon.py is laid out like this:\ndef main():\n ...code...\n\nif __name__ == '__main__':\n main()\n\nAlso, in the directory ~/PROJECT/APP there needs to exist a file __init__.py... | [
1,
1
] | [] | [] | [
"python",
"shell"
] | stackoverflow_0007598159_python_shell.txt |
Q:
32bit TIFF to another format in Python
I need to convert a 32 bit TIFF file (or the corresponding int32 array) to another format that Tkinter can display (like gif fe)
How do I do that? Converting the array to int16 or so completely blurs the picture...
A:
PIL is your best friend.
A:
You can use PIL, Image Mag... | 32bit TIFF to another format in Python | I need to convert a 32 bit TIFF file (or the corresponding int32 array) to another format that Tkinter can display (like gif fe)
How do I do that? Converting the array to int16 or so completely blurs the picture...
| [
"PIL is your best friend.\n",
"You can use PIL, Image Magick, or GraphicsMagick\nGraphicsMagic and ImageMagick are command-line programs and have python versions. I use Graphics Magic because it is simple. ImageMagick is almost a command-line version of photoshop...\n"
] | [
2,
0
] | [] | [] | [
"image_processing",
"python",
"tiff",
"tkinter"
] | stackoverflow_0007597899_image_processing_python_tiff_tkinter.txt |
Q:
SQLAlchemy: Dynamically loading tables from a list
I am trying to create a program that loads in over 100 tables from a database so that I can change all appearances of a user's user id.
Rather than map all of the tables individually, I decided to use a loop to map each of the tables using an array of objects. Thi... | SQLAlchemy: Dynamically loading tables from a list | I am trying to create a program that loads in over 100 tables from a database so that I can change all appearances of a user's user id.
Rather than map all of the tables individually, I decided to use a loop to map each of the tables using an array of objects. This way, the table definitions can be stored in a config f... | [
"Well, in your case it *is the same Class you try to map to different Tables. To solve this, create a class dynamically for each Table:\nclass Table(object):\n tableID = ''\n primaryKey = ''\n pkType = sa.types.String()\n def __init__(self):\n self.mappedClass = type('TempClass', (object,), {})\n... | [
1
] | [] | [] | [
"dynamic",
"loading",
"python",
"sqlalchemy"
] | stackoverflow_0007597386_dynamic_loading_python_sqlalchemy.txt |
Q:
Python: variables by references (hack)
Is there any way (hack) to push Python function (def) to return results by reference even for immutable types?
A proposal application (swap as subroutine):
def swap(a, b):
.....a,b = b,a
Note:
def swap(a, b):
.....return b,a
works as function which is not the answer of the qu... | Python: variables by references (hack) | Is there any way (hack) to push Python function (def) to return results by reference even for immutable types?
A proposal application (swap as subroutine):
def swap(a, b):
.....a,b = b,a
Note:
def swap(a, b):
.....return b,a
works as function which is not the answer of the question!
For example there is a function ran... | [
"All names in Python are references. And no, there are no \"out\" references (e.g. in a C++ sense) available. You need to pass a mutable object and then you can mutate it in the function. But then again, returning new value(s) should be the preferred way.\n",
"No, such things don't exist, because you get the give... | [
4,
3,
2
] | [] | [] | [
"function",
"immutability",
"mutable",
"python",
"subroutine"
] | stackoverflow_0007598346_function_immutability_mutable_python_subroutine.txt |
Q:
Save the selected value of a combobox in wxpython
I'm working to design a gui using wxpython, a pecie of my code is that i have a class which a fram
declaration and also i declared variables that i wanna chage their values based on the comboboxes
selection. i did the folowing:
class myMenu(wx.Frame):
def __in... | Save the selected value of a combobox in wxpython | I'm working to design a gui using wxpython, a pecie of my code is that i have a class which a fram
declaration and also i declared variables that i wanna chage their values based on the comboboxes
selection. i did the folowing:
class myMenu(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(se... | [
"I'm not sure what's wrong with that. It looks like it should work. I copied most of it and put it into a runnable example that works on Windows:\nimport wx\n\n########################################################################\nclass MyForm(wx.Frame):\n\n #--------------------------------------------------... | [
3
] | [] | [] | [
"combobox",
"python",
"user_interface",
"wxpython"
] | stackoverflow_0007589238_combobox_python_user_interface_wxpython.txt |
Q:
Update version of Python in Emacs 22.2.1
I've recently install Python 3.1, but Emacs still uses 2.6.5. I'm using Emacs version 22.2.1. I'm not sure which files to edit in order to make Emacs use Python 3.1 by default!
I'm using python-mode.el and pyemacs, if that helps...
Best,
Georgina
A:
See a previous discuss... | Update version of Python in Emacs 22.2.1 | I've recently install Python 3.1, but Emacs still uses 2.6.5. I'm using Emacs version 22.2.1. I'm not sure which files to edit in order to make Emacs use Python 3.1 by default!
I'm using python-mode.el and pyemacs, if that helps...
Best,
Georgina
| [
"See a previous discussion on this\n\nBoth Python 2 and 3 in Emacs\n\nIn your .emacs file, following should do:\n;; python 3\n(setq python-python-command \"python3\")\n\n",
"All I had to do was add\n(setq py-python-command \"/usr/bin/python3.1\")\n\nTo my .emacs file.\n",
"There are actually a number of differe... | [
1,
1,
0
] | [] | [] | [
"emacs",
"python",
"python_3.x",
"python_mode"
] | stackoverflow_0004300021_emacs_python_python_3.x_python_mode.txt |
Q:
How to convert image which mode is "1" between PIL and numpy?
I'm new to image processing with Python and met a strange problem.
For example I have a 2*2 black-white bitmap image which pixels are following:
black white
white black
Use PIL and convert it to numpy:
>>> import Image
>>> import numpy
>>> im = Image.... | How to convert image which mode is "1" between PIL and numpy? | I'm new to image processing with Python and met a strange problem.
For example I have a 2*2 black-white bitmap image which pixels are following:
black white
white black
Use PIL and convert it to numpy:
>>> import Image
>>> import numpy
>>> im = Image.open('test.bmp')
>>> im
<BmpImagePlugin.BmpImageFile image mode=1 s... | [
"It looks like there are some bugs with converting to/from numpy with the 1 mode.\nIf you convert it to L first, it works fine:\n>>> im\n<BmpImagePlugin.BmpImageFile image mode=1 size=2x2 at 0x17F17E8>\n>>> im2 = im.convert('L')\n>>> numpy.asarray(im2)\narray([[ 0, 255],\n [255, 0]], dtype=uint8)\n\nAlso, ... | [
7
] | [] | [] | [
"numpy",
"python",
"python_imaging_library"
] | stackoverflow_0007597525_numpy_python_python_imaging_library.txt |
Q:
Python: Confused about random.choice within join
Here is my code:
s = 'Hello world'
c = ['a','b','c','d','e','f']
n = ['1','2','3','4','5','6']
l = [random.choice(c),random.choice(n)]
return ''.join('%s%s' % (x, random.choice(l) if random.random() > 0.5 else '') for x in s)
This will output:
He5lloe w5o5rl5de
Bu... | Python: Confused about random.choice within join | Here is my code:
s = 'Hello world'
c = ['a','b','c','d','e','f']
n = ['1','2','3','4','5','6']
l = [random.choice(c),random.choice(n)]
return ''.join('%s%s' % (x, random.choice(l) if random.random() > 0.5 else '') for x in s)
This will output:
He5lloe w5o5rl5de
But what I am aiming for is something like this code wou... | [
"By doing l = [random.choice(c),random.choice(n)] you're limiting random.choice(l) to only 2 possible chars (one from each list c and n).\nTry this instead:\nfrom random import random, choice\ns = 'Hello world'\nc = ['a','b','c','d','e','f']\nn = ['1','2','3','4','5','6']\nL = choice([c, n]) # randomly choose eith... | [
5
] | [] | [] | [
"python"
] | stackoverflow_0007599508_python.txt |
Q:
Python trying to Refactor (DRY out) a long Control Flow
I am grabbing a lot of data from and SQL query that takes a long time to run. Since the SQL query takes so long to run, I am grabbing the data from the database in its most granular form. I then cycle through this data once and aggregate it in the forms that ... | Python trying to Refactor (DRY out) a long Control Flow | I am grabbing a lot of data from and SQL query that takes a long time to run. Since the SQL query takes so long to run, I am grabbing the data from the database in its most granular form. I then cycle through this data once and aggregate it in the forms that are useful to me.
My problem is that I am repeating myself ov... | [
"The entire structure you're using to store the data is probably wrong, but since I don't know how you're using it, I can't help you with that.\nYou can get rid of all of those has_key() calls by using collections.defaultdict. Note thedict.has_key(key) is deprecated anyway, you should just use key in thedict instea... | [
1
] | [] | [] | [
"control_flow",
"dry",
"python",
"python_2.5",
"refactoring"
] | stackoverflow_0007599347_control_flow_dry_python_python_2.5_refactoring.txt |
Q:
How do I express this query in sqlalchemy?
I'm using this as an example to help me learn sqlalchemy. Here is the mySQL:
select f.type, f.variety, f.price
from (
select type, min(price) as minprice
from fruits group by type
) as x inner join fruits as f on f.type = x.type and f.price = x.minprice;
Here is w... | How do I express this query in sqlalchemy? | I'm using this as an example to help me learn sqlalchemy. Here is the mySQL:
select f.type, f.variety, f.price
from (
select type, min(price) as minprice
from fruits group by type
) as x inner join fruits as f on f.type = x.type and f.price = x.minprice;
Here is what I have so far:
s = Session()
sq = s.query(fu... | [
"I can't be sure of this because I don't know what exception you're getting.\nSince you're trying to get SQLAlchemy to execute a similar query to the one you posted, in which you have a select statement in your from clause, you'll need to call mapper on the result of a sqlalchemy.select similar to the linked exampl... | [
1,
1,
0
] | [] | [] | [
"mysql",
"python",
"sqlalchemy"
] | stackoverflow_0007534937_mysql_python_sqlalchemy.txt |
Q:
Python - SqlAlchemy: Filter query by great circle distance?
I am using Python and Sqlalchemy to store latitude and longitude values in a Sqlite database. I have created a hybrid method for my Location object,
@hybrid_method
def great_circle_distance(self, other):
"""
Tries to calculate the great circle dis... | Python - SqlAlchemy: Filter query by great circle distance? | I am using Python and Sqlalchemy to store latitude and longitude values in a Sqlite database. I have created a hybrid method for my Location object,
@hybrid_method
def great_circle_distance(self, other):
"""
Tries to calculate the great circle distance between the two locations
If it succeeds, it will retu... | [
"You can't really use the math module that way: \n>>> c = toyschema.Contact()\n>>> c.lat = 10\n>>> c.lat\n10\n>>> import math\n>>> math.cos(c.lat)\n-0.83907152907645244\n>>> math.cos(toyschema.Contact.lat)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: a float is required\n... | [
7,
0,
0
] | [] | [] | [
"database",
"pylons",
"python",
"sqlalchemy",
"sqlite"
] | stackoverflow_0007595050_database_pylons_python_sqlalchemy_sqlite.txt |
Q:
Shortest way to do this Python 3 list operation in PHP, JavaScript?
I am learning Python and I just read in a book that Python 3 lets you do this cool list operation:
first, *middle, last = [1, 2, 3, 4, 5]
first: 1
middle: [2, 3, 4]
last: 5
This is great if I want to iterate through the middle of the list, and do... | Shortest way to do this Python 3 list operation in PHP, JavaScript? | I am learning Python and I just read in a book that Python 3 lets you do this cool list operation:
first, *middle, last = [1, 2, 3, 4, 5]
first: 1
middle: [2, 3, 4]
last: 5
This is great if I want to iterate through the middle of the list, and do separate things with the first and last items.
What's the easiest (read:... | [
"python 2.x\nfirst, middle, last = a[0], a[1:-1], a[-1]\n\n",
"A solution in PHP could be the following, using array_shift and array_pop:\n$first = array_shift($arr);\n$last = array_pop($arr);\n$middle = $arr;\n\n",
"On Python2, you can just use slice notation, also it's easier to read I think.\n>>> t = (1, 2, ... | [
3,
2,
1,
1,
0
] | [] | [] | [
"javascript",
"list",
"php",
"python",
"python_3.x"
] | stackoverflow_0007053424_javascript_list_php_python_python_3.x.txt |
Q:
Downloading MMS emails sent to Gmail using Python
So I tried the code below and it downloads attachments alright. The problem is on my gmail account, there are emails that were sent using MMS mail through mobile phone. Email attachments from mobile network A can be downloaded by the script below , while those that... | Downloading MMS emails sent to Gmail using Python | So I tried the code below and it downloads attachments alright. The problem is on my gmail account, there are emails that were sent using MMS mail through mobile phone. Email attachments from mobile network A can be downloaded by the script below , while those that came from mobile network B fails.
Here are the links ... | [
"The failing e-mail doesn't have Content-Disposition set in the headers for the attachment, so you're skipping over it. Looks like you're going to have to relax the if statement that checks for Content-Disposition a bit. \nMaybe you could just look too see if the Content-Type is image/jpeg and work with that.\n"
] | [
4
] | [] | [] | [
"imaplib",
"python"
] | stackoverflow_0007596789_imaplib_python.txt |
Q:
Python non-ascii characters
I have a python file that creates and populates a table in ms sql. The only sticking point is that the code breaks if there are any non-ascii characters or single apostrophes (and there are quite a few of each). Although I can run the replace function to rid the strings of apostrophes,... | Python non-ascii characters | I have a python file that creates and populates a table in ms sql. The only sticking point is that the code breaks if there are any non-ascii characters or single apostrophes (and there are quite a few of each). Although I can run the replace function to rid the strings of apostrophes, I would prefer to keep them inta... | [
"James, I believe the real issue is that your are not using Unicode accross the board. Try to do the following:\n\nMake sure that your input file that you are using to populate the DB is in UTF-8 and that you are reading it with the UTF-8 encoder.\nMake sure your DB is actually storing the data as Unicode\nWhen you... | [
3,
2,
1,
0,
0
] | [] | [] | [
"python",
"sql_server",
"utf_8"
] | stackoverflow_0007590030_python_sql_server_utf_8.txt |
Q:
In Python how to add headers for a file after gzip before writing it
I am trying to open a javascript file, read it, gzip it and then write it back to another file.. able to do all that.. but how can set the "Content-Encoding : gzip" before writing the compressed content... here is the code:
import os, sys, mimety... | In Python how to add headers for a file after gzip before writing it | I am trying to open a javascript file, read it, gzip it and then write it back to another file.. able to do all that.. but how can set the "Content-Encoding : gzip" before writing the compressed content... here is the code:
import os, sys, mimetypes, zipfile, gzip, cStringIO
from optparse import OptionParser
def main()... | [
"That is usually determined by whatever is serving the file. Your job is usually limited to setting the correct file name extension (.gz in this case) when you create the file and configuring the server properly. \n"
] | [
0
] | [] | [] | [
"content_encoding",
"gzip",
"python"
] | stackoverflow_0007597587_content_encoding_gzip_python.txt |
Q:
How can a disconnected TCP socket be reliably detected using MsgWaitForMultipleObjects?
Twisted includes a reactor implemented on top of MsgWaitForMultipleObjects. Apparently the reactor has problems reliably noticing when a TCP connection ends, at least in the case where a peer sends some bytes and then quickly ... | How can a disconnected TCP socket be reliably detected using MsgWaitForMultipleObjects? | Twisted includes a reactor implemented on top of MsgWaitForMultipleObjects. Apparently the reactor has problems reliably noticing when a TCP connection ends, at least in the case where a peer sends some bytes and then quickly closes the connection. What seems to happen is:
The reactor calls MsgWaitForMultipleObjects... | [
"In order to use WSAEventSelect and differentiate activities, you need to call WSAEnumNetworkEvents. Make sure you're processing each event that was reported, not just the first.\nWSAAsyncSelect makes it easy to determine the cause, and is often used together with MsgWaitForMultipleObjects.\nSo you might use WSAAs... | [
1
] | [] | [] | [
"networking",
"python",
"reactor",
"twisted",
"windows"
] | stackoverflow_0007598936_networking_python_reactor_twisted_windows.txt |
Q:
python: why "IndentationError: expected an indented block" for this code?
Refer to Listing 9. Iteration and a dictionary
>>> d = {0: 'zero', 3: 'a tuple', 'two': [0, 1, 2], 'one': 1}
>>> for k in d.iterkeys():
... print(d[k])
File "<stdin>", line 2
print(d[k])
^
IndentationError: expected an indented... | python: why "IndentationError: expected an indented block" for this code? | Refer to Listing 9. Iteration and a dictionary
>>> d = {0: 'zero', 3: 'a tuple', 'two': [0, 1, 2], 'one': 1}
>>> for k in d.iterkeys():
... print(d[k])
File "<stdin>", line 2
print(d[k])
^
IndentationError: expected an indented block
Why?
| [
"Indentation level of your statements is significant in Python.\n",
"Python 3 doesn't have iterkeys. Just use: \nfor k in d:\n print(d[k])\n\nor even better:\nfor v in d.values():\n print(v)\n\n",
"Even when using the Python interactive interpreter, you need to make sure you have some indentation for a ne... | [
3,
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0007600289_python.txt |
Q:
Using Django to summarize Report
I'm trying to produce a table that will show the total maturity amounts for each financial institution that a plan has.
A plan is the term I use for person. So each person can have multiple investments. I'm having trouble creating a table that will do this correctly.
Currently I ... | Using Django to summarize Report | I'm trying to produce a table that will show the total maturity amounts for each financial institution that a plan has.
A plan is the term I use for person. So each person can have multiple investments. I'm having trouble creating a table that will do this correctly.
Currently I have a report that displays each inves... | [
"So, you want to aggregate the values of the investments for a plan:\nfrom django.db.models import Sum\nmy_plan.investment_set.filter(\n maturity_date__gte=whenever\n).values('financial_institution').annotate(Sum('value'))\n\n"
] | [
5
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0007600431_django_django_models_django_templates_django_views_python.txt |
Q:
How to Query/Filter M2M 'through' object in Django
I have the following basic model…
class Campaign(models.Model):
name = models.CharField(_('name'), max_length=80, unique=True)
recipients = models.ManyToManyField('Person', blank=True, null=True, through='Recipient')
class Recipient(models.Model):
... | How to Query/Filter M2M 'through' object in Django | I have the following basic model…
class Campaign(models.Model):
name = models.CharField(_('name'), max_length=80, unique=True)
recipients = models.ManyToManyField('Person', blank=True, null=True, through='Recipient')
class Recipient(models.Model):
campaign = models.ForeignKey(Campaign)
person = mo... | [
"I believe this will do it.\nfrom django.db.models import Q\nPerson.objects.filter(~Q(id__in=<mycampaign>.recipients.all())\n\n",
"Here's the answer… the problem was that my form was for the Recipient object instead of the Campaign object… the Furbeenator answer was a good step in the right direction… along with ... | [
1,
1
] | [] | [] | [
"django",
"django_forms",
"python"
] | stackoverflow_0007579020_django_django_forms_python.txt |
Q:
sqlalchemy joined alias doesn't have columns from both tables
All I want is the count from TableA grouped by a column from TableB, but of course I need the item from TableB each count is associated with. Better explained with code:
TableA and B are Model objects.
I'm trying to follow this syntax as best I can.
Tr... | sqlalchemy joined alias doesn't have columns from both tables | All I want is the count from TableA grouped by a column from TableB, but of course I need the item from TableB each count is associated with. Better explained with code:
TableA and B are Model objects.
I'm trying to follow this syntax as best I can.
Trying to run this query:
sq = session.query(TableA).join(TableB).\
... | [
"When you make a subquery out of a select statement, the columns that can be accessed from it must be in the columns clause. Take for example a statement like:\nselect x, y from mytable where z=5\n\nIf we wanted to make a subquery, then GROUP BY 'z', this would not be legal SQL:\nselect * from (select x, y from my... | [
3
] | [] | [] | [
"group_by",
"join",
"python",
"sqlalchemy"
] | stackoverflow_0007600420_group_by_join_python_sqlalchemy.txt |
Q:
PlotCanvas on a wx.Panel?
I'm having difficulties with the wx.lib.plot.PlotCanvas module, getting it to display in a panel. Can someone please help me understand what I'm doing wrong?
#!/usr/bin/python
import wx
import logging
import wx.lib.plot as plot
class PlotCanvasExample(wx.Panel):
def __init__(self,... | PlotCanvas on a wx.Panel? | I'm having difficulties with the wx.lib.plot.PlotCanvas module, getting it to display in a panel. Can someone please help me understand what I'm doing wrong?
#!/usr/bin/python
import wx
import logging
import wx.lib.plot as plot
class PlotCanvasExample(wx.Panel):
def __init__(self, parent, id, size):
'''... | [
"This works by subclassing PlotCanvas.\nI do not put it in a panel but directly in the Frame\n!/usr/bin/python\n\nimport wx\nimport logging\nimport wx.lib.plot as plot\n\nclass PlotCanvasExample(plot.PlotCanvas):\n def __init__(self, parent, id, size):\n ''' Initialization routine for the this panel.'''\n... | [
6
] | [] | [] | [
"python",
"wxpython"
] | stackoverflow_0007600652_python_wxpython.txt |
Q:
Python adding config files to path
I have directory structure like following:
analytics
/ / \ \
conf script src other
/ \ / \ / \
<setup> <source>
< setup >:
setup.yaml
sql.yaml
< source >:
src/
folder A/ ... | Python adding config files to path | I have directory structure like following:
analytics
/ / \ \
conf script src other
/ \ / \ / \
<setup> <source>
< setup >:
setup.yaml
sql.yaml
< source >:
src/
folder A/
s1.py
... | [
"open() (and all the other file access functions) don't care about sys.path. It's only used when importing modules.\nCreate your own variable that contains the path that contains your files, and use it.\n"
] | [
4
] | [] | [] | [
"python"
] | stackoverflow_0007601108_python.txt |
Q:
Getting absolute file/dir path in python
From the code below both returns me the same output. When should I use one over the other?
import os
from os.path import abspath, dirname
print abspath(dirname(__file__))
print os.getcwd()
PS: I wanted to use this for dynamically changing the path for logs, static files a... | Getting absolute file/dir path in python | From the code below both returns me the same output. When should I use one over the other?
import os
from os.path import abspath, dirname
print abspath(dirname(__file__))
print os.getcwd()
PS: I wanted to use this for dynamically changing the path for logs, static files and templates in my django project to run it in... | [
"Use the first when you want to know the location of the file being executed. Use the second when you want to know the process's current working directory.\n",
"os.getcwd can be used at places where you want to move from your current directory to perform some actions on other directory, for this you save your cur... | [
3,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0007601116_django_python.txt |
Q:
Python equivalent to Bash $()
I search the Python equivalent for the following Bash code:
VAR=$(echo $VAR)
Pseudo Python code could be:
var = print var
Can you help? :-)
Regards
Edit:
I search a way to do this:
for dhIP in open('dh-ips.txt', 'r'):
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
print gi.country... | Python equivalent to Bash $() | I search the Python equivalent for the following Bash code:
VAR=$(echo $VAR)
Pseudo Python code could be:
var = print var
Can you help? :-)
Regards
Edit:
I search a way to do this:
for dhIP in open('dh-ips.txt', 'r'):
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
print gi.country_code_by_addr(print dhIP) # <-- thi... | [
"You don't need a print in there, just use the name of the variable:\nfor dhIP in open('dh-ips.txt', 'r'):\n gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)\n print gi.country_code_by_addr(dhIP)\n\nAlso note that iterating through a file object gives you lines with the newline characters at the end. You may want to ... | [
3,
2,
1,
0
] | [] | [] | [
"equivalent",
"python"
] | stackoverflow_0007601010_equivalent_python.txt |
Q:
Dragon Curve in Python
I created a program to draw a dragon curve using turtle graphics.. but my result doesn't really look like the picture does in the link:
One problem I noticed is that I want to save the produced string into the variable newWord.. but I can't use newWord as a parameter in my function drawit,... | Dragon Curve in Python | I created a program to draw a dragon curve using turtle graphics.. but my result doesn't really look like the picture does in the link:
One problem I noticed is that I want to save the produced string into the variable newWord.. but I can't use newWord as a parameter in my function drawit, which actually draws lines ... | [
"newWord is locally scoped inside of createWord(), so after createWord() is finished, newWord disappears.\nConsider creating newWord in the global scope so you can modify it with createWord - or better yet, let createWord() return a value, and set newWord to that value.\n\nI would think that printing \"word\" and t... | [
4
] | [] | [] | [
"l_systems",
"python",
"turtle_graphics"
] | stackoverflow_0007562772_l_systems_python_turtle_graphics.txt |
Q:
ipython and python are handling my string differently, why?
In python (2.7.1):
>>> x = u'$€%'
>>> x.find('%')
2
>>> len(x)
3
Whereas in ipython:
>>> x = u'$€%'
>>> x.find('%')
4
>>> len(x)
5
What's going on here?
edit: including the additional info requested from the comments below
ipython
>>> import sys, local... | ipython and python are handling my string differently, why? | In python (2.7.1):
>>> x = u'$€%'
>>> x.find('%')
2
>>> len(x)
3
Whereas in ipython:
>>> x = u'$€%'
>>> x.find('%')
4
>>> len(x)
5
What's going on here?
edit: including the additional info requested from the comments below
ipython
>>> import sys, locale
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.setdefaultenc... | [
"@nye17 It's officially not a good idea to ever call setdefaultencoding() (it is removed from sys after first use for a reason). One common culprit is gtk, which causes all kinds of problems, so if IPython has imported gtk, sys.getdefaultencoding() will return utf8. IPython does not set the default encoding itsel... | [
5,
1
] | [] | [] | [
"encoding",
"ipython",
"python",
"string",
"unicode"
] | stackoverflow_0007593454_encoding_ipython_python_string_unicode.txt |
Q:
Getting the endpoints of sets across a range
For the life of me, I can't see how to do this. I need to collect the non-overlapping endpoints of several sets within a range of numbers with python.
For example the user could input a range of 10 and two sets 2 and 3. I need to get the end points of these sets within ... | Getting the endpoints of sets across a range | For the life of me, I can't see how to do this. I need to collect the non-overlapping endpoints of several sets within a range of numbers with python.
For example the user could input a range of 10 and two sets 2 and 3. I need to get the end points of these sets within this range such that:
set 2 groupings: 1-2,6-7
set... | [
"I don't think there's a good built-in solution to this. (It would be easier if there were a built-in equivalent to Haskell's scan function.) But this is concise enough:\n>>> import itertools\n>>> from collections import defaultdict\n>>> partition_lengths = [1, 2, 3]\n>>> range_start = 1\n>>> range_end = 12\n>>> en... | [
2,
0
] | [] | [] | [
"algorithm",
"math",
"python",
"range",
"set"
] | stackoverflow_0007600235_algorithm_math_python_range_set.txt |
Q:
Need a PHP script to return an exact match of a python script
Please I need help getting the exact md5 value of this python script in PHP
The Python script
def md5code(params):
params = {'identifier': ' ', 'amount': '0.0', 'code': 'UNIA'}
req = dict([[key, params.get(key, '')] for key in ['code', 'identifi... | Need a PHP script to return an exact match of a python script | Please I need help getting the exact md5 value of this python script in PHP
The Python script
def md5code(params):
params = {'identifier': ' ', 'amount': '0.0', 'code': 'UNIA'}
req = dict([[key, params.get(key, '')] for key in ['code', 'identifier', 'amount']])
secret = '2fd0bba6b1774ed391c1ff8467f52a5d'
... | [
"ok, seems you're using foreach in a wrong way. Try this:\n$secret = '2fd0bba6b1774ed391c1ff8467f52a5d';\n$code = 'UNIA';\n$valid_institution = array('amount' => '0.0', 'code' => $code, 'identifier' => ' ');\n$text = \n $valid_institution['code'] . \":\" . \n $valid_institution['identifier'] . \":\" . \n $... | [
2,
1,
0
] | [] | [] | [
"md5",
"php",
"python"
] | stackoverflow_0007601223_md5_php_python.txt |
Q:
group_concat only when more than one to group
I'd like to perform a group-concat in SQLite only on those records where there is more than one row to concatenate. It seems like you could do this beforehand (count records using a group by then remove those singleton rows before proceeding with the group_concat); af... | group_concat only when more than one to group | I'd like to perform a group-concat in SQLite only on those records where there is more than one row to concatenate. It seems like you could do this beforehand (count records using a group by then remove those singleton rows before proceeding with the group_concat); after (complete the group_concat then remove rows whe... | [
"Add a HAVING clause to your query:\nINSERT INTO fooc(a,b) \n SELECT x, group_concat(y) \n FROM foo \n GROUP BY x\n HAVING COUNT(*) > 1\n\n"
] | [
1
] | [] | [] | [
"python",
"sqlite"
] | stackoverflow_0007601341_python_sqlite.txt |
Q:
GAE/Python: collection_name not working with Polymodel?
I'm having trouble using db.ReferenceProperty with PolyModel in GAE. If I have two models derived from a base PolyModel, and each one has a reference to another "container" model, the collections on the container contain both PolyModels, not just the one as ... | GAE/Python: collection_name not working with Polymodel? | I'm having trouble using db.ReferenceProperty with PolyModel in GAE. If I have two models derived from a base PolyModel, and each one has a reference to another "container" model, the collections on the container contain both PolyModels, not just the one as you would expect. Here is a test case that shows the problem... | [
"So looking at the SDK source, it appears that _ReverseReferenceProperty (which translates collections into Query objects) doesn't make any attempt to handle PolyModels. There are a few related complaints on the issue tracker, here and here.\nIMO, if this is a known limitation it ought to be mentioned somewhere in ... | [
2
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0007601175_google_app_engine_google_cloud_datastore_python.txt |
Q:
Facebook App Wall Posting no longer showing in Facebook iPhone App
I use the GRAPH API with django for Facebook wall postings. Since yesterday, the wall posts only show on the Facebook web app but not the Facebook iPhone app. I tried Yelp, and their postings still show up. How can I debug this? Anyone notice t... | Facebook App Wall Posting no longer showing in Facebook iPhone App | I use the GRAPH API with django for Facebook wall postings. Since yesterday, the wall posts only show on the Facebook web app but not the Facebook iPhone app. I tried Yelp, and their postings still show up. How can I debug this? Anyone notice this issue with their Facebook connect? Is this a Facebook algorithm iss... | [
"I have the same problem. I am writing an iPhone app in Objective C and my post code uses the FBStreamDialog box to prompt for input and then post to a news feed. So, it appears the problem is more likely to be a Facebook problem rather than a coding problem.\n"
] | [
0
] | [] | [] | [
"django",
"facebook",
"facebook_graph_api",
"objective_c",
"python"
] | stackoverflow_0007587107_django_facebook_facebook_graph_api_objective_c_python.txt |
Q:
Looping through annotate query
Initially I asked this question, and I wanted to give credit to Daniel. Here is the new issue I have however.
I have this which works great, but I'm having a minor issue.
total_list = plan.investment_set.filter(maturity_date__gte= '%s-1-1' % current_year).values('financial_instituti... | Looping through annotate query | Initially I asked this question, and I wanted to give credit to Daniel. Here is the new issue I have however.
I have this which works great, but I'm having a minor issue.
total_list = plan.investment_set.filter(maturity_date__gte= '%s-1-1' % current_year).values('financial_institution').annotate(Sum('maturity_amount')... | [
"Assuming that the \"financial_institution\" model has a name field, I think you could just add it to the list of values you're asking for:\ntotal_list = plan.investment_set.filter(\n maturity_date__gte= '%s-1-1' % current_year\n).values(\n 'financial_institution',\n 'financial_institution__name'\n).annota... | [
1
] | [] | [] | [
"django",
"django_models",
"django_templates",
"django_views",
"python"
] | stackoverflow_0007601780_django_django_models_django_templates_django_views_python.txt |
Q:
Search and Replace Strings in a Text File Using Wildcards
Trying to do a search/replace in python using wildcards on the contents of a text file:
If the contents of the text file looks like:
"all_bcar_v0038.ma";
"all_bcar_v0002.ma";
"all_bcar_v0011.ma";
"all_bcar_v0011.ma";
Looking to replace all the version num... | Search and Replace Strings in a Text File Using Wildcards | Trying to do a search/replace in python using wildcards on the contents of a text file:
If the contents of the text file looks like:
"all_bcar_v0038.ma";
"all_bcar_v0002.ma";
"all_bcar_v0011.ma";
"all_bcar_v0011.ma";
Looking to replace all the version numbers with v1000 to get this:
"all_bcar_v1000.ma";
"all_bcar_v1... | [
"Your life would be vastly improved with the use of regexes. You should be able to do this in 2 lines (assuming I understand the problem correctly):\nimport re\n\nfor line in fileinput.input(file, inplace=1):\n re.sub(r\"_v\\d{4}\", \"_v1000\", line)\n\n",
"Try - \nimport re\n\nre.sub(\"_v\\d{4}\", \"_v1000.\", ... | [
6,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007601820_python_regex.txt |
Q:
How to improve efficiency in this numpy iterating?
I'm working on an assignment about converting a grayscale image to 1-bit binary image by dithering. I'm trying a simple 4x4 matrix that will make the image 16 times larger than original.
dithering_matrix = array([[ 0, 8, 2, 10],
[12, 4... | How to improve efficiency in this numpy iterating? | I'm working on an assignment about converting a grayscale image to 1-bit binary image by dithering. I'm trying a simple 4x4 matrix that will make the image 16 times larger than original.
dithering_matrix = array([[ 0, 8, 2, 10],
[12, 4, 14, 6],
[ 3, 11, 1, 9],
... | [
"If you use the Kronecker product to turn every pixel into a 4x4 submatrix, that'll enable you to get rid of the Python loops:\nim2 = np.kron(im, np.ones((4,4)))\ndm2 = np.tile(dithering_matrix,(512,512))\nout2 = ((im2 / (256 / split_num)) > dm2) * 255\n\nOn my machine this is roughly 20x faster than your version.\... | [
7
] | [] | [] | [
"image_processing",
"numpy",
"python",
"python_imaging_library"
] | stackoverflow_0007601611_image_processing_numpy_python_python_imaging_library.txt |
Q:
Creating Segments in Video
I'm using Python 2.7, PyGTK 2.24, and PyGST (Gstreamer).
To ensure smooth playback from one clip to another (without a blink), I combined all the clips I needed into one larger video. This lets me seek to the exact place I need in code. One of the clips is like a "fill-in", which should ... | Creating Segments in Video | I'm using Python 2.7, PyGTK 2.24, and PyGST (Gstreamer).
To ensure smooth playback from one clip to another (without a blink), I combined all the clips I needed into one larger video. This lets me seek to the exact place I need in code. One of the clips is like a "fill-in", which should loop whenever one of the other c... | [
"Looks like only GstElement's can generate NEWSEGMENT events, you can't simply attach it to an existing element. The closest thing you could do if not using Python, would be creating a single shot or periodic GstClockID or and use gst_clock_id_wait_async until the clock time hit. But the problem is, GstClockID is n... | [
1
] | [] | [] | [
"gstreamer",
"pygtk",
"python"
] | stackoverflow_0007434770_gstreamer_pygtk_python.txt |
Q:
python: difference of two timedate strings
I have two date strings (taken from user input and can vary greatly)
s1 = '2011:10:01:10:30:00'
s2 = '2011:10:01:11:15:00'
I wish to find the difference between the two as minutes.
How should I proceed to tackle this ?
A:
import datetime
d1 = datetime.datetime.strpti... | python: difference of two timedate strings | I have two date strings (taken from user input and can vary greatly)
s1 = '2011:10:01:10:30:00'
s2 = '2011:10:01:11:15:00'
I wish to find the difference between the two as minutes.
How should I proceed to tackle this ?
| [
"import datetime\n\nd1 = datetime.datetime.strptime('2011:10:01:10:30:00', '%Y:%m:%d:%H:%M:%S')\nd2 = datetime.datetime.strptime('2011:10:01:11:15:00', '%Y:%m:%d:%H:%M:%S')\ndiff = (d2 - d1).total_seconds() / 60\n\nIf you need to handle arbitrary datetime formats, I don't believe the built in datetime library will ... | [
9,
5,
4,
1
] | [] | [] | [
"datediff",
"datetime",
"python"
] | stackoverflow_0007601781_datediff_datetime_python.txt |
Q:
SystemExit and NameError issues with exiting
def main():
try:
print "hardfart"
return 0
except:
return 1
if __name__ == '__main__':
exit(main())
Can one kind programmer tell me why this spits out the following error on exit?
Traceback (most recent call last):
File "C:/Apps/exp... | SystemExit and NameError issues with exiting | def main():
try:
print "hardfart"
return 0
except:
return 1
if __name__ == '__main__':
exit(main())
Can one kind programmer tell me why this spits out the following error on exit?
Traceback (most recent call last):
File "C:/Apps/exp_exit.py", line 9, in ,module.
exit(main())
File "... | [
"You exit a program by raising SystemExit. This is what exit() does. Someone has incorrectly written an exception handler that catches all exceptions. This is why you only catch the exceptions you can handle.\n"
] | [
1
] | [] | [] | [
"exit",
"python"
] | stackoverflow_0007601947_exit_python.txt |
Q:
Scrapy middleware order
Scrapy documentation says :
the first
middleware is the one closer to the
engine and the last is the one closer
to the downloader.
To decide which order to assign to
your middleware see the
DOWNLOADER_MIDDLEWARES_BASE setting
and pick a value according to where
you want to i... | Scrapy middleware order | Scrapy documentation says :
the first
middleware is the one closer to the
engine and the last is the one closer
to the downloader.
To decide which order to assign to
your middleware see the
DOWNLOADER_MIDDLEWARES_BASE setting
and pick a value according to where
you want to insert the middleware. The
o... | [
"I know this has been answered, but really it's a more complicated thing -- requests and responses are handled in opposite order.\nyou can think of it like this:\n\n0 - engine makes request\n1..inf - process_request middleware calls\ninf - actual download happens (if a request middleware didn't handle it)\ninf..1 -... | [
10,
3
] | [] | [] | [
"middleware",
"python",
"scrapy"
] | stackoverflow_0006623470_middleware_python_scrapy.txt |
Q:
EOF Error in Imaplib
I am programming a python applet that watches the unread count of the email boxes for my workplace, and ran into an EOF error when I try to use any imaplib methods after the applet sits idle for about 10 minutes. Everything works fine until the applet has been alive for more than 10 minutes.
H... | EOF Error in Imaplib | I am programming a python applet that watches the unread count of the email boxes for my workplace, and ran into an EOF error when I try to use any imaplib methods after the applet sits idle for about 10 minutes. Everything works fine until the applet has been alive for more than 10 minutes.
Here is the relevant code f... | [
"You need to reconnect by re-initialize class, not just login, using\nconn = imaplib.IMAP4_SSL(\"imap.gmail.com\", 993)\n\nA complete example:\nwhile True:\n imap = imaplib.IMAP4_SSL(SERVER)\n r, d = imap.login(ACCOUNT, PASSWORD)\n assert r == 'OK', 'login failed'\n try:\n # do things with imap\n... | [
14,
6
] | [] | [] | [
"eof",
"imaplib",
"python"
] | stackoverflow_0007575943_eof_imaplib_python.txt |
Q:
dependency resolution pip virtualenv
I have 2 local libraries which are dependent on different version of suds.
Example -
Module-A-1.0's setup.py has a requirement of suds ==0.3.9.
Module-B-1.0's setup.py has a requirement of suds ==0.4.0.
Both these modules are required by Module-C, which has the following ... | dependency resolution pip virtualenv | I have 2 local libraries which are dependent on different version of suds.
Example -
Module-A-1.0's setup.py has a requirement of suds ==0.3.9.
Module-B-1.0's setup.py has a requirement of suds ==0.4.0.
Both these modules are required by Module-C, which has the following its setup.py
django
Module-A-1.0
Module-B... | [
"Using pip + virtualenv you can't have two versions of a library installed at the same time.\nAnd, unfortunately, I don't know of any good ways of handling this situation. Sorry.\n"
] | [
1
] | [] | [] | [
"dependencies",
"pip",
"python",
"virtualenv"
] | stackoverflow_0007601098_dependencies_pip_python_virtualenv.txt |
Q:
Python Streaming : how to reduce to multiple outputs?(its possible with Java though)
I read Hadoop in Action and found that in Java using MultipleOutputFormat and MultipleOutputs classes we can reduce the data to multiple files but what I am not sure is how to achieve the same thing using Python streaming.
for e... | Python Streaming : how to reduce to multiple outputs?(its possible with Java though) | I read Hadoop in Action and found that in Java using MultipleOutputFormat and MultipleOutputs classes we can reduce the data to multiple files but what I am not sure is how to achieve the same thing using Python streaming.
for example:
/ out1/part-0000
mapper -> reducer
\ out2... | [
"The Dumbo Feathers, a set of java classes to use together with Dumbo (a python library that makes it easy to write efficient python M/R programs for hadoop), does this in its output classes. \nBasically, in your python dumbo M/R job, you output a key that is a tuple of two elements - the first element being the na... | [
2
] | [] | [] | [
"hadoop",
"hadoop_streaming",
"mapreduce",
"python"
] | stackoverflow_0007600095_hadoop_hadoop_streaming_mapreduce_python.txt |
Q:
Change C object instance to Python subclass
Is it possible to change a class of a C object to a python subclass?
I am using PyGTK, and I have a ListModel that I have wrapped my own class around, but I want to turn it into a TreeModelFilter. The directions tell me to create it by doing:
class MyListStore(gtk.ListSt... | Change C object instance to Python subclass | Is it possible to change a class of a C object to a python subclass?
I am using PyGTK, and I have a ListModel that I have wrapped my own class around, but I want to turn it into a TreeModelFilter. The directions tell me to create it by doing:
class MyListStore(gtk.ListStore):
def __init__(self, title):
self.title... | [
"Inheritance can be a very fluid concept in python. For starters, you should always use new style classes. To do that, make sure your classes should always inherit from \"object\".\nIt's important to note that Classes must inherit from other classes, not instances of other classes, so your example really wouldn't... | [
1,
1
] | [] | [] | [
"inheritance",
"pygtk",
"python"
] | stackoverflow_0007589861_inheritance_pygtk_python.txt |
Q:
Why are my requests from urllib2 delayed with Apache2?
I'm dealing with two internal web servers, one running Apache2 on Ubuntu Server 10.04, and the other IIS on Windows Server 2008. When I hit either of the root URLs from a web browser with a cleared cache, calling the server by IP address, both pop up with no ... | Why are my requests from urllib2 delayed with Apache2? | I'm dealing with two internal web servers, one running Apache2 on Ubuntu Server 10.04, and the other IIS on Windows Server 2008. When I hit either of the root URLs from a web browser with a cleared cache, calling the server by IP address, both pop up with no delay. I also see no delays browsing sites on either server... | [
"The lookup is happening because that's what Windows does. It's always going to check NetBIOS before anything else. \nFurther reading:\n\nMicrosoft TCP/IP Host Name Resolution Order\nNetBIOS over TCP/IP Name Resolution and WINS\n\n"
] | [
0
] | [] | [] | [
"apache",
"iis",
"python",
"urllib2"
] | stackoverflow_0007600267_apache_iis_python_urllib2.txt |
Q:
Python cgi weird behaviour
I have a simple CGI python script with an html output:
print "Content-Type: text/html"
print
print hours,minutes,seconds,","
When I run it from my linux shell, it runs fine but when called from the browser, all I get is a blank page. I used to have this problem before when I used CRLF E... | Python cgi weird behaviour | I have a simple CGI python script with an html output:
print "Content-Type: text/html"
print
print hours,minutes,seconds,","
When I run it from my linux shell, it runs fine but when called from the browser, all I get is a blank page. I used to have this problem before when I used CRLF EOF instead of LF but I changed t... | [
"<!-- SHTML Wrapper - 500 Server Error --> means that something is going wrong on the server. The most common cause in CGI scripts for this error is that there is an uncaught error in the CGI script itself, causing it to prematurely terminate. Your best bet is to check your Apache error logs. These will normally be... | [
1
] | [] | [] | [
"cgi",
"python"
] | stackoverflow_0007602557_cgi_python.txt |
Q:
Batch Scripting: Running python script on all directories in a folder
I have a python script called script.py which I would like to run on all of the directories inside of a specific directory. What is the easiest way to do this using batch scripting?
My assumption is some usage of the FOR command, but I can't qu... | Batch Scripting: Running python script on all directories in a folder | I have a python script called script.py which I would like to run on all of the directories inside of a specific directory. What is the easiest way to do this using batch scripting?
My assumption is some usage of the FOR command, but I can't quite make any leads to solve the problem using the command...
| [
"Use the /d operator on for:\nfor /D %%d in (*) do script.py %%d\n\nThis assumes you only need to execute one command per directory (script.py %%d) if you need to execute more use braces (). Also I'm guessing there's an execution engine needed first, but not sure what it is for you.\nA multi-line example:\nfor /D ... | [
3,
0
] | [] | [] | [
"batch_file",
"python"
] | stackoverflow_0007586936_batch_file_python.txt |
Q:
What is the best way to get the values of a radio button set with lxml?
For example I have the following radio buttons:
<input type="radio" name="hand" id='hand_left' checked value="L">
<label for='hand_left'>Left</label>
<input type="radio" name="hand" id='hand_right' value="R">
<label for='hand_right'>Ri... | What is the best way to get the values of a radio button set with lxml? | For example I have the following radio buttons:
<input type="radio" name="hand" id='hand_left' checked value="L">
<label for='hand_left'>Left</label>
<input type="radio" name="hand" id='hand_right' value="R">
<label for='hand_right'>Right</label>
And have the following parsing code:
import lxml.html as lh
doc... | [
"You could use el.attrib['value'] instead of el.value\n"
] | [
0
] | [] | [] | [
"lxml",
"python"
] | stackoverflow_0007602406_lxml_python.txt |
Q:
pygtk popup executes out of order
I have pygtk menu, in which a function is called on menuitem click, in this function i am showing a popup to user saying wait while checking internet connectivity and then calling a function which checks internet connectivity,
My problem is the my programs is first calling the int... | pygtk popup executes out of order | I have pygtk menu, in which a function is called on menuitem click, in this function i am showing a popup to user saying wait while checking internet connectivity and then calling a function which checks internet connectivity,
My problem is the my programs is first calling the internet connectivity check function and t... | [
"The main loop calls your handler for the menu item and waits for it to return before it does anything else, including dismissing the menu so your dialog can get the focus.\nThe easiest workaround might be to use timeout_add to call your connection check when the main loop gets around to it, i.e. after showing the ... | [
0,
0
] | [] | [] | [
"pygtk",
"python"
] | stackoverflow_0007598182_pygtk_python.txt |
Q:
Python-twilio api error?
im using twilio-python and im following this tutorial:
http://readthedocs.org/docs/twilio-python/en/latest/usage/twiml.html?highlight=nest
But when i try this:
from twilio import twiml
r = twiml.Response()
r.say("hello")
with r.gather(finishOnKey=4) as g:
g.say("world")
print str(r)
... | Python-twilio api error? | im using twilio-python and im following this tutorial:
http://readthedocs.org/docs/twilio-python/en/latest/usage/twiml.html?highlight=nest
But when i try this:
from twilio import twiml
r = twiml.Response()
r.say("hello")
with r.gather(finishOnKey=4) as g:
g.say("world")
print str(r)
But i get this:
AttributeError... | [
"It seems they aren't really compatible with the with statement. Try this:\nfrom twilio import twiml\n\nr = twiml.Response()\nr.say(\"hello\")\ng = r.gather(finishOnKey=4)\ng.say(\"world\")\nprint str(r)\n\nHere's what I get:\n>>> from twilio import twiml\n>>> \n>>> r = twiml.Response()\n>>> r.say(\"hello\")\n<twil... | [
2,
2
] | [] | [] | [
"python",
"twilio"
] | stackoverflow_0007591009_python_twilio.txt |
Q:
Relationship between form and formset on same webpage
I'm trying to relate all the objects created in a formset to an object created on the same webpage as the formset. So, an example of the code is this:
def create_b(request):
SpeciesFormSet = modelformset_factory(Species, fields=('common', 'scientific'))
... | Relationship between form and formset on same webpage | I'm trying to relate all the objects created in a formset to an object created on the same webpage as the formset. So, an example of the code is this:
def create_b(request):
SpeciesFormSet = modelformset_factory(Species, fields=('common', 'scientific'))
if request.method == 'POST':
formset = SpeciesFor... | [
"This exact pattern is what inline model formsets are for.\n",
"From the error, it looks like you are assigning a BName where the property is supposed to be a BModel. Either, you want to change the BName with a BModel, or you need to fix your models so they match with a BName for the Species.\nformset1 = Species.... | [
1,
0
] | [] | [] | [
"django",
"foreign_key_relationship",
"forms",
"formset",
"python"
] | stackoverflow_0007601990_django_foreign_key_relationship_forms_formset_python.txt |
Q:
Calculating the sum of aggregate query set
So I have a query set that returns a list of financial institutions and also the total amount of money in investments I have with each institution.
views.py
total_list = plan.investment_set.filter(maturity_date__gte= '%s-1-1' % current_year).values('financial_institution_... | Calculating the sum of aggregate query set | So I have a query set that returns a list of financial institutions and also the total amount of money in investments I have with each institution.
views.py
total_list = plan.investment_set.filter(maturity_date__gte= '%s-1-1' % current_year).values('financial_institution__abbr').annotate(Sum('maturity_amount'))
What I... | [
"I believe you're looking for .aggregate():\ntotal_list = plan.investment_set.filter(\n maturity_date__gte= '%s-1-1' % current_year\n).aggregate(Sum('maturity_amount'))\n\nwhich should give you:\n{'maturity_amount__sum': <total amount>}\n\n",
"Sorry this is creating a hassle. Is the field that you're calculati... | [
1,
0
] | [] | [] | [
"django",
"django_models",
"django_views",
"python"
] | stackoverflow_0007602451_django_django_models_django_views_python.txt |
Q:
Regex? Search Engine?
I've read through some documentation on the re module that comes with built-in python, but I just can't seem to get a grasp on it. In fact, I'm not exactly sure that is what I'm looking for, so let me explain:
I have a huge dictionary. What I want is to be able to type in a search criteria, l... | Regex? Search Engine? | I've read through some documentation on the re module that comes with built-in python, but I just can't seem to get a grasp on it. In fact, I'm not exactly sure that is what I'm looking for, so let me explain:
I have a huge dictionary. What I want is to be able to type in a search criteria, let's say for example hello,... | [
"Since you are using Python, you should look at Xapian, it had great Python bindings.\nWhat you are asking for is way more sophisticated that what regular expressions are for.\nYou need full text search, with stemming and other tricks to do the fuzzy matching.\n",
"You might want to look at something that can com... | [
2,
2,
1
] | [] | [] | [
"python",
"regex",
"search"
] | stackoverflow_0007602798_python_regex_search.txt |
Q:
automatically print stack trace on any uncaught exception
How can I automatically print the stack trace to stdout on any uncaught exceptions ?
I am using
pipe = subprocess.Popen(cmd, shell=False, cwd=cwd, env=env,stdout=open(pth,'w'),stderr=open(pth,'w'))
On uncaught Exception, the file will only contain
Unhand... | automatically print stack trace on any uncaught exception | How can I automatically print the stack trace to stdout on any uncaught exceptions ?
I am using
pipe = subprocess.Popen(cmd, shell=False, cwd=cwd, env=env,stdout=open(pth,'w'),stderr=open(pth,'w'))
On uncaught Exception, the file will only contain
Unhandled Exception:
but I'd like in addition the trace to be writt... | [
"In the child process initialize the logging module and assign sys.stdout = LoggerFile(). Then any exception not handled within the child process will be written to your log file instead of to standard out. If you want it to be written to both, enhance the LoggerFile class.\nPlease note that because the child pro... | [
0,
0
] | [] | [] | [
"debugging",
"python"
] | stackoverflow_0007584779_debugging_python.txt |
Q:
web.py not importing MySQLdb
I'm working with web.py and for some reason I am getting the following error:
[Thu Sep 29 13:47:20 2011] [error] [client 64.8.210.120] File "/usr/lib/python2.6/site-packages/web.py-0.36-py2.6.egg/web/db.py", line 975, in __init__
[Thu Sep 29 13:47:20 2011] [error] [client 64.8.210.1... | web.py not importing MySQLdb | I'm working with web.py and for some reason I am getting the following error:
[Thu Sep 29 13:47:20 2011] [error] [client 64.8.210.120] File "/usr/lib/python2.6/site-packages/web.py-0.36-py2.6.egg/web/db.py", line 975, in __init__
[Thu Sep 29 13:47:20 2011] [error] [client 64.8.210.120] import MySQLdb as db
[Thu ... | [
"At the bottom of your bashrc (usually in /etc/bashrc) file put this (or just update the PYTHONPATH env variable to include /usr/lib/python2.6/site-packages):\nif [ $PYTHONPATH ]\nthen\n export PYTHONPATH=$PYTHONPATH:/usr/lib/python2.6/:/usr/lib/python2.6/site-packages/\nelse\n export PYTHONPATH=/usr/lib/pyth... | [
1,
0,
0
] | [] | [] | [
"mysql_python",
"python",
"sys.path",
"web.py"
] | stackoverflow_0007602713_mysql_python_python_sys.path_web.py.txt |
Q:
openID in wsgi with Python 3
I have never done authentication stuff before, but would like to be able to track and authenticate users via openID. I saw a couple modules that allow for openID authentication with WSGI, but all are old and none mention python3, so I'm guessing they do not work.
I'd like some suggest... | openID in wsgi with Python 3 | I have never done authentication stuff before, but would like to be able to track and authenticate users via openID. I saw a couple modules that allow for openID authentication with WSGI, but all are old and none mention python3, so I'm guessing they do not work.
I'd like some suggestions as to how to handle/authentic... | [
"Two caveats on this answer right away:\n\nI've you're well versed in your framework, urllib and it's friends, implementing this will still take a bit of time. It's not trivial.\nThe openid2rp code doesn't look all that, uhm, ready.\n\nNone the less. The latest version of openid2rp can be translated with 2to3 to wo... | [
3
] | [] | [] | [
"mod_wsgi",
"openid",
"python",
"python_3.x",
"wsgi"
] | stackoverflow_0005656866_mod_wsgi_openid_python_python_3.x_wsgi.txt |
Q:
How to retrieve dirs in a zipfile using python?
How do I traverse the contents of a zip file in python without having to extract them?
If extracting is the only way, is it efficient if I create a unique temp folder and extract them there then traverse and remove the temp folder afterwards?
A:
Use the namelist() ... | How to retrieve dirs in a zipfile using python? | How do I traverse the contents of a zip file in python without having to extract them?
If extracting is the only way, is it efficient if I create a unique temp folder and extract them there then traverse and remove the temp folder afterwards?
| [
"Use the namelist() method of the ZipFile class to get a list of all of the filenames in the archive without having to extract them. For example:\nimport zipfile\n\nmyzip = zipfile.ZipFile('myzip.zip', 'r')\nfilenames = myzip.namelist()\n# Do something with filenames\n\n"
] | [
3
] | [] | [] | [
"python",
"zip"
] | stackoverflow_0007603709_python_zip.txt |
Q:
Python regex and splitting
I have a string like this
mystr = "K1_L1_L2 XX"
I want to break it to the following format
K1 L1 L2 XX
where K1, L1, L2 can be anything but have this format of a char followed by a number. I am doing this in python using the following regex:
a = "K1_L1_L2 XX"
re.split("[\c\d\_]+",... | Python regex and splitting | I have a string like this
mystr = "K1_L1_L2 XX"
I want to break it to the following format
K1 L1 L2 XX
where K1, L1, L2 can be anything but have this format of a char followed by a number. I am doing this in python using the following regex:
a = "K1_L1_L2 XX"
re.split("[\c\d\_]+",a)
which gives me the following... | [
"There are problems with the code you have included in your example above. I would edit them but I'm not 100% sure what you are looking for.\nThe following:\nimport re\n\na = \"K1_L1_L2 XX\"\nprint re.split(\"[ _]\", a)\n\nwill print:\n['K1', 'L1', 'L2', '', 'XX']\n\n",
"maybe\nre.split(\"([A-Za-z]\\d)\",a)\n\n?... | [
4,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0007603693_python_regex.txt |
Q:
bbfreeze and protobuf
I'm trying to package a script with bbfreeze that uses the protocol buffers. Using bbfreeze like so:
#!/usr/bin/python
from bbfreeze import Freezer
import os
f = Freezer('dist')
f.addScript('main.py')
f()
Results in No module named google.protbuf on the client. Reading the docs a bit, I tr... | bbfreeze and protobuf | I'm trying to package a script with bbfreeze that uses the protocol buffers. Using bbfreeze like so:
#!/usr/bin/python
from bbfreeze import Freezer
import os
f = Freezer('dist')
f.addScript('main.py')
f()
Results in No module named google.protbuf on the client. Reading the docs a bit, I try this:
#!/usr/bin/python
f... | [
"Sounds like you have not installed protobuf... try \"pip install protobuf\" to install it from pypi.python.org/pypi/protobuf .\n"
] | [
1
] | [] | [] | [
"protocol_buffers",
"python"
] | stackoverflow_0007603491_protocol_buffers_python.txt |
Q:
How to use simple sqlalchemy calls while using thread/multiprocessing
Problem
I am writing a program that reads a set of documents from a corpus (each line is a document). Each document is processed using a function processdocument, assigned a unique ID, and then written to a database. Ideally, we want to do this ... | How to use simple sqlalchemy calls while using thread/multiprocessing | Problem
I am writing a program that reads a set of documents from a corpus (each line is a document). Each document is processed using a function processdocument, assigned a unique ID, and then written to a database. Ideally, we want to do this using several processes. The logic is as follows:
The main routine creates... | [
"The MetaData and its collection of Table objects should be considered a fixed, immutable structure of your application, not unlike your function and class definitions. As you know with forking a child process, all of the module-level structures of your application remain present across process boundaries, and tab... | [
5
] | [] | [] | [
"database",
"multiprocessing",
"multithreading",
"python",
"sqlalchemy"
] | stackoverflow_0007603790_database_multiprocessing_multithreading_python_sqlalchemy.txt |
Q:
python stripping chars from list item
I'm trying to strip characters from timestamp stored in matrix (or list of lists if you want). I want to extract the item and use it as a filename after stripping unwanted characters (it should stay unchanged in the original list). I'm quite familiar with stripping and other s... | python stripping chars from list item | I'm trying to strip characters from timestamp stored in matrix (or list of lists if you want). I want to extract the item and use it as a filename after stripping unwanted characters (it should stay unchanged in the original list). I'm quite familiar with stripping and other string operations I use it routinely, but no... | [
"That's not what str.strip() does, and that's not how it works. Strings are immutable, so the result is returned from the method.\nflnm = flnm.replace(':', '')\n\nRepeat with the other characters you want to remove.\n",
"Try this:\nimport re\nflnm = re.sub('[^0-9]', '', flnm)\n\n",
"This is pretty fast (if you ... | [
3,
3,
2,
2,
0
] | [] | [] | [
"list",
"python",
"string",
"strip"
] | stackoverflow_0007603658_list_python_string_strip.txt |
Q:
how to download a file returned "indirectly"(??) from html form submission? (python, urllib, urllib2, etc.)
EDIT: Problem solve. Ultimately it turned out to be a matter of "http:" instead of "https:" in the url (just a stupid mistake on my part). But it was the nice clean code example from cetver that helped me... | how to download a file returned "indirectly"(??) from html form submission? (python, urllib, urllib2, etc.) | EDIT: Problem solve. Ultimately it turned out to be a matter of "http:" instead of "https:" in the url (just a stupid mistake on my part). But it was the nice clean code example from cetver that helped me isolate the problem. Thanks to all who offered suggestions.
Putting this url in firefox triggers the appropriat... | [
"CODE BELLOW ISN'T TESTED\nsomething like: \nimport urllib, urllib2,\n\nHOST = 'https://www.virwox.com'\nFORMS = {\n 'login': {\n 'action': HOST + '/index.php',\n 'data': urllib.urlencode( {\n 'uname':'username', \n 'password':'******'\n } )\n },\n 'orders': {\n ... | [
1,
1,
0
] | [] | [] | [
"download",
"forms",
"python",
"urllib",
"urllib2"
] | stackoverflow_0007603044_download_forms_python_urllib_urllib2.txt |
Q:
Quoting a Python function in order to apply it later
Given an object Foo, which has a set of methods Bar, Baz, Quux, and Close.
I want to wrap calls into Foo as follows
def wrapper(method_symbol, *args):
object = Foo()
apply(object.method_symbol, args)
object.Close()
So later on, I can call wrapper(Bar, ... | Quoting a Python function in order to apply it later | Given an object Foo, which has a set of methods Bar, Baz, Quux, and Close.
I want to wrap calls into Foo as follows
def wrapper(method_symbol, *args):
object = Foo()
apply(object.method_symbol, args)
object.Close()
So later on, I can call wrapper(Bar, MySweetArgs) and have wrapper correctly dispatch.
Obviousl... | [
"If you want to call the method by its name, the wrapper function could look like this:\ndef wrapper(method_symbol, *args):\n obj = Foo()\n getattr(obj, method_symbol)(*args)\n obj.Close()\n\nwrapper('Bar', 1, 2, 3)\n\nYou could also use the method directly, instead of its name:\ndef wrapper(method, *args):\n... | [
4
] | [
"If method_symbol is the string name then:\nFoo.__dict__[method_symbol](*args)\n\nwould probably do it.\n"
] | [
-1
] | [
"python"
] | stackoverflow_0007604048_python.txt |
Q:
How to get the tag of a shape when clicked
Lets say I have created a canvas in a Tkinter app.
In the canvas, I have drawn several rectangles.
What I want in essence, is to know in which rectangle the user has clicked, that is my main concern, but this is what I have tried and what I think might be the solution.
Th... | How to get the tag of a shape when clicked | Lets say I have created a canvas in a Tkinter app.
In the canvas, I have drawn several rectangles.
What I want in essence, is to know in which rectangle the user has clicked, that is my main concern, but this is what I have tried and what I think might be the solution.
This is my layout:
for x in range(1,6):
fo... | [
"You can use something like this to reference the clicked-on object:\nevent.widget.find_withtag(\"current\")\n\nThe tag \"current\" is special and represents the top-most object under the mouse.\n",
"w.tag_bind(\"table\" + str(tableNumber), '<Button-1>', do(event, tag))\n\nshould be changed to\ntag = \"table\" + ... | [
8,
4
] | [] | [] | [
"click",
"events",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0007602122_click_events_python_tkinter_user_interface.txt |
Q:
Splitting C string in Python
I would like to split a string similar to
'abc "defg hijk \\"l; mn\\" opqrs"; tuv'
into
(['abc', '"defg hijk \\"l; mn\\" opqrs"'], 33)
i.e. I don't want to break on semicolon inside (nested) quotes. What's the easiest way, tokenize? It doesn't hurt if it's fast, but short is better.... | Splitting C string in Python | I would like to split a string similar to
'abc "defg hijk \\"l; mn\\" opqrs"; tuv'
into
(['abc', '"defg hijk \\"l; mn\\" opqrs"'], 33)
i.e. I don't want to break on semicolon inside (nested) quotes. What's the easiest way, tokenize? It doesn't hurt if it's fast, but short is better.
Edit: I forgot one more detail th... | [
"It's unlikely there is an easy way to solve this without a proper parser. You could probably get away with a hand built parser that doesn't require tokenizing though.\nSomething like the following should be a good guide:\ndef parse(s):\n cur_s = []\n strings = []\n\n def flush_string():\n strings.p... | [
1,
0,
0
] | [] | [] | [
"python",
"split",
"string"
] | stackoverflow_0007603694_python_split_string.txt |
Q:
Django admin post-save method - how to do?
I've got an admin form with a couple of inlines for displaying m2m fields, like so:
class ArticleAdmin(admin.ModelAdmin):
form = ArticleCustomAdminForm
inlines = (SpecificGemInline, SuiteInline,)
Base class looks something like that:
class Article(models.Model):
... | Django admin post-save method - how to do? | I've got an admin form with a couple of inlines for displaying m2m fields, like so:
class ArticleAdmin(admin.ModelAdmin):
form = ArticleCustomAdminForm
inlines = (SpecificGemInline, SuiteInline,)
Base class looks something like that:
class Article(models.Model):
article_code = models.CharField(max_length=1... | [
"In order to catch changes to a ManyToManyField, you need to hook up the m2m_changed signal. You might want to have a look at the documentation for signals in general and the m2m_changed signal in particular.\n"
] | [
1
] | [] | [] | [
"admin",
"django",
"inline",
"python"
] | stackoverflow_0007604218_admin_django_inline_python.txt |
Q:
Why does this Program run from Aptana IDE and not in python command?
The following code results in a
htmlbody,emailaddress = ConnEmailParser()
TypeError: 'NoneType' object is not iterable
Error but works fine in IDE. Emails are being sent and PDF files generated. But from command line just ConnEmailParser() is ... | Why does this Program run from Aptana IDE and not in python command? | The following code results in a
htmlbody,emailaddress = ConnEmailParser()
TypeError: 'NoneType' object is not iterable
Error but works fine in IDE. Emails are being sent and PDF files generated. But from command line just ConnEmailParser() is working.
What can I do, that the program runs smoothly?
Here the code snip... | [
"In def ConnEmailParser(), check if data is None before calling data[0].split().\nIf it is None, check if imap4 is correctly initiated and if login worked. If that is the case, post a reduced part of your code pinpointing on where it actually goes wrong.\nAs @Jim Garrison pointed out, a traceback would help us (and... | [
1
] | [] | [] | [
"python",
"typeerror"
] | stackoverflow_0007604399_python_typeerror.txt |
Q:
How to modify external process using Python
Beginner here. I am trying to figure out how to modify a running process on a linux system using Python.
Example: I have a python program that takes in as an argument a PID. My goal is to use this PID and get info about the running process with that PID.
(1) Find where ... | How to modify external process using Python | Beginner here. I am trying to figure out how to modify a running process on a linux system using Python.
Example: I have a python program that takes in as an argument a PID. My goal is to use this PID and get info about the running process with that PID.
(1) Find where it is located in memory
(2) Where is the instruct... | [
"Also a newer python user. Can you do all these things with just the command line? If so then you could use os.system('[command]') or the subprocess module. For example you could use the pmap command to get the memory mappings. As for 2-5 I have no experience there. Good Luck.\n"
] | [
0
] | [] | [] | [
"debugging",
"memory",
"process",
"python"
] | stackoverflow_0007604068_debugging_memory_process_python.txt |
Q:
How to display point cloud in vtk in different colors?
I have a point cloud which I want to visualize in vtk. I want to see them in different colors depending on some conditions. I am using python.
Any suggestions on how to do that?
Thanks a lot
A:
Here is an example that sets the point color based on z-axis val... | How to display point cloud in vtk in different colors? | I have a point cloud which I want to visualize in vtk. I want to see them in different colors depending on some conditions. I am using python.
Any suggestions on how to do that?
Thanks a lot
| [
"Here is an example that sets the point color based on z-axis value.\nimport vtk\nfrom numpy import random\n\nclass VtkPointCloud:\n\n def __init__(self, zMin=-10.0, zMax=10.0, maxNumPoints=1e6):\n self.maxNumPoints = maxNumPoints\n self.vtkPolyData = vtk.vtkPolyData()\n self.clearPoints()\n... | [
25
] | [] | [] | [
"python",
"vtk"
] | stackoverflow_0007591204_python_vtk.txt |
Q:
Check for [] operator
How do I check whether an object supports [] operation in Python? I think of something like the following:
if supports(obj, ?[]?):
print("Supports")
A:
You don't "check for support". You just use it:
try:
a = obj[whatever]
except TypeError:
# whatever your fall-back plan is w... | Check for [] operator | How do I check whether an object supports [] operation in Python? I think of something like the following:
if supports(obj, ?[]?):
print("Supports")
| [
"You don't \"check for support\". You just use it:\ntry:\n a = obj[whatever]\nexcept TypeError:\n # whatever your fall-back plan is when obj doesn't support [] (__getitem__) \n\nWriting your own isinstance is always the wrong thing to do. A new type that doesn't inherit from the collections ABC classes can ... | [
14,
11,
3,
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0007604380_python.txt |
Q:
How to select some urls with BeautifulSoup?
I want to scrape the following information except the last row and "class="Region" row:
...
<td>7</td>
<td bgcolor="" align="left" style=" width:496px"><a class="xnternal" href="http://www.whitecase.com">White and Case</a></td>
<td bgcolor="" align="left">New York</td> ... | How to select some urls with BeautifulSoup? | I want to scrape the following information except the last row and "class="Region" row:
...
<td>7</td>
<td bgcolor="" align="left" style=" width:496px"><a class="xnternal" href="http://www.whitecase.com">White and Case</a></td>
<td bgcolor="" align="left">New York</td>
<td bgcolor="" align="left" class="Region">N/A</... | [
"I think this may be what you are looking for. The attrs argument can be helpful for isolating the sections you want.\nfrom BeautifulSoup import BeautifulSoup\nimport urllib\n\nsoup = BeautifulSoup(urllib.urlopen(\"http://www.ilrg.com/nlj250/\"))\n\nrows = soup.findAll(name='tr',attrs={'class':'small'})\nfor row in... | [
3,
1
] | [] | [] | [
"beautifulsoup",
"python",
"screen_scraping",
"web_scraping"
] | stackoverflow_0007604272_beautifulsoup_python_screen_scraping_web_scraping.txt |
Q:
generate a patterned numpy matrix
Is it possible to generate a numpy matrix with a circular pattern of "1"s in a rest matrix of "0"s? So basically a
generate(ysize, xsize, ycenter, xcenter, radius)
Should look something like
[000000000]
[000000000]
[000001000]
[000011100]
[000111110]
[000011100]
[000001000]
[000... | generate a patterned numpy matrix | Is it possible to generate a numpy matrix with a circular pattern of "1"s in a rest matrix of "0"s? So basically a
generate(ysize, xsize, ycenter, xcenter, radius)
Should look something like
[000000000]
[000000000]
[000001000]
[000011100]
[000111110]
[000011100]
[000001000]
[000000000]
(ok this looks stupid but on a... | [
"def generate(ysize, xsize, ycenter, xcenter, radius):\n x = np.arange(xsize)[None,:]\n y = np.arange(ysize)[:,None]\n return ((xcenter - x) ** 2 + (ycenter - y) ** 2 <= radius ** 2) * 1\n\n\ngenerate(10,8,4,3,2)\n\n\narray([[0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 1, 0... | [
6,
5
] | [] | [] | [
"matrix",
"numpy",
"python"
] | stackoverflow_0007598264_matrix_numpy_python.txt |
Q:
Call external program from python and get its output
I want to call a program (.exe), which is written in C++ and compiled, from Python. The executable takes as input two files and returns a score.
I need to do this for multiple files. So, I would like to write a small script in python which loops over multiple f... | Call external program from python and get its output | I want to call a program (.exe), which is written in C++ and compiled, from Python. The executable takes as input two files and returns a score.
I need to do this for multiple files. So, I would like to write a small script in python which loops over multiple files, passes them to the executable and gets back the valu... | [
"To run an external program and get its output, use subprocess.check_output on Python 2.7+. The example from the docs:\n>>> subprocess.check_output([\"ls\", \"-l\", \"/dev/null\"])\n'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\\n'\n\ncheck_call just returns the return code of the program, not the output.\n",... | [
5,
2
] | [] | [] | [
"call",
"python",
"subprocess"
] | stackoverflow_0007604621_call_python_subprocess.txt |
Q:
dict.get() method returns a pointer
Let's say I have this code:
my_dict = {}
default_value = {'surname': '', 'age': 0}
# get info about john, or a default dict
item = my_dict.get('john', default_value)
# edit the data
item[surname] = 'smith'
item[age] = 68
my_dict['john'] = item
The problem becomes clear, if w... | dict.get() method returns a pointer | Let's say I have this code:
my_dict = {}
default_value = {'surname': '', 'age': 0}
# get info about john, or a default dict
item = my_dict.get('john', default_value)
# edit the data
item[surname] = 'smith'
item[age] = 68
my_dict['john'] = item
The problem becomes clear, if we now check the value of default_value:
>... | [
"item = my_dict.get('john', default_value.copy())\n\nYou're always passing a reference in Python.\nThis doesn't matter for immutable objects like str, int, tuple, etc. since you can't change them, only point a name at a different object, but it does for mutable objects like list, set, and dict. You need to get used... | [
30,
12,
10,
5,
4
] | [] | [] | [
"dictionary",
"pass_by_reference",
"python"
] | stackoverflow_0007153893_dictionary_pass_by_reference_python.txt |
Q:
GQL Not Recognising a ReferenceProperty in Filter
I have a datastore thats has ~850 groups and ~19,000 items. Each item may belong to only one group, I have two models in my app that represent a Group and an Item:
class Group(db.Model):
Id = db.IntegerProperty()
Name = db.StringProperty()
# ... some ot... | GQL Not Recognising a ReferenceProperty in Filter | I have a datastore thats has ~850 groups and ~19,000 items. Each item may belong to only one group, I have two models in my app that represent a Group and an Item:
class Group(db.Model):
Id = db.IntegerProperty()
Name = db.StringProperty()
# ... some other properties
class Item(db.Model):
Id = db.Inte... | [
"The most likely explanation is that when you inserted the data, the reference property was set as indexed=False. Changes to a model only affect entities written after the model was changed, so rows inserted while indexing was disabled for that column will not have index rows.\n"
] | [
1
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"gql",
"python"
] | stackoverflow_0007585589_google_app_engine_google_cloud_datastore_gql_python.txt |
Q:
passing a return statement into another function in a class
I have the following code that I am using to send a message from a gmail account to another gmail account:
import smtplib
class GmailSmpt:
global server
server = smtplib.SMTP('smtp.gmail.com','587')
def __init__(self,sendfrom,sendto,usrnam... | passing a return statement into another function in a class | I have the following code that I am using to send a message from a gmail account to another gmail account:
import smtplib
class GmailSmpt:
global server
server = smtplib.SMTP('smtp.gmail.com','587')
def __init__(self,sendfrom,sendto,usrname,pswd):
self.sendfrom = sendfrom
self.sendto = s... | [
"How about make server an attribute of each instance of GmailSmpt:\nclass GmailSmpt:\n def __init__(self,sendfrom,sendto,usrname,pswd):\n self.server = smtplib.SMTP('smtp.gmail.com','587')\n ...\n\nAfter all, server.login uses self.usrname, and self.pswd, so server's domain of relevance is bound to... | [
2
] | [] | [] | [
"class",
"function",
"python",
"return"
] | stackoverflow_0007605261_class_function_python_return.txt |
Q:
SQLAlchemy - build query filter dynamically from dict
So I have a dict passed from a web page. I want to build the query dynamically based on the dict. I know I can do:
session.query(myClass).filter_by(**web_dict)
However, that only works when the values are an exact match. I need to do 'like' filtering. My b... | SQLAlchemy - build query filter dynamically from dict | So I have a dict passed from a web page. I want to build the query dynamically based on the dict. I know I can do:
session.query(myClass).filter_by(**web_dict)
However, that only works when the values are an exact match. I need to do 'like' filtering. My best attempt using the __dict__ attribute:
for k,v in web_di... | [
"You're on the right track!\nFirst thing you want to do different is access attributes using getattr, not __dict__; getattr will always do the right thing, even when (as may be the case for more convoluted models) a mapped attribute isn't a column property.\nThe other missing piece is that you can specify filter() ... | [
56
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0007604967_python_sqlalchemy.txt |
Q:
Using Pygments with PHP (Python in PHP)
Is it possible to use Python (specifically Pygments) with PHP? Currently, I have a phpBB forum that I'm developing for and JS Syntax Highlighters just haven't been working for me. There's already a GeSHI mod, but I want to develop something myself just for experience.
Also, ... | Using Pygments with PHP (Python in PHP) | Is it possible to use Python (specifically Pygments) with PHP? Currently, I have a phpBB forum that I'm developing for and JS Syntax Highlighters just haven't been working for me. There's already a GeSHI mod, but I want to develop something myself just for experience.
Also, would there be performance issues?
| [
"There is now a library for this at:\nhttp://derek.simkowiak.net/pygments-for-php/\n",
"Pretty much the only way to perform that integration (with PHP as the dominant language) is to shell out. This means starting python manually every time you need it. \nThat can be a little slow if you need to do it a lot. Y... | [
6,
1,
0
] | [] | [] | [
"php",
"phpbb",
"pygments",
"python"
] | stackoverflow_0003153961_php_phpbb_pygments_python.txt |
Q:
Self-referential tables with polymorphism in SQLAlchemy
So I'm having issues with my model right now. I came across these two (1) (2) questions which helped me a lot, but now I'm stuck. Here's my current code:
class Post(Base):
__tablename__ = 'post'
id = Column(Integer, primary_key=True)
type = Column... | Self-referential tables with polymorphism in SQLAlchemy | So I'm having issues with my model right now. I came across these two (1) (2) questions which helped me a lot, but now I'm stuck. Here's my current code:
class Post(Base):
__tablename__ = 'post'
id = Column(Integer, primary_key=True)
type = Column('type', String(10))
created = Column(TIMESTAMP(), defaul... | [
"id is a really unfortunate name for a column; id is a built-in function, and so it's always defined. If you had chosen a less mainstream name for your primary keys, you would be seeing a different error and it would be obvious; \nclass Comment(Post):\n __tablename__ = 'comment'\n __mapper_args__ = {'polym... | [
3
] | [] | [] | [
"python",
"sqlalchemy"
] | stackoverflow_0007604115_python_sqlalchemy.txt |
Q:
How to put a single column item into a single row?
I have a file like this:
a
b
c
d
e
f
g
h
and so on, with a single word/number on each line. and after 4/5 lines a couple of ( or three ) space. what I want to do is put them like this
a,b,c,d
e,f,g,h
I was working with sed, but sed is oneliner and seems to help... | How to put a single column item into a single row? | I have a file like this:
a
b
c
d
e
f
g
h
and so on, with a single word/number on each line. and after 4/5 lines a couple of ( or three ) space. what I want to do is put them like this
a,b,c,d
e,f,g,h
I was working with sed, but sed is oneliner and seems to helpless for the addition of multiple lines. Can anybody h... | [
"This can be done a wide variety of ways without anything even as complicated as sed, much less Perl or Python. My weapon of choice would be tr:\ncat inFile.txt | tr \"\\n\" \",\" | tr \",,,,\" \" \" > outFile.txt\n\n"
] | [
0
] | [] | [] | [
"c",
"python"
] | stackoverflow_0007605197_c_python.txt |
Q:
Is there a shorter code to join the keys and values for a dictionary?
Is there a shorter or better snippet that accomplishes the following:
>>> h = { 'apple' : 'ipad' , 'amazon': 'kindle' }
>>> [' '.join(item) for item in zip( h.keys(), h.values())]
[ 'apple ipad', 'amazon kindle' ]
A:
>>> [' '.join(item) for it... | Is there a shorter code to join the keys and values for a dictionary? | Is there a shorter or better snippet that accomplishes the following:
>>> h = { 'apple' : 'ipad' , 'amazon': 'kindle' }
>>> [' '.join(item) for item in zip( h.keys(), h.values())]
[ 'apple ipad', 'amazon kindle' ]
| [
">>> [' '.join(item) for item in h.iteritems()]\n['amazon kindle', 'apple ipad']\n\n>>> map(' '.join, h.iteritems())\n['amazon kindle', 'apple ipad']\n\nBut avoid using map() these days. And list comprehensions if you can help it.\n"
] | [
7
] | [] | [] | [
"python"
] | stackoverflow_0007605831_python.txt |
Q:
Python: Optimal algorithm to avoid downloading unchanged pages while crawling
I am writing a crawler which regularly inspects a list of news websites for new articles.
I have read about different approaches for avoiding unnecessary pages downloads, basically identified 5 header elements that could be useful to det... | Python: Optimal algorithm to avoid downloading unchanged pages while crawling | I am writing a crawler which regularly inspects a list of news websites for new articles.
I have read about different approaches for avoiding unnecessary pages downloads, basically identified 5 header elements that could be useful to determine if the page has changed or not:
HTTP Status
ETAG
Last_modified (to combine... | [
"The only thing you need to check before making the request is Expires. If-Modified-Since is not something the server sends you, but something you send the server.\nWhat you want to do is an HTTP GET with an If-Modified-Since header indicating when you last retrieved the resource. If you get back status code 304 ra... | [
2,
1
] | [] | [] | [
"etag",
"http_headers",
"if_modified_since",
"python",
"web_crawler"
] | stackoverflow_0007605710_etag_http_headers_if_modified_since_python_web_crawler.txt |
Q:
Translate one line please from python to ruby
Need to calculate IP => int just like in here:
https://bitbucket.org/lorien/django-ipgeo/src/d19648c9b14f/ipgeo/models.py
but in ruby.
I'm pretty new in ruby, so cannot translate this into ruby:
number = struct.unpack('!L', socket.inet_aton(ip))[0]
struct, socket are ... | Translate one line please from python to ruby | Need to calculate IP => int just like in here:
https://bitbucket.org/lorien/django-ipgeo/src/d19648c9b14f/ipgeo/models.py
but in ruby.
I'm pretty new in ruby, so cannot translate this into ruby:
number = struct.unpack('!L', socket.inet_aton(ip))[0]
struct, socket are python std, ip is a string like '127.0.0.1'
| [
"Ruby comes with an ipaddr module that specifies an IPAddr class that can return a representation as an integer.\nrequire 'ipaddr'\n\naddr = IPAddr.new '127.0.0.1'\nprint addr.to_i\n\nHere it is in irb:\nruby-1.9.2-p290 :002 > require 'ipaddr'\n => true \nruby-1.9.2-p290 :003 > addr = IPAddr.new '127.0.0.1'\n => #<... | [
3
] | [] | [] | [
"ip",
"python",
"ruby",
"sockets",
"struct"
] | stackoverflow_0007605968_ip_python_ruby_sockets_struct.txt |
Q:
Interactive 2D plotting in python
I'm trying to write a program that creates a 2D grid in which the user chooses some edges between the points in the grid. Then the program dynamically manipulate those edges(eg. flip them, connect them, ...) till it converges to a particular shape.
Now my question is there any pa... | Interactive 2D plotting in python | I'm trying to write a program that creates a 2D grid in which the user chooses some edges between the points in the grid. Then the program dynamically manipulate those edges(eg. flip them, connect them, ...) till it converges to a particular shape.
Now my question is there any particular module that suits this kind of... | [
"Have you tried PyGame or SFML?\nBoth support 'setting pixels' on a canvas.\n"
] | [
2
] | [] | [] | [
"chaco",
"graphics",
"plot",
"python"
] | stackoverflow_0007606139_chaco_graphics_plot_python.txt |
Q:
Unable to view item in browser based on its key in Python GAE
I'm using python GAE with webapp.
I have a form for a user to create a object in the database, something like:
class SpamRecord(db.Model):
author = db.ReferenceProperty(Author, required=True)
text = db.StringProperty()
After it's created, the... | Unable to view item in browser based on its key in Python GAE | I'm using python GAE with webapp.
I have a form for a user to create a object in the database, something like:
class SpamRecord(db.Model):
author = db.ReferenceProperty(Author, required=True)
text = db.StringProperty()
After it's created, the user is redirected to a page whose URL contains that object's key.... | [
"In regular expressions, \\w doesn't match hyphens. (It will match underscores.) For that second pair of keys, this'll result in only passing part of the key to your handler.\nIn your URL pattern, try r\"/view_spam/(.*)\" instead.\n"
] | [
6
] | [] | [] | [
"google_app_engine",
"python",
"web_applications"
] | stackoverflow_0007606240_google_app_engine_python_web_applications.txt |
Q:
Python: wait for a key press or until timeout
I have a long-running Python script inside a terminal session (the host machine is a FreeBSD box) that performs a task every 9 minutes. Now, I'd like to be able to interrupt that sleep call at any moment so that it performs the task right away.
How can I do that? Catch... | Python: wait for a key press or until timeout | I have a long-running Python script inside a terminal session (the host machine is a FreeBSD box) that performs a task every 9 minutes. Now, I'd like to be able to interrupt that sleep call at any moment so that it performs the task right away.
How can I do that? Catching Ctrl+C is not an option as I need it to stop th... | [
"With Thomas's suggestion, I came up with this function:\nimport signal\n\ndef input_or_timeout(timeout):\n def nothing(sig, frame): pass\n signal.signal(signal.SIGALRM, nothing)\n signal.alarm(timeout)\n try:\n raw_input()\n signal.alarm(0)\n except (IOError, EOFError): pass\n\nIt wait... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0007606064_python.txt |
Q:
stretch, scale, or double up an array with numpy?
I was wondering if there is a numpy function to "stretch" an array along a specific axis
like the following:
a =[[1,2,3,4],[1,2,3,4]]
to
a = [[1,1,2,2,3,3,4,4],[1,1,2,2,3,3,4,4]]
Thanks in advance!
A:
import numpy as np
a = np.array([[1,2,3,4],[1,2,3,4]])
First ... | stretch, scale, or double up an array with numpy? | I was wondering if there is a numpy function to "stretch" an array along a specific axis
like the following:
a =[[1,2,3,4],[1,2,3,4]]
to
a = [[1,1,2,2,3,3,4,4],[1,1,2,2,3,3,4,4]]
Thanks in advance!
| [
"import numpy as np\na = np.array([[1,2,3,4],[1,2,3,4]])\n\nFirst possibility:\na.repeat(2, axis=1)\n\nor the second:\nnp.kron(a, [1,1])\n\nBoth returning:\narray([[1, 1, 2, 2, 3, 3, 4, 4],\n [1, 1, 2, 2, 3, 3, 4, 4]])\n\n"
] | [
5
] | [] | [] | [
"arrays",
"numpy",
"python"
] | stackoverflow_0007606102_arrays_numpy_python.txt |
Q:
Python: counting unique instance of words across several lines
I have a text file with several observations. Each observation is in one line. I would like to detect unique occurrence of each word in a line. In other words, if same word occurs twice or more on the same line, it is still counted as once. However, I ... | Python: counting unique instance of words across several lines | I have a text file with several observations. Each observation is in one line. I would like to detect unique occurrence of each word in a line. In other words, if same word occurs twice or more on the same line, it is still counted as once. However, I would like to count the frequency of occurrence of each words across... | [
"You're running re.sub on each character of the line, one at a time. That's slow. Do it on the whole line:\ns = re.sub(r'[0-9#$?*_><@\\(\\)&;:,.!-+%=\\[\\]\\-\\/\\^]', \"_\", line)\n\nAlso, have a look at sets and the Counter class in the collections module. It may be faster if you just count and then discard those... | [
1,
1,
0
] | [] | [] | [
"counting",
"performance",
"python",
"words"
] | stackoverflow_0007605199_counting_performance_python_words.txt |
Q:
How to build Python into a C++ .exe
I have a c++ application and would like to take advantage of one of pythons libraries. I have seen info on how to run the python interpreter inside the program, however I want the program to be self-sufficient, so I can run it on any windows computer, even if it does not have py... | How to build Python into a C++ .exe | I have a c++ application and would like to take advantage of one of pythons libraries. I have seen info on how to run the python interpreter inside the program, however I want the program to be self-sufficient, so I can run it on any windows computer, even if it does not have python. How can i compile the python into t... | [
"You can't. You must have the DLL.\n"
] | [
1
] | [] | [] | [
"c++",
"embed",
"python"
] | stackoverflow_0007606520_c++_embed_python.txt |
Q:
Python's setup.py: how to install different files for different platforms
I'm writing a cross-platform package which need to include different binary file for different platforms (e.g. Linux/MAC OS/Windows and even 32bit/64bit Windows)
I need my package's setup.py to install different binary data files based on th... | Python's setup.py: how to install different files for different platforms | I'm writing a cross-platform package which need to include different binary file for different platforms (e.g. Linux/MAC OS/Windows and even 32bit/64bit Windows)
I need my package's setup.py to install different binary data files based on the platform. The problem is that I need the data files for all platforms to be i... | [
"It's not too hard, at least in simple cases: you can for instance see how the setup.py of the uncertainties Python package does it (it selects an install directory based on the version of Python, but you would simply check sys.platform and friends, in your case).\nThe key lines are\nif sys.version_info >= (2, 5):\... | [
2
] | [] | [] | [
"cross_platform",
"distutils",
"python",
"setup.py",
"setuptools"
] | stackoverflow_0007606776_cross_platform_distutils_python_setup.py_setuptools.txt |
Q:
paste image without background PIL
I am trying to paste many small grayscale images into a bigger one. All images are jpegs. The small images had been previously rotated, so they have black background. What I wanted to do is to paste them without a background color, in other words, I need the background color to b... | paste image without background PIL | I am trying to paste many small grayscale images into a bigger one. All images are jpegs. The small images had been previously rotated, so they have black background. What I wanted to do is to paste them without a background color, in other words, I need the background color to be transparent.
Thank you for your sugges... | [
"to my knowledge, jpg does not support transparency, you probably want your output to be a png, and you will need to set the alpha channel to be nothing\nhttp://www.talkgraphics.com/showthread.php?22385-How-do-I-make-jpeg-image-background-transparent\n"
] | [
1
] | [] | [] | [
"python",
"python_imaging_library"
] | stackoverflow_0007607027_python_python_imaging_library.txt |
Q:
Making google analytics ID a variable
My app serves multiple domains which I understand should be done by namespaces which I'm researching. Since multiple domains should have multiple analytics ID:s I get the analytics ID from the code but I want to make it even more configurable:
if os.environ.get('HTTP_HOST'... | Making google analytics ID a variable | My app serves multiple domains which I understand should be done by namespaces which I'm researching. Since multiple domains should have multiple analytics ID:s I get the analytics ID from the code but I want to make it even more configurable:
if os.environ.get('HTTP_HOST').endswith('.br') \
or os.environ['... | [
"The simplest way to do this is with a Python dict:\nanalytics_ids = {\n 'mydomain.br': 'UA-637933-12',\n 'mydomain.com': 'UA-637933-18',\n}\n\ndata['analytics'] = analytics_ids[self.request.host]\n\nIf you have other per-domain stats, you may want to make each dictionary entry a tuple, a nested dict, or a config... | [
3,
1
] | [] | [] | [
"google_analytics",
"google_app_engine",
"namespaces",
"python"
] | stackoverflow_0007606472_google_analytics_google_app_engine_namespaces_python.txt |
Q:
django-chronograph script wont run from cron job or manually due to permissions issue
I've created a custom management command as a py file, in the usual place.
chronograph is installed in the right place and syncd ok.
I've created the cron job as the following
* * * * * /home/shofty/virtualenvs/webbricks/bin/chr... | django-chronograph script wont run from cron job or manually due to permissions issue | I've created a custom management command as a py file, in the usual place.
chronograph is installed in the right place and syncd ok.
I've created the cron job as the following
* * * * * /home/shofty/virtualenvs/webbricks/bin/chronograph -e /home/shofty/virtualenvs/webbricks/bin/activate_this.py -p /home/shofty/virtual... | [
"The answer for this was that chronograph.sh has been superseded by chronograph. despite this supposedly being able to activate an env, it wasn't doing it early enough to import argparse which as far as i can tell isn't inbuilt to python 2.5 but is in 2.6. then its just down to getting the right combination of argu... | [
1,
0,
0,
0
] | [] | [] | [
"cron",
"debian",
"django",
"linux",
"python"
] | stackoverflow_0007432422_cron_debian_django_linux_python.txt |
Q:
pyvnc2swf not working? outputs video of duration 0sec
i need to convert video from swf to flv. im using pyvnc2swf : edit.py but it's not working. shows no errors but outputs a file with one blank frame.
here is the command:
/usr/share/pyvnc2swf/edit.py -o outlet.flv -s 1 1.swf
output:
Using pygame 1.9.1release t... | pyvnc2swf not working? outputs video of duration 0sec | i need to convert video from swf to flv. im using pyvnc2swf : edit.py but it's not working. shows no errors but outputs a file with one blank frame.
here is the command:
/usr/share/pyvnc2swf/edit.py -o outlet.flv -s 1 1.swf
output:
Using pygame 1.9.1release there is no soundcard Input movie: version=7, size=718x351, ... | [
"i got the answer on my own :\npyvnc2swf is working perfectly but it won't work with the swf's which are interative(require clicking etc). u can only convert simple swf's to flv.\n"
] | [
0
] | [] | [] | [
"linux",
"python",
"video_codecs",
"video_conversion"
] | stackoverflow_0007593087_linux_python_video_codecs_video_conversion.txt |
Q:
Multithreading with pyqt - Can't get the separate threads running at the same time?
I am trying to get a PyQT GUI running ontop of my python application and I have tried to get it separated into 2 threads so the GUI would be responsive while my main running loop goes, but I have not been able to get it going. Mayb... | Multithreading with pyqt - Can't get the separate threads running at the same time? | I am trying to get a PyQT GUI running ontop of my python application and I have tried to get it separated into 2 threads so the GUI would be responsive while my main running loop goes, but I have not been able to get it going. Maybe I am misunderstanding it. Here is what I've tried:
My Window and Worker thread are def... | [
"After looking more closely at your code, you have MAIN_WORLD started before QApplication, which isn't what you want.\nYou want to do something like this:\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n sys.exit(app.exec_())\n\nAnd, in your Window class:\nclass Window(QWidget):\n def __init__(... | [
1,
0
] | [] | [] | [
"multithreading",
"pyqt",
"python"
] | stackoverflow_0002186076_multithreading_pyqt_python.txt |
Q:
Make TortoiseHg use a separate Mercurial package
I have installed Mercurial as a Python package. Now I want TortoiseHg to work with them. However, all versions of TortoiseHg are bundled with its own version of hg and Python libraries. How do I make sure that TortoiseHg is using Mercurial which I have installed?
A... | Make TortoiseHg use a separate Mercurial package | I have installed Mercurial as a Python package. Now I want TortoiseHg to work with them. However, all versions of TortoiseHg are bundled with its own version of hg and Python libraries. How do I make sure that TortoiseHg is using Mercurial which I have installed?
| [
"\nI'm extending Mercurial and want to test if it works with TortoiseHg correctly\n\nIt is good to test compatibility with both official Mercurial binaries and TortoiseHg.\nThey are organized the same way. Namely, all Python binaries are stored in library.zip\nSo to make your extension working with either of these ... | [
1
] | [] | [] | [
"mercurial",
"python",
"tortoisehg",
"windows"
] | stackoverflow_0007155729_mercurial_python_tortoisehg_windows.txt |
Q:
Python app crashes when emit signal from callback
I use my c++ library from python application with QT. It uses callback to communicate with UI.
My library is 'ts'. The problem is that my program crashes sometimes.
As I understood it crashes when call to emit(), but it happens rarely.
The simplified version of my ... | Python app crashes when emit signal from callback | I use my c++ library from python application with QT. It uses callback to communicate with UI.
My library is 'ts'. The problem is that my program crashes sometimes.
As I understood it crashes when call to emit(), but it happens rarely.
The simplified version of my program looks like this:
import ts
...
class Parser(QOb... | [
"After finding out that the cause of crash is C++ exception (with help of phihag), I changed my code in this way, and that fixed the problem:\ndef SetProgramListCB(programDesc): \n try:\n print ui.ravisParser.sig\n ui.ravisParser.sig.emit(programDesc)\n except:\n print \"Error\"\n\... | [
0
] | [] | [] | [
"callback",
"crash",
"pyside",
"python",
"signals"
] | stackoverflow_0007580581_callback_crash_pyside_python_signals.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.